context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Collections; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Gearset.Components { /// <summary> /// Draw lines in 3D space, can draw line lists and line strips. /// </summary> public class InternalLineDrawer : Gear { /// <summary> /// Maps an id to an index in the dictionary. /// </summary> private Dictionary<String, int> persistentLine3DTable = new Dictionary<String, int>(); /// <summary> /// Maps an id to an index in the dictionary. /// </summary> private Dictionary<String, int> persistentLine2DTable = new Dictionary<String, int>(); private VertexPositionColor[] persistentVertices3D; private VertexPositionColor[] persistentVertices2D; private VertexPositionColor[] singleFrameVertices2D; private VertexPositionColor[] singleFrameVertices3D; /// <summary> /// Number of lines to be drawn on this frame. There /// will be twice as vertices in the singleFrameVertices array. /// </summary> private int singleFrameLine2DCount = 0; /// <summary> /// Number of lines to be drawn on this frame. There /// will be twice as vertices in the singleFrameVertices array. /// </summary> private int singleFrameLine3DCount = 0; /// <summary> /// Number of lines to be drawn on this frame. There /// will be twice as vertices in the singleFrameVertices array. /// </summary> private int persistentLine3DCount = 0; /// <summary> /// Number of lines to be drawn on this frame. There /// will be twice as vertices in the singleFrameVertices array. /// </summary> private int persistentLine2DCount = 0; /// <summary> /// Sets a maximun of lines we can draw. /// </summary> private const int MaxLineCount = 10000; // Implies a 32k per buffer. private readonly int _lineCount; // Implies a 32k per buffer. /// <summary> /// When a persistent line is deleted it's index will be /// stored here so the next one can take it. /// </summary> private Queue<int> freeSpots3D; /// <summary> /// When a persistent line is deleted it's index will be /// stored here so the next one can take it. /// </summary> private Queue<int> freeSpots2D; /// <summary> /// Gets or sets the config for the Line Drawer. /// </summary> public virtual LineDrawerConfig Config { get { return config; } } /// <summary> /// Defines the way that coordinates will be interpreted in 2D space. Defaults to Screen space. /// </summary> public CoordinateSpace CoordinateSpace; private LineDrawerConfig config; #region Constructor public InternalLineDrawer() : this(new LineDrawerConfig(), MaxLineCount) { } public InternalLineDrawer(int lineCount) : this(new LineDrawerConfig(), lineCount) { } public InternalLineDrawer(LineDrawerConfig config) : this(config, MaxLineCount) { } public InternalLineDrawer(LineDrawerConfig config, int lineCount) : base(config) { this.config = config; config.Cleared += new EventHandler(Config_Cleared); _lineCount = lineCount; this.persistentVertices3D = new VertexPositionColor[_lineCount * 2]; this.persistentVertices2D = new VertexPositionColor[_lineCount * 2]; this.singleFrameVertices2D = new VertexPositionColor[_lineCount * 2]; this.singleFrameVertices3D = new VertexPositionColor[_lineCount * 2]; CoordinateSpace = Components.CoordinateSpace.ScreenSpace; freeSpots3D = new Queue<int>(); freeSpots2D = new Queue<int>(); } public void Clear() { for (int i = 0; i < persistentVertices3D.Length; i++) { persistentVertices3D[i].Position = Vector3.Zero; persistentVertices3D[i].Color = new Color(persistentVertices3D[i].Color.R, persistentVertices3D[i].Color.G, persistentVertices3D[i].Color.B, 1); } for (int i = 0; i < persistentVertices2D.Length; i++) { persistentVertices2D[i].Position = Vector3.Zero; persistentVertices2D[i].Color = new Color(persistentVertices2D[i].Color.R, persistentVertices2D[i].Color.G, persistentVertices2D[i].Color.B, 1); } } void Config_Cleared(object sender, EventArgs e) { Clear(); } #endregion public override void Update(GameTime gameTime) { // Make space for new frame data. singleFrameLine2DCount = 0; singleFrameLine3DCount = 0; base.Update(gameTime); } #region ShowLine (public methods) /// <summary> /// Draws a line and keeps drawing it, its values can be changed /// by calling ShowLine again with the same key. If you want to /// make more efficient subsequent calls, get the returned index ( /// and call it again but with the index overload. /// </summary> public int ShowLine(String key, Vector3 v1, Vector3 v2, Color color) { int index = 0; // Do we already know this line? if (persistentLine3DTable.ContainsKey(key)) { index = persistentLine3DTable[key]; ShowLine(index, v1, v2, color); } else // We don't know this line, assign a new index to it. { // Can we take a spot left by other line? if (freeSpots3D.Count > 0) { index = freeSpots3D.Dequeue(); persistentLine3DTable.Add(key, index); ShowLine(index, v1, v2, color); } else if (persistentLine3DCount + 1 <= _lineCount) { index = (persistentLine3DCount++) * 2; persistentLine3DTable.Add(key, index); ShowLine(index, v1, v2, color); } } return index; } /// <summary> /// Draws a line and keeps drawing it, its values can be changed /// by calling ShowLine again with the same key. If you want to /// make more efficient subsequent calls, get the returned index ( /// and call it again but with the index overload. /// </summary> public int ShowLine(String key, Vector2 v1, Vector2 v2, Color color) { int index = 0; // Do we already know this line? if (persistentLine2DTable.ContainsKey(key)) { index = persistentLine2DTable[key]; ShowLine(index, v1, v2, color); } else // We don't know this line, assign a new index to it. { // Can we take a spot left by other line? if (freeSpots2D.Count > 0) { index = freeSpots2D.Dequeue(); persistentLine2DTable.Add(key, index); ShowLine(index, v1, v2, color); } else if (persistentLine2DCount + 1 <= _lineCount) { index = (persistentLine2DCount++) * 2; persistentLine2DTable.Add(key, index); ShowLine(index, v1, v2, color); } } return index; } /// <summary> /// Use this method only once, then if you want to update the line /// use the (int, Vector3, Vector3, Color) overload with the index /// returned by this method. /// </summary> internal int ShowLine(Vector3 v1, Vector3 v2, Color color) { int index; // Can we take a spot left by other line? if (freeSpots3D.Count > 0) index = freeSpots3D.Dequeue(); else { if ((persistentLine3DCount + 1) * 2 + 1 >= persistentVertices3D.Length) return 0; index = (persistentLine3DCount++) * 2; } ShowLine(index, v1, v2, color); return index; } /// <summary> /// Use this method only once, then if you want to update the line /// use the (int, Vector2, Vector2, Color) overload with the index /// returned by this method. /// </summary> internal int ShowLine(Vector2 v1, Vector2 v2, Color color) { int index; // Can we take a spot left by other line? if (freeSpots2D.Count > 0) index = freeSpots2D.Dequeue(); else { if ((persistentLine2DCount + 1) * 2 + 1 >= persistentVertices2D.Length) return 0; index = (persistentLine2DCount++) * 2; } ShowLine(index, v1, v2, color); return index; } /// <summary> /// Only use this method if you know you have a valid index. You /// can get a valid index by calling the other overlaods. /// </summary> internal void ShowLine(int index, Vector3 v1, Vector3 v2, Color color) { if (index + 1 >= persistentVertices3D.Length) return; persistentVertices3D[index + 0].Position = v1; persistentVertices3D[index + 0].Color = color; persistentVertices3D[index + 1].Position = v2; persistentVertices3D[index + 1].Color = color; } /// <summary> /// Only use this method if you know you have a valid index. You /// can get a valid index by calling the other overlaods. /// </summary> internal void ShowLine(int index, Vector2 v1, Vector2 v2, Color color) { if (index + 1 >= persistentVertices2D.Length) return; persistentVertices2D[index + 0].Position = new Vector3(v1, 0); persistentVertices2D[index + 0].Color = color; persistentVertices2D[index + 1].Position = new Vector3(v2, 0); persistentVertices2D[index + 1].Color = color; } /// <summary> /// Draws a line for one frame. /// </summary> public void ShowLineOnce(Vector3 v1, Vector3 v2, Color color) { if (!Visible || GearsetResources.GlobalAlpha <= 0) return; if (singleFrameLine3DCount >= _lineCount) return; var index = singleFrameLine3DCount * 2; singleFrameVertices3D[index + 0].Position = v1; singleFrameVertices3D[index + 0].Color = color; singleFrameVertices3D[index + 1].Position = v2; singleFrameVertices3D[index + 1].Color = color; singleFrameLine3DCount++; } /// <summary> /// Draws a line for one frame. /// </summary> public void ShowLineOnce(Vector2 v1, Vector2 v2, Color color) { if (!Visible || GearsetResources.GlobalAlpha <= 0) return; if (singleFrameLine2DCount >= _lineCount) return; var index = singleFrameLine2DCount * 2; singleFrameVertices2D[index + 0].Position = new Vector3(v1, 0); singleFrameVertices2D[index + 0].Color = color; singleFrameVertices2D[index + 1].Position = new Vector3(v2, 0); singleFrameVertices2D[index + 1].Color = color; singleFrameLine2DCount++; } /// <summary> /// If a line with the specified key existe, remove it. Else, do nothing. /// </summary> public void DeleteLine3(String key) { if (persistentLine3DTable.ContainsKey(key)) { freeSpots3D.Enqueue(persistentLine3DTable[key]); persistentLine3DTable.Remove(key); } } /// <summary> /// If a line with the specified key existe, remove it. Else, do nothing. /// </summary> public void DeleteLine3(int index) { // Make the current line invisible persistentVertices3D[index].Color = Color.Transparent; persistentVertices3D[index + 1].Color = Color.Transparent; // Let someone else take that index. freeSpots3D.Enqueue(index); } /// <summary> /// If a line with the specified key exists, remove it. Else, do nothing. /// </summary> public void DeleteLine2(String key) { if (persistentLine2DTable.ContainsKey(key)) { freeSpots2D.Enqueue(persistentLine2DTable[key]); persistentLine2DTable.Remove(key); } } /// <summary> /// If a line with the specified key exists, remove it. Else, do nothing. /// </summary> public void DeleteLine2(int index) { // Make the current line invisible persistentVertices2D[index].Color = Color.Transparent; persistentVertices2D[index + 1].Color = Color.Transparent; // Let someone else take that index. freeSpots2D.Enqueue(index); } #endregion #region Draw public override void Draw(Microsoft.Xna.Framework.GameTime gameTime) { // Only draw if we're doing a BasicEffectPass pass if (GearsetResources.CurrentRenderPass == RenderPass.BasicEffectPass) { // If there are no lines, don't draw anything. if (persistentLine3DCount > 0) GearsetResources.Device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, persistentVertices3D, 0, persistentLine3DCount); if (singleFrameLine3DCount > 0) { GearsetResources.Device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, singleFrameVertices3D, 0, singleFrameLine3DCount); singleFrameLine3DCount = 0; } } RenderPass valid2DPass = (CoordinateSpace == CoordinateSpace.ScreenSpace ? RenderPass.ScreenSpacePass : RenderPass.GameSpacePass); if (GearsetResources.CurrentRenderPass == valid2DPass) { // If there are no lines, don't draw anything. if (persistentLine2DCount > 0) GearsetResources.Device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, persistentVertices2D, 0, persistentLine2DCount); if (singleFrameLine2DCount > 0) { GearsetResources.Device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, singleFrameVertices2D, 0, singleFrameLine2DCount); singleFrameLine2DCount = 0; } } } #endregion } public enum CoordinateSpace { /// <summary> /// The geometry will be interpreted as being in screen space. /// </summary> ScreenSpace, /// <summary> /// The geometry will be interpreted as being in game space, thus the Transform2D matrix will be applied. /// </summary> GameSpace, } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Metadata.ManagedReference.Tests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Xunit; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.DocAsCode.DataContracts.ManagedReference; using static Microsoft.DocAsCode.Metadata.ManagedReference.ExtractMetadataWorker; [Trait("Owner", "vwxyzh")] [Trait("Language", "VB")] [Trait("EntityType", "Model")] [Collection("docfx STA")] public class GenerateMetadataFromVBUnitTest { private static readonly MSBuildWorkspace Workspace = MSBuildWorkspace.Create(); [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithClass() { string code = @" Imports System.Collections.Generic Namespace Test1 Public Class Class1 End Class Public Class Class2(Of T) Inherits List(Of T) End Class Public Class Class3(Of T1, T2 As T1) End Class Public Class Class4(Of T1 As { Structure, IEnumerable(Of T2) }, T2 As { Class, New }) End Class End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Class1", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class1", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class1", type.Name); Assert.Equal(@"Public Class Class1", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Class" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("Class2(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class2(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class2`1", type.Name); Assert.Equal(@"Public Class Class2(Of T) Inherits List(Of T) Implements IList(Of T), ICollection(Of T), IList, ICollection, IReadOnlyList(Of T), IReadOnlyCollection(Of T), IEnumerable(Of T), IEnumerable", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Class" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("Class3(Of T1, T2)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class3(Of T1, T2)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class3`2", type.Name); Assert.Equal(@"Public Class Class3(Of T1, T2 As T1)", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Class" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[3]; Assert.NotNull(type); Assert.Equal("Class4(Of T1, T2)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class4(Of T1, T2)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Class4`2", type.Name); Assert.Equal(@"Public Class Class4(Of T1 As {Structure, IEnumerable(Of T2)}, T2 As {Class, New})", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Class" }, type.Modifiers[SyntaxLanguage.VB]); } } [Fact] public void TestGenereateMetadataWithEnum() { string code = @" Namespace Test1 Public Enum Enum1 End Enum Public Enum Enum2 As Byte End Enum Public Enum Enum3 As Integer End Enum End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Enum1", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Enum1", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Enum1", type.Name); Assert.Equal(@"Public Enum Enum1", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Enum" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("Enum2", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Enum2", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Enum2", type.Name); Assert.Equal(@"Public Enum Enum2 As Byte", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Enum" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("Enum3", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Enum3", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Enum3", type.Name); Assert.Equal(@"Public Enum Enum3", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Enum" }, type.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithInterface() { string code = @" Namespace Test1 Public Interface IA End Interface Public Interface IB(Of T As Class) End Interface Public Interface IC(Of TItem As {IA, New}) Inherits IA, IB(Of TItem()) End Interface End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("IA", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IA", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IA", type.Name); Assert.Equal(@"Public Interface IA", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Interface" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("IB(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IB(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IB`1", type.Name); Assert.Equal(@"Public Interface IB(Of T As Class)", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Interface" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("IC(Of TItem)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IC(Of TItem)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IC`1", type.Name); Assert.Equal(@"Public Interface IC(Of TItem As {IA, New}) Inherits IA, IB(Of TItem())", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Interface" }, type.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithStructure() { string code = @" Namespace Test1 Public Structure S1 End Structure Public Structure S2(Of T As Class) End Structure Public Structure S3(Of T1 As {Class, IA, New}, T2 As IB(Of T1)) Implements IA, IB(Of T1()) End Structure Public Interface IA End Interface Public Interface IB(Of T As Class) End Interface End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("S1", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.S1", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.S1", type.Name); Assert.Equal(@"Public Structure S1", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Structure" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("S2(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.S2(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.S2`1", type.Name); Assert.Equal(@"Public Structure S2(Of T As Class)", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Structure" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("S3(Of T1, T2)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.S3(Of T1, T2)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.S3`2", type.Name); Assert.Equal(@"Public Structure S3(Of T1 As {Class, IA, New}, T2 As IB(Of T1)) Implements IA, IB(Of T1())", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Structure" }, type.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithDelegate() { string code = @" Namespace Test1 Public Delegate Sub D1 Public Delegate Sub D2(Of T As Class)(x() as integer) Public Delegate Function D3(Of T1 As Class, T2 As {T1, New})(ByRef x As T1) As T2 End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("D1", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.D1", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.D1", type.Name); Assert.Equal(@"Public Delegate Sub D1", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Delegate" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[1]; Assert.NotNull(type); Assert.Equal("D2(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.D2(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.D2`1", type.Name); Assert.Equal(@"Public Delegate Sub D2(Of T As Class)(x As Integer())", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Delegate" }, type.Modifiers[SyntaxLanguage.VB]); } { var type = output.Items[0].Items[2]; Assert.NotNull(type); Assert.Equal("D3(Of T1, T2)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.D3(Of T1, T2)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.D3`2", type.Name); Assert.Equal(@"Public Delegate Function D3(Of T1 As Class, T2 As {T1, New})(ByRef x As T1) As T2", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Delegate" }, type.Modifiers[SyntaxLanguage.VB]); } } [Fact] public void TestGenereateMetadataWithModule() { string code = @" Namespace Test1 Public Module M1 End Module End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("M1", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.M1", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.M1", type.Name); Assert.Equal(@"Public Module M1", type.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Module" }, type.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Trait("Related", "Inheritance")] [Fact] public void TestGenereateMetadataWithMethod() { string code = @" Namespace Test1 Public MustInherit Class Foo(Of T) Public Overridable Sub M1(x As Integer, ParamArray y() As Integer) End Sub Public MustOverride Sub M2(Of T1 As Class, T2 As Foo(Of T1))(x As T1, ByRef y As T2()) Public Sub M3 End Sub Protected Friend Shared Function M4(Of T1 As Class)(x As T) As T1 Return Nothing End Function End Class Public MustInherit Class Bar Inherits Foo(Of String) Implements IFooBar Public Overrides Sub M1(x As Integer, y() As Integer) End Sub Public NotOverridable Overrides Sub M2(Of T1 As Class, T2 As Foo(Of T1))(x As T1, ByRef y() As T2) End Sub Public Shadows Sub M3() End Sub End Class Public Interface IFooBar Sub M1(x As Integer, ParamArray y() As Integer) Sub M2(Of T1 As Class, T2 As Foo(Of T1))(x As T1, ByRef y() As T2) Sub M3() End Interface End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); // Foo<T> { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("M1(Int32, Int32())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).M1(System.Int32, System.Int32())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.M1(System.Int32,System.Int32[])", method.Name); Assert.Equal("Public Overridable Sub M1(x As Integer, ParamArray y As Integer())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overridable" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[1]; Assert.NotNull(method); Assert.Equal("M2(Of T1, T2)(T1, ByRef T2())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).M2(Of T1, T2)(T1, ByRef T2())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.M2``2(``0,``1[]@)", method.Name); Assert.Equal("Public MustOverride Sub M2(Of T1 As Class, T2 As Foo(Of T1))(x As T1, ByRef y As T2())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "MustOverride" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[2]; Assert.NotNull(method); Assert.Equal("M3()", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).M3()", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.M3", method.Name); Assert.Equal("Public Sub M3", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[3]; Assert.NotNull(method); Assert.Equal("M4(Of T1)(T)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).M4(Of T1)(T)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.M4``1(`0)", method.Name); Assert.Equal("Protected Shared Function M4(Of T1 As Class)(x As T) As T1", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } // Bar { var method = output.Items[0].Items[1].Items[0]; Assert.NotNull(method); Assert.Equal("M1(Int32, Int32())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.M1(System.Int32, System.Int32())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.M1(System.Int32,System.Int32[])", method.Name); Assert.Equal("Public Overrides Sub M1(x As Integer, y As Integer())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overrides" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[1].Items[1]; Assert.NotNull(method); Assert.Equal("M2(Of T1, T2)(T1, ByRef T2())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.M2(Of T1, T2)(T1, ByRef T2())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.M2``2(``0,``1[]@)", method.Name); Assert.Equal("Public NotOverridable Overrides Sub M2(Of T1 As Class, T2 As Foo(Of T1))(x As T1, ByRef y As T2())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overrides", "NotOverridable" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[1].Items[2]; Assert.NotNull(method); Assert.Equal("M3()", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.M3()", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.M3", method.Name); Assert.Equal("Public Sub M3", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, method.Modifiers[SyntaxLanguage.VB]); } // IFooBar { var method = output.Items[0].Items[2].Items[0]; Assert.NotNull(method); Assert.Equal("M1(Int32, Int32())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.M1(System.Int32, System.Int32())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.M1(System.Int32,System.Int32[])", method.Name); Assert.Equal("Sub M1(x As Integer, ParamArray y As Integer())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[2].Items[1]; Assert.NotNull(method); Assert.Equal("M2(Of T1, T2)(T1, ByRef T2())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.M2(Of T1, T2)(T1, ByRef T2())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.M2``2(``0,``1[]@)", method.Name); Assert.Equal("Sub M2(Of T1 As Class, T2 As Foo(Of T1))(x As T1, ByRef y As T2())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[2].Items[2]; Assert.NotNull(method); Assert.Equal("M3()", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.M3()", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.M3", method.Name); Assert.Equal("Sub M3", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], method.Modifiers[SyntaxLanguage.VB]); } // inheritance of Foo<T> { var inheritedMembers = output.Items[0].Items[0].InheritedMembers; Assert.NotNull(inheritedMembers); Assert.Equal( new string[] { "System.Object.ToString", "System.Object.Equals(System.Object)", "System.Object.Equals(System.Object,System.Object)", "System.Object.ReferenceEquals(System.Object,System.Object)", "System.Object.GetHashCode", "System.Object.GetType", "System.Object.Finalize", "System.Object.MemberwiseClone", }.OrderBy(s => s), inheritedMembers.OrderBy(s => s)); } // inheritance of Bar { var inheritedMembers = output.Items[0].Items[1].InheritedMembers; Assert.NotNull(inheritedMembers); Assert.Equal( new string[] { "Test1.Foo{System.String}.M4``1(System.String)", "System.Object.ToString", "System.Object.Equals(System.Object)", "System.Object.Equals(System.Object,System.Object)", "System.Object.ReferenceEquals(System.Object,System.Object)", "System.Object.GetHashCode", "System.Object.GetType", "System.Object.Finalize", "System.Object.MemberwiseClone", }.OrderBy(s => s), inheritedMembers.OrderBy(s => s)); } } [Fact] public void TestGenereateMetadataWithOperator() { string code = @" Namespace Test1 Public Class Foo Public Shared Operator +(x As Foo) As Foo Return x End Operator Public Shared Operator -(x As Foo) As Foo Return x End Operator Public Shared Operator Not(x As Foo) As Foo Return x End Operator Public Shared Operator IsTrue(x As Foo) As Boolean Return True End Operator Public Shared Operator IsFalse(x As Foo) As Boolean Return False End Operator Public Shared Operator +(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator -(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator *(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator /(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator Mod(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator And(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator Or(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator Xor(x As Foo, y As Foo) As Foo Return x End Operator Public Shared Operator >>(x As Foo, y As Integer) As Foo Return x End Operator Public Shared Operator <<(x As Foo, y As Integer) As Foo Return x End Operator Public Shared Operator =(x As Foo, y As Integer) As Boolean Return True End Operator Public Shared Operator <>(x As Foo, y As Integer) As Boolean Return True End Operator Public Shared Operator >(x As Foo, y As Integer) As Boolean Return True End Operator Public Shared Operator <(x As Foo, y As Integer) As Boolean Return True End Operator Public Shared Operator >=(x As Foo, y As Integer) As Boolean Return True End Operator Public Shared Operator <=(x As Foo, y As Integer) As Boolean Return True End Operator Public Shared Widening Operator CType(x As Integer) As Foo Return Nothing End Operator Public Shared Narrowing Operator CType(x As Foo) As Integer Return 1 End Operator End Class End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); // unary { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("UnaryPlus(Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.UnaryPlus(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_UnaryPlus(Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator +(x As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[1]; Assert.NotNull(method); Assert.Equal("UnaryNegation(Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.UnaryNegation(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_UnaryNegation(Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator -(x As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[2]; Assert.NotNull(method); Assert.Equal("OnesComplement(Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.OnesComplement(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_OnesComplement(Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator Not(x As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[3]; Assert.NotNull(method); Assert.Equal("True(Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.True(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_True(Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator IsTrue(x As Foo) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[4]; Assert.NotNull(method); Assert.Equal("False(Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.False(Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_False(Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator IsFalse(x As Foo) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } // binary { var method = output.Items[0].Items[0].Items[5]; Assert.NotNull(method); Assert.Equal("Addition(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Addition(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Addition(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator +(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[6]; Assert.NotNull(method); Assert.Equal("Subtraction(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Subtraction(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Subtraction(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator -(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[7]; Assert.NotNull(method); Assert.Equal("Multiply(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Multiply(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Multiply(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator *(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[8]; Assert.NotNull(method); Assert.Equal("Division(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Division(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Division(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator /(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[9]; Assert.NotNull(method); Assert.Equal("Modulus(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Modulus(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Modulus(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator Mod(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[10]; Assert.NotNull(method); Assert.Equal("BitwiseAnd(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.BitwiseAnd(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_BitwiseAnd(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator And(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[11]; Assert.NotNull(method); Assert.Equal("BitwiseOr(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.BitwiseOr(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_BitwiseOr(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator Or(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[12]; Assert.NotNull(method); Assert.Equal("ExclusiveOr(Foo, Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.ExclusiveOr(Test1.Foo, Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_ExclusiveOr(Test1.Foo,Test1.Foo)", method.Name); Assert.Equal(@"Public Shared Operator Xor(x As Foo, y As Foo) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[13]; Assert.NotNull(method); Assert.Equal("RightShift(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.RightShift(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_RightShift(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator >>(x As Foo, y As Integer) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[14]; Assert.NotNull(method); Assert.Equal("LeftShift(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.LeftShift(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_LeftShift(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator <<(x As Foo, y As Integer) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } // comparison { var method = output.Items[0].Items[0].Items[15]; Assert.NotNull(method); Assert.Equal("Equality(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Equality(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Equality(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator =(x As Foo, y As Integer) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[16]; Assert.NotNull(method); Assert.Equal("Inequality(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Inequality(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Inequality(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator <>(x As Foo, y As Integer) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[17]; Assert.NotNull(method); Assert.Equal("GreaterThan(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.GreaterThan(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_GreaterThan(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator>(x As Foo, y As Integer) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[18]; Assert.NotNull(method); Assert.Equal("LessThan(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.LessThan(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_LessThan(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator <(x As Foo, y As Integer) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[19]; Assert.NotNull(method); Assert.Equal("GreaterThanOrEqual(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.GreaterThanOrEqual(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_GreaterThanOrEqual(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator >=(x As Foo, y As Integer) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[20]; Assert.NotNull(method); Assert.Equal("LessThanOrEqual(Foo, Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.LessThanOrEqual(Test1.Foo, System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_LessThanOrEqual(Test1.Foo,System.Int32)", method.Name); Assert.Equal(@"Public Shared Operator <=(x As Foo, y As Integer) As Boolean", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } // conversion { var method = output.Items[0].Items[0].Items[21]; Assert.NotNull(method); Assert.Equal("Widening(Int32 to Foo)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Widening(System.Int32 to Test1.Foo)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Implicit(System.Int32)~Test1.Foo", method.Name); Assert.Equal(@"Public Shared Widening Operator CType(x As Integer) As Foo", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[0].Items[22]; Assert.NotNull(method); Assert.Equal("Narrowing(Foo to Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.Narrowing(Test1.Foo to System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo.op_Explicit(Test1.Foo)~System.Int32", method.Name); Assert.Equal(@"Public Shared Narrowing Operator CType(x As Foo) As Integer", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Shared" }, method.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithConstructor() { string code = @" Namespace Test1 Public MustInherit Class Foo(Of T) Protected Sub New(x As T()) End Sub End Class Public Class Bar Inherits Foo(Of String) Protected Friend Sub New() MyBase.New(New String() {}) End Sub Public Sub New(x As String()) End Sub End Class End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); // Foo<T> { var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("Foo(T())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).Foo(T())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.#ctor(`0[])", method.Name); Assert.Equal("Protected Sub New(x As T())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected" }, method.Modifiers[SyntaxLanguage.VB]); } // Bar { var method = output.Items[0].Items[1].Items[0]; Assert.NotNull(method); Assert.Equal("Bar()", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Bar()", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.#ctor", method.Name); Assert.Equal("Protected Sub New", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected" }, method.Modifiers[SyntaxLanguage.VB]); } { var method = output.Items[0].Items[1].Items[1]; Assert.NotNull(method); Assert.Equal("Bar(String())", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Bar(System.String())", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.#ctor(System.String[])", method.Name); Assert.Equal("Public Sub New(x As String())", method.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, method.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithField() { string code = @" Namespace Test1 Public Class Foo(Of T) Public X As Integer Protected Shared ReadOnly Y As Foo(Of T) = Nothing Protected Friend Const Z As String = """" End Class Public Enum Bar Black, Red, Blue = 2, Green = 4, White = Red Or Blue Or Green, End Enum End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var field = output.Items[0].Items[0].Items[0]; Assert.NotNull(field); Assert.Equal("X", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).X", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.X", field.Name); Assert.Equal("Public X As Integer", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[0].Items[1]; Assert.NotNull(field); Assert.Equal("Y", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).Y", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.Y", field.Name); Assert.Equal("Protected Shared ReadOnly Y As Foo(Of T)", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "Shared", "ReadOnly" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[0].Items[2]; Assert.NotNull(field); Assert.Equal("Z", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).Z", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.Z", field.Name); Assert.Equal(@"Protected Const Z As String = """"", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "Const" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[1].Items[0]; Assert.NotNull(field); Assert.Equal("Black", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Black", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Black", field.Name); Assert.Equal("Black = 0", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Const" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[1].Items[1]; Assert.NotNull(field); Assert.Equal("Red", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Red", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Red", field.Name); Assert.Equal("Red = 1", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Const" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[1].Items[2]; Assert.NotNull(field); Assert.Equal("Blue", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Blue", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Blue", field.Name); Assert.Equal(@"Blue = 2", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Const" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[1].Items[3]; Assert.NotNull(field); Assert.Equal("Green", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Green", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.Green", field.Name); Assert.Equal("Green = 4", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Const" }, field.Modifiers[SyntaxLanguage.VB]); } { var field = output.Items[0].Items[1].Items[4]; Assert.NotNull(field); Assert.Equal("White", field.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.White", field.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.White", field.Name); Assert.Equal(@"White = 7", field.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Const" }, field.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithEvent() { string code = @" Imports System Namespace Test1 Public MustInherit Class Foo(Of T As EventArgs) Implements IFooBar(Of T) Public Event A As EventHandler Protected Shared Custom Event B As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Private Event C As EventHandler(Of T) Implements IFooBar(Of T).Bar End Class Public Interface IFooBar(Of TEventArgs As EventArgs) Event Bar As EventHandler(Of TEventArgs) End Interface End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); { var a = output.Items[0].Items[0].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).A", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.A", a.Name); Assert.Equal("Public Event A As EventHandler", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[0].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).B", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.B", b.Name); Assert.Equal("Protected Shared Event B As EventHandler", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "Shared" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[0].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).C", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.C", c.Name); Assert.Equal("Event C As EventHandler(Of T) Implements IFooBar(Of T).Bar", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], c.Modifiers[SyntaxLanguage.VB]); } { var a = output.Items[0].Items[1].Items[0]; Assert.NotNull(a); Assert.Equal("Bar", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar(Of TEventArgs).Bar", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar`1.Bar", a.Name); Assert.Equal("Event Bar As EventHandler(Of TEventArgs)", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], a.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithProperty() { string code = @" Namespace Test1 Public MustInherit Class Foo(Of T As Class) Public Property A As Integer Public Overridable ReadOnly Property B As Integer Get Return 1 End Get End Property Public MustOverride WriteOnly Property C As Integer Protected Property D As Integer Get Return 1 End Get Private Set(value As Integer) End Set End Property Public Property E As T Get Return Nothing End Get Protected Set(value As T) End Set End Property Protected Friend Shared Property F As Integer Get Return 1 End Get Protected Set(value As Integer) End Set End Property End Class Public Class Bar Inherits Foo(Of String) Public Overridable Shadows Property A As Integer Public Overrides ReadOnly Property B As Integer Get Return 2 End Get End Property Public Overrides WriteOnly Property C As Integer Set(value As Integer) End Set End Property End Class Public Interface IFooBar Property A As Integer ReadOnly Property B As Integer WriteOnly Property C As Integer End Interface End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); // Foo { var a = output.Items[0].Items[0].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).A", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.A", a.Name); Assert.Equal("Public Property A As Integer", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[0].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).B", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.B", b.Name); Assert.Equal("Public Overridable ReadOnly Property B As Integer", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overridable", "ReadOnly" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[0].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).C", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.C", c.Name); Assert.Equal("Public MustOverride WriteOnly Property C As Integer", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "MustOverride", "WriteOnly" }, c.Modifiers[SyntaxLanguage.VB]); } { var d = output.Items[0].Items[0].Items[3]; Assert.NotNull(d); Assert.Equal("D", d.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).D", d.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.D", d.Name); Assert.Equal(@"Protected ReadOnly Property D As Integer", d.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "ReadOnly" }, d.Modifiers[SyntaxLanguage.VB]); } { var e = output.Items[0].Items[0].Items[4]; Assert.NotNull(e); Assert.Equal("E", e.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).E", e.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.E", e.Name); Assert.Equal(@"Public Property E As T", e.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Get", "Protected Set" }, e.Modifiers[SyntaxLanguage.VB]); } { var f = output.Items[0].Items[0].Items[5]; Assert.NotNull(f); Assert.Equal("F", f.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).F", f.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.F", f.Name); Assert.Equal(@"Protected Shared Property F As Integer", f.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "Shared" }, f.Modifiers[SyntaxLanguage.VB]); } // Bar { var a = output.Items[0].Items[1].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.A", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.A", a.Name); Assert.Equal("Public Overridable Property A As Integer", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overridable" }, a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[1].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.B", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.B", b.Name); Assert.Equal("Public Overrides ReadOnly Property B As Integer", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overrides", "ReadOnly" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[1].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.C", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.C", c.Name); Assert.Equal("Public Overrides WriteOnly Property C As Integer", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overrides", "WriteOnly" }, c.Modifiers[SyntaxLanguage.VB]); } // IFooBar { var a = output.Items[0].Items[2].Items[0]; Assert.NotNull(a); Assert.Equal("A", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.A", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.A", a.Name); Assert.Equal("Property A As Integer", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[2].Items[1]; Assert.NotNull(b); Assert.Equal("B", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.B", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.B", b.Name); Assert.Equal("ReadOnly Property B As Integer", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "ReadOnly" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[2].Items[2]; Assert.NotNull(c); Assert.Equal("C", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.C", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.C", c.Name); Assert.Equal("WriteOnly Property C As Integer", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "WriteOnly" }, c.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Fact] public void TestGenereateMetadataWithIndex() { string code = @" Imports System Namespace Test1 Public MustInherit Class Foo(Of T As Class) Public Property A(x As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable ReadOnly Property B(x As String) As Integer Get Return 1 End Get End Property Public MustOverride WriteOnly Property C(x As Object) As Integer Protected Property D(x As Date) As Integer Get Return 1 End Get Private Set(value As Integer) End Set End Property Public Property E(t As T) As Integer Get Return 0 End Get Protected Set(value As Integer) End Set End Property Protected Friend Shared Property F(x As Integer, t As T) As Integer Get Return 1 End Get Protected Set(value As Integer) End Set End Property End Class Public Class Bar Inherits Foo(Of String) Public Overridable Shadows Property A(x As Integer) As Integer Get Return 1 End Get Set(value As Integer) End Set End Property Public Overrides ReadOnly Property B(x As String) As Integer Get Return 2 End Get End Property Public Overrides WriteOnly Property C(x As Object) As Integer Set(value As Integer) End Set End Property End Class Public Interface IFooBar Property A(x As Integer) As Integer ReadOnly Property B(x As String) As Integer WriteOnly Property C(x As Object) As Integer End Interface End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); Assert.Equal(1, output.Items.Count); // Foo { var a = output.Items[0].Items[0].Items[0]; Assert.NotNull(a); Assert.Equal("A(Int32)", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).A(System.Int32)", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.A(System.Int32)", a.Name); Assert.Equal("Public Property A(x As Integer) As Integer", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public" }, a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[0].Items[1]; Assert.NotNull(b); Assert.Equal("B(String)", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).B(System.String)", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.B(System.String)", b.Name); Assert.Equal("Public Overridable ReadOnly Property B(x As String) As Integer", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overridable", "ReadOnly" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[0].Items[2]; Assert.NotNull(c); Assert.Equal("C(Object)", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).C(System.Object)", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.C(System.Object)", c.Name); Assert.Equal("Public MustOverride WriteOnly Property C(x As Object) As Integer", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "MustOverride", "WriteOnly" }, c.Modifiers[SyntaxLanguage.VB]); } { var d = output.Items[0].Items[0].Items[3]; Assert.NotNull(d); Assert.Equal("D(DateTime)", d.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).D(System.DateTime)", d.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.D(System.DateTime)", d.Name); Assert.Equal(@"Protected ReadOnly Property D(x As Date) As Integer", d.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "ReadOnly" }, d.Modifiers[SyntaxLanguage.VB]); } { var e = output.Items[0].Items[0].Items[4]; Assert.NotNull(e); Assert.Equal("E(T)", e.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).E(T)", e.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.E(`0)", e.Name); Assert.Equal(@"Public Property E(t As T) As Integer", e.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Get", "Protected Set" }, e.Modifiers[SyntaxLanguage.VB]); } { var f = output.Items[0].Items[0].Items[5]; Assert.NotNull(f); Assert.Equal("F(Int32, T)", f.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo(Of T).F(System.Int32, T)", f.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.F(System.Int32,`0)", f.Name); Assert.Equal(@"Protected Shared Property F(x As Integer, t As T) As Integer", f.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Protected", "Shared" }, f.Modifiers[SyntaxLanguage.VB]); } // Bar { var a = output.Items[0].Items[1].Items[0]; Assert.NotNull(a); Assert.Equal("A(Int32)", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.A(System.Int32)", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.A(System.Int32)", a.Name); Assert.Equal("Public Overridable Property A(x As Integer) As Integer", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overridable" }, a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[1].Items[1]; Assert.NotNull(b); Assert.Equal("B(String)", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.B(System.String)", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.B(System.String)", b.Name); Assert.Equal("Public Overrides ReadOnly Property B(x As String) As Integer", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overrides", "ReadOnly" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[1].Items[2]; Assert.NotNull(c); Assert.Equal("C(Object)", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.C(System.Object)", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Bar.C(System.Object)", c.Name); Assert.Equal("Public Overrides WriteOnly Property C(x As Object) As Integer", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "Public", "Overrides", "WriteOnly" }, c.Modifiers[SyntaxLanguage.VB]); } // IFooBar { var a = output.Items[0].Items[2].Items[0]; Assert.NotNull(a); Assert.Equal("A(Int32)", a.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.A(System.Int32)", a.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.A(System.Int32)", a.Name); Assert.Equal("Property A(x As Integer) As Integer", a.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new string[0], a.Modifiers[SyntaxLanguage.VB]); } { var b = output.Items[0].Items[2].Items[1]; Assert.NotNull(b); Assert.Equal("B(String)", b.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.B(System.String)", b.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.B(System.String)", b.Name); Assert.Equal("ReadOnly Property B(x As String) As Integer", b.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "ReadOnly" }, b.Modifiers[SyntaxLanguage.VB]); } { var c = output.Items[0].Items[2].Items[2]; Assert.NotNull(c); Assert.Equal("C(Object)", c.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.C(System.Object)", c.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.IFooBar.C(System.Object)", c.Name); Assert.Equal("WriteOnly Property C(x As Object) As Integer", c.Syntax.Content[SyntaxLanguage.VB]); Assert.Equal(new[] { "WriteOnly" }, c.Modifiers[SyntaxLanguage.VB]); } } [Trait("Related", "Generic")] [Trait("Related", "Multilanguage")] [Fact] public void TestGenereateMetadataAsyncWithMultilanguage() { string code = @" Namespace Test1 Public Class Foo(Of T) Public Sub Bar(Of K)(i as Integer) End Sub End Class End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code)); var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal("Foo<T>", type.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Foo(Of T)", type.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T>", type.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T)", type.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1", type.Name); var method = output.Items[0].Items[0].Items[0]; Assert.NotNull(method); Assert.Equal("Bar<K>(Int32)", method.DisplayNames[SyntaxLanguage.CSharp]); Assert.Equal("Bar(Of K)(Int32)", method.DisplayNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo<T>.Bar<K>(System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.CSharp]); Assert.Equal("Test1.Foo(Of T).Bar(Of K)(System.Int32)", method.DisplayQualifiedNames[SyntaxLanguage.VB]); Assert.Equal("Test1.Foo`1.Bar``1(System.Int32)", method.Name); Assert.Equal(1, output.Items.Count); var parameter = method.Syntax.Parameters[0]; Assert.Equal("i", parameter.Name); Assert.Equal("System.Int32", parameter.Type); var returnValue = method.Syntax.Return; Assert.Null(returnValue); } [Trait("Related", "Attribute")] [Fact] public void TestGenereateMetadataWithAttribute() { string code = @" Imports System Imports System.ComponentModel Namespace Test1 <Serializable> <AttributeUsage(AttributeTargets.All, Inherited := true, AllowMultiple := true)> <TypeConverter(GetType(TestAttribute))> <Test(""test"")> <Test(New Integer(){1,2,3})> <Test(New Object(){Nothing, ""abc"", ""d""c, 1.1f, 1.2, CType(2, SByte), CType(3, Byte), 4s, 5us, 6, 8L, 9UL, New Integer(){ 10, 11, 12 }})> <Test(New Type(){GetType(Func(Of )), GetType(Func(Of ,)), GetType(Func(Of String, String))})> Public Class TestAttribute Inherits Attribute <Test(1)> <Test(2)> Public Sub New(o As Object) End Sub End Class End Namespace "; MetadataItem output = GenerateYamlMetadata(CreateCompilationFromVBCode(code, MetadataReference.CreateFromFile(typeof(System.ComponentModel.TypeConverterAttribute).Assembly.Location))); Assert.Equal(1, output.Items.Count); var type = output.Items[0].Items[0]; Assert.NotNull(type); Assert.Equal(@"<Serializable> <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Module Or AttributeTargets.Class Or AttributeTargets.Struct Or AttributeTargets.Enum Or AttributeTargets.Constructor Or AttributeTargets.Method Or AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Event Or AttributeTargets.Interface Or AttributeTargets.Parameter Or AttributeTargets.Delegate Or AttributeTargets.ReturnValue Or AttributeTargets.GenericParameter Or AttributeTargets.All, Inherited:=True, AllowMultiple:=True)> <TypeConverter(GetType(TestAttribute))> <Test(""test"")> <Test(New Integer() {1, 2, 3})> <Test(New Object() {Nothing, ""abc"", ""d""c, 1.1F, 1.2, CType(2, SByte), CType(3, Byte), CType(4, Short), CType(5, UShort), 6, 8L, 9UL, New Integer() {10, 11, 12}})> <Test(New Type() {GetType(Func(Of )), GetType(Func(Of , )), GetType(Func(Of String, String))})> Public Class TestAttribute Inherits Attribute Implements _Attribute", type.Syntax.Content[SyntaxLanguage.VB]); var ctor = type.Items[0]; Assert.NotNull(type); Assert.Equal(@"<Test(1)> <Test(2)> Public Sub New(o As Object)", ctor.Syntax.Content[SyntaxLanguage.VB]); } private static Compilation CreateCompilationFromVBCode(string code, params MetadataReference[] references) { return CreateCompilationFromVBCode(code, "test.dll", references); } private static Compilation CreateCompilationFromVBCode(string code, string assemblyName, params MetadataReference[] references) { var tree = SyntaxFactory.ParseSyntaxTree(code); var defaultReferences = new List<MetadataReference> { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) }; if (references != null) { defaultReferences.AddRange(references); } var compilation = VisualBasicCompilation.Create( assemblyName, options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree }, references: defaultReferences); return compilation; } private static Assembly CreateAssemblyFromVBCode(string code, string assemblyName) { // MemoryStream fails when MetadataReference.CreateFromAssembly with error: Empty path name is not legal var compilation = CreateCompilationFromVBCode(code); EmitResult result; using (FileStream stream = new FileStream(assemblyName, FileMode.Create)) { result = compilation.Emit(stream); } Assert.True(result.Success, string.Join(",", result.Diagnostics.Select(s => s.GetMessage()))); return Assembly.LoadFile(Path.GetFullPath(assemblyName)); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Reflection.Emit { using System.Text; using System; using CultureInfo = System.Globalization.CultureInfo; using System.Diagnostics.SymbolStore; using System.Reflection; using System.Security; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [HostProtection(MayLeakOnAbort = true)] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class MethodBuilder : MethodInfo, _MethodBuilder { #region Private Data Members // Identity internal String m_strName; // The name of the method private MethodToken m_tkMethod; // The token of this method private ModuleBuilder m_module; internal TypeBuilder m_containingType; // IL private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. internal LocalSymInfo m_localSymInfo; // keep track debugging local information internal ILGenerator m_ilGenerator; // Null if not used. private byte[] m_ubBody; // The IL for the method private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; private int m_maxStack = DefaultMaxStack; // Flags internal bool m_bIsBaked; private bool m_bIsGlobalMethod; private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not. // Attributes private MethodAttributes m_iAttributes; private CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; // Parameters private SignatureHelper m_signature; internal Type[] m_parameterTypes; private ParameterBuilder m_retParam; private Type m_returnType; private Type[] m_returnTypeRequiredCustomModifiers; private Type[] m_returnTypeOptionalCustomModifiers; private Type[][] m_parameterTypeRequiredCustomModifiers; private Type[][] m_parameterTypeOptionalCustomModifiers; // Generics private GenericTypeParameterBuilder[] m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { Init(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, mod, type, bIsGlobalMethod); } internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { Init(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, mod, type, bIsGlobalMethod); } private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); if (name[0] == '\0') throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "name"); if (mod == null) throw new ArgumentNullException("mod"); Contract.EndContractBlock(); if (parameterTypes != null) { foreach(Type t in parameterTypes) { if (t == null) throw new ArgumentNullException("parameterTypes"); } } m_strName = name; m_module = mod; m_containingType = type; // //if (returnType == null) //{ // m_returnType = typeof(void); //} //else { m_returnType = returnType; } if ((attributes & MethodAttributes.Static) == 0) { // turn on the has this calling convention callingConvention = callingConvention | CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0) { // A method can't be both static and virtual throw new ArgumentException(Environment.GetResourceString("Arg_NoStaticVirtual")); } if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName) { if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface) { // methods on interface have to be abstract + virtual except special name methods such as type initializer if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) != (MethodAttributes.Abstract | MethodAttributes.Virtual) && (attributes & MethodAttributes.Static) == 0) throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod")); } } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention, // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); m_iAttributes = attributes; m_bIsGlobalMethod = bIsGlobalMethod; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; // Default is managed IL. Manged IL has bit flag 0x0020 set off m_dwMethodImplFlags = MethodImplAttributes.IL; } #endregion #region Internal Members internal void CheckContext(params Type[][] typess) { m_module.CheckContext(typess); } internal void CheckContext(params Type[] types) { m_module.CheckContext(types); } [System.Security.SecurityCritical] // auto-generated internal void CreateMethodBodyHelper(ILGenerator il) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. if (il == null) { throw new ArgumentNullException("il"); } Contract.EndContractBlock(); __ExceptionInfo[] excp; int counter=0; int[] filterAddrs; int[] catchAddrs; int[] catchEndAddrs; Type[] catchClass; int[] type; int numCatch; int start, end; ModuleBuilder dynMod = (ModuleBuilder) m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody")); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { // you don't need to call DefineBody when you get your ILGenerator // through MethodBuilder::GetILGenerator. // throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage")); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { // There are still unclosed local scope throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope")); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); //Okay, now the fun part. Calculate all of the exceptions. excp = il.GetExceptions(); int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { m_exceptions = new ExceptionHandler[numExceptions]; for (int i = 0; i < excp.Length; i++) { filterAddrs = excp[i].GetFilterAddresses(); catchAddrs = excp[i].GetCatchAddresses(); catchEndAddrs = excp[i].GetCatchEndAddresses(); catchClass = excp[i].GetCatchClass(); numCatch = excp[i].GetNumberOfCatches(); start = excp[i].GetStartAddress(); end = excp[i].GetEndAddress(); type = excp[i].GetExceptionTypes(); for (int j = 0; j < numCatch; j++) { int tkExceptionClass = 0; if (catchClass[j] != null) { tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token; } switch (type[j]) { case __ExceptionInfo.None: case __ExceptionInfo.Fault: case __ExceptionInfo.Filter: m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; case __ExceptionInfo.Finally: m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; } } } } m_bIsBaked=true; if (dynMod.GetSymWriter() != null) { // set the debugging information such as scope and line number // if it is in a debug module // SymbolToken tk = new SymbolToken(MetadataTokenInternal); ISymbolWriter symWriter = dynMod.GetSymWriter(); // call OpenMethod to make this method the current method symWriter.OpenMethod(tk); // call OpenScope because OpenMethod no longer implicitly creating // the top-levelsmethod scope // symWriter.OpenScope(0); if (m_symCustomAttrs != null) { foreach(SymCustomAttr symCustomAttr in m_symCustomAttrs) dynMod.GetSymWriter().SetSymAttribute( new SymbolToken (MetadataTokenInternal), symCustomAttr.m_name, symCustomAttr.m_data); } if (m_localSymInfo != null) m_localSymInfo.EmitLocalSymInfo(symWriter); il.m_ScopeTree.EmitScopeTree(symWriter); il.m_LineNumberInfo.EmitLineNumberInfo(symWriter); symWriter.CloseScope(il.ILOffset); symWriter.CloseMethod(); } } // This is only called from TypeBuilder.CreateType after the method has been created internal void ReleaseBakedStructures() { if (!m_bIsBaked) { // We don't need to do anything here if we didn't baked the method body return; } m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } internal override Type[] GetParameterTypes() { if (m_parameterTypes == null) m_parameterTypes = EmptyArray<Type>.Value; return m_parameterTypes; } internal static Type GetMethodBaseReturnType(MethodBase method) { MethodInfo mi = null; ConstructorInfo ci = null; if ( (mi = method as MethodInfo) != null ) { return mi.ReturnType; } else if ( (ci = method as ConstructorInfo) != null) { return ci.GetReturnType(); } else { Contract.Assert(false, "We should never get here!"); return null; } } internal void SetToken(MethodToken token) { m_tkMethod = token; } internal byte[] GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } internal int[] GetTokenFixups() { return m_mdMethodFixups; } [System.Security.SecurityCritical] // auto-generated internal SignatureHelper GetMethodSignature() { if (m_parameterTypes == null) m_parameterTypes = EmptyArray<Type>.Value; m_signature = SignatureHelper.GetMethodSigHelper (m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0, m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } // Returns a buffer whose initial signatureLength bytes contain encoded local signature. internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null) { if (m_ilGenerator.m_localCount != 0) { // If user is using ILGenerator::DeclareLocal, then get local signaturefrom there. return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } else { // this is the case when client provide an array of IL byte stream rather than going through ILGenerator. return m_maxStack; } } internal ExceptionHandler[] GetExceptionHandlers() { return m_exceptions; } internal int ExceptionHandlerCount { get { return m_exceptions != null ? m_exceptions.Length : 0; } } internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num=0; if (excp==null) { return 0; } for (int i=0; i<excp.Length; i++) { num+=excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { return (m_containingType != null && m_containingType.IsCreated()); } internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } #endregion #region Object Overrides [System.Security.SecuritySafeCritical] // auto-generated public override bool Equals(Object obj) { if (!(obj is MethodBuilder)) { return false; } if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) { return false; } if (m_iAttributes!=(((MethodBuilder)obj).m_iAttributes)) { return false; } SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature(); if (thatSig.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return this.m_strName.GetHashCode(); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { StringBuilder sb = new StringBuilder(1000); sb.Append("Name: " + m_strName + " " + Environment.NewLine); sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine); sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine); sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #region MemberInfo Overrides public override String Name { get { return m_strName; } } internal int MetadataTokenInternal { get { return GetToken().Token; } } public override Module Module { get { return m_containingType.Module; } } public override Type DeclaringType { get { if (m_containingType.m_isHiddenGlobalType == true) return null; return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return null; } } public override Type ReflectedType { get { return DeclaringType; } } #endregion #region MethodBase Overrides public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodAttributes Attributes { get { return m_iAttributes; } } public override CallingConventions CallingConvention { get {return m_callingConvention;} } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } public override bool IsSecurityCritical { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } public override bool IsSecuritySafeCritical { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } public override bool IsSecurityTransparent { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } } #endregion #region MethodInfo Overrides public override MethodInfo GetBaseDefinition() { return this; } public override Type ReturnType { get { return m_returnType; } } [Pure] public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_TypeNotCreated")); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.GetParameters(); } public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeNotCreated")); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.ReturnParameter; } } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } #endregion #region Generic Members public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } } public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; } public override bool IsGenericMethod { get { return m_inst != null; } } public override Type[] GetGenericArguments() { return m_inst; } public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names) { if (names == null) throw new ArgumentNullException("names"); if (names.Length == 0) throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), "names"); Contract.EndContractBlock(); if (m_inst != null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GenericParametersAlreadySet")); for (int i = 0; i < names.Length; i ++) if (names[i] == null) throw new ArgumentNullException("names"); if (m_tkMethod.Token != 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked")); m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int i = 0; i < names.Length; i ++) m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this)); return m_inst; } internal void ThrowIfGeneric () { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException (); } #endregion #region Public Members [System.Security.SecuritySafeCritical] // auto-generated public MethodToken GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 // we only "tokenize" a method when requested. But the order in which the methods are tokenized // didn't change: the same order the MethodBuilders are constructed. The recursion introduced // will overflow the stack when there are many methods on the same type (10000 in my experiment). // The change also introduced race conditions. Before the code change GetToken is called from // the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it // could be called more than once on the the same method introducing duplicate (invalid) tokens. // I don't fully understand this change. So I will keep the logic and only fix the recursion and // the race condition. if (m_tkMethod.Token != 0) { return m_tkMethod; } MethodBuilder currentMethod = null; MethodToken currentToken = new MethodToken(0); int i; // We need to lock here to prevent a method from being "tokenized" twice. // We don't need to synchronize this with Type.DefineMethod because it only appends newly // constructed MethodBuilders to the end of m_listMethods lock (m_containingType.m_listMethods) { if (m_tkMethod.Token != 0) { return m_tkMethod; } // If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller // than the index of the current method. for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i) { currentMethod = m_containingType.m_listMethods[i]; currentToken = currentMethod.GetTokenNoLock(); if (currentMethod == this) break; } m_containingType.m_lastTokenizedMethod = i; } Contract.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); Contract.Assert(currentToken.Token != 0, "The token should not be 0"); return currentToken; } [System.Security.SecurityCritical] // auto-generated private MethodToken GetTokenNoLock() { Contract.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); int sigLength; byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength); int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes); m_tkMethod = new MethodToken(token); if (m_inst != null) foreach (GenericTypeParameterBuilder tb in m_inst) if (!tb.m_type.IsCreated()) tb.m_type.CreateType(); TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags); return m_tkMethod; } public void SetParameters (params Type[] parameterTypes) { CheckContext(parameterTypes); SetSignature (null, null, null, parameterTypes, null, null); } public void SetReturnType (Type returnType) { CheckContext(returnType); SetSignature (returnType, null, null, null, null, null); } public void SetSignature( Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. if (m_tkMethod.Token != 0) return; CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); CheckContext(parameterTypeRequiredCustomModifiers); CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy (parameterTypes, m_parameterTypes, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } [System.Security.SecuritySafeCritical] // auto-generated public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence")); Contract.EndContractBlock(); ThrowIfGeneric(); m_containingType.ThrowIfCreated (); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence")); attributes = attributes & ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } [System.Security.SecuritySafeCritical] // auto-generated [Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")] public void SetMarshal(UnmanagedMarshal unmanagedMarshal) { ThrowIfGeneric (); // set Marshal info for the return type m_containingType.ThrowIfCreated(); if (m_retParam == null) { m_retParam = new ParameterBuilder(this, 0, 0, null); } m_retParam.SetMarshal(unmanagedMarshal); } private List<SymCustomAttr> m_symCustomAttrs; private struct SymCustomAttr { public SymCustomAttr(String name, byte[] data) { m_name = name; m_data = data; } public String m_name; public byte[] m_data; } public void SetSymCustomAttribute(String name, byte[] data) { // Note that this API is rarely used. Support for custom attributes in PDB files was added in // Whidbey and as of 8/2007 the only known user is the C# compiler. There seems to be little // value to this for Reflection.Emit users since they can always use metadata custom attributes. // Some versions of the symbol writer used in the CLR will ignore these entirely. This API has // been removed from the Silverlight API surface area, but we should also consider removing it // from future desktop product versions as well. ThrowIfGeneric (); // This is different from CustomAttribute. This is stored into the SymWriter. m_containingType.ThrowIfCreated(); ModuleBuilder dynMod = (ModuleBuilder) m_module; if ( dynMod.GetSymWriter() == null) { // Cannot SetSymCustomAttribute when it is not a debug module throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule")); } if (m_symCustomAttrs == null) m_symCustomAttrs = new List<SymCustomAttr>(); m_symCustomAttrs.Add(new SymCustomAttr(name, data)); } #if FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset) { if (pset == null) throw new ArgumentNullException("pset"); Contract.EndContractBlock(); ThrowIfGeneric (); #pragma warning disable 618 if (!Enum.IsDefined(typeof(SecurityAction), action) || action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) { throw new ArgumentOutOfRangeException("action"); } #pragma warning restore 618 // cannot declarative security after type is created m_containingType.ThrowIfCreated(); // Translate permission set into serialized format (uses standard binary serialization format). byte[] blob = null; int length = 0; if (!pset.IsEmpty()) { blob = pset.EncodeXml(); length = blob.Length; } // Write the blob into the metadata. TypeBuilder.AddDeclarativeSecurity(m_module.GetNativeHandle(), MetadataTokenInternal, action, blob, length); } #endif // FEATURE_CAS_POLICY #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups) { if (il == null) { throw new ArgumentNullException("il", Environment.GetResourceString("ArgumentNull_Array")); } if (maxStack < 0) { throw new ArgumentOutOfRangeException("maxStack", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (m_bIsBaked) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked")); } m_containingType.ThrowIfCreated(); ThrowIfGeneric(); byte[] newLocalSignature = null; ExceptionHandler[] newHandlers = null; int[] newTokenFixups = null; byte[] newIL = (byte[])il.Clone(); if (localSignature != null) { newLocalSignature = (byte[])localSignature.Clone(); } if (exceptionHandlers != null) { newHandlers = ToArray(exceptionHandlers); CheckExceptionHandlerRanges(newHandlers, newIL.Length); // Note: Fixup entries for type tokens stored in ExceptionHandlers are added by the method body emitter. } if (tokenFixups != null) { newTokenFixups = ToArray(tokenFixups); int maxTokenOffset = newIL.Length - 4; for (int i = 0; i < newTokenFixups.Length; i++) { // Check that fixups are within the range of this method's IL, otherwise some random memory might get "fixed up". if (newTokenFixups[i] < 0 || newTokenFixups[i] > maxTokenOffset) { throw new ArgumentOutOfRangeException("tokenFixups[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxTokenOffset)); } } } m_ubBody = newIL; m_localSignature = newLocalSignature; m_exceptions = newHandlers; m_mdMethodFixups = newTokenFixups; m_maxStack = maxStack; // discard IL generator, all information stored in it is now irrelevant m_ilGenerator = null; m_bIsBaked = true; } private static T[] ToArray<T>(IEnumerable<T> sequence) { T[] array = sequence as T[]; if (array != null) { return (T[])array.Clone(); } return new List<T>(sequence).ToArray(); } private static void CheckExceptionHandlerRanges(ExceptionHandler[] exceptionHandlers, int maxOffset) { // Basic checks that the handler ranges are within the method body (ranges are end-exclusive). // Doesn't verify that the ranges are otherwise correct - it is very well possible to emit invalid IL. for (int i = 0; i < exceptionHandlers.Length; i++) { var handler = exceptionHandlers[i]; if (handler.m_filterOffset > maxOffset || handler.m_tryEndOffset > maxOffset || handler.m_handlerEndOffset > maxOffset) { throw new ArgumentOutOfRangeException("exceptionHandlers[" + i + "]", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, maxOffset)); } // Type token might be 0 if the ExceptionHandler was created via a default constructor. // Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it, // and we can't check for valid tokens until the module is baked. if (handler.Kind == ExceptionHandlingClauseOptions.Clause && handler.ExceptionTypeToken == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", handler.ExceptionTypeToken), "exceptionHandlers[" + i + "]"); } } } /// <summary> /// Obsolete. /// </summary> #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public void CreateMethodBody(byte[] il, int count) { ThrowIfGeneric(); // Note that when user calls this function, there are a few information that client is // not able to supply: local signature, exception handlers, max stack size, a list of Token fixup, a list of RVA fixup if (m_bIsBaked) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked")); } m_containingType.ThrowIfCreated(); if (il != null && (count < 0 || count > il.Length)) { throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (il == null) { m_ubBody = null; return; } m_ubBody = new byte[count]; Array.Copy(il,m_ubBody,count); m_localSignature = null; m_exceptions = null; m_mdMethodFixups = null; m_maxStack = DefaultMaxStack; m_bIsBaked = true; } [System.Security.SecuritySafeCritical] // auto-generated public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric (); m_containingType.ThrowIfCreated (); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes); } public ILGenerator GetILGenerator() { Contract.Ensures(Contract.Result<ILGenerator>() != null); ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this); return m_ilGenerator; } public ILGenerator GetILGenerator(int size) { Contract.Ensures(Contract.Result<ILGenerator>() != null); ThrowIfGeneric (); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this, size); return m_ilGenerator; } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { // cannot attach method body if methodimpl is marked not marked as managed IL // throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody")); } } public bool InitLocals { // Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false. get { ThrowIfGeneric (); return m_fInitLocals; } set { ThrowIfGeneric (); m_fInitLocals = value; } } public Module GetModule() { return GetModuleBuilder(); } public String Signature { [System.Security.SecuritySafeCritical] // auto-generated get { return GetMethodSignature().ToString(); } } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #else [System.Security.SecuritySafeCritical] #endif [System.Runtime.InteropServices.ComVisible(true)] public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) throw new ArgumentNullException("con"); if (binaryAttribute == null) throw new ArgumentNullException("binaryAttribute"); Contract.EndContractBlock(); ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal, ((ModuleBuilder)m_module).GetConstructorToken(con).Token, binaryAttribute, false, false); if (IsKnownCA(con)) ParseCA(con, binaryAttribute); } [System.Security.SecuritySafeCritical] // auto-generated public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException("customBuilder"); Contract.EndContractBlock(); ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal); if (IsKnownCA(customBuilder.m_con)) ParseCA(customBuilder.m_con, customBuilder.m_blob); } // this method should return true for any and every ca that requires more work // than just setting the ca private bool IsKnownCA(ConstructorInfo con) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true; else if (caType == typeof(DllImportAttribute)) return true; else return false; } private void ParseCA(ConstructorInfo con, byte[] blob) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag // that must be in the MethodCodeType field // for now we simply set a flag that relaxes the check when saving and // allows this method to have no body when any kind of MethodImplAttribute is present m_canBeRuntimeImpl = true; } else if (caType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } internal bool m_canBeRuntimeImpl = false; internal bool m_isDllImport = false; #endregion #if !FEATURE_CORECLR void _MethodBuilder.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _MethodBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } internal class LocalSymInfo { // This class tracks the local variable's debugging information // and namespace information with a given active lexical scope. #region Internal Data Members internal String[] m_strName; internal byte[][] m_ubSignature; internal int[] m_iLocalSlot; internal int[] m_iStartOffset; internal int[] m_iEndOffset; internal int m_iLocalSymCount; // how many entries in the arrays are occupied internal String[] m_namespace; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion #region Constructor internal LocalSymInfo() { // initialize data variables m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } #endregion #region Private Members private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new String[InitialSize]; } else if (m_iNameSpaceCount == m_namespace.Length) { String [] strTemp = new String [checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, strTemp, m_iNameSpaceCount); m_namespace = strTemp; } } private void EnsureCapacity() { if (m_iLocalSymCount == 0) { // First time. Allocate the arrays. m_strName = new String[InitialSize]; m_ubSignature = new byte[InitialSize][]; m_iLocalSlot = new int[InitialSize]; m_iStartOffset = new int[InitialSize]; m_iEndOffset = new int[InitialSize]; } else if (m_iLocalSymCount == m_strName.Length) { // the arrays are full. Enlarge the arrays // why aren't we just using lists here? int newSize = checked(m_iLocalSymCount * 2); int[] temp = new int [newSize]; Array.Copy(m_iLocalSlot, temp, m_iLocalSymCount); m_iLocalSlot = temp; temp = new int [newSize]; Array.Copy(m_iStartOffset, temp, m_iLocalSymCount); m_iStartOffset = temp; temp = new int [newSize]; Array.Copy(m_iEndOffset, temp, m_iLocalSymCount); m_iEndOffset = temp; String [] strTemp = new String [newSize]; Array.Copy(m_strName, strTemp, m_iLocalSymCount); m_strName = strTemp; byte[][] ubTemp = new byte[newSize][]; Array.Copy(m_ubSignature, ubTemp, m_iLocalSymCount); m_ubSignature = ubTemp; } } #endregion #region Internal Members internal void AddLocalSymInfo(String strName,byte[] signature,int slot,int startOffset,int endOffset) { // make sure that arrays are large enough to hold addition info EnsureCapacity(); m_iStartOffset[m_iLocalSymCount] = startOffset; m_iEndOffset[m_iLocalSymCount] = endOffset; m_iLocalSlot[m_iLocalSymCount] = slot; m_strName[m_iLocalSymCount] = strName; m_ubSignature[m_iLocalSymCount] = signature; checked {m_iLocalSymCount++; } } internal void AddUsingNamespace(String strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter) { int i; for (i = 0; i < m_iLocalSymCount; i ++) { symWriter.DefineLocalVariable( m_strName[i], FieldAttributes.PrivateScope, m_ubSignature[i], SymAddressKind.ILOffset, m_iLocalSlot[i], 0, // addr2 is not used yet 0, // addr3 is not used m_iStartOffset[i], m_iEndOffset[i]); } for (i = 0; i < m_iNameSpaceCount; i ++) { symWriter.UsingNamespace(m_namespace[i]); } } #endregion } /// <summary> /// Describes exception handler in a method body. /// </summary> [StructLayout(LayoutKind.Sequential)] [ComVisible(false)] public struct ExceptionHandler : IEquatable<ExceptionHandler> { // Keep in [....] with unmanged structure. internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; public int ExceptionTypeToken { get { return m_exceptionClass; } } public int TryOffset { get { return m_tryStartOffset; } } public int TryLength { get { return m_tryEndOffset - m_tryStartOffset; } } public int FilterOffset { get { return m_filterOffset; } } public int HandlerOffset { get { return m_handlerStartOffset; } } public int HandlerLength { get { return m_handlerEndOffset - m_handlerStartOffset; } } public ExceptionHandlingClauseOptions Kind { get { return m_kind; } } #region Constructors /// <summary> /// Creates a description of an exception handler. /// </summary> /// <param name="tryOffset">The offset of the first instruction protected by this handler.</param> /// <param name="tryLength">The number of bytes protected by this handler.</param> /// <param name="filterOffset">The filter code begins at the specified offset and ends at the first instruction of the handler block. Specify 0 if not applicable (this is not a filter handler).</param> /// <param name="handlerOffset">The offset of the first instruction of this handler.</param> /// <param name="handlerLength">The number of bytes of the handler.</param> /// <param name="kind">The kind of handler, the handler might be a catch handler, filter handler, fault handler, or finally handler.</param> /// <param name="exceptionTypeToken">The token of the exception type handled by this handler. Specify 0 if not applicable (this is finally handler).</param> /// <exception cref="ArgumentOutOfRangeException"> /// Some of the instruction offset is negative, /// the end offset of specified range is less than its start offset, /// or <paramref name="kind"/> has an invalid value. /// </exception> public ExceptionHandler(int tryOffset, int tryLength, int filterOffset, int handlerOffset, int handlerLength, ExceptionHandlingClauseOptions kind, int exceptionTypeToken) { if (tryOffset < 0) { throw new ArgumentOutOfRangeException("tryOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (tryLength < 0) { throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (filterOffset < 0) { throw new ArgumentOutOfRangeException("filterOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (handlerOffset < 0) { throw new ArgumentOutOfRangeException("handlerOffset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (handlerLength < 0) { throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if ((long)tryOffset + tryLength > Int32.MaxValue) { throw new ArgumentOutOfRangeException("tryLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - tryOffset)); } if ((long)handlerOffset + handlerLength > Int32.MaxValue) { throw new ArgumentOutOfRangeException("handlerLength", Environment.GetResourceString("ArgumentOutOfRange_Range", 0, Int32.MaxValue - handlerOffset)); } // Other tokens migth also be invalid. We only check nil tokens as the implementation (SectEH_Emit in corhlpr.cpp) requires it, // and we can't check for valid tokens until the module is baked. if (kind == ExceptionHandlingClauseOptions.Clause && (exceptionTypeToken & 0x00FFFFFF) == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeToken", exceptionTypeToken), "exceptionTypeToken"); } Contract.EndContractBlock(); if (!IsValidKind(kind)) { throw new ArgumentOutOfRangeException("kind", Environment.GetResourceString("ArgumentOutOfRange_Enum")); } m_tryStartOffset = tryOffset; m_tryEndOffset = tryOffset + tryLength; m_filterOffset = filterOffset; m_handlerStartOffset = handlerOffset; m_handlerEndOffset = handlerOffset + handlerLength; m_kind = kind; m_exceptionClass = exceptionTypeToken; } internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { Contract.Assert(tryStartOffset >= 0); Contract.Assert(tryEndOffset >= 0); Contract.Assert(filterOffset >= 0); Contract.Assert(handlerStartOffset >= 0); Contract.Assert(handlerEndOffset >= 0); Contract.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); Contract.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } private static bool IsValidKind(ExceptionHandlingClauseOptions kind) { switch (kind) { case ExceptionHandlingClauseOptions.Clause: case ExceptionHandlingClauseOptions.Filter: case ExceptionHandlingClauseOptions.Finally: case ExceptionHandlingClauseOptions.Fault: return true; default: return false; } } #endregion #region Equality public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(Object obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } public bool Equals(ExceptionHandler other) { return other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset && other.m_kind == m_kind; } public static bool operator ==(ExceptionHandler left, ExceptionHandler right) { return left.Equals(right); } public static bool operator !=(ExceptionHandler left, ExceptionHandler right) { return !left.Equals(right); } #endregion } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] [Migration("20160110190842_UpdatingModelForUserEmailChange")] partial class UpdatingModelForUserEmailChange { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.Property<int>("ActivityId"); b.Property<int>("SkillId"); b.HasKey("ActivityId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTime"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<int?>("OrganizationId"); b.Property<DateTimeOffset?>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", 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<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<int?>("OrganizationId"); b.Property<string>("PasswordHash"); b.Property<string>("PendingNewEmail"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<string>("TimeZoneId") .IsRequired(); 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:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<int>("ManagingOrganizationId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("OrganizationId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ClosestLocation", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<double>("Distance"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCodePostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.Property<int>("OrganizationId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("OrganizationId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b => { b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.HasKey("Latitude", "Longitude"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); 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("AllReady.Models.Activity", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("ManagingOrganizationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.HasOne("AllReady.Models.PostalCodeGeo") .WithMany() .HasForeignKey("PostalCodePostalCode"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .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("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; namespace System.Linq.Expressions { /// <summary> /// Represents indexing a property or array. /// </summary> [DebuggerTypeProxy(typeof(Expression.IndexExpressionProxy))] public sealed class IndexExpression : Expression, IArgumentProvider { private readonly Expression _instance; private readonly PropertyInfo _indexer; private IList<Expression> _arguments; internal IndexExpression( Expression instance, PropertyInfo indexer, IList<Expression> arguments) { if (indexer == null) { Debug.Assert(instance != null && instance.Type.IsArray); Debug.Assert(instance.Type.GetArrayRank() == arguments.Count); } _instance = instance; _indexer = indexer; _arguments = arguments; } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Index; } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { if (_indexer != null) { return _indexer.PropertyType; } return _instance.Type.GetElementType(); } } /// <summary> /// An object to index. /// </summary> public Expression Object { get { return _instance; } } /// <summary> /// Gets the <see cref="PropertyInfo"/> for the property if the expression represents an indexed property, returns null otherwise. /// </summary> public PropertyInfo Indexer { get { return _indexer; } } /// <summary> /// Gets the arguments to be used to index the property or array. /// </summary> public ReadOnlyCollection<Expression> Arguments { get { return ReturnReadOnly(ref _arguments); } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="object">The <see cref="Object" /> property of the result.</param> /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public IndexExpression Update(Expression @object, IEnumerable<Expression> arguments) { if (@object == Object && arguments == Arguments) { return this; } return Expression.MakeIndex(@object, Indexer, arguments); } public Expression GetArgument(int index) { return _arguments[index]; } public int ArgumentCount { get { return _arguments.Count; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitIndex(this); } internal Expression Rewrite(Expression instance, Expression[] arguments) { Debug.Assert(instance != null); Debug.Assert(arguments == null || arguments.Length == _arguments.Count); return Expression.MakeIndex(instance, _indexer, arguments ?? _arguments); } } public partial class Expression { /// <summary> /// Creates an <see cref="IndexExpression"/> that represents accessing an indexed property in an object. /// </summary> /// <param name="instance">The object to which the property belongs. Should be null if the property is static(shared).</param> /// <param name="indexer">An <see cref="Expression"/> representing the property to index.</param> /// <param name="arguments">An IEnumerable{Expression} containing the arguments to be used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression MakeIndex(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) { if (indexer != null) { return Property(instance, indexer, arguments); } else { return ArrayAccess(instance, arguments); } } #region ArrayAccess /// <summary> /// Creates an <see cref="IndexExpression"></see> to access an array. /// </summary> /// <param name="array">An expression representing the array to index.</param> /// <param name="indexes">An array containing expressions used to index the array.</param> /// <remarks>The expression representing the array can be obtained by using the MakeMemberAccess method, /// or through NewArrayBounds or NewArrayInit.</remarks> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression ArrayAccess(Expression array, params Expression[] indexes) { return ArrayAccess(array, (IEnumerable<Expression>)indexes); } /// <summary> /// Creates an <see cref="IndexExpression"></see> to access an array. /// </summary> /// <param name="array">An expression representing the array to index.</param> /// <param name="indexes">An <see cref="IEnumerable{Expression}"/> containing expressions used to index the array.</param> /// <remarks>The expression representing the array can be obtained by using the MakeMemberAccess method, /// or through NewArrayBounds or NewArrayInit.</remarks> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression ArrayAccess(Expression array, IEnumerable<Expression> indexes) { RequiresCanRead(array, nameof(array)); Type arrayType = array.Type; if (!arrayType.IsArray) { throw Error.ArgumentMustBeArray(nameof(array)); } var indexList = indexes.ToReadOnly(); if (arrayType.GetArrayRank() != indexList.Count) { throw Error.IncorrectNumberOfIndexes(); } foreach (Expression e in indexList) { RequiresCanRead(e, nameof(indexes)); if (e.Type != typeof(int)) { throw Error.ArgumentMustBeArrayIndexType(nameof(indexes)); } } return new IndexExpression(array, null, indexList); } #endregion #region Property /// <summary> /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property. /// </summary> /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param> /// <param name="propertyName">The name of the indexer.</param> /// <param name="arguments">An array of <see cref="Expression"/> objects that are used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression Property(Expression instance, string propertyName, params Expression[] arguments) { RequiresCanRead(instance, nameof(instance)); ContractUtils.RequiresNotNull(propertyName, nameof(propertyName)); PropertyInfo pi = FindInstanceProperty(instance.Type, propertyName, arguments); return Property(instance, pi, arguments); } #region methods for finding a PropertyInfo by its name /// <summary> /// The method finds the instance property with the specified name in a type. The property's type signature needs to be compatible with /// the arguments if it is a indexer. If the arguments is null or empty, we get a normal property. /// </summary> private static PropertyInfo FindInstanceProperty(Type type, string propertyName, Expression[] arguments) { // bind to public names first BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; PropertyInfo pi = FindProperty(type, propertyName, arguments, flags); if (pi == null) { flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy; pi = FindProperty(type, propertyName, arguments, flags); } if (pi == null) { if (arguments == null || arguments.Length == 0) { throw Error.InstancePropertyWithoutParameterNotDefinedForType(propertyName, type); } else { throw Error.InstancePropertyWithSpecifiedParametersNotDefinedForType(propertyName, GetArgTypesString(arguments), type); } } return pi; } private static string GetArgTypesString(Expression[] arguments) { StringBuilder argTypesStr = new StringBuilder(); argTypesStr.Append('('); for (int i = 0; i < arguments.Length; i++) { if (i != 0) { argTypesStr.Append(", "); } argTypesStr.Append(arguments[i].Type.Name); } argTypesStr.Append(')'); return argTypesStr.ToString(); } private static PropertyInfo FindProperty(Type type, string propertyName, Expression[] arguments, BindingFlags flags) { var props = type.GetProperties(flags).Where(x => x.Name.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase)); ; PropertyInfo[] members = new List<PropertyInfo>(props).ToArray(); if (members == null || members.Length == 0) return null; PropertyInfo pi; var propertyInfos = members.Map(t => (PropertyInfo)t); int count = FindBestProperty(propertyInfos, arguments, out pi); if (count == 0) return null; if (count > 1) throw Error.PropertyWithMoreThanOneMatch(propertyName, type); return pi; } private static int FindBestProperty(IEnumerable<PropertyInfo> properties, Expression[] args, out PropertyInfo property) { int count = 0; property = null; foreach (PropertyInfo pi in properties) { if (pi != null && IsCompatible(pi, args)) { if (property == null) { property = pi; count = 1; } else { count++; } } } return count; } private static bool IsCompatible(PropertyInfo pi, Expression[] args) { MethodInfo mi; mi = pi.GetGetMethod(true); ParameterInfo[] parms; if (mi != null) { parms = mi.GetParametersCached(); } else { mi = pi.GetSetMethod(true); //The setter has an additional parameter for the value to set, //need to remove the last type to match the arguments. parms = mi.GetParametersCached().RemoveLast(); } if (mi == null) { return false; } if (args == null) { return parms.Length == 0; } if (parms.Length != args.Length) return false; for (int i = 0; i < args.Length; i++) { if (args[i] == null) return false; if (!TypeUtils.AreReferenceAssignable(parms[i].ParameterType, args[i].Type)) { return false; } } return true; } #endregion /// <summary> /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property. /// </summary> /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param> /// <param name="indexer">The <see cref="PropertyInfo"/> that represents the property to index.</param> /// <param name="arguments">An array of <see cref="Expression"/> objects that are used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression Property(Expression instance, PropertyInfo indexer, params Expression[] arguments) { return Property(instance, indexer, (IEnumerable<Expression>)arguments); } /// <summary> /// Creates an <see cref="IndexExpression"/> representing the access to an indexed property. /// </summary> /// <param name="instance">The object to which the property belongs. If the property is static/shared, it must be null.</param> /// <param name="indexer">The <see cref="PropertyInfo"/> that represents the property to index.</param> /// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects that are used to index the property.</param> /// <returns>The created <see cref="IndexExpression"/>.</returns> public static IndexExpression Property(Expression instance, PropertyInfo indexer, IEnumerable<Expression> arguments) { var argList = arguments.ToReadOnly(); ValidateIndexedProperty(instance, indexer, ref argList); return new IndexExpression(instance, indexer, argList); } // CTS places no restrictions on properties (see ECMA-335 8.11.3), // so we validate that the property conforms to CLS rules here. // // Does reflection help us out at all? Expression.Property skips all of // these checks, so either it needs more checks or we need less here. private static void ValidateIndexedProperty(Expression instance, PropertyInfo property, ref ReadOnlyCollection<Expression> argList) { // If both getter and setter specified, all their parameter types // should match, with exception of the last setter parameter which // should match the type returned by the get method. // Accessor parameters cannot be ByRef. ContractUtils.RequiresNotNull(property, nameof(property)); if (property.PropertyType.IsByRef) throw Error.PropertyCannotHaveRefType(nameof(property)); if (property.PropertyType == typeof(void)) throw Error.PropertyTypeCannotBeVoid(nameof(property)); ParameterInfo[] getParameters = null; MethodInfo getter = property.GetGetMethod(true); if (getter != null) { getParameters = getter.GetParametersCached(); ValidateAccessor(instance, getter, getParameters, ref argList, nameof(property)); } MethodInfo setter = property.GetSetMethod(true); if (setter != null) { ParameterInfo[] setParameters = setter.GetParametersCached(); if (setParameters.Length == 0) throw Error.SetterHasNoParams(nameof(property)); // valueType is the type of the value passed to the setter (last parameter) Type valueType = setParameters[setParameters.Length - 1].ParameterType; if (valueType.IsByRef) throw Error.PropertyCannotHaveRefType(nameof(property)); if (setter.ReturnType != typeof(void)) throw Error.SetterMustBeVoid(nameof(property)); if (property.PropertyType != valueType) throw Error.PropertyTypeMustMatchSetter(nameof(property)); if (getter != null) { if (getter.IsStatic ^ setter.IsStatic) throw Error.BothAccessorsMustBeStatic(nameof(property)); if (getParameters.Length != setParameters.Length - 1) throw Error.IndexesOfSetGetMustMatch(nameof(property)); for (int i = 0; i < getParameters.Length; i++) { if (getParameters[i].ParameterType != setParameters[i].ParameterType) throw Error.IndexesOfSetGetMustMatch(nameof(property)); } } else { ValidateAccessor(instance, setter, setParameters.RemoveLast(), ref argList, nameof(property)); } } if (getter == null && setter == null) { throw Error.PropertyDoesNotHaveAccessor(property, nameof(property)); } } private static void ValidateAccessor(Expression instance, MethodInfo method, ParameterInfo[] indexes, ref ReadOnlyCollection<Expression> arguments, string paramName) { ContractUtils.RequiresNotNull(arguments, nameof(arguments)); ValidateMethodInfo(method, nameof(method)); if ((method.CallingConvention & CallingConventions.VarArgs) != 0) throw Error.AccessorsCannotHaveVarArgs(nameof(method)); if (method.IsStatic) { if (instance != null) throw Error.OnlyStaticMethodsHaveNullInstance(); } else { if (instance == null) throw Error.OnlyStaticMethodsHaveNullInstance(); RequiresCanRead(instance, nameof(instance)); ValidateCallInstanceType(instance.Type, method); } ValidateAccessorArgumentTypes(method, indexes, ref arguments, paramName); } private static void ValidateAccessorArgumentTypes(MethodInfo method, ParameterInfo[] indexes, ref ReadOnlyCollection<Expression> arguments, string paramName) { if (indexes.Length > 0) { if (indexes.Length != arguments.Count) { throw Error.IncorrectNumberOfMethodCallArguments(method, paramName); } Expression[] newArgs = null; for (int i = 0, n = indexes.Length; i < n; i++) { Expression arg = arguments[i]; ParameterInfo pi = indexes[i]; RequiresCanRead(arg, nameof(arguments)); Type pType = pi.ParameterType; if (pType.IsByRef) throw Error.AccessorsCannotHaveByRefArgs($"{nameof(indexes)}[{i}]"); TypeUtils.ValidateType(pType, $"{nameof(indexes)}[{i}]"); if (!TypeUtils.AreReferenceAssignable(pType, arg.Type)) { if (!TryQuote(pType, ref arg)) { throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method); } } if (newArgs == null && arg != arguments[i]) { newArgs = new Expression[arguments.Count]; for (int j = 0; j < i; j++) { newArgs[j] = arguments[j]; } } if (newArgs != null) { newArgs[i] = arg; } } if (newArgs != null) { arguments = new TrueReadOnlyCollection<Expression>(newArgs); } } else if (arguments.Count > 0) { throw Error.IncorrectNumberOfMethodCallArguments(method, paramName); } } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace PlayFab { /// <summary> /// Error codes returned by PlayFabAPIs /// </summary> public enum PlayFabErrorCode { Unknown = 1, Success = 0, InvalidParams = 1000, AccountNotFound = 1001, AccountBanned = 1002, InvalidUsernameOrPassword = 1003, InvalidTitleId = 1004, InvalidEmailAddress = 1005, EmailAddressNotAvailable = 1006, InvalidUsername = 1007, InvalidPassword = 1008, UsernameNotAvailable = 1009, InvalidSteamTicket = 1010, AccountAlreadyLinked = 1011, LinkedAccountAlreadyClaimed = 1012, InvalidFacebookToken = 1013, AccountNotLinked = 1014, FailedByPaymentProvider = 1015, CouponCodeNotFound = 1016, InvalidContainerItem = 1017, ContainerNotOwned = 1018, KeyNotOwned = 1019, InvalidItemIdInTable = 1020, InvalidReceipt = 1021, ReceiptAlreadyUsed = 1022, ReceiptCancelled = 1023, GameNotFound = 1024, GameModeNotFound = 1025, InvalidGoogleToken = 1026, UserIsNotPartOfDeveloper = 1027, InvalidTitleForDeveloper = 1028, TitleNameConflicts = 1029, UserisNotValid = 1030, ValueAlreadyExists = 1031, BuildNotFound = 1032, PlayerNotInGame = 1033, InvalidTicket = 1034, InvalidDeveloper = 1035, InvalidOrderInfo = 1036, RegistrationIncomplete = 1037, InvalidPlatform = 1038, UnknownError = 1039, SteamApplicationNotOwned = 1040, WrongSteamAccount = 1041, TitleNotActivated = 1042, RegistrationSessionNotFound = 1043, NoSuchMod = 1044, FileNotFound = 1045, DuplicateEmail = 1046, ItemNotFound = 1047, ItemNotOwned = 1048, ItemNotRecycleable = 1049, ItemNotAffordable = 1050, InvalidVirtualCurrency = 1051, WrongVirtualCurrency = 1052, WrongPrice = 1053, NonPositiveValue = 1054, InvalidRegion = 1055, RegionAtCapacity = 1056, ServerFailedToStart = 1057, NameNotAvailable = 1058, InsufficientFunds = 1059, InvalidDeviceID = 1060, InvalidPushNotificationToken = 1061, NoRemainingUses = 1062, InvalidPaymentProvider = 1063, PurchaseInitializationFailure = 1064, DuplicateUsername = 1065, InvalidBuyerInfo = 1066, NoGameModeParamsSet = 1067, BodyTooLarge = 1068, ReservedWordInBody = 1069, InvalidTypeInBody = 1070, InvalidRequest = 1071, ReservedEventName = 1072, InvalidUserStatistics = 1073, NotAuthenticated = 1074, StreamAlreadyExists = 1075, ErrorCreatingStream = 1076, StreamNotFound = 1077, InvalidAccount = 1078, PurchaseDoesNotExist = 1080, InvalidPurchaseTransactionStatus = 1081, APINotEnabledForGameClientAccess = 1082, NoPushNotificationARNForTitle = 1083, BuildAlreadyExists = 1084, BuildPackageDoesNotExist = 1085, CustomAnalyticsEventsNotEnabledForTitle = 1087, InvalidSharedGroupId = 1088, NotAuthorized = 1089, MissingTitleGoogleProperties = 1090, InvalidItemProperties = 1091, InvalidPSNAuthCode = 1092, InvalidItemId = 1093, PushNotEnabledForAccount = 1094, PushServiceError = 1095, ReceiptDoesNotContainInAppItems = 1096, ReceiptContainsMultipleInAppItems = 1097, InvalidBundleID = 1098, JavascriptException = 1099, InvalidSessionTicket = 1100, UnableToConnectToDatabase = 1101, InternalServerError = 1110, InvalidReportDate = 1111, ReportNotAvailable = 1112, DatabaseThroughputExceeded = 1113, InvalidGameTicket = 1115, ExpiredGameTicket = 1116, GameTicketDoesNotMatchLobby = 1117, LinkedDeviceAlreadyClaimed = 1118, DeviceAlreadyLinked = 1119, DeviceNotLinked = 1120, PartialFailure = 1121, PublisherNotSet = 1122, ServiceUnavailable = 1123, VersionNotFound = 1124, RevisionNotFound = 1125, InvalidPublisherId = 1126, DownstreamServiceUnavailable = 1127, APINotIncludedInTitleUsageTier = 1128, DAULimitExceeded = 1129, APIRequestLimitExceeded = 1130, InvalidAPIEndpoint = 1131, BuildNotAvailable = 1132, ConcurrentEditError = 1133, ContentNotFound = 1134, CharacterNotFound = 1135, CloudScriptNotFound = 1136, ContentQuotaExceeded = 1137, InvalidCharacterStatistics = 1138, PhotonNotEnabledForTitle = 1139, PhotonApplicationNotFound = 1140, PhotonApplicationNotAssociatedWithTitle = 1141, InvalidEmailOrPassword = 1142, FacebookAPIError = 1143, InvalidContentType = 1144, KeyLengthExceeded = 1145, DataLengthExceeded = 1146, TooManyKeys = 1147, FreeTierCannotHaveVirtualCurrency = 1148, MissingAmazonSharedKey = 1149, AmazonValidationError = 1150, InvalidPSNIssuerId = 1151, PSNInaccessible = 1152, ExpiredAuthToken = 1153, FailedToGetEntitlements = 1154, FailedToConsumeEntitlement = 1155, TradeAcceptingUserNotAllowed = 1156, TradeInventoryItemIsAssignedToCharacter = 1157, TradeInventoryItemIsBundle = 1158, TradeStatusNotValidForCancelling = 1159, TradeStatusNotValidForAccepting = 1160, TradeDoesNotExist = 1161, TradeCancelled = 1162, TradeAlreadyFilled = 1163, TradeWaitForStatusTimeout = 1164, TradeInventoryItemExpired = 1165, TradeMissingOfferedAndAcceptedItems = 1166, TradeAcceptedItemIsBundle = 1167, TradeAcceptedItemIsStackable = 1168, TradeInventoryItemInvalidStatus = 1169, TradeAcceptedCatalogItemInvalid = 1170, TradeAllowedUsersInvalid = 1171, TradeInventoryItemDoesNotExist = 1172, TradeInventoryItemIsConsumed = 1173, TradeInventoryItemIsStackable = 1174, TradeAcceptedItemsMismatch = 1175, InvalidKongregateToken = 1176, FeatureNotConfiguredForTitle = 1177, NoMatchingCatalogItemForReceipt = 1178, InvalidCurrencyCode = 1179, NoRealMoneyPriceForCatalogItem = 1180, TradeInventoryItemIsNotTradable = 1181, TradeAcceptedCatalogItemIsNotTradable = 1182, UsersAlreadyFriends = 1183, LinkedIdentifierAlreadyClaimed = 1184, CustomIdNotLinked = 1185, TotalDataSizeExceeded = 1186, DeleteKeyConflict = 1187, InvalidXboxLiveToken = 1188, ExpiredXboxLiveToken = 1189, ResettableStatisticVersionRequired = 1190, NotAuthorizedByTitle = 1191, NoPartnerEnabled = 1192, InvalidPartnerResponse = 1193, APINotEnabledForGameServerAccess = 1194, StatisticNotFound = 1195, StatisticNameConflict = 1196, StatisticVersionClosedForWrites = 1197, StatisticVersionInvalid = 1198, APIClientRequestRateLimitExceeded = 1199, InvalidJSONContent = 1200, InvalidDropTable = 1201, StatisticVersionAlreadyIncrementedForScheduledInterval = 1202, StatisticCountLimitExceeded = 1203, StatisticVersionIncrementRateExceeded = 1204, ContainerKeyInvalid = 1205, CloudScriptExecutionTimeLimitExceeded = 1206, NoWritePermissionsForEvent = 1207, CloudScriptFunctionArgumentSizeExceeded = 1208, CloudScriptAPIRequestCountExceeded = 1209, CloudScriptAPIRequestError = 1210, CloudScriptHTTPRequestError = 1211, InsufficientGuildRole = 1212, GuildNotFound = 1213, OverLimit = 1214, EventNotFound = 1215, InvalidEventField = 1216, InvalidEventName = 1217, CatalogNotConfigured = 1218, OperationNotSupportedForPlatform = 1219, SegmentNotFound = 1220, StoreNotFound = 1221, InvalidStatisticName = 1222, TitleNotQualifiedForLimit = 1223, InvalidServiceLimitLevel = 1224, ServiceLimitLevelInTransition = 1225, CouponAlreadyRedeemed = 1226, GameServerBuildSizeLimitExceeded = 1227, GameServerBuildCountLimitExceeded = 1228, VirtualCurrencyCountLimitExceeded = 1229, VirtualCurrencyCodeExists = 1230, TitleNewsItemCountLimitExceeded = 1231, InvalidTwitchToken = 1232, TwitchResponseError = 1233, ProfaneDisplayName = 1234, UserAlreadyAdded = 1235, InvalidVirtualCurrencyCode = 1236, VirtualCurrencyCannotBeDeleted = 1237, IdentifierAlreadyClaimed = 1238, IdentifierNotLinked = 1239, InvalidContinuationToken = 1240, ExpiredContinuationToken = 1241, InvalidSegment = 1242, InvalidSessionId = 1243, SessionLogNotFound = 1244, InvalidSearchTerm = 1245, TwoFactorAuthenticationTokenRequired = 1246, GameServerHostCountLimitExceeded = 1247, PlayerTagCountLimitExceeded = 1248, RequestAlreadyRunning = 1249, ActionGroupNotFound = 1250, MaximumSegmentBulkActionJobsRunning = 1251, NoActionsOnPlayersInSegmentJob = 1252, DuplicateStatisticName = 1253, ScheduledTaskNameConflict = 1254, ScheduledTaskCreateConflict = 1255, InvalidScheduledTaskName = 1256, InvalidTaskSchedule = 1257, SteamNotEnabledForTitle = 1258, LimitNotAnUpgradeOption = 1259, NoSecretKeyEnabledForCloudScript = 1260, TaskNotFound = 1261, TaskInstanceNotFound = 1262, InvalidIdentityProviderId = 1263, MisconfiguredIdentityProvider = 1264, InvalidScheduledTaskType = 1265, BillingInformationRequired = 1266, LimitedEditionItemUnavailable = 1267, InvalidAdPlacementAndReward = 1268, AllAdPlacementViewsAlreadyConsumed = 1269, GoogleOAuthNotConfiguredForTitle = 1270, GoogleOAuthError = 1271, UserNotFriend = 1272, InvalidSignature = 1273, InvalidPublicKey = 1274, GoogleOAuthNoIdTokenIncludedInResponse = 1275, StatisticUpdateInProgress = 1276, LeaderboardVersionNotAvailable = 1277, StatisticAlreadyHasPrizeTable = 1279, PrizeTableHasOverlappingRanks = 1280, PrizeTableHasMissingRanks = 1281, PrizeTableRankStartsAtZero = 1282, InvalidStatistic = 1283, ExpressionParseFailure = 1284, ExpressionInvokeFailure = 1285, ExpressionTooLong = 1286, DataUpdateRateExceeded = 1287, RestrictedEmailDomain = 1288, EncryptionKeyDisabled = 1289, EncryptionKeyMissing = 1290, EncryptionKeyBroken = 1291, NoSharedSecretKeyConfigured = 1292, SecretKeyNotFound = 1293, PlayerSecretAlreadyConfigured = 1294, APIRequestsDisabledForTitle = 1295, InvalidSharedSecretKey = 1296, PrizeTableHasNoRanks = 1297, ProfileDoesNotExist = 1298, ContentS3OriginBucketNotConfigured = 1299, InvalidEnvironmentForReceipt = 1300, EncryptedRequestNotAllowed = 1301, SignedRequestNotAllowed = 1302, RequestViewConstraintParamsNotAllowed = 1303, BadPartnerConfiguration = 1304, XboxBPCertificateFailure = 1305, XboxXASSExchangeFailure = 1306, InvalidEntityId = 1307, StatisticValueAggregationOverflow = 1308, EmailMessageFromAddressIsMissing = 1309, EmailMessageToAddressIsMissing = 1310, SmtpServerAuthenticationError = 1311, SmtpServerLimitExceeded = 1312, SmtpServerInsufficientStorage = 1313, SmtpServerCommunicationError = 1314, SmtpServerGeneralFailure = 1315, EmailClientTimeout = 1316, EmailClientCanceledTask = 1317, EmailTemplateMissing = 1318, InvalidHostForTitleId = 1319, EmailConfirmationTokenDoesNotExist = 1320, EmailConfirmationTokenExpired = 1321, AccountDeleted = 1322, PlayerSecretNotConfigured = 1323, InvalidSignatureTime = 1324, NoContactEmailAddressFound = 1325, InvalidAuthToken = 1326, AuthTokenDoesNotExist = 1327, AuthTokenExpired = 1328, AuthTokenAlreadyUsedToResetPassword = 1329, MembershipNameTooLong = 1330, MembershipNotFound = 1331, GoogleServiceAccountInvalid = 1332, GoogleServiceAccountParseFailure = 1333, EntityTokenMissing = 1334, EntityTokenInvalid = 1335, EntityTokenExpired = 1336, EntityTokenRevoked = 1337, InvalidProductForSubscription = 1338, XboxInaccessible = 1339, SubscriptionAlreadyTaken = 1340, SmtpAddonNotEnabled = 1341, APIConcurrentRequestLimitExceeded = 1342, XboxRejectedXSTSExchangeRequest = 1343, VariableNotDefined = 1344, TemplateVersionNotDefined = 1345, FileTooLarge = 1346, TitleDeleted = 1347, TitleContainsUserAccounts = 1348, TitleDeletionPlayerCleanupFailure = 1349 } public delegate void ErrorCallback(PlayFabError error); public class PlayFabError { public int HttpCode; public string HttpStatus; public PlayFabErrorCode Error; public string ErrorMessage; public Dictionary<string, List<string> > ErrorDetails; public object CustomData; public override string ToString() { var sb = new System.Text.StringBuilder(); if (ErrorDetails != null) { foreach (var kv in ErrorDetails) { sb.Append(kv.Key); sb.Append(": "); sb.Append(string.Join(", ", kv.Value.ToArray())); sb.Append(" | "); } } return string.Format("PlayFabError({0}, {1}, {2} {3}", Error, ErrorMessage, HttpCode, HttpStatus) + (sb.Length > 0 ? " - Details: " + sb.ToString() + ")" : ")"); } [ThreadStatic] private static StringBuilder _tempSb; public string GenerateErrorReport() { if (_tempSb == null) _tempSb = new StringBuilder(); _tempSb.Length = 0; _tempSb.Append(ErrorMessage); if (ErrorDetails != null) foreach (var pair in ErrorDetails) foreach (var msg in pair.Value) _tempSb.Append("\n").Append(pair.Key).Append(": ").Append(msg); return _tempSb.ToString(); } } }
namespace dotless.Test.Specs { using System.Collections.Generic; using NUnit.Framework; public class VariablesFixture : SpecFixtureBase { [Test] public void VariableOperators() { var input = @" @a: 2; @x: @a * @a; @y: @x + 1; @z: @x * 2 + @y; .variables { width: @z + 1cm; // 14cm }"; var expected = @" .variables { width: 14cm; }"; AssertLess(input, expected); } [Test] public void StringVariables() { var input = @" @fonts: ""Trebuchet MS"", Verdana, sans-serif; @f: @fonts; .variables { font-family: @f; } "; var expected = @" .variables { font-family: ""Trebuchet MS"", Verdana, sans-serif; } "; AssertLess(input, expected); } [Test] public void VariablesWithNumbers() { var input = @"@widget-container: widget-container-8675309; #@{widget-container} { color: blue; }"; var expected = @" #widget-container-8675309 { color: blue; } "; AssertLess(input, expected); } [Test] public void VariablesChangingUnit() { var input = @" @a: 2; @x: @a * @a; @b: @a * 10; .variables { height: @b + @x + 0px; // 24px } "; var expected = @" .variables { height: 24px; } "; AssertLess(input, expected); } [Test] public void VariablesColor() { var input = @" @c: #888; .variables { color: @c; } "; var expected = @" .variables { color: #888; } "; AssertLess(input, expected); } [Test] public void VariablesQuoted() { var input = @" @quotes: ""~"" ""~""; @q: @quotes; .variables { quotes: @q; } "; var expected = @" .variables { quotes: ""~"" ""~""; } "; AssertLess(input, expected); } [Test] public void VariableOverridesPreviousValue1() { var input = @" @var: 10px; .init { width: @var; } @var: 20px; .overridden { width: @var; } "; var expected = @" .init { width: 20px; } .overridden { width: 20px; } "; AssertLess(input, expected); } [Test] public void VariableOverridesPreviousValue2() { var input = @" @var: 10px; .test { width: @var; @var: 20px; height: @var; } "; var expected = @" .test { width: 20px; height: 20px; } "; AssertLess(input, expected); } [Test] public void VariableOverridesPreviousValue3() { var input = @" @var: 10px; .test { @var: 15px; width: @var; @var: 20px; height: @var; } "; var expected = @" .test { width: 20px; height: 20px; } "; AssertLess(input, expected); } [Test] public void VariableOverridesPreviousValue4() { var input = @" @var: 10px; .test1 { @var: 20px; width: @var; } .test2 { width: @var; } "; var expected = @" .test1 { width: 20px; } .test2 { width: 10px; } "; AssertLess(input, expected); } [Test] public void VariableOverridesPreviousValue5() { var input = @" .mixin(@a) { width: @a; } .test { @var: 15px; .mixin(@var); @var: 20px; .mixin(@var); } "; var expected = @" .test { width: 20px; } "; AssertLess(input, expected); } [Test] public void Redefine() { var input = @" #redefine { @var: 4; @var: 2; @var: 3; width: @var; } "; var expected = @" #redefine { width: 3; } "; AssertLess(input, expected); } [Test] public void ThrowsIfNotFound() { AssertExpressionError("variable @var is undefined", 0, "@var"); } [Test] public void VariablesKeepImportantKeyword() { var variables = new Dictionary<string, string>(); variables["a"] = "#335577"; variables["b"] = "#335577 !important"; AssertExpression("#335577 !important", "@a !important", variables); AssertExpression("#335577 !important", "@b", variables); } [Test] public void VariablesKeepImportantKeyword2() { var input = @" @var: 0 -120px !important; .mixin(@a) { background-position: @a; } .class1 { .mixin( @var ); } .class2 { background-position: @var; } "; var expected = @" .class1 { background-position: 0 -120px !important; } .class2 { background-position: 0 -120px !important; } "; AssertLess(input, expected); } [Test] public void VariableValuesMulti() { var input = @" .values { @a: 'Trebuchet'; font-family: @a, @a, @a; }"; var expected = @" .values { font-family: 'Trebuchet', 'Trebuchet', 'Trebuchet'; }"; AssertLess(input, expected); } [Test] public void VariableValuesUrl() { var input = @" .values { @a: 'Trebuchet'; url: url(@a); }"; var expected = @" .values { url: url('Trebuchet'); }"; AssertLess(input, expected); } [Test] public void VariableValuesImportant() { var input = @" @c: #888; .values { color: @c !important; }"; var expected = @" .values { color: #888 !important; }"; AssertLess(input, expected); } [Test] public void VariableValuesMultipleValues() { var input = @" .values { @a: 'Trebuchet'; @multi: 'A', B, C; multi: something @multi, @a; }"; var expected = @" .values { multi: something 'A', B, C, 'Trebuchet'; }"; AssertLess(input, expected); } [Test] public void VariablesNames() { var input = @".variable-names { @var: 'hello'; @name: 'var'; name: @@name; }"; var expected = @" .variable-names { name: 'hello'; }"; AssertLess(input, expected); } [Test] public void VariableSelector() { string input = @"// Variables @mySelector: banner; // Usage .@{mySelector} { font-weight: bold; line-height: 40px; margin: 0 auto; } "; string expected = @".banner { font-weight: bold; line-height: 40px; margin: 0 auto; } "; AssertLess(input,expected); } [Test] public void SimpleRecursiveVariableDefinition() { string input = @" @var: 1px; @var: @var + 1; .rule { left: @var; } "; string expectedError = @" Recursive variable definition for @var on line 2 in file 'test.less': [1]: @var: 1px; [2]: @var: @var + 1; ------^ [3]: "; AssertError(expectedError, input); } [Test] public void IndirectRecursiveVariableDefinition() { string input = @" @var: 1px; @var2: @var; @var: @var2 + 1; .rule { left: @var; } "; string expectedError = @" Recursive variable definition for @var on line 2 in file 'test.less': [1]: @var: 1px; [2]: @var2: @var; -------^ [3]: @var: @var2 + 1;"; AssertError(expectedError, input); } [Test] public void VariableDeclarationWithMissingSemicolon() { var input = @" @v1:Normal; @v2: "; AssertError("missing semicolon in expression", "@v2:", 2, 3, input); } [Test] public void VariablesInAttributeSelectorValue() { var input = @" @breakpoint-alias: ""desktop""; [class*=""@{breakpoint-alias}-rule""] { margin-top: 0; zoom: 1; }"; var expected = @" [class*=""desktop-rule""] { margin-top: 0; zoom: 1; }"; AssertLess(input, expected); } [Test] public void VariablesAsAttributeName() { var input = @" @key: ""desktop""; [@{key}=""value""] { margin-top: 0; zoom: 1; }"; var expected = @" [""desktop""=""value""] { margin-top: 0; zoom: 1; }"; AssertLess(input, expected); } [Test] public void VariablesAsPartOfAttributeNameNotAllowed() { var input = @" @key: ""desktop""; [@{key}-something=""value""] { margin-top: 0; zoom: 1; }"; var expected = @" [""desktop""=""value""] { margin-top: 0; zoom: 1; }"; AssertError("Expected ']' but found '\"'", "[@{key}-something=\"value\"] {", 2, 17, input); } [Test] public void SelectorIsLegalVariableValue() { var input = @" @test: .foo; "; AssertLess(input, ""); } [Test] public void VariableInterpolationInPropertyName() { var input = @" .test { @var: color; @{var}: red; } "; var expected = @" .test { color: red; }"; AssertLess(input, expected); } } }
#pragma warning disable 1634, 1691 using System.CodeDom; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Workflow.Activities.Common; using System.Workflow.ComponentModel.Compiler; namespace System.Workflow.Activities.Rules { [Serializable] public abstract class RuleAction { public abstract bool Validate(RuleValidation validator); public abstract void Execute(RuleExecution context); public abstract ICollection<string> GetSideEffects(RuleValidation validation); public abstract RuleAction Clone(); } [Serializable] public class RuleHaltAction : RuleAction { public override bool Validate(RuleValidation validator) { // Trivial... nothing to validate. return true; } public override void Execute(RuleExecution context) { if (context == null) throw new ArgumentNullException("context"); context.Halted = true; } public override ICollection<string> GetSideEffects(RuleValidation validation) { return null; } public override RuleAction Clone() { return (RuleAction)this.MemberwiseClone(); } public override string ToString() { return "Halt"; } public override bool Equals(object obj) { return (obj is RuleHaltAction); } public override int GetHashCode() { return base.GetHashCode(); } } [Serializable] public class RuleUpdateAction : RuleAction { private string path; public RuleUpdateAction(string path) { this.path = path; } public RuleUpdateAction() { } public string Path { get { return path; } set { path = value; } } public override bool Validate(RuleValidation validator) { if (validator == null) throw new ArgumentNullException("validator"); bool success = true; if (path == null) { ValidationError error = new ValidationError(Messages.NullUpdate, ErrorNumbers.Error_ParameterNotSet); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; } // now make sure that the path is valid string[] parts = path.Split('/'); if (parts[0] == "this") { Type currentType = validator.ThisType; for (int i = 1; i < parts.Length; ++i) { if (parts[i] == "*") { if (i < parts.Length - 1) { // The "*" occurred in the middle of the path, which is a no-no. ValidationError error = new ValidationError(Messages.InvalidWildCardInPathQualifier, ErrorNumbers.Error_InvalidWildCardInPathQualifier); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; break; } else { // It occurred at the end, which is okay. break; } } else if (string.IsNullOrEmpty(parts[i]) && i == parts.Length - 1) { // It's okay to end with a "/". break; } while (currentType.IsArray) currentType = currentType.GetElementType(); BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy; if (validator.AllowInternalMembers(currentType)) bindingFlags |= BindingFlags.NonPublic; FieldInfo field = currentType.GetField(parts[i], bindingFlags); if (field != null) { currentType = field.FieldType; } else { PropertyInfo property = currentType.GetProperty(parts[i], bindingFlags); if (property != null) { currentType = property.PropertyType; } else { string message = string.Format(CultureInfo.CurrentCulture, Messages.UpdateUnknownFieldOrProperty, parts[i]); ValidationError error = new ValidationError(message, ErrorNumbers.Error_InvalidUpdate); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; break; } } } } else { ValidationError error = new ValidationError(Messages.UpdateNotThis, ErrorNumbers.Error_InvalidUpdate); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); success = false; } return success; } public override void Execute(RuleExecution context) { // This action has no execution behaviour. } public override ICollection<string> GetSideEffects(RuleValidation validation) { return new string[] { this.path }; } public override RuleAction Clone() { return (RuleAction)this.MemberwiseClone(); } public override string ToString() { return "Update(\"" + this.path + "\")"; } public override bool Equals(object obj) { #pragma warning disable 56506 RuleUpdateAction other = obj as RuleUpdateAction; return ((other != null) && (string.Equals(this.Path, other.Path, StringComparison.Ordinal))); #pragma warning restore 56506 } public override int GetHashCode() { return base.GetHashCode(); } } [Serializable] public class RuleStatementAction : RuleAction { private CodeStatement codeDomStatement; public RuleStatementAction(CodeStatement codeDomStatement) { this.codeDomStatement = codeDomStatement; } public RuleStatementAction(CodeExpression codeDomExpression) { this.codeDomStatement = new CodeExpressionStatement(codeDomExpression); } public RuleStatementAction() { } public CodeStatement CodeDomStatement { get { return codeDomStatement; } set { codeDomStatement = value; } } public override bool Validate(RuleValidation validator) { if (validator == null) throw new ArgumentNullException("validator"); if (codeDomStatement == null) { ValidationError error = new ValidationError(Messages.NullStatement, ErrorNumbers.Error_ParameterNotSet); error.UserData[RuleUserDataKeys.ErrorObject] = this; validator.AddError(error); return false; } else { return CodeDomStatementWalker.Validate(validator, codeDomStatement); } } public override void Execute(RuleExecution context) { if (codeDomStatement == null) throw new InvalidOperationException(Messages.NullStatement); CodeDomStatementWalker.Execute(context, codeDomStatement); } public override ICollection<string> GetSideEffects(RuleValidation validation) { RuleAnalysis analysis = new RuleAnalysis(validation, true); if (codeDomStatement != null) CodeDomStatementWalker.AnalyzeUsage(analysis, codeDomStatement); return analysis.GetSymbols(); } public override RuleAction Clone() { RuleStatementAction newAction = (RuleStatementAction)this.MemberwiseClone(); newAction.codeDomStatement = CodeDomStatementWalker.Clone(codeDomStatement); return newAction; } public override string ToString() { if (codeDomStatement == null) return ""; StringBuilder decompilation = new StringBuilder(); CodeDomStatementWalker.Decompile(decompilation, codeDomStatement); return decompilation.ToString(); } public override bool Equals(object obj) { #pragma warning disable 56506 RuleStatementAction other = obj as RuleStatementAction; return ((other != null) && (CodeDomStatementWalker.Match(CodeDomStatement, other.CodeDomStatement))); #pragma warning restore 56506 } public override int GetHashCode() { return base.GetHashCode(); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Reflection; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; partial class MetaPythonType : MetaPythonObject, IPythonInvokable { #region IPythonInvokable Members public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) { DynamicMetaObject translated = BuiltinFunction.TranslateArguments(pythonInvoke, codeContext, target, args, false, Value.Name); if (translated != null) { return translated; } return InvokeWorker(pythonInvoke, args, codeContext); } #endregion #region MetaObject Overrides public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { foreach (PythonType pt in Value.ResolutionOrder) { PythonTypeSlot dummy; if (pt.IsSystemType) { return action.FallbackInvokeMember(this, args); } else if (pt.TryResolveSlot(DefaultContext.DefaultCLS, action.Name, out dummy)) { break; } } return BindingHelpers.GenericInvokeMember(action, null, this, args); } public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ call, params DynamicMetaObject/*!*/[]/*!*/ args) { return InvokeWorker(call, args, PythonContext.GetCodeContext(call)); } #endregion #region Invoke Implementation private DynamicMetaObject/*!*/ InvokeWorker(DynamicMetaObjectBinder/*!*/ call, DynamicMetaObject/*!*/[]/*!*/ args, Expression/*!*/ codeContext) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Type Invoke " + Value.UnderlyingSystemType.FullName + args.Length); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "Type Invoke"); if (this.NeedsDeferral()) { return call.Defer(ArrayUtils.Insert(this, args)); } for (int i = 0; i < args.Length; i++) { if (args[i].NeedsDeferral()) { return call.Defer(ArrayUtils.Insert(this, args)); } } DynamicMetaObject res; if (IsStandardDotNetType(call)) { res = MakeStandardDotNetTypeCall(call, codeContext, args); } else { res = MakePythonTypeCall(call, codeContext, args); } return BindingHelpers.AddPythonBoxing(res); } /// <summary> /// Creating a standard .NET type is easy - we just call it's constructor with the provided /// arguments. /// </summary> private DynamicMetaObject/*!*/ MakeStandardDotNetTypeCall(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject/*!*/[]/*!*/ args) { CallSignature signature = BindingHelpers.GetCallSignature(call); PythonContext state = PythonContext.GetPythonContext(call); MethodBase[] ctors = CompilerHelpers.GetConstructors(Value.UnderlyingSystemType, state.Binder.PrivateBinding); if (ctors.Length > 0) { return state.Binder.CallMethod( new PythonOverloadResolver( state.Binder, args, signature, codeContext ), ctors, Restrictions.Merge(BindingRestrictions.GetInstanceRestriction(Expression, Value)) ); } else { string msg; if (Value.UnderlyingSystemType.IsAbstract()) { msg = String.Format("Cannot create instances of {0} because it is abstract", Value.Name); }else{ msg = String.Format("Cannot create instances of {0} because it has no public constructors", Value.Name); } return new DynamicMetaObject( call.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(msg) ) ), Restrictions.Merge(BindingRestrictions.GetInstanceRestriction(Expression, Value)) ); } } /// <summary> /// Creating a Python type involves calling __new__ and __init__. We resolve them /// and generate calls to either the builtin funcions directly or embed sites which /// call the slots at runtime. /// </summary> private DynamicMetaObject/*!*/ MakePythonTypeCall(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject/*!*/[]/*!*/ args) { ValidationInfo valInfo = MakeVersionCheck(); DynamicMetaObject self = new RestrictedMetaObject( AstUtils.Convert(Expression, LimitType), BindingRestrictionsHelpers.GetRuntimeTypeRestriction(Expression, LimitType), Value ); CallSignature sig = BindingHelpers.GetCallSignature(call); ArgumentValues ai = new ArgumentValues(sig, self, args); NewAdapter newAdapter; InitAdapter initAdapter; if (TooManyArgsForDefaultNew(call, args)) { return MakeIncorrectArgumentsForCallError(call, ai, valInfo); } else if (Value.UnderlyingSystemType.IsGenericTypeDefinition()) { return MakeGenericTypeDefinitionError(call, ai, valInfo); } else if (Value.HasAbstractMethods(PythonContext.GetPythonContext(call).SharedContext)) { return MakeAbstractInstantiationError(call, ai, valInfo); } DynamicMetaObject translated = BuiltinFunction.TranslateArguments(call, codeContext, self, args, false, Value.Name); if (translated != null) { return translated; } GetAdapters(ai, call, codeContext, out newAdapter, out initAdapter); PythonContext state = PythonContext.GetPythonContext(call); // get the expression for calling __new__ DynamicMetaObject createExpr = newAdapter.GetExpression(state.Binder); if (createExpr.Expression.Type == typeof(void)) { return BindingHelpers.AddDynamicTestAndDefer( call, createExpr, args, valInfo ); } Expression res; BindingRestrictions additionalRestrictions = BindingRestrictions.Empty; if (!Value.IsSystemType && (!(newAdapter is DefaultNewAdapter) || HasFinalizer(call))) { // we need to dynamically check the return value to see if it's a subtype of // the type that we are calling. If it is then we need to call __init__/__del__ // for the actual returned type. res = DynamicExpression.Dynamic( Value.GetLateBoundInitBinder(sig), typeof(object), ArrayUtils.Insert( codeContext, Expression.Convert(createExpr.Expression, typeof(object)), DynamicUtils.GetExpressions(args) ) ); additionalRestrictions = createExpr.Restrictions; } else { // just call the __init__ method, built-in types currently have // no wacky return values which don't return the derived type. // then get the statement for calling __init__ ParameterExpression allocatedInst = Ast.Variable(createExpr.GetLimitType(), "newInst"); Expression tmpRead = allocatedInst; DynamicMetaObject initCall = initAdapter.MakeInitCall( state.Binder, new RestrictedMetaObject( AstUtils.Convert(allocatedInst, Value.UnderlyingSystemType), createExpr.Restrictions ) ); List<Expression> body = new List<Expression>(); Debug.Assert(!HasFinalizer(call)); // add the call to init if we need to if (initCall.Expression != tmpRead) { // init can fail but if __new__ returns a different type // no exception is raised. DynamicMetaObject initStmt = initCall; if (body.Count == 0) { body.Add( Ast.Assign(allocatedInst, createExpr.Expression) ); } if (!Value.UnderlyingSystemType.IsAssignableFrom(createExpr.Expression.Type)) { // return type of object, we need to check the return type before calling __init__. body.Add( AstUtils.IfThen( Ast.TypeIs(allocatedInst, Value.UnderlyingSystemType), initStmt.Expression ) ); } else { // just call the __init__ method, no type check necessary (TODO: need null check?) body.Add(initStmt.Expression); } } // and build the target from everything we have if (body.Count == 0) { res = createExpr.Expression; } else { body.Add(allocatedInst); res = Ast.Block(body); } res = Ast.Block(new ParameterExpression[] { allocatedInst }, res); additionalRestrictions = initCall.Restrictions; } return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( res, self.Restrictions.Merge(additionalRestrictions) ), ArrayUtils.Insert(this, args), valInfo ); } #endregion #region Adapter support private void GetAdapters(ArgumentValues/*!*/ ai, DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, out NewAdapter/*!*/ newAdapter, out InitAdapter/*!*/ initAdapter) { PythonTypeSlot newInst, init; Value.TryResolveSlot(PythonContext.GetPythonContext(call).SharedContext, "__new__", out newInst); Value.TryResolveSlot(PythonContext.GetPythonContext(call).SharedContext, "__init__", out init); // these are never null because we always resolve to __new__ or __init__ somewhere. Assert.NotNull(newInst, init); newAdapter = GetNewAdapter(ai, newInst, call, codeContext); initAdapter = GetInitAdapter(ai, init, call, codeContext); } private InitAdapter/*!*/ GetInitAdapter(ArgumentValues/*!*/ ai, PythonTypeSlot/*!*/ init, DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext) { PythonContext state = PythonContext.GetPythonContext(call); if ((init == InstanceOps.Init && !HasFinalizer(call)) || (Value == TypeCache.PythonType && ai.Arguments.Length == 2)) { return new DefaultInitAdapter(ai, state, codeContext); } else if (init is BuiltinMethodDescriptor) { return new BuiltinInitAdapter(ai, ((BuiltinMethodDescriptor)init).Template, state, codeContext); } else if (init is BuiltinFunction) { return new BuiltinInitAdapter(ai, (BuiltinFunction)init, state, codeContext); } else { return new SlotInitAdapter(init, ai, state, codeContext); } } private NewAdapter/*!*/ GetNewAdapter(ArgumentValues/*!*/ ai, PythonTypeSlot/*!*/ newInst, DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext) { PythonContext state = PythonContext.GetPythonContext(call); if (newInst == InstanceOps.New) { return new DefaultNewAdapter(ai, Value, state, codeContext); } else if (newInst is ConstructorFunction) { return new ConstructorNewAdapter(ai, Value, state, codeContext); } else if (newInst is BuiltinFunction) { return new BuiltinNewAdapter(ai, Value, ((BuiltinFunction)newInst), state, codeContext); } return new NewAdapter(ai, state, codeContext); } private class CallAdapter { private readonly ArgumentValues/*!*/ _argInfo; private readonly PythonContext/*!*/ _state; private readonly Expression/*!*/ _context; public CallAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) { _argInfo = ai; _state = state; _context = codeContext; } protected PythonContext PythonContext { get { return _state; } } protected Expression CodeContext { get { return _context; } } protected ArgumentValues/*!*/ Arguments { get { return _argInfo; } } } private class ArgumentValues { public readonly DynamicMetaObject/*!*/ Self; public readonly DynamicMetaObject/*!*/[]/*!*/ Arguments; public readonly CallSignature Signature; public ArgumentValues(CallSignature signature, DynamicMetaObject/*!*/ self, DynamicMetaObject/*!*/[]/*!*/ args) { Self = self; Signature = signature; Arguments = args; } } #endregion #region __new__ adapters private class NewAdapter : CallAdapter { public NewAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public virtual DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { return MakeDefaultNew( binder, Ast.Call( typeof(PythonOps).GetMethod("PythonTypeGetMember"), CodeContext, AstUtils.Convert(Arguments.Self.Expression, typeof(PythonType)), AstUtils.Constant(null), AstUtils.Constant("__new__") ) ); } protected DynamicMetaObject/*!*/ MakeDefaultNew(DefaultBinder/*!*/ binder, Expression/*!*/ function) { // calling theType.__new__(theType, args) List<Expression> args = new List<Expression>(); args.Add(CodeContext); args.Add(function); AppendNewArgs(args); return new DynamicMetaObject( DynamicExpression.Dynamic( PythonContext.Invoke( GetDynamicNewSignature() ), typeof(object), args.ToArray() ), Arguments.Self.Restrictions ); } private void AppendNewArgs(List<Expression> args) { // theType args.Add(Arguments.Self.Expression); // args foreach (DynamicMetaObject mo in Arguments.Arguments) { args.Add(mo.Expression); } } protected CallSignature GetDynamicNewSignature() { return Arguments.Signature.InsertArgument(Argument.Simple); } } private class DefaultNewAdapter : NewAdapter { private readonly PythonType/*!*/ _creating; public DefaultNewAdapter(ArgumentValues/*!*/ ai, PythonType/*!*/ creating, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _creating = creating; } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { PythonOverloadResolver resolver; if (_creating.IsSystemType || _creating.HasSystemCtor) { resolver = new PythonOverloadResolver(binder, DynamicMetaObject.EmptyMetaObjects, new CallSignature(0), CodeContext); } else { resolver = new PythonOverloadResolver(binder, new[] { Arguments.Self }, new CallSignature(1), CodeContext); } return binder.CallMethod(resolver, _creating.UnderlyingSystemType.GetConstructors(), BindingRestrictions.Empty, _creating.Name); } } private class ConstructorNewAdapter : NewAdapter { private readonly PythonType/*!*/ _creating; public ConstructorNewAdapter(ArgumentValues/*!*/ ai, PythonType/*!*/ creating, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _creating = creating; } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { PythonOverloadResolver resolve; if (_creating.IsSystemType || _creating.HasSystemCtor) { resolve = new PythonOverloadResolver( binder, Arguments.Arguments, Arguments.Signature, CodeContext ); } else { resolve = new PythonOverloadResolver( binder, ArrayUtils.Insert(Arguments.Self, Arguments.Arguments), GetDynamicNewSignature(), CodeContext ); } return binder.CallMethod( resolve, _creating.UnderlyingSystemType.GetConstructors(), Arguments.Self.Restrictions, _creating.Name ); } } private class BuiltinNewAdapter : NewAdapter { private readonly PythonType/*!*/ _creating; private readonly BuiltinFunction/*!*/ _ctor; public BuiltinNewAdapter(ArgumentValues/*!*/ ai, PythonType/*!*/ creating, BuiltinFunction/*!*/ ctor, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _creating = creating; _ctor = ctor; } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { return binder.CallMethod( new PythonOverloadResolver( binder, ArrayUtils.Insert(Arguments.Self, Arguments.Arguments), Arguments.Signature.InsertArgument(new Argument(ArgumentType.Simple)), CodeContext ), _ctor.Targets, _creating.Name ); } } private class MixedNewAdapter : NewAdapter { public MixedNewAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public override DynamicMetaObject/*!*/ GetExpression(PythonBinder/*!*/ binder) { return MakeDefaultNew( binder, Ast.Call( typeof(PythonOps).GetMethod("GetMixedMember"), CodeContext, Arguments.Self.Expression, AstUtils.Constant(null), AstUtils.Constant("__new__") ) ); } } #endregion #region __init__ adapters private abstract class InitAdapter : CallAdapter { protected InitAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public abstract DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr); protected DynamicMetaObject/*!*/ MakeDefaultInit(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr, Expression/*!*/ init) { List<Expression> args = new List<Expression>(); args.Add(CodeContext); args.Add(Expression.Convert(createExpr.Expression, typeof(object))); foreach (DynamicMetaObject mo in Arguments.Arguments) { args.Add(mo.Expression); } return new DynamicMetaObject( DynamicExpression.Dynamic( ((PythonType)Arguments.Self.Value).GetLateBoundInitBinder(Arguments.Signature), typeof(object), args.ToArray() ), Arguments.Self.Restrictions.Merge(createExpr.Restrictions) ); } } private class SlotInitAdapter : InitAdapter { private readonly PythonTypeSlot/*!*/ _slot; public SlotInitAdapter(PythonTypeSlot/*!*/ slot, ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _slot = slot; } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { Expression init = Ast.Call( typeof(PythonOps).GetMethod("GetInitSlotMember"), CodeContext, Ast.Convert(Arguments.Self.Expression, typeof(PythonType)), Ast.Convert(AstUtils.WeakConstant(_slot), typeof(PythonTypeSlot)), AstUtils.Convert(createExpr.Expression, typeof(object)) ); return MakeDefaultInit(binder, createExpr, init); } } private class DefaultInitAdapter : InitAdapter { public DefaultInitAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { // default init, we can just return the value from __new__ return createExpr; } } private class BuiltinInitAdapter : InitAdapter { private readonly BuiltinFunction/*!*/ _method; public BuiltinInitAdapter(ArgumentValues/*!*/ ai, BuiltinFunction/*!*/ method, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { _method = method; } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { if (_method == InstanceOps.Init.Template) { // we have a default __init__, don't call it. return createExpr; } return binder.CallMethod( new PythonOverloadResolver( binder, createExpr, Arguments.Arguments, Arguments.Signature, CodeContext ), _method.Targets, Arguments.Self.Restrictions ); } } private class MixedInitAdapter : InitAdapter { public MixedInitAdapter(ArgumentValues/*!*/ ai, PythonContext/*!*/ state, Expression/*!*/ codeContext) : base(ai, state, codeContext) { } public override DynamicMetaObject/*!*/ MakeInitCall(PythonBinder/*!*/ binder, DynamicMetaObject/*!*/ createExpr) { Expression init = Ast.Call( typeof(PythonOps).GetMethod("GetMixedMember"), CodeContext, Ast.Convert(Arguments.Self.Expression, typeof(PythonType)), AstUtils.Convert(createExpr.Expression, typeof(object)), AstUtils.Constant("__init__") ); return MakeDefaultInit(binder, createExpr, init); } } #endregion #region Helpers private DynamicMetaObject/*!*/ MakeIncorrectArgumentsForCallError(DynamicMetaObjectBinder/*!*/ call, ArgumentValues/*!*/ ai, ValidationInfo/*!*/ valInfo) { string message; if (Value.IsSystemType) { if (Value.UnderlyingSystemType.GetConstructors().Length == 0) { // this is a type we can't create ANY instances of, give the user a half-way decent error message message = "cannot create instances of " + Value.Name; } else { message = InstanceOps.ObjectNewNoParameters; } } else { message = InstanceOps.ObjectNewNoParameters; } return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( call.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(message) ) ), GetErrorRestrictions(ai) ), ai.Arguments, valInfo ); } private DynamicMetaObject/*!*/ MakeGenericTypeDefinitionError(DynamicMetaObjectBinder/*!*/ call, ArgumentValues/*!*/ ai, ValidationInfo/*!*/ valInfo) { Debug.Assert(Value.IsSystemType); string message = "cannot create instances of " + Value.Name + " because it is a generic type definition"; return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( call.Throw( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(message) ), typeof(object) ), GetErrorRestrictions(ai) ), ai.Arguments, valInfo ); } private DynamicMetaObject/*!*/ MakeAbstractInstantiationError(DynamicMetaObjectBinder/*!*/ call, ArgumentValues/*!*/ ai, ValidationInfo/*!*/ valInfo) { CodeContext context = PythonContext.GetPythonContext(call).SharedContext; string message = Value.GetAbstractErrorMessage(context); Debug.Assert(message != null); return BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject( Ast.Throw( Ast.New( typeof(ArgumentTypeException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(message) ), typeof(object) ), GetErrorRestrictions(ai) ), ai.Arguments, valInfo ); } private BindingRestrictions/*!*/ GetErrorRestrictions(ArgumentValues/*!*/ ai) { BindingRestrictions res = Restrict(this.GetRuntimeType()).Restrictions; res = res.Merge(GetInstanceRestriction(ai)); foreach (DynamicMetaObject mo in ai.Arguments) { if (mo.HasValue) { res = res.Merge(mo.Restrict(mo.GetRuntimeType()).Restrictions); } } return res; } private static BindingRestrictions GetInstanceRestriction(ArgumentValues ai) { return BindingRestrictions.GetInstanceRestriction(ai.Self.Expression, ai.Self.Value); } private bool HasFinalizer(DynamicMetaObjectBinder/*!*/ action) { // only user types have finalizers... if (Value.IsSystemType) return false; PythonTypeSlot del; bool hasDel = Value.TryResolveSlot(PythonContext.GetPythonContext(action).SharedContext, "__del__", out del); return hasDel; } private bool HasDefaultNew(DynamicMetaObjectBinder/*!*/ action) { PythonTypeSlot newInst; Value.TryResolveSlot(PythonContext.GetPythonContext(action).SharedContext, "__new__", out newInst); return newInst == InstanceOps.New; } private bool HasDefaultInit(DynamicMetaObjectBinder/*!*/ action) { PythonTypeSlot init; Value.TryResolveSlot(PythonContext.GetPythonContext(action).SharedContext, "__init__", out init); return init == InstanceOps.Init; } private bool HasDefaultNewAndInit(DynamicMetaObjectBinder/*!*/ action) { return HasDefaultNew(action) && HasDefaultInit(action); } /// <summary> /// Checks if we have a default new and init - in this case if we have any /// arguments we don't allow the call. /// </summary> private bool TooManyArgsForDefaultNew(DynamicMetaObjectBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) { if (args.Length > 0 && HasDefaultNewAndInit(action)) { Argument[] infos = BindingHelpers.GetCallSignature(action).GetArgumentInfos(); for (int i = 0; i < infos.Length; i++) { Argument curArg = infos[i]; switch(curArg.Kind) { case ArgumentType.List: // Deferral? if (((IList<object>)args[i].Value).Count > 0) { return true; } break; case ArgumentType.Dictionary: // Deferral? if (PythonOps.Length(args[i].Value) > 0) { return true; } break; default: return true; } } } return false; } /// <summary> /// Creates a test which tests the specific version of the type. /// </summary> private ValidationInfo/*!*/ MakeVersionCheck() { int version = Value.Version; return new ValidationInfo( Ast.Equal( Ast.Call( typeof(PythonOps).GetMethod("GetTypeVersion"), Ast.Convert(Expression, typeof(PythonType)) ), AstUtils.Constant(version) ) ); } private bool IsStandardDotNetType(DynamicMetaObjectBinder/*!*/ action) { PythonContext bState = PythonContext.GetPythonContext(action); return Value.IsSystemType && !Value.IsPythonType && !bState.Binder.HasExtensionTypes(Value.UnderlyingSystemType) && !typeof(Delegate).IsAssignableFrom(Value.UnderlyingSystemType) && !Value.UnderlyingSystemType.IsArray; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Environment; using OpenQA.Selenium.Interactions; namespace OpenQA.Selenium { [TestFixture] public class CorrectEventFiringTest : DriverTestFixture { [Test] public void ShouldFireFocusEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); AssertEventFired("focus", driver); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver does not support multiple instances")] [IgnoreBrowser(Browser.Safari, "Safari driver does not support multiple instances")] public void ShouldFireFocusEventInNonTopmostWindow() { IWebDriver driver2 = EnvironmentManager.Instance.CreateDriverInstance(); try { // topmost driver2.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver2); AssertEventFired("focus", driver2); // non-topmost driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); AssertEventFired("focus", driver); } finally { driver2.Quit(); } } [Test] public void ShouldFireClickEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); AssertEventFired("click", driver); } [Test] public void ShouldFireMouseDownEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); AssertEventFired("mousedown", driver); } [Test] public void ShouldFireMouseUpEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); AssertEventFired("mouseup", driver); } [Test] public void ShouldFireMouseOverEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); AssertEventFired("mouseover", driver); } [Test] [IgnoreBrowser(Browser.Firefox, "Firefox does not report mouse move event when clicking")] public void ShouldFireMouseMoveEventWhenClicking() { driver.Url = javascriptPage; // This bears some explanation. In certain cases, if the prior test // leaves the mouse cursor immediately over the wrong element, then // the mousemove event may not get fired, because the mouse does not // actually move. Prevent this situation by forcing the mouse to move // to the origin. new Actions(driver).MoveToElement(driver.FindElement(By.TagName("body"))).Perform(); ClickOnElementWhichRecordsEvents(driver); AssertEventFired("mousemove", driver); } [Test] public void ShouldNotThrowIfEventHandlerThrows() { driver.Url = javascriptPage; driver.FindElement(By.Id("throwing-mouseover")).Click(); } [Test] public void ShouldFireEventsInTheRightOrder() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(driver); string text = driver.FindElement(By.Id("result")).Text; int lastIndex = -1; List<string> eventList = new List<string>() { "mousedown", "focus", "mouseup", "click" }; foreach (string eventName in eventList) { int index = text.IndexOf(eventName); Assert.That(text, Does.Contain(eventName), eventName + " did not fire at all. Text is " + text); Assert.That(index, Is.GreaterThan(lastIndex), eventName + " did not fire in the correct order. Text is " + text); lastIndex = index; } } [Test] public void ShouldIssueMouseDownEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mousedown")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] public void ShouldIssueClickEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseclick")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse click"); } [Test] public void ShouldIssueMouseUpEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseup")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse up"); } [Test] public void MouseEventsShouldBubbleUpToContainingElements() { driver.Url = javascriptPage; driver.FindElement(By.Id("child")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] public void ShouldEmitOnChangeEventsWhenSelectingElements() { driver.Url = javascriptPage; //Intentionally not looking up the select tag. See selenium r7937 for details. ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector']//option")); String initialTextValue = driver.FindElement(By.Id("result")).Text; IWebElement foo = allOptions[0]; IWebElement bar = allOptions[1]; foo.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, initialTextValue); bar.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar"); } [Test] public void ShouldEmitOnClickEventsWhenSelectingElements() { driver.Url = javascriptPage; // Intentionally not looking up the select tag. See selenium r7937 for details. ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector2']//option")); IWebElement foo = allOptions[0]; IWebElement bar = allOptions[1]; foo.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "foo"); bar.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar"); } [Test] [IgnoreBrowser(Browser.IE, "IE does not fire change event when clicking on checkbox")] public void ShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox() { driver.Url = javascriptPage; IWebElement checkbox = driver.FindElement(By.Id("checkbox")); checkbox.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "checkbox thing"); } [Test] public void ShouldEmitClickEventWhenClickingOnATextInputElement() { driver.Url = javascriptPage; IWebElement clicker = driver.FindElement(By.Id("clickField")); clicker.Click(); Assert.AreEqual(clicker.GetAttribute("value"), "Clicked"); } [Test] public void ShouldFireTwoClickEventsWhenClickingOnALabel() { driver.Url = javascriptPage; driver.FindElement(By.Id("labelForCheckbox")).Click(); IWebElement result = driver.FindElement(By.Id("result")); Assert.That(WaitFor(() => { return result.Text.Contains("labelclick chboxclick"); }, "Did not find text: " + result.Text), Is.True); } [Test] public void ClearingAnElementShouldCauseTheOnChangeHandlerToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("clearMe")); element.Clear(); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual(result.Text, "Cleared"); } [Test] public void SendingKeysToAnotherElementShouldCauseTheBlurEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); IWebElement element2 = driver.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur", driver); } [Test] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver does not support multiple instances")] [IgnoreBrowser(Browser.Safari, "Safari driver does not support multiple instances")] public void SendingKeysToAnotherElementShouldCauseTheBlurEventToFireInNonTopmostWindow() { IWebElement element = null; IWebElement element2 = null; IWebDriver driver2 = EnvironmentManager.Instance.CreateDriverInstance(); try { // topmost driver2.Url = javascriptPage; element = driver2.FindElement(By.Id("theworks")); element.SendKeys("foo"); element2 = driver2.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur", driver2); // non-topmost driver.Url = javascriptPage; element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); element2 = driver.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur", driver); } finally { driver2.Quit(); } driver.Url = javascriptPage; element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); element2 = driver.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur", driver); } [Test] public void SendingKeysToAnElementShouldCauseTheFocusEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); AssertEventFired("focus", driver); } [Test] public void SendingKeysToAFocusedElementShouldNotBlurThatElement() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.Click(); //Wait until focused bool focused = false; IWebElement result = driver.FindElement(By.Id("result")); for (int i = 0; i < 5; ++i) { string fired = result.Text; if (fired.Contains("focus")) { focused = true; break; } try { System.Threading.Thread.Sleep(200); } catch (Exception e) { throw e; } } if (!focused) { Assert.Fail("Clicking on element didn't focus it in time - can't proceed so failing"); } element.SendKeys("a"); AssertEventNotFired("blur"); } [Test] [IgnoreBrowser(Browser.IE, "Clicking on child does blur parent, whether focused or not.")] public void ClickingAnUnfocusableChildShouldNotBlurTheParent() { if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = javascriptPage; // Click on parent, giving it the focus. IWebElement parent = driver.FindElement(By.Id("hideOnBlur")); parent.Click(); AssertEventNotFired("blur"); // Click on child. It is not focusable, so focus should stay on the parent. driver.FindElement(By.Id("hideOnBlurChild")).Click(); System.Threading.Thread.Sleep(2000); Assert.That(parent.Displayed, Is.True, "#hideOnBlur should still be displayed after click"); AssertEventNotFired("blur"); // Click elsewhere, and let the element disappear. driver.FindElement(By.Id("result")).Click(); AssertEventFired("blur", driver); } [Test] public void SubmittingFormFromFormElementShouldFireOnSubmitForThatForm() { driver.Url = javascriptPage; IWebElement formElement = driver.FindElement(By.Id("submitListeningForm")); formElement.Submit(); AssertEventFired("form-onsubmit", driver); } [Test] public void SubmittingFormFromFormInputSubmitElementShouldFireOnSubmitForThatForm() { driver.Url = javascriptPage; IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit")); submit.Submit(); AssertEventFired("form-onsubmit", driver); } [Test] public void SubmittingFormFromFormInputTextElementShouldFireOnSubmitForThatFormAndNotClickOnThatInput() { driver.Url = javascriptPage; IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit")); submit.Submit(); AssertEventFired("form-onsubmit", driver); AssertEventNotFired("text-onclick"); } [Test] public void UploadingFileShouldFireOnChangeEvent() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); IWebElement result = driver.FindElement(By.Id("fileResults")); Assert.AreEqual(string.Empty, result.Text); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); // Shift focus to something else because send key doesn't make the focus leave driver.FindElement(By.Id("id-name1")).Click(); inputFile.Delete(); Assert.AreEqual("changed", result.Text); } [Test] public void ShouldReportTheXAndYCoordinatesWhenClicking() { driver.Url = clickEventPage; IWebElement element = driver.FindElement(By.Id("eventish")); element.Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2); string clientX = driver.FindElement(By.Id("clientX")).Text; string clientY = driver.FindElement(By.Id("clientY")).Text; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0); Assert.AreNotEqual("0", clientX); Assert.AreNotEqual("0", clientY); } [Test] public void ClickEventsShouldBubble() { driver.Url = clicksPage; driver.FindElement(By.Id("bubblesFrom")).Click(); bool eventBubbled = (bool)((IJavaScriptExecutor)driver).ExecuteScript("return !!window.bubbledClick;"); Assert.That(eventBubbled, Is.True, "Event didn't bubble up"); } [Test] public void ClickOverlappingElements() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/overlapping_elements.html"); Assert.That(() => driver.FindElement(By.Id("under")).Click(), Throws.InstanceOf<ElementClickInterceptedException>().Or.InstanceOf<WebDriverException>().With.Message.Contains("Other element would receive the click")); } [Test] [IgnoreBrowser(Browser.Chrome, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.Edge, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.EdgeLegacy, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.Firefox, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.IE, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.Safari, "Driver checks for overlapping elements")] public void ClickPartiallyOverlappingElements() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } StringBuilder expectedLogBuilder = new StringBuilder(); expectedLogBuilder.AppendLine("Log:"); expectedLogBuilder.AppendLine("mousedown in under (handled by under)"); expectedLogBuilder.AppendLine("mousedown in under (handled by body)"); expectedLogBuilder.AppendLine("mouseup in under (handled by under)"); expectedLogBuilder.AppendLine("mouseup in under (handled by body)"); expectedLogBuilder.AppendLine("click in under (handled by under)"); expectedLogBuilder.Append("click in under (handled by body)"); for (int i = 1; i < 6; i++) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/partially_overlapping_elements.html"); IWebElement over = driver.FindElement(By.Id("over" + i)); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.display = 'none'", over); driver.FindElement(By.Id("under")).Click(); Assert.AreEqual(expectedLogBuilder.ToString(), driver.FindElement(By.Id("log")).Text); } } [Test] [IgnoreBrowser(Browser.Chrome, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.Edge, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.EdgeLegacy, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.Firefox, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.IE, "Driver checks for overlapping elements")] [IgnoreBrowser(Browser.Safari, "Driver checks for overlapping elements")] public void NativelyClickOverlappingElements() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } StringBuilder expectedLogBuilder = new StringBuilder(); expectedLogBuilder.AppendLine("Log:"); expectedLogBuilder.AppendLine("mousedown in over (handled by over)"); expectedLogBuilder.AppendLine("mousedown in over (handled by body)"); expectedLogBuilder.AppendLine("mouseup in over (handled by over)"); expectedLogBuilder.AppendLine("mouseup in over (handled by body)"); expectedLogBuilder.AppendLine("click in over (handled by over)"); expectedLogBuilder.Append("click in over (handled by body)"); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/overlapping_elements.html"); driver.FindElement(By.Id("under")).Click(); Assert.AreEqual(expectedLogBuilder.ToString(), driver.FindElement(By.Id("log")).Text); } [Test] public void ClickAnElementThatDisappear() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } StringBuilder expectedLogBuilder = new StringBuilder(); expectedLogBuilder.AppendLine("Log:"); expectedLogBuilder.AppendLine("mousedown in over (handled by over)"); expectedLogBuilder.AppendLine("mousedown in over (handled by body)"); expectedLogBuilder.AppendLine("mouseup in under (handled by under)"); expectedLogBuilder.Append("mouseup in under (handled by body)"); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/disappearing_element.html"); driver.FindElement(By.Id("over")).Click(); Assert.That(driver.FindElement(By.Id("log")).Text.StartsWith(expectedLogBuilder.ToString())); } private void AssertEventNotFired(string eventName) { IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.That(text, Does.Not.Contain(eventName)); } private void ClickOnElementWhichRecordsEvents(IWebDriver focusedDriver) { focusedDriver.FindElement(By.Id("plainButton")).Click(); } private void AssertEventFired(string eventName, IWebDriver focusedDriver) { IWebElement result = focusedDriver.FindElement(By.Id("result")); string text = result.Text; Assert.That(text, Does.Contain(eventName)); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** File: ObjRef.cs ** ** ** Purpose: Defines the marshaled object reference class and related ** classes ** ** ** ===========================================================*/ namespace System.Runtime.Remoting { using System; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Metadata; using System.Runtime.Serialization; using System.Reflection; using System.Security.Permissions; using Win32Native = Microsoft.Win32.Win32Native; using System.Runtime.ConstrainedExecution; using System.Globalization; //** Purpose: Interface for providing type information. Users can use this //** interface to provide custom type information which is carried //** along with the ObjRef. [System.Runtime.InteropServices.ComVisible(true)] public interface IRemotingTypeInfo { // Return the fully qualified type name String TypeName { [System.Security.SecurityCritical] // auto-generated_required get; [System.Security.SecurityCritical] // auto-generated_required set; } // Check whether the given type can be cast to the type this // interface represents [System.Security.SecurityCritical] // auto-generated_required bool CanCastTo(Type fromType, Object o); } //** Purpose: Interface for providing channel information. Users can use this //** interface to provide custom channel information which is carried //** along with the ObjRef. [System.Runtime.InteropServices.ComVisible(true)] public interface IChannelInfo { // Get/Set the channel data for each channel Object[] ChannelData { [System.Security.SecurityCritical] // auto-generated_required get; [System.Security.SecurityCritical] // auto-generated_required set; } } //** Purpose: Interface for providing envoy information. Users can use this //** interface to provide custom envoy information which is carried //** along with the ObjRef. [System.Runtime.InteropServices.ComVisible(true)] public interface IEnvoyInfo { // Get/Set the envoy sinks IMessageSink EnvoySinks { [System.Security.SecurityCritical] // auto-generated_required get; [System.Security.SecurityCritical] // auto-generated_required set; } } [Serializable] internal class TypeInfo : IRemotingTypeInfo { private String serverType; private String[] serverHierarchy; private String[] interfacesImplemented; // Return the fully qualified type name public virtual String TypeName { [System.Security.SecurityCritical] // auto-generated get { return serverType;} [System.Security.SecurityCritical] // auto-generated set { serverType = value;} } // Check whether the given type can be cast to the type this // interface represents [System.Security.SecurityCritical] // auto-generated public virtual bool CanCastTo(Type castType, Object o) { if (null != castType) { // check for System.Object and MBRO since those aren't included in the // heirarchy if ((castType == typeof(MarshalByRefObject)) || (castType == typeof(System.Object))) { return true; } else if (castType.IsInterface) { if (interfacesImplemented != null) return CanCastTo(castType, InterfacesImplemented); else return false; } else if (castType.IsMarshalByRef) { if (CompareTypes(castType, serverType)) return true; if ((serverHierarchy != null) && CanCastTo(castType, ServerHierarchy)) return true; } } return false; } [System.Security.SecurityCritical] // auto-generated internal static String GetQualifiedTypeName(RuntimeType type) { if (type == null) return null; return RemotingServices.GetDefaultQualifiedTypeName(type); } internal static bool ParseTypeAndAssembly(String typeAndAssembly, out String typeName, out String assemName) { if (typeAndAssembly == null) { typeName = null; assemName = null; return false; } int index = typeAndAssembly.IndexOf(','); if (index == -1) { typeName = typeAndAssembly; assemName = null; return true; } // type name is everything up to the first comma typeName = typeAndAssembly.Substring(0, index); // assembly name is the rest assemName = typeAndAssembly.Substring(index + 1).Trim(); return true; } // ParseTypeAndAssembly [System.Security.SecurityCritical] // auto-generated internal TypeInfo(RuntimeType typeOfObj) { ServerType = GetQualifiedTypeName(typeOfObj); // Compute the length of the server hierarchy RuntimeType currType = (RuntimeType)typeOfObj.BaseType; // typeOfObj is the root of all classes, but not included in the hierarachy. Message.DebugOut("RemotingServices::TypeInfo: Determining length of server heirarchy\n"); int hierarchyLen = 0; while ((currType != typeof(MarshalByRefObject)) && (currType != null)) { currType = (RuntimeType)currType.BaseType; hierarchyLen++; } // Allocate an array big enough to store the hierarchy Message.DebugOut("RemotingServices::TypeInfo: Determined length of server heirarchy\n"); String[] serverHierarchy = null; if (hierarchyLen > 0) { serverHierarchy = new String[hierarchyLen]; currType = (RuntimeType)typeOfObj.BaseType; for (int i = 0; i < hierarchyLen; i++) { serverHierarchy[i] = GetQualifiedTypeName(currType); currType = (RuntimeType)currType.BaseType; } } this.ServerHierarchy = serverHierarchy; Message.DebugOut("RemotingServices::TypeInfo: Getting implemented interfaces\n"); // Set the interfaces implemented Type[] interfaces = typeOfObj.GetInterfaces(); String[] interfaceNames = null; // If the requested type itself is an interface we should add that to the // interfaces list as well bool isInterface = typeOfObj.IsInterface; if (interfaces.Length > 0 || isInterface) { interfaceNames = new String[interfaces.Length + (isInterface ? 1 : 0)]; for (int i = 0; i < interfaces.Length; i++) { interfaceNames[i] = GetQualifiedTypeName((RuntimeType)interfaces[i]); } if (isInterface) interfaceNames[interfaceNames.Length - 1] = GetQualifiedTypeName(typeOfObj); } this.InterfacesImplemented = interfaceNames; } // TypeInfo internal String ServerType { get { return serverType; } set { serverType = value; } } private String[] ServerHierarchy { get { return serverHierarchy;} set { serverHierarchy = value;} } private String[] InterfacesImplemented { get { return interfacesImplemented;} set { interfacesImplemented = value;} } [System.Security.SecurityCritical] // auto-generated private bool CompareTypes(Type type1, String type2) { Type type = RemotingServices.InternalGetTypeFromQualifiedTypeName(type2); return type1 == type; } [System.Security.SecurityCritical] // auto-generated private bool CanCastTo(Type castType, String[] types) { bool fCastOK = false; // Run through the type names and see if there is a // matching type if (null != castType) { for (int i = 0; i < types.Length; i++) { if (CompareTypes(castType,types[i])) { fCastOK = true; break; } } } Message.DebugOut("CanCastTo returning " + fCastOK + " for type " + castType.FullName + "\n"); return fCastOK; } } [Serializable] internal class DynamicTypeInfo : TypeInfo { [System.Security.SecurityCritical] // auto-generated internal DynamicTypeInfo(RuntimeType typeOfObj) : base(typeOfObj) { } [System.Security.SecurityCritical] // auto-generated public override bool CanCastTo(Type castType, Object o) { // < return((MarshalByRefObject)o).IsInstanceOfType(castType); } } [Serializable] internal sealed class ChannelInfo : IChannelInfo { private Object[] channelData; [System.Security.SecurityCritical] // auto-generated internal ChannelInfo() { ChannelData = ChannelServices.CurrentChannelData; } public Object[] ChannelData { [System.Security.SecurityCritical] // auto-generated get { return channelData; } [System.Security.SecurityCritical] // auto-generated set { channelData = value; } } } [Serializable] internal sealed class EnvoyInfo : IEnvoyInfo { private IMessageSink envoySinks; [System.Security.SecurityCritical] // auto-generated internal static IEnvoyInfo CreateEnvoyInfo(ServerIdentity serverID) { IEnvoyInfo info = null; if (null != serverID) { // Set the envoy sink chain if (serverID.EnvoyChain == null) { // < serverID.RaceSetEnvoyChain( serverID.ServerContext.CreateEnvoyChain( serverID.TPOrObject)); } // Create an envoy info object only if necessary IMessageSink sink = serverID.EnvoyChain as EnvoyTerminatorSink; if(null == sink) { // The chain consists of more than a terminator sink // Go ahead and create an envoy info structure, otherwise // a null is returned and we recreate the terminator sink // on the other side, automatically. info = new EnvoyInfo(serverID.EnvoyChain); } } return info; } [System.Security.SecurityCritical] // auto-generated private EnvoyInfo(IMessageSink sinks) { BCLDebug.Assert(null != sinks, "null != sinks"); EnvoySinks = sinks; } public IMessageSink EnvoySinks { [System.Security.SecurityCritical] // auto-generated get { return envoySinks;} [System.Security.SecurityCritical] // auto-generated set { envoySinks = value;} } } [System.Security.SecurityCritical] // auto-generated_required [Serializable] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)] [System.Runtime.InteropServices.ComVisible(true)] public class ObjRef : IObjectReference, ISerializable { // This flag is used to distinguish between the case where // an actual object was marshaled as compared to the case // where someone wants to pass the ObjRef itself to a remote call internal const int FLG_MARSHALED_OBJECT = 0x00000001; // This flag is used to mark a wellknown objRef (i.e. result // of marshaling a proxy that was obtained through a Connect call) internal const int FLG_WELLKNOWN_OBJREF = 0x00000002; // This flag is used for a lightweight Object Reference. It is sent to those clients // which are not interested in receiving a full-fledged ObjRef. An example // of such a client will be a mobile device with hard memory and processing // constraints. // NOTE: In this case ALL the fields EXCEPT the uri/flags field are NULL. internal const int FLG_LITE_OBJREF = 0x00000004; internal const int FLG_PROXY_ATTRIBUTE = 0x00000008; // //If you change the fields here, you must all change them in //RemotingSurrogate::GetObjectData // internal String uri; internal IRemotingTypeInfo typeInfo; internal IEnvoyInfo envoyInfo; internal IChannelInfo channelInfo; internal int objrefFlags; internal GCHandle srvIdentity; internal int domainID; internal void SetServerIdentity(GCHandle hndSrvIdentity) { srvIdentity = hndSrvIdentity; } internal GCHandle GetServerIdentity() { return srvIdentity; } internal void SetDomainID(int id) { domainID = id; } internal int GetDomainID() { return domainID; } // Static fields private static Type orType = typeof(ObjRef); // shallow copy constructor used for smuggling. [System.Security.SecurityCritical] // auto-generated private ObjRef(ObjRef o) { BCLDebug.Assert(o.GetType() == typeof(ObjRef), "this should be just an ObjRef"); uri = o.uri; typeInfo = o.typeInfo; envoyInfo = o.envoyInfo; channelInfo = o.channelInfo; objrefFlags = o.objrefFlags; SetServerIdentity(o.GetServerIdentity()); SetDomainID(o.GetDomainID()); } // ObjRef [System.Security.SecurityCritical] // auto-generated public ObjRef(MarshalByRefObject o, Type requestedType) { bool fServer; if (o == null) { throw new ArgumentNullException("o"); } RuntimeType rt = requestedType as RuntimeType; if (requestedType != null && rt == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); Identity id = MarshalByRefObject.GetIdentity(o, out fServer); Init(o, id, rt); } [System.Security.SecurityCritical] // auto-generated protected ObjRef(SerializationInfo info, StreamingContext context) { String url = null; // an objref lite url bool bFoundFIsMarshalled = false; SerializationInfoEnumerator e = info.GetEnumerator(); while (e.MoveNext()) { if (e.Name.Equals("uri")) { uri = (String) e.Value; } else if (e.Name.Equals("typeInfo")) { typeInfo = (IRemotingTypeInfo) e.Value; } else if (e.Name.Equals("envoyInfo")) { envoyInfo = (IEnvoyInfo) e.Value; } else if (e.Name.Equals("channelInfo")) { channelInfo = (IChannelInfo) e.Value; } else if (e.Name.Equals("objrefFlags")) { Object o = e.Value; if(o.GetType() == typeof(String)) { objrefFlags = ((IConvertible)o).ToInt32(null); } else { objrefFlags = (int)o; } } else if (e.Name.Equals("fIsMarshalled")) { int value; Object o = e.Value; if(o.GetType() == typeof(String)) value = ((IConvertible)o).ToInt32(null); else value = (int)o; if (value == 0) bFoundFIsMarshalled = true; } else if (e.Name.Equals("url")) { url = (String)e.Value; } else if (e.Name.Equals("SrvIdentity")) { SetServerIdentity((GCHandle)e.Value); } else if (e.Name.Equals("DomainId")) { SetDomainID((int)e.Value); } } if (!bFoundFIsMarshalled) { // This ObjRef was not passed as a parameter, so we need to unmarshal it. objrefFlags |= FLG_MARSHALED_OBJECT; } else objrefFlags &= ~FLG_MARSHALED_OBJECT; // If only url is present, then it is an ObjRefLite. if (url != null) { uri = url; objrefFlags |= FLG_LITE_OBJREF; } } // ObjRef .ctor [System.Security.SecurityCritical] // auto-generated internal bool CanSmuggle() { // make sure this isn't a derived class or an ObjRefLite if ((this.GetType() != typeof(ObjRef)) || IsObjRefLite()) return false; Type typeOfTypeInfo = null; if (typeInfo != null) typeOfTypeInfo = typeInfo.GetType(); Type typeOfChannelInfo = null; if (channelInfo != null) typeOfChannelInfo = channelInfo.GetType(); if (((typeOfTypeInfo == null) || (typeOfTypeInfo == typeof(TypeInfo)) || (typeOfTypeInfo == typeof(DynamicTypeInfo))) && (envoyInfo == null) && ((typeOfChannelInfo == null) || (typeOfChannelInfo == typeof(ChannelInfo)))) { if (channelInfo != null) { foreach (Object channelData in channelInfo.ChannelData) { // Only consider CrossAppDomainData smuggleable. if (!(channelData is CrossAppDomainData)) { return false; } } } return true; } else { return false; } } // CanSmuggle [System.Security.SecurityCritical] // auto-generated internal ObjRef CreateSmuggleableCopy() { BCLDebug.Assert(CanSmuggle(), "Caller should have made sure that CanSmuggle() was true first."); return new ObjRef(this); } // CreateSmuggleableCopy [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { throw new ArgumentNullException("info"); } info.SetType(orType); if(!IsObjRefLite()) { info.AddValue("uri", uri, typeof(String)); info.AddValue("objrefFlags", (int) objrefFlags); info.AddValue("typeInfo", typeInfo, typeof(IRemotingTypeInfo)); info.AddValue("envoyInfo", envoyInfo, typeof(IEnvoyInfo)); info.AddValue("channelInfo", GetChannelInfoHelper(), typeof(IChannelInfo)); } else { info.AddValue("url", uri, typeof(String)); } } // GetObjectDataHelper // This method retrieves the channel info object to be serialized. // It does special checking to see if a channel url needs to be bashed // (currently used for switching "http://..." url to "https://...". [System.Security.SecurityCritical] // auto-generated private IChannelInfo GetChannelInfoHelper() { ChannelInfo oldChannelInfo = channelInfo as ChannelInfo; if (oldChannelInfo == null) return channelInfo; Object[] oldChannelData = oldChannelInfo.ChannelData; if (oldChannelData == null) return oldChannelInfo; // <STRIP>This will work for the IIS scenario since the machine name + application name // will differentiate the url. If we generalize this mechanism in the future, // we should only [....] the url if the ObjRef is from the current appdomain.</STRIP> String[] bashInfo = (String[])CallContext.GetData("__bashChannelUrl"); if (bashInfo == null) return oldChannelInfo; String urlToBash = bashInfo[0]; String replacementUrl = bashInfo[1]; // Copy channel info and go [....] urls. ChannelInfo newChInfo = new ChannelInfo(); newChInfo.ChannelData = new Object[oldChannelData.Length]; for (int co = 0; co < oldChannelData.Length; co++) { newChInfo.ChannelData[co] = oldChannelData[co]; // see if this is one of the ones that we need to [....] ChannelDataStore channelDataStore = newChInfo.ChannelData[co] as ChannelDataStore; if (channelDataStore != null) { String[] urls = channelDataStore.ChannelUris; if ((urls != null) && (urls.Length == 1) && urls[0].Equals(urlToBash)) { // We want to [....] just the url, so we do a shallow copy // and replace the url array with the replacementUrl. ChannelDataStore newChannelDataStore = channelDataStore.InternalShallowCopy(); newChannelDataStore.ChannelUris = new String[1]; newChannelDataStore.ChannelUris[0] = replacementUrl; newChInfo.ChannelData[co] = newChannelDataStore; } } } return newChInfo; } // GetChannelInfoHelper // Note: The uri will be either objURI (for normal marshals) or // it will be the URL if a wellknown object's proxy is marshaled // Basically we will take whatever the URI getter on Identity gives us public virtual String URI { get { return uri;} set { uri = value;} } public virtual IRemotingTypeInfo TypeInfo { get { return typeInfo;} set { typeInfo = value;} } public virtual IEnvoyInfo EnvoyInfo { get { return envoyInfo;} set { envoyInfo = value;} } public virtual IChannelInfo ChannelInfo { [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] get { return channelInfo;} set { channelInfo = value;} } // This is called when doing fix-ups during deserialization [System.Security.SecurityCritical] // auto-generated_required public virtual Object GetRealObject(StreamingContext context) { return GetRealObjectHelper(); } // This is the common helper called by serialization / smuggling [System.Security.SecurityCritical] // auto-generated internal Object GetRealObjectHelper() { // Check if we are a result of serialiazing an MBR object // or if someone wanted to pass an ObjRef itself if (!IsMarshaledObject()) { BCLDebug.Trace("REMOTE", "ObjRef.GetRealObject: Returning *this*\n"); return this; } else { // Check if this is a lightweight objref if(IsObjRefLite()) { BCLDebug.Assert(null != uri, "null != uri"); // transform the url, if this is a local object (we know it is local // if we find the current application id in the url) int index = uri.IndexOf(RemotingConfiguration.ApplicationId); // we need to be past 0, since we have to back up a space and pick up // a slash. if (index > 0) uri = uri.Substring(index - 1); } // In the general case, 'this' is the // objref of an activated object // It may also be a well known object ref ... which came by // because someone did a Connect(URL) and then passed the proxy // over to a remote method call. // The below call handles both cases. bool fRefine = !(GetType() == typeof(ObjRef)); Object ret = RemotingServices.Unmarshal(this, fRefine); // Check for COMObject & do some special custom marshaling ret = GetCustomMarshaledCOMObject(ret); return ret; } } [System.Security.SecurityCritical] // auto-generated private Object GetCustomMarshaledCOMObject(Object ret) { #if FEATURE_COMINTEROP // Some special work we need to do for __COMObject // (Note that we use typeInfo to detect this case instead of // calling GetType on 'ret' so as to not refine the proxy) DynamicTypeInfo dt = this.TypeInfo as DynamicTypeInfo; if (dt != null) { // This is a COMObject type ... we do the special work // only if it is from the same process but another appDomain // We rely on the x-appDomain channel data in the objRef // to provide us with the answers. Object ret1 = null; IntPtr pUnk = IntPtr.Zero; if (IsFromThisProcess() && !IsFromThisAppDomain()) { try { bool fIsURTAggregated; pUnk = ((__ComObject)ret).GetIUnknown(out fIsURTAggregated); if (pUnk != IntPtr.Zero && !fIsURTAggregated) { // The RCW for an IUnk is per-domain. This call // gets (or creates) the RCW for this pUnk for // the current domain. String srvTypeName = TypeInfo.TypeName; String typeName = null; String assemName = null; System.Runtime.Remoting.TypeInfo.ParseTypeAndAssembly(srvTypeName, out typeName, out assemName); BCLDebug.Assert((null != typeName) && (null != assemName), "non-null values expected"); Assembly asm = FormatterServices.LoadAssemblyFromStringNoThrow(assemName); if (asm==null) { BCLDebug.Trace("REMOTE", "ObjRef.GetCustomMarshaledCOMObject. AssemblyName is: ", assemName, " but we can't load it."); throw new RemotingException(Environment.GetResourceString("Serialization_AssemblyNotFound", assemName)); } Type serverType = asm.GetType(typeName, false, false); if (serverType != null && !serverType.IsVisible) serverType = null; BCLDebug.Assert(serverType!=null, "bad objRef!"); ret1 = InteropServices.Marshal.GetTypedObjectForIUnknown(pUnk, serverType); if (ret1 != null) { ret = ret1; } } } finally { if (pUnk != IntPtr.Zero) { InteropServices.Marshal.Release(pUnk); } } } } #endif // FEATURE_COMINTEROP return ret; } public ObjRef() { objrefFlags = 0x0; } internal bool IsMarshaledObject() { return (objrefFlags & FLG_MARSHALED_OBJECT) == FLG_MARSHALED_OBJECT; } internal void SetMarshaledObject() { objrefFlags |= FLG_MARSHALED_OBJECT; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal bool IsWellKnown() { return (objrefFlags & FLG_WELLKNOWN_OBJREF) == FLG_WELLKNOWN_OBJREF; } internal void SetWellKnown() { objrefFlags |= FLG_WELLKNOWN_OBJREF; } internal bool HasProxyAttribute() { return (objrefFlags & FLG_PROXY_ATTRIBUTE) == FLG_PROXY_ATTRIBUTE; } internal void SetHasProxyAttribute() { objrefFlags |= FLG_PROXY_ATTRIBUTE; } internal bool IsObjRefLite() { return (objrefFlags & FLG_LITE_OBJREF) == FLG_LITE_OBJREF; } internal void SetObjRefLite() { objrefFlags |= FLG_LITE_OBJREF; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private CrossAppDomainData GetAppDomainChannelData() { BCLDebug.Assert( ObjRef.IsWellFormed(this), "ObjRef.IsWellFormed()"); // Look at the ChannelData part to find CrossAppDomainData int i=0; CrossAppDomainData xadData = null; while (i<ChannelInfo.ChannelData.Length) { xadData = ChannelInfo.ChannelData[i] as CrossAppDomainData; if (null != xadData) { return xadData; } i++; } // AdData could be null for user-created objRefs. return null; } [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public bool IsFromThisProcess() { //Wellknown objects may or may not be in the same process //Hence return false; if (IsWellKnown()) return false; CrossAppDomainData xadData = GetAppDomainChannelData(); if (xadData != null) { return xadData.IsFromThisProcess(); } return false; } [System.Security.SecurityCritical] // auto-generated public bool IsFromThisAppDomain() { CrossAppDomainData xadData = GetAppDomainChannelData(); if (xadData != null) { return xadData.IsFromThisAppDomain(); } return false; } // returns the internal context ID for the server context if // it is from the same process && the appDomain of the server // is still valid. If the objRef is from this process, the domain // id found in the objref is always returned. [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal Int32 GetServerDomainId() { if (!IsFromThisProcess()) return 0; CrossAppDomainData xadData = GetAppDomainChannelData(); BCLDebug.Assert(xadData != null, "bad objRef?"); return xadData.DomainID; } [System.Security.SecurityCritical] // auto-generated internal IntPtr GetServerContext(out int domainId) { IntPtr contextId = IntPtr.Zero; domainId = 0; if (IsFromThisProcess()) { CrossAppDomainData xadData = GetAppDomainChannelData(); BCLDebug.Assert(xadData != null, "bad objRef?"); domainId = xadData.DomainID; if (AppDomain.IsDomainIdValid(xadData.DomainID)) { contextId = xadData.ContextID; } } return contextId; } // // [System.Security.SecurityCritical] // auto-generated internal void Init(Object o, Identity idObj, RuntimeType requestedType) { Message.DebugOut("RemotingServices::FillObjRef: IN"); BCLDebug.Assert(idObj != null,"idObj != null"); // Set the URI of the object to be marshaled uri = idObj.URI; // Figure out the type MarshalByRefObject obj = idObj.TPOrObject; BCLDebug.Assert(null != obj, "Identity not setup correctly"); // Get the type of the object RuntimeType serverType = null; if(!RemotingServices.IsTransparentProxy(obj)) { serverType = (RuntimeType)obj.GetType(); } else { serverType = (RuntimeType)RemotingServices.GetRealProxy(obj).GetProxiedType(); } RuntimeType typeOfObj = (null == requestedType ? serverType : requestedType); // Make sure that the server and requested types are compatible // (except for objects that implement IMessageSink, since we // just hand off the message instead of invoking the proxy) if ((null != requestedType) && !requestedType.IsAssignableFrom(serverType) && (!typeof(IMessageSink).IsAssignableFrom(serverType))) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Remoting_InvalidRequestedType"), requestedType.ToString())); ; } #if FEATURE_COMINTEROP // Create the type info if(serverType.IsCOMObject) { // __ComObjects need dynamic TypeInfo DynamicTypeInfo dt = new DynamicTypeInfo(typeOfObj); TypeInfo = (IRemotingTypeInfo) dt; } else #endif // FEATURE_COMINTEROP { RemotingTypeCachedData cache = (RemotingTypeCachedData) InternalRemotingServices.GetReflectionCachedData(typeOfObj); TypeInfo = (IRemotingTypeInfo)cache.TypeInfo; } if (!idObj.IsWellKnown()) { // Create the envoy info EnvoyInfo = System.Runtime.Remoting.EnvoyInfo.CreateEnvoyInfo(idObj as ServerIdentity); // Create the channel info IChannelInfo chan = (IChannelInfo)new ChannelInfo(); // Make sure the channelInfo only has x-appdomain data since the objref is agile while other // channelData might not be and regardless this data is useless for an appdomain proxy if (o is AppDomain){ Object[] channelData = chan.ChannelData; int channelDataLength = channelData.Length; Object[] newChannelData = new Object[channelDataLength]; // Clone the data so that we dont [....] the current appdomain data which is stored // as a static Array.Copy(channelData, newChannelData, channelDataLength); for (int i = 0; i < channelDataLength; i++) { if (!(newChannelData[i] is CrossAppDomainData)) newChannelData[i] = null; } chan.ChannelData = newChannelData; } ChannelInfo = chan; if (serverType.HasProxyAttribute) { SetHasProxyAttribute(); } } else { SetWellKnown(); } // See if we should and can use a url obj ref? if (ShouldUseUrlObjRef()) { if (IsWellKnown()) { // full uri already supplied. SetObjRefLite(); } else { String httpUri = ChannelServices.FindFirstHttpUrlForObject(URI); if (httpUri != null) { URI = httpUri; SetObjRefLite(); } } } } // Init // determines if a particular type should use a url obj ref internal static bool ShouldUseUrlObjRef() { return RemotingConfigHandler.UrlObjRefMode; } // ShouldUseUrlObjRef // Check whether the objref is well formed [System.Security.SecurityCritical] // auto-generated internal static bool IsWellFormed(ObjRef objectRef) { // We skip the wellformed check for wellKnown, // objref-lite and custom objrefs bool wellFormed = true; if ((null == objectRef) || (null == objectRef.URI) || (!(objectRef.IsWellKnown() || objectRef.IsObjRefLite() || objectRef.GetType() != orType) && (null == objectRef.ChannelInfo))) { wellFormed = false; } return wellFormed; } } // ObjRef }
/* * 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 Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid { public class LocalGridServicesConnector : ISharedRegionModule, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static LocalGridServicesConnector m_MainInstance; private IGridService m_GridService; private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>(); private bool m_Enabled = false; public LocalGridServicesConnector() { } public LocalGridServicesConnector(IConfigSource source) { m_log.Debug("[LOCAL GRID CONNECTOR]: LocalGridServicesConnector instantiated"); m_MainInstance = this; InitialiseService(source); } #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalGridServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("GridServices", ""); if (name == Name) { InitialiseService(source); m_MainInstance = this; m_Enabled = true; m_log.Info("[LOCAL GRID CONNECTOR]: Local grid connector enabled"); } } } private void InitialiseService(IConfigSource source) { IConfig assetConfig = source.Configs["GridService"]; if (assetConfig == null) { m_log.Error("[LOCAL GRID CONNECTOR]: GridService missing from OpenSim.ini"); return; } string serviceDll = assetConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL GRID CONNECTOR]: No LocalServiceModule named in section GridService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IGridService>(serviceDll, args); if (m_GridService == null) { m_log.Error("[LOCAL GRID CONNECTOR]: Can't load grid service"); return; } } public void PostInitialise() { if (m_MainInstance == this) { MainConsole.Instance.Commands.AddCommand("LocalGridConnector", false, "show neighbours", "show neighbours", "Shows the local regions' neighbours", NeighboursCommand); } } public void Close() { } public void AddRegion(Scene scene) { if (m_Enabled) scene.RegisterModuleInterface<IGridService>(this); if (m_MainInstance == this) { if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID)) m_log.ErrorFormat("[LOCAL GRID CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!"); else m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene)); } } public void RemoveRegion(Scene scene) { if (m_MainInstance == this) { m_LocalCache[scene.RegionInfo.RegionID].Clear(); m_LocalCache.Remove(scene.RegionInfo.RegionID); } } public void RegionLoaded(Scene scene) { } #endregion #region IGridService public bool RegisterRegion(UUID scopeID, GridRegion regionInfo) { return m_GridService.RegisterRegion(scopeID, regionInfo); } public bool DeregisterRegion(UUID regionID) { return m_GridService.DeregisterRegion(regionID); } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { if (m_LocalCache.ContainsKey(regionID)) { List<GridRegion> neighbours = m_LocalCache[regionID].GetNeighbours(); if (neighbours.Count == 0) // try the DB neighbours = m_GridService.GetNeighbours(scopeID, regionID); return neighbours; } else { m_log.WarnFormat("[LOCAL GRID CONNECTOR]: GetNeighbours: Requested region {0} is not on this sim", regionID); return new List<GridRegion>(); } // Don't go to the DB //return m_GridService.GetNeighbours(scopeID, regionID); } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { return m_GridService.GetRegionByUUID(scopeID, regionID); } public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { GridRegion region = null; // First see if it's a neighbour, even if it isn't on this sim. // Neighbour data is cached in memory, so this is fast foreach (RegionCache rcache in m_LocalCache.Values) { region = rcache.GetRegionByPosition(x, y); if (region != null) { return region; } } // Then try on this sim (may be a lookup in DB if this is using MySql). return m_GridService.GetRegionByPosition(scopeID, x, y); } public GridRegion GetRegionByName(UUID scopeID, string regionName) { return m_GridService.GetRegionByName(scopeID, regionName); } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { return m_GridService.GetRegionsByName(scopeID, name, maxNumber); } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); } #endregion public void NeighboursCommand(string module, string[] cmdparams) { foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache) { m_log.InfoFormat("*** Neighbours of {0} {1} ***", kvp.Key, kvp.Value.RegionName); List<GridRegion> regions = kvp.Value.GetNeighbours(); foreach (GridRegion r in regions) m_log.InfoFormat(" {0} @ {1}={2}", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration namespace _4PosBackOffice.NET { static class SaveArrayAsCSVFile { //Double public static string[,] dChrom; // SaveAsCSV saves an array as csv file. Choosing a delimiter different as a comma, is optional. // // Syntax: // SaveAsCSV dMyArray, sMyFileName, [sMyDelimiter] // // Examples: // SaveAsCSV dChrom, app.path & "\Demo.csv" --> comma as delimiter // SaveAsCSV dChrom, app.path & "\Demo.csv", ";" --> semicolon as delimiter // // written by Baber Abbass // baber_abbass@hotmail.com public static void SaveAsCSV(ref string[,] MyArray, ref string sFileName, ref string sDelimiter = ",") { int n = 0; //counter int M = 0; //counter string sCSV = null; //csv string to print // ERROR: Not supported in C#: OnErrorStatement //check extension and correct if needed if (Strings.InStr(sFileName, ".csv") == 0) { sFileName = sFileName + ".csv"; } else { while ((Strings.Len(sFileName) - Strings.InStr(sFileName, ".csv")) > 3) { sFileName = Strings.Left(sFileName, Strings.Len(sFileName) - 1); } } //If MultiDimensional(MyArray) = False Then '1 dimension //save the file // FileOpen(7, sFileName, OpenMode.Output) // For n = 0 To UBound(MyArray, 1) //PrintLine(7, MyArray(n, 0)) 'Format( MyArray(n, 0), "0.000000E+00") //Next n //FileClose(7) // Else 'more dimensional //save the file FileSystem.FileOpen(7, sFileName, OpenMode.Output); for (n = 0; n <= Information.UBound(MyArray, 1); n++) { sCSV = ""; for (M = 0; M <= Information.UBound(MyArray, 2); M++) { sCSV = sCSV + MyArray[n, M] + sDelimiter; //Format(MyArray(n, M), "0.000000E+00") & sDelimiter } sCSV = Strings.Left(sCSV, Strings.Len(sCSV) - 1); //remove last Delimiter FileSystem.PrintLine(7, sCSV); } FileSystem.FileClose(7); //End If return; ErrHandler_SaveAsCSV: FileSystem.FileClose(7); } // Function ImportCSVinArray imports a csv file into an array. Choosing a delimiter different as a comma, is optional. // // Syntax: // dMyArray() = ImportCSVinArray (sMyFileName, [sMyDelimiter]) // // Examples: // dChrom() = ImportCSVinArray("c:\temp\demo.csv") --> comma as delimiter // dChrom() = ImportCSVinArray("c:\temp\demo.csv",";") --> semicolon as delimiter // // // written by Baber Abbass // baber_abbass@hotmail.com public static double[] ImportCSVinArray(ref string sFileName, ref string sDelimiter = ",") { double[] functionReturnValue = null; double[] MyArray = null; double[,] MyOArray = null; string[] sSplit = null; string sLine = null; int lRows = 0; int lColumns = 0; int lCounter = 0; // ERROR: Not supported in C#: OnErrorStatement //UPGRADE_WARNING: Dir has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' if (!string.IsNullOrEmpty(FileSystem.Dir(sFileName))) { //determine number of rows and columns needed lRows = 0; lColumns = 0; FileSystem.FileOpen(7, sFileName, OpenMode.Input); while (!(FileSystem.EOF(7))) { sLine = FileSystem.LineInput(7); if (Strings.Len(sLine) > 0) { sSplit = Strings.Split(sLine, sDelimiter); if (Information.UBound(sSplit) > lColumns) lColumns = Information.UBound(sSplit); lRows = lRows + 1; } } FileSystem.FileClose(7); //fill array //no csv file! if (lColumns == 1) { MyArray = new double[lRows]; FileSystem.FileOpen(7, sFileName, OpenMode.Input); lRows = 0; while (!(FileSystem.EOF(7))) { sLine = FileSystem.LineInput(7); if (Strings.Len(sLine) > 0) { MyArray[lRows] = Conversion.Val(sLine); lRows = lRows + 1; } } FileSystem.FileClose(7); //multidimensional csv file } else if (lColumns > 1) { MyOArray = new double[lRows, lColumns + 1]; FileSystem.FileOpen(7, sFileName, OpenMode.Input); lRows = 0; while (!(FileSystem.EOF(7))) { sLine = FileSystem.LineInput(7); if (Strings.Len(sLine) > 0) { sSplit = Strings.Split(sLine, sDelimiter); for (lCounter = 0; lCounter <= Information.UBound(sSplit); lCounter++) { MyOArray[lRows, lCounter] = Conversion.Val(sSplit[lCounter]); } lRows = lRows + 1; } } FileSystem.FileClose(7); } //return function functionReturnValue = MyArray.Clone(); } return functionReturnValue; ErrHandler_ImportCSVinArray: return functionReturnValue; } private static bool MultiDimensional(ref string[] CheckArray) { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement if (Information.UBound(CheckArray, 2) > 0) { functionReturnValue = true; //more than 1 dimension } return functionReturnValue; ErrHandler_MultiDimensional: functionReturnValue = false; return functionReturnValue; //1 dimension } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gciv = Google.Cloud.Iam.V1; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.ResourceManager.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTagKeysClientTest { [xunit::FactAttribute] public void GetTagKeyRequestObject() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagKeyRequest request = new GetTagKeyRequest { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), }; TagKey expectedResponse = new TagKey { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); TagKey response = client.GetTagKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagKeyRequestObjectAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagKeyRequest request = new GetTagKeyRequest { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), }; TagKey expectedResponse = new TagKey { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); TagKey responseCallSettings = await client.GetTagKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagKey responseCancellationToken = await client.GetTagKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTagKey() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagKeyRequest request = new GetTagKeyRequest { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), }; TagKey expectedResponse = new TagKey { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); TagKey response = client.GetTagKey(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagKeyAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagKeyRequest request = new GetTagKeyRequest { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), }; TagKey expectedResponse = new TagKey { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); TagKey responseCallSettings = await client.GetTagKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagKey responseCancellationToken = await client.GetTagKeyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTagKeyResourceNames() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagKeyRequest request = new GetTagKeyRequest { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), }; TagKey expectedResponse = new TagKey { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); TagKey response = client.GetTagKey(request.TagKeyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagKeyResourceNamesAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagKeyRequest request = new GetTagKeyRequest { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), }; TagKey expectedResponse = new TagKey { TagKeyName = TagKeyName.FromTagKey("[TAG_KEY]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); TagKey responseCallSettings = await client.GetTagKeyAsync(request.TagKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagKey responseCancellationToken = await client.GetTagKeyAsync(request.TagKeyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyResourceNames() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyResourceNamesAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyResourceNames() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyResourceNamesAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsResourceNames() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsResourceNamesAsync() { moq::Mock<TagKeys.TagKeysClient> mockGrpcClient = new moq::Mock<TagKeys.TagKeysClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagKeysClient client = new TagKeysClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Concurrent; using System.IO; using System.Reflection; using System.Resources; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.Localization { /// <summary> /// An <see cref="IStringLocalizerFactory"/> that creates instances of <see cref="ResourceManagerStringLocalizer"/>. /// </summary> /// <remarks> /// <see cref="ResourceManagerStringLocalizerFactory"/> offers multiple ways to set the relative path of /// resources to be used. They are, in order of precedence: /// <see cref="ResourceLocationAttribute"/> -> <see cref="LocalizationOptions.ResourcesPath"/> -> the project root. /// </remarks> public class ResourceManagerStringLocalizerFactory : IStringLocalizerFactory { private readonly IResourceNamesCache _resourceNamesCache = new ResourceNamesCache(); private readonly ConcurrentDictionary<string, ResourceManagerStringLocalizer> _localizerCache = new ConcurrentDictionary<string, ResourceManagerStringLocalizer>(); private readonly string _resourcesRelativePath; private readonly ILoggerFactory _loggerFactory; /// <summary> /// Creates a new <see cref="ResourceManagerStringLocalizer"/>. /// </summary> /// <param name="localizationOptions">The <see cref="IOptions{LocalizationOptions}"/>.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> public ResourceManagerStringLocalizerFactory( IOptions<LocalizationOptions> localizationOptions, ILoggerFactory loggerFactory) { if (localizationOptions == null) { throw new ArgumentNullException(nameof(localizationOptions)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _resourcesRelativePath = localizationOptions.Value.ResourcesPath ?? string.Empty; _loggerFactory = loggerFactory; if (!string.IsNullOrEmpty(_resourcesRelativePath)) { _resourcesRelativePath = _resourcesRelativePath.Replace(Path.AltDirectorySeparatorChar, '.') .Replace(Path.DirectorySeparatorChar, '.') + "."; } } /// <summary> /// Gets the resource prefix used to look up the resource. /// </summary> /// <param name="typeInfo">The type of the resource to be looked up.</param> /// <returns>The prefix for resource lookup.</returns> protected virtual string GetResourcePrefix(TypeInfo typeInfo) { if (typeInfo == null) { throw new ArgumentNullException(nameof(typeInfo)); } return GetResourcePrefix(typeInfo, GetRootNamespace(typeInfo.Assembly), GetResourcePath(typeInfo.Assembly)); } /// <summary> /// Gets the resource prefix used to look up the resource. /// </summary> /// <param name="typeInfo">The type of the resource to be looked up.</param> /// <param name="baseNamespace">The base namespace of the application.</param> /// <param name="resourcesRelativePath">The folder containing all resources.</param> /// <returns>The prefix for resource lookup.</returns> /// <remarks> /// For the type "Sample.Controllers.Home" if there's a resourceRelativePath return /// "Sample.Resourcepath.Controllers.Home" if there isn't one then it would return "Sample.Controllers.Home". /// </remarks> protected virtual string GetResourcePrefix(TypeInfo typeInfo, string? baseNamespace, string? resourcesRelativePath) { if (typeInfo == null) { throw new ArgumentNullException(nameof(typeInfo)); } if (string.IsNullOrEmpty(baseNamespace)) { throw new ArgumentNullException(nameof(baseNamespace)); } if (string.IsNullOrEmpty(typeInfo.FullName)) { throw new ArgumentException(Resources.FormatLocalization_TypeMustHaveTypeName(typeInfo)); } if (string.IsNullOrEmpty(resourcesRelativePath)) { return typeInfo.FullName; } else { // This expectation is defined by dotnet's automatic resource storage. // We have to conform to "{RootNamespace}.{ResourceLocation}.{FullTypeName - RootNamespace}". return baseNamespace + "." + resourcesRelativePath + TrimPrefix(typeInfo.FullName, baseNamespace + "."); } } /// <summary> /// Gets the resource prefix used to look up the resource. /// </summary> /// <param name="baseResourceName">The name of the resource to be looked up</param> /// <param name="baseNamespace">The base namespace of the application.</param> /// <returns>The prefix for resource lookup.</returns> protected virtual string GetResourcePrefix(string baseResourceName, string baseNamespace) { if (string.IsNullOrEmpty(baseResourceName)) { throw new ArgumentNullException(nameof(baseResourceName)); } if (string.IsNullOrEmpty(baseNamespace)) { throw new ArgumentNullException(nameof(baseNamespace)); } var assemblyName = new AssemblyName(baseNamespace); var assembly = Assembly.Load(assemblyName); var rootNamespace = GetRootNamespace(assembly); var resourceLocation = GetResourcePath(assembly); var locationPath = rootNamespace + "." + resourceLocation; baseResourceName = locationPath + TrimPrefix(baseResourceName, baseNamespace + "."); return baseResourceName; } /// <summary> /// Creates a <see cref="ResourceManagerStringLocalizer"/> using the <see cref="Assembly"/> and /// <see cref="Type.FullName"/> of the specified <see cref="Type"/>. /// </summary> /// <param name="resourceSource">The <see cref="Type"/>.</param> /// <returns>The <see cref="ResourceManagerStringLocalizer"/>.</returns> public IStringLocalizer Create(Type resourceSource) { if (resourceSource == null) { throw new ArgumentNullException(nameof(resourceSource)); } var typeInfo = resourceSource.GetTypeInfo(); var baseName = GetResourcePrefix(typeInfo); var assembly = typeInfo.Assembly; return _localizerCache.GetOrAdd(baseName, _ => CreateResourceManagerStringLocalizer(assembly, baseName)); } /// <summary> /// Creates a <see cref="ResourceManagerStringLocalizer"/>. /// </summary> /// <param name="baseName">The base name of the resource to load strings from.</param> /// <param name="location">The location to load resources from.</param> /// <returns>The <see cref="ResourceManagerStringLocalizer"/>.</returns> public IStringLocalizer Create(string baseName, string location) { if (baseName == null) { throw new ArgumentNullException(nameof(baseName)); } if (location == null) { throw new ArgumentNullException(nameof(location)); } return _localizerCache.GetOrAdd($"B={baseName},L={location}", _ => { var assemblyName = new AssemblyName(location); var assembly = Assembly.Load(assemblyName); baseName = GetResourcePrefix(baseName, location); return CreateResourceManagerStringLocalizer(assembly, baseName); }); } /// <summary>Creates a <see cref="ResourceManagerStringLocalizer"/> for the given input.</summary> /// <param name="assembly">The assembly to create a <see cref="ResourceManagerStringLocalizer"/> for.</param> /// <param name="baseName">The base name of the resource to search for.</param> /// <returns>A <see cref="ResourceManagerStringLocalizer"/> for the given <paramref name="assembly"/> and <paramref name="baseName"/>.</returns> /// <remarks>This method is virtual for testing purposes only.</remarks> protected virtual ResourceManagerStringLocalizer CreateResourceManagerStringLocalizer( Assembly assembly, string baseName) { return new ResourceManagerStringLocalizer( new ResourceManager(baseName, assembly), assembly, baseName, _resourceNamesCache, _loggerFactory.CreateLogger<ResourceManagerStringLocalizer>()); } /// <summary> /// Gets the resource prefix used to look up the resource. /// </summary> /// <param name="location">The general location of the resource.</param> /// <param name="baseName">The base name of the resource.</param> /// <param name="resourceLocation">The location of the resource within <paramref name="location"/>.</param> /// <returns>The resource prefix used to look up the resource.</returns> protected virtual string GetResourcePrefix(string location, string baseName, string resourceLocation) { // Re-root the base name if a resources path is set return location + "." + resourceLocation + TrimPrefix(baseName, location + "."); } /// <summary>Gets a <see cref="ResourceLocationAttribute"/> from the provided <see cref="Assembly"/>.</summary> /// <param name="assembly">The assembly to get a <see cref="ResourceLocationAttribute"/> from.</param> /// <returns>The <see cref="ResourceLocationAttribute"/> associated with the given <see cref="Assembly"/>.</returns> /// <remarks>This method is protected and virtual for testing purposes only.</remarks> protected virtual ResourceLocationAttribute? GetResourceLocationAttribute(Assembly assembly) { return assembly.GetCustomAttribute<ResourceLocationAttribute>(); } /// <summary>Gets a <see cref="RootNamespaceAttribute"/> from the provided <see cref="Assembly"/>.</summary> /// <param name="assembly">The assembly to get a <see cref="RootNamespaceAttribute"/> from.</param> /// <returns>The <see cref="RootNamespaceAttribute"/> associated with the given <see cref="Assembly"/>.</returns> /// <remarks>This method is protected and virtual for testing purposes only.</remarks> protected virtual RootNamespaceAttribute? GetRootNamespaceAttribute(Assembly assembly) { return assembly.GetCustomAttribute<RootNamespaceAttribute>(); } private string? GetRootNamespace(Assembly assembly) { var rootNamespaceAttribute = GetRootNamespaceAttribute(assembly); if (rootNamespaceAttribute != null) { return rootNamespaceAttribute.RootNamespace; } return assembly.GetName().Name; } private string GetResourcePath(Assembly assembly) { var resourceLocationAttribute = GetResourceLocationAttribute(assembly); // If we don't have an attribute assume all assemblies use the same resource location. var resourceLocation = resourceLocationAttribute == null ? _resourcesRelativePath : resourceLocationAttribute.ResourceLocation + "."; resourceLocation = resourceLocation .Replace(Path.DirectorySeparatorChar, '.') .Replace(Path.AltDirectorySeparatorChar, '.'); return resourceLocation; } private static string? TrimPrefix(string name, string prefix) { if (name.StartsWith(prefix, StringComparison.Ordinal)) { return name.Substring(prefix.Length); } return name; } } }
//------------------------------------------------------------------------------ // Symbooglix // // // Copyright 2014-2017 Daniel Liew // // This file is licensed under the MIT license. // See LICENSE.txt for details. //------------------------------------------------------------------------------ using System; using Symbooglix; using System.Linq; using System.Collections.Generic; using CommandLine; using CommandLine.Text; using System.Text; using Microsoft.Boogie; using System.Diagnostics; using Transform = Symbooglix.Transform; using System.IO; namespace SymbooglixPassRunner { class MainClass { static PassBuilder PBuilder = new PassBuilder(); public class CmdLineOpts { [Option("emit-before", DefaultValue = false, HelpText = "Emit Boogie program to stdout before running each pass")] public bool EmitProgramBefore { get; set; } [Option("emit-after", DefaultValue = false, HelpText = "Emit Boogie program to stdout before running each pass")] public bool EmitProgramAfter { get; set; } [OptionList('e', "entry-points", Separator = ',', DefaultValue = null, HelpText = "Comma seperated list of implementations to use as entry points for execution.")] public List<string> EntryPoints { get; set; } // FIXME: Urgh... how do you set the default value of the list? [OptionList('p', "passes", Separator = ',', DefaultValue = null, HelpText = "Comma seperated list of passes to run. Executed in left to right order")] public List<string> PassNames { get; set; } [Option('o', DefaultValue="", HelpText="Output path for Boogie program")] public string OutputPath { get; set; } [Option("use-modset-transform", DefaultValue = 1, HelpText = "Run the modset analysis to fix incorrect modsets before type checking")] public int useModSetTransform { get; set; } // Positional args [ValueOption(0)] public string boogieProgramPath { get; set; } // For printing parser error messages [ParserState] public IParserState LastParserState { get; set; } [HelpOption] public string GetUsage() { var help = new HelpText { Heading = new HeadingInfo("Symbooglix Pass Runner", ""), Copyright = new CopyrightInfo("Dan Liew", 2015), AdditionalNewLineAfterOption = true, AddDashesToOption = true }; // FIXME: Printing parser errors is totally broken. if (LastParserState == null) Console.WriteLine("FIXME: CommandLine parser did not give state"); if (LastParserState != null && LastParserState.Errors.Any()) { var errors = help.RenderParsingErrorsText(this, 2); help.AddPostOptionsLine("Error: Failed to parse command line options"); help.AddPostOptionsLine(errors); } else { help.AddPreOptionsLine("Usage: spr [options] <boogie program>"); help.AddOptions(this); help.AddPostOptionsLine(""); help.AddPostOptionsLine("Passes:"); foreach (var passName in PBuilder.GetPassNames().OrderBy(s => s)) { // FIXME: Show description too help.AddPostOptionsLine(passName); } help.AddPostOptionsLine(""); help.AddPostOptionsLine(""); } return help; } } public enum ExitCode { SUCCESS, COMMAND_LINE_ERROR, PARSE_ERROR, RESOLVE_ERROR, TYPECHECK_ERROR } private static void ExitWith(ExitCode exitCode) { Console.Error.WriteLine("Exiting with {0}", exitCode.ToString()); System.Environment.Exit( (int) exitCode); throw new InvalidOperationException("Unreachable"); } public static int Main(string[] args) { // Debug log output goes to standard error. Debug.Listeners.Add(new ExceptionThrowingTextWritierTraceListener(Console.Error)); // FIXME: Urgh... we are forced to use Boogie's command line // parser becaue the Boogie program resolver/type checker // is dependent on the parser being used...EURGH! CommandLineOptions.Install(new Microsoft.Boogie.CommandLineOptions()); var options = new CmdLineOpts(); if (! CommandLine.Parser.Default.ParseArguments(args, options)) { Console.Error.WriteLine("Failed to parse args"); ExitWith(ExitCode.COMMAND_LINE_ERROR); } if (options.boogieProgramPath == null) { Console.Error.WriteLine("A boogie program must be specified. See --help"); ExitWith(ExitCode.COMMAND_LINE_ERROR); } if (!File.Exists(options.boogieProgramPath)) { Console.WriteLine("Boogie program \"" + options.boogieProgramPath + "\" does not exist"); ExitWith(ExitCode.COMMAND_LINE_ERROR); } // Load Boogie program Program program = null; int errors = Microsoft.Boogie.Parser.Parse(options.boogieProgramPath, /*defines=*/ new List<string>(), out program); if (errors != 0) { Console.WriteLine("Failed to parse"); ExitWith(ExitCode.PARSE_ERROR); } errors = program.Resolve(); if (errors != 0) { Console.WriteLine("Failed to resolve."); ExitWith(ExitCode.RESOLVE_ERROR); } if (options.useModSetTransform > 0) { // This is useful for Boogie Programs produced by the GPUVerify tool that // have had instrumentation added that invalidates the modset attached to // procedures. By running the analysis we may modify the modsets attached to // procedures in the program to be correct so that Boogie's Type checker doesn't // produce an error. var modsetAnalyser = new ModSetCollector(); modsetAnalyser.DoModSetAnalysis(program); } errors = program.Typecheck(); if (errors != 0) { Console.WriteLine("Failed to Typecheck."); ExitWith(ExitCode.TYPECHECK_ERROR); } // Start building passes var PM = new Symbooglix.Transform.PassManager(); if (options.PassNames == null) { Console.Error.WriteLine("At least one pass must be specified"); ExitWith(ExitCode.COMMAND_LINE_ERROR); } // Add the requested passes to the PassManager foreach (var passName in options.PassNames) { try { var newPass = PBuilder.GetPass(passName, options); PM.Add(newPass); } catch (NonExistantPassException) { Console.Error.WriteLine("Pass {0} does not exist", passName); } } PM.BeforePassRun += delegate(Object passManager, Transform.PassManager.PassManagerEventArgs eventArgs) { Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("Running pass " + eventArgs.ThePass.GetName()); Console.ResetColor(); if (options.EmitProgramBefore) { Console.Error.WriteLine("**** Program before pass:"); Symbooglix.Util.ProgramPrinter.Print(eventArgs.TheProgram, Console.Error, /*pretty=*/true, Symbooglix.Util.ProgramPrinter.PrintType.UNSTRUCTURED_ONLY); Console.Error.WriteLine("**** END Program before pass"); } }; PM.AfterPassRun += delegate(Object passManager, Transform.PassManager.PassManagerEventArgs eventArgs) { Console.ForegroundColor = ConsoleColor.Green; Console.Error.WriteLine("Finished running pass " + eventArgs.ThePass.GetName()); Console.ResetColor(); if (options.EmitProgramAfter) { Console.Error.WriteLine("**** Program after pass:"); Symbooglix.Util.ProgramPrinter.Print(eventArgs.TheProgram, Console.Error, /*pretty=*/true, Symbooglix.Util.ProgramPrinter.PrintType.UNSTRUCTURED_ONLY); Console.Error.WriteLine("**** END Program after pass:"); } }; // Run pass manager PM.Run(program); // Emit the program if (options.OutputPath.Length == 0) { // Write to stdout Console.Error.WriteLine("Writing output to stdout"); Symbooglix.Util.ProgramPrinter.Print(program, Console.Out, /*pretty=*/true, Symbooglix.Util.ProgramPrinter.PrintType.UNSTRUCTURED_ONLY); } else { // Write to file Console.Error.WriteLine("Writing output to {0}", options.OutputPath); using (var TW = new StreamWriter(options.OutputPath)) { Symbooglix.Util.ProgramPrinter.Print(program, TW, /*pretty=*/true, Symbooglix.Util.ProgramPrinter.PrintType.UNSTRUCTURED_ONLY); } } return (int)ExitCode.SUCCESS; } internal class PassBuilder { private Dictionary<string, System.Type> Map = new Dictionary<string, System.Type>(); public PassBuilder() { var types = GetPassTypes(); foreach (var type in types) { Map.Add(StripSymbooglixPrefix(type.ToString()), type); } } public Symbooglix.Transform.IPass GetPass(string name, CmdLineOpts cmdLine) { // Passes without default constructors if (name == StripSymbooglixPrefix(typeof(Transform.AxiomAndEntryRequiresCheckTransformPass).ToString())) { // This pass needs to know the entry points if (cmdLine.EntryPoints == null) { Console.Error.WriteLine("Entry points must be specified to use AxiomAndEntryRequiresCheckTransformPass"); ExitWith(ExitCode.COMMAND_LINE_ERROR); } Predicate<Implementation> isEntryPoint = delegate(Implementation impl) { foreach (var entryPointName in cmdLine.EntryPoints) { if (impl.Name == entryPointName) return true; } return false; }; return new Transform.AxiomAndEntryRequiresCheckTransformPass(isEntryPoint); } // Passes with default constructors try { var passType = Map[name]; return (Symbooglix.Transform.IPass) Activator.CreateInstance(passType); } catch (KeyNotFoundException) { throw new NonExistantPassException(); } } public IEnumerable<string> GetPassNames() { return Map.Keys; } public static string StripSymbooglixPrefix(string passName) { int dotPosition = passName.IndexOf('.'); if (dotPosition == -1) throw new Exception("Passname is wrong"); return passName.Substring(dotPosition +1); } public static IList<System.Type> GetPassTypes() { var passInterfaceType = typeof(Symbooglix.Transform.IPass); var typeList = new List<System.Type>(); var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => passInterfaceType.IsAssignableFrom(p)); foreach (var t in types) { if (t == passInterfaceType) continue; typeList.Add(t); } return typeList; } } class NonExistantPassException : Exception { public NonExistantPassException() : base() { } } } }
// 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.Text; using Xunit; namespace System.Linq.Expressions.Tests { public class LoopTests { private static class Unreadable<T> { public static T WriteOnly { set { } } } private class IntegralException : Exception { public IntegralException(int number) { Number = number; } public int Number { get; } } [Fact] public void NullBody() { AssertExtensions.Throws<ArgumentNullException>("body", () => Expression.Loop(null)); AssertExtensions.Throws<ArgumentNullException>("body", () => Expression.Loop(null, null)); AssertExtensions.Throws<ArgumentNullException>("body", () => Expression.Loop(null, null, null)); } [Fact] public void UnreadableBody() { Expression body = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly)); AssertExtensions.Throws<ArgumentException>("body", () => Expression.Loop(body)); AssertExtensions.Throws<ArgumentException>("body", () => Expression.Loop(body, null)); AssertExtensions.Throws<ArgumentException>("body", () => Expression.Loop(body, null, null)); } [Fact] public void NonVoidContinue() { AssertExtensions.Throws<ArgumentException>("continue", () => Expression.Loop(Expression.Empty(), null, Expression.Label(typeof(int)))); } [Fact] public void TypeWithoutBreakIsVoid() { Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3)).Type); Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), null).Type); Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), null, null).Type); } [Fact] public void TypeIsBreaksType() { LabelTarget voidLabelTarget = Expression.Label(); Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), voidLabelTarget).Type); Assert.Equal(typeof(void), Expression.Loop(Expression.Constant(3), voidLabelTarget, null).Type); LabelTarget int32LabelTarget = Expression.Label(typeof(int)); Assert.Equal(typeof(int), Expression.Loop(Expression.Empty(), int32LabelTarget).Type); Assert.Equal(typeof(int), Expression.Loop(Expression.Empty(), int32LabelTarget).Type); } [Theory, ClassData(typeof(CompilationTypes))] public void BreakWithinLoop(bool useInterpreter) { string labelName = "Not likely to appear for any other reason {E90FAF9D-1934-4FC9-93EB-BCE70B586146}"; LabelTarget @break = Expression.Label(labelName); Expression<Action> lambda = Expression.Lambda<Action>(Expression.Loop(Expression.Label(@break), @break)); Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message); } [Theory, ClassData(typeof(CompilationTypes))] public void ContinueWithinLoop(bool useInterpreter) { string labelName = "Not likely to appear for any other reason {F9C549FE-6E6C-44A2-A434-0147E0D49F7F}"; LabelTarget @continue = Expression.Label(labelName); Expression<Action> lambda = Expression.Lambda<Action>(Expression.Loop(Expression.Label(@continue), null, @continue)); Assert.Throws<InvalidOperationException>(() => lambda.Compile()); Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message); } [Theory, ClassData(typeof(CompilationTypes))] public void BreakOutsideLoop(bool useInterpreter) { string labelName = "Not likely to appear for any other reason {D3C6FCD8-EA2F-440B-938F-C81560C3BDBA}"; LabelTarget @break = Expression.Label(labelName); Expression<Action> lambda = Expression.Lambda<Action>( Expression.Block( Expression.Label(@break), Expression.Loop(Expression.Empty(), @break) ) ); Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message); } [Theory, ClassData(typeof(CompilationTypes))] public void ContinueOutsideLoop(bool useInterpreter) { string labelName = "Not likely to appear for any other reason {1107D64D-9FC4-4533-83E2-0F5F78B48315}"; LabelTarget @continue = Expression.Label(labelName); Expression<Action> lambda = Expression.Lambda<Action>( Expression.Block( Expression.Label(@continue), Expression.Loop(Expression.Empty(), null, @continue) ) ); Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message); } [Theory, ClassData(typeof(CompilationTypes))] public void ContinueTheSameAsBreak(bool useInterpreter) { string labelName = "Not likely to appear for any other reason {B9CD9CF5-6C67-41C9-98C0-F445CAAB5082}"; LabelTarget label = Expression.Label(labelName); Expression<Action> lambda = Expression.Lambda<Action>( Expression.Loop(Expression.Empty(), label, label) ); Assert.Contains(labelName, Assert.Throws<InvalidOperationException>(() => lambda.Compile(useInterpreter)).Message); } [Theory, ClassData(typeof(CompilationTypes))] public void NoLabelsInfiniteLoop(bool useInterpreter) { // Have an error condition so the otherwise-infinite loop can complete. ParameterExpression num = Expression.Variable(typeof(int)); Action spinThenThrow = Expression.Lambda<Action>( Expression.Block( new[] {num}, Expression.Assign(num, Expression.Constant(0)), Expression.Loop( Expression.IfThen( Expression.GreaterThan( Expression.PreIncrementAssign(num), Expression.Constant(19) ), Expression.Throw( Expression.New( typeof(IntegralException).GetConstructor(new[] {typeof(int)}), num ) ) ) ) ) ).Compile(useInterpreter); Assert.Equal(20, Assert.Throws<IntegralException>(spinThenThrow).Number); } public void NoBreakToLabelInfiniteLoop(bool useInterpreter) { // Have an error condition so the otherwise-infinite loop can complete. ParameterExpression num = Expression.Variable(typeof(int)); Func<int> spinThenThrow = Expression.Lambda<Func<int>>( Expression.Block( new[] { num }, Expression.Assign(num, Expression.Constant(0)), Expression.Loop( Expression.IfThen( Expression.GreaterThan( Expression.PreIncrementAssign(num), Expression.Constant(19) ), Expression.Throw( Expression.New( typeof(IntegralException).GetConstructor(new[] { typeof(int) }), num ) ) ), Expression.Label(typeof(int)) ) ) ).Compile(useInterpreter); Assert.Equal(20, Assert.Throws<IntegralException>(() => spinThenThrow()).Number); } [Theory, ClassData(typeof(CompilationTypes))] public void ExplicitContinue(bool useInterpreter) { var builder = new StringBuilder(); ParameterExpression value = Expression.Variable(typeof(int)); LabelTarget @break = Expression.Label(); LabelTarget @continue = Expression.Label(); Reflection.MethodInfo append = typeof(StringBuilder).GetMethod(nameof(StringBuilder.Append), new[] {typeof(int)}); Action act = Expression.Lambda<Action>( Expression.Block( new[] {value}, Expression.Assign(value, Expression.Constant(0)), Expression.Loop( Expression.Block( Expression.PostIncrementAssign(value), Expression.IfThen( Expression.GreaterThanOrEqual(value, Expression.Constant(10)), Expression.Break(@break) ), Expression.IfThen( Expression.Equal( Expression.Modulo(value, Expression.Constant(2)), Expression.Constant(0) ), Expression.Continue(@continue) ), Expression.Call(Expression.Constant(builder), append, value) ), @break, @continue ) ) ).Compile(useInterpreter); act(); Assert.Equal("13579", builder.ToString()); } [Theory, ClassData(typeof(CompilationTypes))] public void LoopWithBreak(bool useInterpreter) { ParameterExpression value = Expression.Parameter(typeof(int)); ParameterExpression result = Expression.Variable(typeof(int)); LabelTarget label = Expression.Label(typeof(int)); BlockExpression block = Expression.Block( new[] {result}, Expression.Assign(result, Expression.Constant(1)), Expression.Loop( Expression.IfThenElse( Expression.GreaterThan(value, Expression.Constant(1)), Expression.MultiplyAssign(result, Expression.PostDecrementAssign(value)), Expression.Break(label, result) ), label ) ); Func<int, int> factorial = Expression.Lambda<Func<int, int>>(block, value).Compile(useInterpreter); Assert.Equal(120, factorial(5)); } [Fact] public void CannotReduce() { LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label()); Assert.False(loop.CanReduce); Assert.Same(loop, loop.Reduce()); AssertExtensions.Throws<ArgumentException>(null, () => loop.ReduceAndCheck()); } [Fact] public void UpdateSameIsSame() { LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label()); Assert.Same(loop, loop.Update(loop.BreakLabel, loop.ContinueLabel, loop.Body)); } [Fact] public void UpdateDifferentBodyIsDifferent() { LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label()); Assert.NotSame(loop, loop.Update(loop.BreakLabel, loop.ContinueLabel, Expression.Empty())); } [Fact] public void UpdateDifferentBreakIsDifferent() { LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label()); Assert.NotSame(loop, loop.Update(Expression.Label(), loop.ContinueLabel, loop.Body)); } [Fact] public void UpdateDifferentContinueIsDifferent() { LoopExpression loop = Expression.Loop(Expression.Empty(), Expression.Label(), Expression.Label()); Assert.NotSame(loop, loop.Update(loop.BreakLabel, Expression.Label(), loop.Body)); } [Fact] public void ToStringTest() { LoopExpression e = Expression.Loop(Expression.Empty()); Assert.Equal("loop { ... }", e.ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using DG.Tweening; using Proyecto26; using RSG; using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.UI; using IPromise = RSG.IPromise; public class CommunityHomeScreen : Screen { private static Layout DefaultLayout => new Layout { Sections = new List<Layout.Section> { new Layout.CollectionSection { CollectionIds = new List<string> { "5e23eb6c017d2e2198d2f7cb", "5e23eb6c017d2e2198d2f7cd", "5e23eb6c017d2e2198d2f7d6" }, CollectionTitleKeys = new List<string> { "COMMUNITY_HOME_GETTING_STARTED", "COMMUNITY_HOME_POWERED_BY_STORYBOARD", "COMMUNITY_HOME_OCTOPUS_TOURNAMENT" }, CollectionSloganKeys = new List<string> { "COMMUNITY_HOME_GETTING_STARTED_DESC", "COMMUNITY_HOME_POWERED_BY_STORYBOARD_DESC", "COMMUNITY_HOME_OCTOPUS_TOURNAMENT_DESC" } }, new Layout.LevelSection { TitleKey = "COMMUNITY_HOME_NEW_UPLOADS", Query = new OnlineLevelQuery { sort = "creation_date", order = "desc", category = "all" } }, new Layout.LevelSection { TitleKey = "COMMUNITY_HOME_TRENDING_THIS_MONTH", Query = new OnlineLevelQuery { sort = "rating", order = "desc", category = "all", time = "month" } }, new Layout.LevelSection { TitleKey = "COMMUNITY_HOME_BEST_OF_CYTOID", Query = new OnlineLevelQuery { sort = "creation_date", order = "desc", category = "featured" } } } }; public GameObject levelSectionPrefab; public GameObject levelCardPrefab; public GameObject collectionSectionPrefab; public GameObject collectionCardPrefab; public ScrollRect scrollRect; public CanvasGroup contentHolder; public Transform sectionHolder; public InputField searchInputField; public InputField ownerInputField; public override void OnScreenInitialized() { base.OnScreenInitialized(); searchInputField.onEndEdit.AddListener(_ => SearchLevels()); ownerInputField.onEndEdit.AddListener(_ => SearchLevels()); } public override void OnScreenBecameActive() { contentHolder.alpha = 0; base.OnScreenBecameActive(); } public override void OnScreenBecameInactive() { base.OnScreenBecameInactive(); if (LoadedPayload != null) LoadedPayload.ScrollPosition = scrollRect.verticalNormalizedPosition; } protected override async void LoadPayload(ScreenLoadPromise promise) { if (Context.Player.ShouldOneShot("Agree Copyright Policy")) { Context.Player.ClearOneShot("Agree Copyright Policy"); if (!await TermsOverlay.Show("COPYRIGHT_POLICY".Get())) { promise.Reject(); Context.ScreenManager.ChangeScreen(Context.ScreenManager.PopAndPeekHistory(), ScreenTransition.Out, addTargetScreenToHistory: false); return; } Context.Player.ShouldOneShot("Agree Copyright Policy"); } SpinnerOverlay.Show(); var promises = new List<IPromise>(); foreach (var section in IntentPayload.Layout.Sections) { switch (section) { case Layout.LevelSection levelSection: promises.Add(RestClient.GetArray<OnlineLevel>(new RequestHelper { Uri = levelSection.Query.BuildUri(levelSection.PreviewSize), Headers = Context.OnlinePlayer.GetRequestHeaders(), EnableDebug = true }).Then(data => { levelSection.Levels = data.ToList(); })); break; case Layout.CollectionSection collectionSection: { var collectionPromises = new List<RSG.IPromise<CollectionMeta>>(); foreach (var collectionId in collectionSection.CollectionIds) { collectionPromises.Add( RestClient.Get<CollectionMeta>(new RequestHelper { Uri = $"{Context.ApiUrl}/collections/{collectionId}", Headers = Context.OnlinePlayer.GetRequestHeaders(), EnableDebug = true })); } promises.Add(Promise<CollectionMeta>.All(collectionPromises).Then(data => { collectionSection.Collections = data.ToList() .Zip(collectionSection.CollectionIds, (meta, id) => meta.Also(it => it.id = id)) .Zip(collectionSection.CollectionTitleKeys, (meta, title) => meta.Also(it => it.title = title.Get())) .Zip(collectionSection.CollectionSloganKeys, (meta, slogan) => meta.Also(it => it.slogan = slogan.Get())) .ToList(); })); break; } } } Promise.All(promises) .Then(() => { promise.Resolve(IntentPayload); }) .Catch(error => { Dialog.PromptGoBack("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get()); Debug.LogError(error); promise.Reject(); }) .Finally(() => SpinnerOverlay.Hide()); } protected override void Render() { foreach (Transform child in sectionHolder.transform) Destroy(child.gameObject); foreach (var section in LoadedPayload.Layout.Sections) { switch (section) { case Layout.LevelSection levelSection: { var sectionGameObject = Instantiate(levelSectionPrefab, sectionHolder.transform); var sectionBehavior = sectionGameObject.GetComponent<LevelSection>(); sectionBehavior.titleText.text = levelSection.TitleKey.Get(); foreach (var onlineLevel in levelSection.Levels) { var levelCardGameObject = Instantiate(levelCardPrefab, sectionBehavior.levelCardHolder.transform); var levelCard = levelCardGameObject.GetComponent<LevelCard>(); levelCard.SetModel(new LevelView{Level = onlineLevel.ToLevel(LevelType.User), DisplayOwner = true}); } sectionBehavior.viewMoreButton.GetComponentInChildren<Text>().text = "COMMUNITY_HOME_VIEW_ALL".Get(); sectionBehavior.viewMoreButton.onPointerClick.AddListener(_ => { Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, 0.4f, transitionFocus: ((RectTransform) sectionBehavior.viewMoreButton.transform).GetScreenSpaceCenter(), payload: new CommunityLevelSelectionScreen.Payload {Query = levelSection.Query.JsonDeepCopy()}); }); break; } case Layout.CollectionSection collectionSection: { var sectionGameObject = Instantiate(collectionSectionPrefab, sectionHolder.transform); var sectionBehavior = sectionGameObject.GetComponent<CollectionSection>(); foreach (var collection in collectionSection.Collections) { var collectionGameObject = Instantiate(collectionCardPrefab, sectionBehavior.collectionCardHolder.transform); var collectionCard = collectionGameObject.GetComponent<CollectionCard>(); collectionCard.SetModel(collection); collectionCard.titleOverride = collection.title; collectionCard.sloganOverride = collection.slogan; } break; } } } LayoutFixer.Fix(contentHolder.transform); base.Render(); } protected override async void OnRendered() { base.OnRendered(); await UniTask.DelayFrame(3); // Scroll position not set fix if (LoadedPayload.ScrollPosition > -1) scrollRect.verticalNormalizedPosition = LoadedPayload.ScrollPosition; contentHolder.DOFade(1, 0.4f).SetEase(Ease.OutCubic); } public void SearchLevels() { var search = searchInputField.text; var owner = ownerInputField.text.ToLower(); if (search.IsNullOrEmptyTrimmed() && owner.IsNullOrEmptyTrimmed()) return; Context.ScreenManager.ChangeScreen(CommunityLevelSelectionScreen.Id, ScreenTransition.In, payload: new CommunityLevelSelectionScreen.Payload { Query = new OnlineLevelQuery { sort = search != null ? "relevance" : "creation_date", order = "desc", category = "all", time = "all", search = search, owner = owner, } }); } public override void OnScreenChangeFinished(Screen from, Screen to) { base.OnScreenChangeFinished(from, to); if (from == this && to is MainMenuScreen) { Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.LocalLevelCoverThumbnail); Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.RemoteLevelCoverThumbnail); Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.CollectionCoverThumbnail); searchInputField.SetTextWithoutNotify(""); ownerInputField.SetTextWithoutNotify(""); LoadedPayload = null; foreach (Transform child in sectionHolder) Destroy(child.gameObject); } } public class Layout { public List<Section> Sections; public class Section { } public class LevelSection : Section { public string TitleKey; public int PreviewSize = 6; public OnlineLevelQuery Query; public List<OnlineLevel> Levels; } public class CollectionSection : Section { public List<string> CollectionIds; public List<CollectionMeta> Collections; public List<string> CollectionTitleKeys { get; set; } public List<string> CollectionSloganKeys { get; set; } } } public class Payload : ScreenPayload { public Layout Layout; public float ScrollPosition = -1; } public new Payload IntentPayload => (Payload) base.IntentPayload; public new Payload LoadedPayload { get => (Payload) base.LoadedPayload; set => base.LoadedPayload = value; } public override ScreenPayload GetDefaultPayload() => new Payload {Layout = DefaultLayout}; public const string Id = "CommunityHome"; public override string GetId() => Id; }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 RazorDBx.C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests.trees.RBDictionary { using DictionaryIntToInt = TreeDictionary<int, int>; static class Factory { public static IDictionary<K, V> New<K, V> () { return new TreeDictionary<K, V> (); } } //[TestFixture] //public class GenericTesters //{ // [Test] // public void TestSerialize() // { // C5UnitTests.Templates.Extensible.Serialization.DTester<DictionaryIntToInt>(); // } //} [TestFixture] public class Formatting { IDictionary<int, int> coll; IFormatProvider rad16; [SetUp] public void Init () { coll = Factory.New<int, int> (); rad16 = new RadixFormatProvider (16); } [TearDown] public void Dispose () { coll = null; rad16 = null; } [Test] public void Format () { Assert.AreEqual ("[ ]", coll.ToString ()); coll.Add (23, 67); coll.Add (45, 89); Assert.AreEqual ("[ 23 => 67, 45 => 89 ]", coll.ToString ()); Assert.AreEqual ("[ 17 => 43, 2D => 59 ]", coll.ToString (null, rad16)); Assert.AreEqual ("[ 23 => 67, ... ]", coll.ToString ("L14", null)); Assert.AreEqual ("[ 17 => 43, ... ]", coll.ToString ("L14", rad16)); } } [TestFixture] public class RBDict { private TreeDictionary<string, string> dict; [SetUp] public void Init () { dict = new TreeDictionary<string, string> (new SC ()); } [TearDown] public void Dispose () { dict = null; } [Test] [ExpectedException(typeof(NullReferenceException))] public void NullEqualityComparerinConstructor1 () { new TreeDictionary<int, int> (null); } [Test] public void Choose () { dict.Add ("YES", "NO"); Assert.AreEqual (new KeyValuePair<string, string> ("YES", "NO"), dict.Choose ()); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void BadChoose () { dict.Choose (); } [Test] public void Pred1 () { dict.Add ("A", "1"); dict.Add ("C", "2"); dict.Add ("E", "3"); Assert.AreEqual ("1", dict.Predecessor ("B").Value); Assert.AreEqual ("1", dict.Predecessor ("C").Value); Assert.AreEqual ("1", dict.WeakPredecessor ("B").Value); Assert.AreEqual ("2", dict.WeakPredecessor ("C").Value); Assert.AreEqual ("2", dict.Successor ("B").Value); Assert.AreEqual ("3", dict.Successor ("C").Value); Assert.AreEqual ("2", dict.WeakSuccessor ("B").Value); Assert.AreEqual ("2", dict.WeakSuccessor ("C").Value); } [Test] public void Pred2 () { dict.Add ("A", "1"); dict.Add ("C", "2"); dict.Add ("E", "3"); KeyValuePair<String, String> res; Assert.IsTrue (dict.TryPredecessor ("B", out res)); Assert.AreEqual ("1", res.Value); Assert.IsTrue (dict.TryPredecessor ("C", out res)); Assert.AreEqual ("1", res.Value); Assert.IsTrue (dict.TryWeakPredecessor ("B", out res)); Assert.AreEqual ("1", res.Value); Assert.IsTrue (dict.TryWeakPredecessor ("C", out res)); Assert.AreEqual ("2", res.Value); Assert.IsTrue (dict.TrySuccessor ("B", out res)); Assert.AreEqual ("2", res.Value); Assert.IsTrue (dict.TrySuccessor ("C", out res)); Assert.AreEqual ("3", res.Value); Assert.IsTrue (dict.TryWeakSuccessor ("B", out res)); Assert.AreEqual ("2", res.Value); Assert.IsTrue (dict.TryWeakSuccessor ("C", out res)); Assert.AreEqual ("2", res.Value); Assert.IsFalse (dict.TryPredecessor ("A", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); Assert.IsFalse (dict.TryWeakPredecessor ("@", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); Assert.IsFalse (dict.TrySuccessor ("E", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); Assert.IsFalse (dict.TryWeakSuccessor ("F", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); } [Test] public void Initial () { bool res; Assert.IsFalse (dict.IsReadOnly); Assert.AreEqual (dict.Count, 0, "new dict should be empty"); dict.Add ("A", "B"); Assert.AreEqual (dict.Count, 1, "bad count"); Assert.AreEqual (dict ["A"], "B", "Wrong value for dict[A]"); dict.Add ("C", "D"); Assert.AreEqual (dict.Count, 2, "bad count"); Assert.AreEqual (dict ["A"], "B", "Wrong value"); Assert.AreEqual (dict ["C"], "D", "Wrong value"); res = dict.Remove ("A"); Assert.IsTrue (res, "bad return value from Remove(A)"); Assert.IsTrue (dict.Check ()); Assert.AreEqual (dict.Count, 1, "bad count"); Assert.AreEqual (dict ["C"], "D", "Wrong value of dict[C]"); res = dict.Remove ("Z"); Assert.IsFalse (res, "bad return value from Remove(Z)"); Assert.AreEqual (dict.Count, 1, "bad count"); Assert.AreEqual (dict ["C"], "D", "Wrong value of dict[C] (2)"); dict.Clear (); Assert.AreEqual (dict.Count, 0, "dict should be empty"); } [Test] public void Contains () { dict.Add ("C", "D"); Assert.IsTrue (dict.Contains ("C")); Assert.IsFalse (dict.Contains ("D")); } [Test] [ExpectedException(typeof(DuplicateNotAllowedException), ExpectedMessage = "Key being added: 'A'")] public void IllegalAdd () { dict.Add ("A", "B"); dict.Add ("A", "B"); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void GettingNonExisting () { Console.WriteLine (dict ["R"]); } [Test] public void Setter () { dict ["R"] = "UYGUY"; Assert.AreEqual (dict ["R"], "UYGUY"); dict ["R"] = "UIII"; Assert.AreEqual (dict ["R"], "UIII"); dict ["S"] = "VVV"; Assert.AreEqual (dict ["R"], "UIII"); Assert.AreEqual (dict ["S"], "VVV"); //dict.dump(); } } [TestFixture] public class GuardedSortedDictionaryTest { private GuardedSortedDictionary<string, string> dict; [SetUp] public void Init () { ISortedDictionary<string, string> dict = new TreeDictionary<string, string> (new SC ()); dict.Add ("A", "1"); dict.Add ("C", "2"); dict.Add ("E", "3"); this.dict = new GuardedSortedDictionary<string, string> (dict); } [TearDown] public void Dispose () { dict = null; } [Test] public void Pred1 () { Assert.AreEqual ("1", dict.Predecessor ("B").Value); Assert.AreEqual ("1", dict.Predecessor ("C").Value); Assert.AreEqual ("1", dict.WeakPredecessor ("B").Value); Assert.AreEqual ("2", dict.WeakPredecessor ("C").Value); Assert.AreEqual ("2", dict.Successor ("B").Value); Assert.AreEqual ("3", dict.Successor ("C").Value); Assert.AreEqual ("2", dict.WeakSuccessor ("B").Value); Assert.AreEqual ("2", dict.WeakSuccessor ("C").Value); } [Test] public void Pred2 () { KeyValuePair<String, String> res; Assert.IsTrue (dict.TryPredecessor ("B", out res)); Assert.AreEqual ("1", res.Value); Assert.IsTrue (dict.TryPredecessor ("C", out res)); Assert.AreEqual ("1", res.Value); Assert.IsTrue (dict.TryWeakPredecessor ("B", out res)); Assert.AreEqual ("1", res.Value); Assert.IsTrue (dict.TryWeakPredecessor ("C", out res)); Assert.AreEqual ("2", res.Value); Assert.IsTrue (dict.TrySuccessor ("B", out res)); Assert.AreEqual ("2", res.Value); Assert.IsTrue (dict.TrySuccessor ("C", out res)); Assert.AreEqual ("3", res.Value); Assert.IsTrue (dict.TryWeakSuccessor ("B", out res)); Assert.AreEqual ("2", res.Value); Assert.IsTrue (dict.TryWeakSuccessor ("C", out res)); Assert.AreEqual ("2", res.Value); Assert.IsFalse (dict.TryPredecessor ("A", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); Assert.IsFalse (dict.TryWeakPredecessor ("@", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); Assert.IsFalse (dict.TrySuccessor ("E", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); Assert.IsFalse (dict.TryWeakSuccessor ("F", out res)); Assert.AreEqual (null, res.Key); Assert.AreEqual (null, res.Value); } [Test] public void Initial () { Assert.IsTrue (dict.IsReadOnly); Assert.AreEqual (3, dict.Count); Assert.AreEqual ("1", dict ["A"]); } [Test] public void Contains () { Assert.IsTrue (dict.Contains ("A")); Assert.IsFalse (dict.Contains ("1")); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalAdd () { dict.Add ("Q", "7"); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalClear () { dict.Clear (); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalSet () { dict ["A"] = "8"; } [ExpectedException(typeof(ReadOnlyCollectionException))] public void IllegalRemove () { dict.Remove ("A"); } [Test] [ExpectedException(typeof(NoSuchItemException))] public void GettingNonExisting () { Console.WriteLine (dict ["R"]); } } [TestFixture] public class Enumerators { private TreeDictionary<string, string> dict; private SCG.IEnumerator<KeyValuePair<string, string>> dictenum; [SetUp] public void Init () { dict = new TreeDictionary<string, string> (new SC ()); dict ["S"] = "A"; dict ["T"] = "B"; dict ["R"] = "C"; dictenum = dict.GetEnumerator (); } [TearDown] public void Dispose () { dictenum = null; dict = null; } [Test] public void KeysEnumerator () { SCG.IEnumerator<string> keys = dict.Keys.GetEnumerator (); Assert.AreEqual (3, dict.Keys.Count); Assert.IsTrue (keys.MoveNext ()); Assert.AreEqual ("R", keys.Current); Assert.IsTrue (keys.MoveNext ()); Assert.AreEqual ("S", keys.Current); Assert.IsTrue (keys.MoveNext ()); Assert.AreEqual ("T", keys.Current); Assert.IsFalse (keys.MoveNext ()); } [Test] public void KeysISorted () { ISorted<string> keys = dict.Keys; Assert.IsTrue (keys.IsReadOnly); Assert.AreEqual ("R", keys.FindMin ()); Assert.AreEqual ("T", keys.FindMax ()); Assert.IsTrue (keys.Contains ("S")); Assert.AreEqual (3, keys.Count); // This doesn't hold, maybe because the dict uses a special key comparer? // Assert.IsTrue(keys.SequencedEquals(new WrappedArray<string>(new string[] { "R", "S", "T" }))); Assert.IsTrue (keys.UniqueItems ().All (delegate(String s) { return s == "R" || s == "S" || s == "T"; })); Assert.IsTrue (keys.All (delegate(String s) { return s == "R" || s == "S" || s == "T"; })); Assert.IsFalse (keys.Exists (delegate(String s) { return s != "R" && s != "S" && s != "T"; })); String res; Assert.IsTrue (keys.Find (delegate(String s) { return s == "R"; }, out res)); Assert.AreEqual ("R", res); Assert.IsFalse (keys.Find (delegate(String s) { return s == "Q"; }, out res)); Assert.AreEqual (null, res); } [Test] public void KeysISortedPred () { ISorted<string> keys = dict.Keys; String res; Assert.IsTrue (keys.TryPredecessor ("S", out res)); Assert.AreEqual ("R", res); Assert.IsTrue (keys.TryWeakPredecessor ("R", out res)); Assert.AreEqual ("R", res); Assert.IsTrue (keys.TrySuccessor ("S", out res)); Assert.AreEqual ("T", res); Assert.IsTrue (keys.TryWeakSuccessor ("T", out res)); Assert.AreEqual ("T", res); Assert.IsFalse (keys.TryPredecessor ("R", out res)); Assert.AreEqual (null, res); Assert.IsFalse (keys.TryWeakPredecessor ("P", out res)); Assert.AreEqual (null, res); Assert.IsFalse (keys.TrySuccessor ("T", out res)); Assert.AreEqual (null, res); Assert.IsFalse (keys.TryWeakSuccessor ("U", out res)); Assert.AreEqual (null, res); Assert.AreEqual ("R", keys.Predecessor ("S")); Assert.AreEqual ("R", keys.WeakPredecessor ("R")); Assert.AreEqual ("T", keys.Successor ("S")); Assert.AreEqual ("T", keys.WeakSuccessor ("T")); } [Test] public void ValuesEnumerator () { SCG.IEnumerator<string> values = dict.Values.GetEnumerator (); Assert.AreEqual (3, dict.Values.Count); Assert.IsTrue (values.MoveNext ()); Assert.AreEqual ("C", values.Current); Assert.IsTrue (values.MoveNext ()); Assert.AreEqual ("A", values.Current); Assert.IsTrue (values.MoveNext ()); Assert.AreEqual ("B", values.Current); Assert.IsFalse (values.MoveNext ()); } [Test] public void Fun () { Assert.AreEqual ("B", dict.Func ("T")); } [Test] public void NormalUse () { Assert.IsTrue (dictenum.MoveNext ()); Assert.AreEqual (dictenum.Current, new KeyValuePair<string, string> ("R", "C")); Assert.IsTrue (dictenum.MoveNext ()); Assert.AreEqual (dictenum.Current, new KeyValuePair<string, string> ("S", "A")); Assert.IsTrue (dictenum.MoveNext ()); Assert.AreEqual (dictenum.Current, new KeyValuePair<string, string> ("T", "B")); Assert.IsFalse (dictenum.MoveNext ()); } } namespace PathCopyPersistence { [TestFixture] public class Simple { private TreeDictionary<string, string> dict; private TreeDictionary<string, string> snap; [SetUp] public void Init () { dict = new TreeDictionary<string, string> (new SC ()); dict ["S"] = "A"; dict ["T"] = "B"; dict ["R"] = "C"; dict ["V"] = "G"; snap = (TreeDictionary<string, string>)dict.Snapshot (); } [Test] public void Test () { dict ["SS"] = "D"; Assert.AreEqual (5, dict.Count); Assert.AreEqual (4, snap.Count); dict ["T"] = "bb"; Assert.AreEqual (5, dict.Count); Assert.AreEqual (4, snap.Count); Assert.AreEqual ("B", snap ["T"]); Assert.AreEqual ("bb", dict ["T"]); Assert.IsFalse (dict.IsReadOnly); Assert.IsTrue (snap.IsReadOnly); //Finally, update of root node: TreeDictionary<string, string> snap2 = (TreeDictionary<string, string>)dict.Snapshot (); dict ["S"] = "abe"; Assert.AreEqual ("abe", dict ["S"]); } [Test] [ExpectedException(typeof(ReadOnlyCollectionException))] public void UpdateSnap () { snap ["Y"] = "J"; } [TearDown] public void Dispose () { dict = null; snap = null; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using QuantConnect.Data.Market; using QuantConnect.Securities; using static QuantConnect.StringExtensions; namespace QuantConnect.Data.Auxiliary { /// <summary> /// Defines a single row in a factor_factor file. This is a csv file ordered as {date, price factor, split factor, reference price} /// </summary> public class FactorFileRow { private decimal _splitFactor; private decimal _priceFactor; /// <summary> /// Gets the date associated with this data /// </summary> public DateTime Date { get; private set; } /// <summary> /// Gets the price factor associated with this data /// </summary> public decimal PriceFactor { get { return _priceFactor; } set { _priceFactor = value; UpdatePriceScaleFactor(); } } /// <summary> /// Gets the split factor associated with the date /// </summary> public decimal SplitFactor { get { return _splitFactor; } set { _splitFactor = value; UpdatePriceScaleFactor(); } } /// <summary> /// Gets the combined factor used to create adjusted prices from raw prices /// </summary> public decimal PriceScaleFactor { get; private set; } /// <summary> /// Gets the raw closing value from the trading date before the updated factor takes effect /// </summary> public decimal ReferencePrice { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="FactorFileRow"/> class /// </summary> public FactorFileRow(DateTime date, decimal priceFactor, decimal splitFactor, decimal referencePrice = 0) { Date = date; ReferencePrice = referencePrice; PriceFactor = priceFactor; SplitFactor = splitFactor; } /// <summary> /// Reads in the factor file for the specified equity symbol /// </summary> public static IEnumerable<FactorFileRow> Read(Stream file, out DateTime? factorFileMinimumDate) { factorFileMinimumDate = null; var streamReader = new StreamReader(file, Encoding.UTF8); string line; var lines = new List<string>(); while (!streamReader.EndOfStream) { line = streamReader.ReadLine(); if (!string.IsNullOrWhiteSpace(line)) { lines.Add(line); } } streamReader.Dispose(); return Parse(lines, out factorFileMinimumDate); } /// <summary> /// Parses the lines as factor files rows while properly handling inf entries /// </summary> /// <param name="lines">The lines from the factor file to be parsed</param> /// <param name="factorFileMinimumDate">The minimum date from the factor file</param> /// <returns>An enumerable of factor file rows</returns> public static List<FactorFileRow> Parse(IEnumerable<string> lines, out DateTime? factorFileMinimumDate) { factorFileMinimumDate = null; var rows = new List<FactorFileRow>(); // parse factor file lines foreach (var line in lines) { // Exponential notation is treated as inf is because of the loss of precision. In // all cases, the significant part has fewer decimals than the needed for a correct // representation, E.g., 1.6e+6 when the correct factor is 1562500. if (line.Contains("inf") || line.Contains("e+")) { continue; } var row = Parse(line); // ignore zero factor rows if (row.PriceScaleFactor > 0) { rows.Add(row); } } if (factorFileMinimumDate == null && rows.Count > 0) { factorFileMinimumDate = rows.Min(ffr => ffr.Date).AddDays(-1); } return rows; } /// <summary> /// Applies the dividend to this factor file row. /// This dividend date must be on or before the factor /// file row date /// </summary> /// <param name="dividend">The dividend to apply with reference price and distribution specified</param> /// <param name="exchangeHours">Exchange hours used for resolving the previous trading day</param> /// <returns>A new factor file row that applies the dividend to this row's factors</returns> public FactorFileRow Apply(Dividend dividend, SecurityExchangeHours exchangeHours) { if (dividend.ReferencePrice == 0m) { throw new ArgumentException("Unable to apply dividend with reference price of zero."); } var previousTradingDay = exchangeHours.GetPreviousTradingDay(dividend.Time); // this instance must be chronologically at or in front of the dividend // this is because the factors are defined working from current to past if (Date < previousTradingDay) { throw new ArgumentException(Invariant( $"Factor file row date '{Date:yyy-MM-dd}' is before dividend previous trading date '{previousTradingDay.Date:yyyy-MM-dd}'." )); } // pfi - new price factor pf(i+1) - this price factor D - distribution C - previous close // pfi = pf(i+1) * (C-D)/C var priceFactor = PriceFactor * (dividend.ReferencePrice - dividend.Distribution) / dividend.ReferencePrice; return new FactorFileRow( previousTradingDay, priceFactor, SplitFactor, dividend.ReferencePrice ); } /// <summary> /// Applies the split to this factor file row. /// This split date must be on or before the factor /// file row date /// </summary> /// <param name="split">The split to apply with reference price and split factor specified</param> /// <param name="exchangeHours">Exchange hours used for resolving the previous trading day</param> /// <returns>A new factor file row that applies the split to this row's factors</returns> public FactorFileRow Apply(Split split, SecurityExchangeHours exchangeHours) { if (split.Type == SplitType.Warning) { throw new ArgumentException("Unable to apply split with type warning. Only actual splits may be applied"); } if (split.ReferencePrice == 0m) { throw new ArgumentException("Unable to apply split with reference price of zero."); } var previousTradingDay = exchangeHours.GetPreviousTradingDay(split.Time); // this instance must be chronologically at or in front of the split // this is because the factors are defined working from current to past if (Date < previousTradingDay) { throw new ArgumentException(Invariant( $"Factor file row date '{Date:yyy-MM-dd}' is before split date '{split.Time.Date:yyyy-MM-dd}'." )); } return new FactorFileRow( previousTradingDay, PriceFactor, SplitFactor * split.SplitFactor, split.ReferencePrice ); } /// <summary> /// Creates a new dividend from this factor file row and the one chronologically in front of it /// This dividend may have a distribution of zero if this row doesn't represent a dividend /// </summary> /// <param name="futureFactorFileRow">The next factor file row in time</param> /// <param name="symbol">The symbol to use for the dividend</param> /// <param name="exchangeHours">Exchange hours used for resolving the previous trading day</param> /// <param name="decimalPlaces">The number of decimal places to round the dividend's distribution to, defaulting to 2</param> /// <returns>A new dividend instance</returns> public Dividend GetDividend(FactorFileRow futureFactorFileRow, Symbol symbol, SecurityExchangeHours exchangeHours, int decimalPlaces=2) { if (futureFactorFileRow.PriceFactor == 0m) { throw new InvalidOperationException(Invariant( $"Unable to resolve dividend for '{symbol.ID}' at {Date:yyyy-MM-dd}. Price factor is zero." )); } // find previous trading day var previousTradingDay = exchangeHours.GetNextTradingDay(Date); return Dividend.Create( symbol, previousTradingDay, ReferencePrice, PriceFactor / futureFactorFileRow.PriceFactor, decimalPlaces ); } /// <summary> /// Creates a new split from this factor file row and the one chronologically in front of it /// This split may have a split factor of one if this row doesn't represent a split /// </summary> /// <param name="futureFactorFileRow">The next factor file row in time</param> /// <param name="symbol">The symbol to use for the split</param> /// <param name="exchangeHours">Exchange hours used for resolving the previous trading day</param> /// <returns>A new split instance</returns> public Split GetSplit(FactorFileRow futureFactorFileRow, Symbol symbol, SecurityExchangeHours exchangeHours) { if (futureFactorFileRow.SplitFactor == 0m) { throw new InvalidOperationException(Invariant( $"Unable to resolve split for '{symbol.ID}' at {Date:yyyy-MM-dd}. Split factor is zero." )); } // find previous trading day var previousTradingDay = exchangeHours.GetNextTradingDay(Date); return new Split( symbol, previousTradingDay, ReferencePrice, SplitFactor / futureFactorFileRow.SplitFactor, SplitType.SplitOccurred ); } /// <summary> /// Parses the specified line as a factor file row /// </summary> private static FactorFileRow Parse(string line) { var csv = line.Split(','); return new FactorFileRow( QuantConnect.Parse.DateTimeExact(csv[0], DateFormat.EightCharacter, DateTimeStyles.None), QuantConnect.Parse.Decimal(csv[1]), QuantConnect.Parse.Decimal(csv[2]), csv.Length > 3 ? QuantConnect.Parse.Decimal(csv[3]) : 0m ); } /// <summary> /// Writes this row to csv format /// </summary> public string ToCsv(string source = null) { source = source == null ? "" : $",{source}"; return $"{Date.ToStringInvariant(DateFormat.EightCharacter)}," + Invariant($"{Math.Round(PriceFactor, 7)},") + Invariant($"{Math.Round(SplitFactor, 8)},") + Invariant($"{Math.Round(ReferencePrice, 4).Normalize()}") + $"{source}"; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { return Invariant($"{Date:yyyy-MM-dd}: {PriceScaleFactor:0.0000} {SplitFactor:0.0000}"); } /// <summary> /// For performance we update <see cref="PriceScaleFactor"/> when underlying /// values are updated to avoid decimal multiplication on each get operation. /// </summary> private void UpdatePriceScaleFactor() { PriceScaleFactor = _priceFactor * _splitFactor; } } }
//////////////////////////////////////////////////////////////// // // // Neoforce Controls // // // //////////////////////////////////////////////////////////////// // // // File: Renderer.cs // // // // Version: 0.7 // // // // Date: 11/09/2010 // // // // Author: Tom Shane // // // //////////////////////////////////////////////////////////////// // // // Copyright (c) by Tom Shane // // // //////////////////////////////////////////////////////////////// #region //// Using ///////////// //////////////////////////////////////////////////////////////////////////// using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; //////////////////////////////////////////////////////////////////////////// #endregion namespace TomShane.Neoforce.Controls { public enum BlendingMode { Default, None, } #region //// Classes /////////// //////////////////////////////////////////////////////////////////////////// public class DeviceStates { public readonly BlendState BlendState; public readonly RasterizerState RasterizerState; public readonly DepthStencilState DepthStencilState; public readonly SamplerState SamplerState; public DeviceStates() { BlendState = new BlendState(); BlendState.AlphaBlendFunction = BlendState.AlphaBlend.AlphaBlendFunction; BlendState.AlphaDestinationBlend = BlendState.AlphaBlend.AlphaDestinationBlend; BlendState.AlphaSourceBlend = BlendState.AlphaBlend.AlphaSourceBlend; BlendState.BlendFactor = BlendState.AlphaBlend.BlendFactor; BlendState.ColorBlendFunction = BlendState.AlphaBlend.ColorBlendFunction; BlendState.ColorDestinationBlend = BlendState.AlphaBlend.ColorDestinationBlend; BlendState.ColorSourceBlend = BlendState.AlphaBlend.ColorSourceBlend; BlendState.ColorWriteChannels = BlendState.AlphaBlend.ColorWriteChannels; BlendState.ColorWriteChannels1 = BlendState.AlphaBlend.ColorWriteChannels1; BlendState.ColorWriteChannels2 = BlendState.AlphaBlend.ColorWriteChannels2; BlendState.ColorWriteChannels3 = BlendState.AlphaBlend.ColorWriteChannels3; BlendState.MultiSampleMask = BlendState.AlphaBlend.MultiSampleMask; RasterizerState = new RasterizerState(); RasterizerState.CullMode = RasterizerState.CullNone.CullMode; RasterizerState.DepthBias = RasterizerState.CullNone.DepthBias; RasterizerState.FillMode = RasterizerState.CullNone.FillMode; RasterizerState.MultiSampleAntiAlias = RasterizerState.CullNone.MultiSampleAntiAlias; RasterizerState.ScissorTestEnable = RasterizerState.CullNone.ScissorTestEnable; RasterizerState.SlopeScaleDepthBias = RasterizerState.CullNone.SlopeScaleDepthBias; RasterizerState.ScissorTestEnable = true; SamplerState = new SamplerState(); SamplerState.AddressU = SamplerState.AnisotropicClamp.AddressU; SamplerState.AddressV = SamplerState.AnisotropicClamp.AddressV; SamplerState.AddressW = SamplerState.AnisotropicClamp.AddressW; SamplerState.Filter = SamplerState.AnisotropicClamp.Filter; SamplerState.MaxAnisotropy = SamplerState.AnisotropicClamp.MaxAnisotropy; SamplerState.MaxMipLevel = SamplerState.AnisotropicClamp.MaxMipLevel; SamplerState.MipMapLevelOfDetailBias = SamplerState.AnisotropicClamp.MipMapLevelOfDetailBias; DepthStencilState = new DepthStencilState(); DepthStencilState = DepthStencilState.None; } } //////////////////////////////////////////////////////////////////////////// #endregion public class Renderer: Component { #region //// Fields //////////// //////////////////////////////////////////////////////////////////////////// private SpriteBatch sb = null; private DeviceStates states = new DeviceStates(); //////////////////////////////////////////////////////////////////////////// #endregion #region //// Properties //////// //////////////////////////////////////////////////////////////////////////// public virtual SpriteBatch SpriteBatch { get { return sb; } } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Constructors ////// //////////////////////////////////////////////////////////////////////////// public Renderer(Manager manager): base(manager) { sb = new SpriteBatch(Manager.GraphicsDevice); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Destructors /////// //////////////////////////////////////////////////////////////////////////// protected override void Dispose(bool disposing) { if (disposing) { if (sb != null) { sb.Dispose(); sb = null; } } base.Dispose(disposing); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Methods /////////// //////////////////////////////////////////////////////////////////////////// public override void Init() { base.Init(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void Begin(BlendingMode mode) { if (mode != BlendingMode.None) { sb.Begin(SpriteSortMode.Immediate, states.BlendState, states.SamplerState, states.DepthStencilState, states.RasterizerState); } else { sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque, states.SamplerState, states.DepthStencilState, states.RasterizerState); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void End() { sb.End(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void Draw(Texture2D texture, Rectangle destination, Color color) { if (destination.Width > 0 && destination.Height > 0) { sb.Draw(texture, destination, null, color, 0.0f, Vector2.Zero, SpriteEffects.None, Manager.GlobalDepth); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void Draw(Texture2D texture, Rectangle destination, Rectangle source, Color color) { if (source.Width > 0 && source.Height > 0 && destination.Width > 0 && destination.Height > 0) { sb.Draw(texture, destination, source, color, 0.0f, Vector2.Zero, SpriteEffects.None, Manager.GlobalDepth); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void Draw(Texture2D texture, int left, int top, Color color) { sb.Draw(texture, new Vector2(left, top), null, color, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, Manager.GlobalDepth); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void Draw(Texture2D texture, int left, int top, Rectangle source, Color color) { if (source.Width > 0 && source.Height > 0) { sb.Draw(texture, new Vector2(left, top), source, color, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, Manager.GlobalDepth); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(SpriteFont font, string text, int left, int top, Color color) { sb.DrawString(font, text, new Vector2(left, top), color, 0.0f, Vector2.Zero, 1.0f, SpriteEffects.None, Manager.GlobalDepth); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(SpriteFont font, string text, Rectangle rect, Color color, Alignment alignment) { DrawString(font, text, rect, color, alignment, 0, 0, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(SpriteFont font, string text, Rectangle rect, Color color, Alignment alignment, bool ellipsis) { DrawString(font, text, rect, color, alignment, 0, 0, ellipsis); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect) { DrawString(control, layer, text, rect, true, 0, 0, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, ControlState state) { DrawString(control, layer, text, rect, state, true, 0, 0, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, bool margins) { DrawString(control, layer, text, rect, margins, 0, 0, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, ControlState state, bool margins) { DrawString(control, layer, text, rect, state, margins, 0, 0, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, bool margins, int ox, int oy) { DrawString(control, layer, text, rect, margins, ox, oy, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, ControlState state, bool margins, int ox, int oy) { DrawString(control, layer, text, rect, state, margins, ox, oy, true); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, bool margins, int ox, int oy, bool ellipsis) { DrawString(control, layer, text, rect, control.ControlState, margins, ox, oy, ellipsis); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(Control control, SkinLayer layer, string text, Rectangle rect, ControlState state, bool margins, int ox, int oy, bool ellipsis) { Color col = Color.White; if (layer.Text != null) { if (margins) { Margins m = layer.ContentMargins; rect = new Rectangle(rect.Left + m.Left, rect.Top + m.Top, rect.Width - m.Horizontal, rect.Height - m.Vertical); } if (state == ControlState.Hovered && (layer.States.Hovered.Index != -1)) { col = layer.Text.Colors.Hovered; } else if (state == ControlState.Pressed) { col = layer.Text.Colors.Pressed; } else if (state == ControlState.Focused || (control.Focused && state == ControlState.Hovered && layer.States.Hovered.Index == -1)) { col = layer.Text.Colors.Focused; } else if (state == ControlState.Disabled) { col = layer.Text.Colors.Disabled; } else { col = layer.Text.Colors.Enabled; } if (text != null && text != "") { SkinText font = layer.Text; if (control.TextColor != Control.UndefinedColor && control.ControlState != ControlState.Disabled) col = control.TextColor; DrawString(font.Font.Resource, text, rect, col, font.Alignment, font.OffsetX + ox, font.OffsetY + oy, ellipsis); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawString(SpriteFont font, string text, Rectangle rect, Color color, Alignment alignment, int offsetX, int offsetY, bool ellipsis) { if (ellipsis) { const string elli = "..."; int size = (int)Math.Ceiling(font.MeasureString(text).X); if (size > rect.Width) { int es = (int)Math.Ceiling(font.MeasureString(elli).X); for (int i = text.Length - 1; i > 0; i--) { int c = 1; if (char.IsWhiteSpace(text[i - 1])) { c = 2; i--; } text = text.Remove(i, c); size = (int)Math.Ceiling(font.MeasureString(text).X); if (size + es <= rect.Width) { break; } } text += elli; } } if (rect.Width > 0 && rect.Height > 0) { Vector2 pos = new Vector2(rect.Left, rect.Top); Vector2 size = font.MeasureString(text); int x = 0; int y = 0; switch (alignment) { case Alignment.TopLeft: break; case Alignment.TopCenter: x = GetTextCenter(rect.Width, size.X); break; case Alignment.TopRight: x = rect.Width - (int)size.X; break; case Alignment.MiddleLeft: y = GetTextCenter(rect.Height, size.Y); break; case Alignment.MiddleRight: x = rect.Width - (int)size.X; y = GetTextCenter(rect.Height, size.Y); break; case Alignment.BottomLeft: y = rect.Height - (int)size.Y; break; case Alignment.BottomCenter: x = GetTextCenter(rect.Width, size.X); y = rect.Height - (int)size.Y; break; case Alignment.BottomRight: x = rect.Width - (int)size.X; y = rect.Height - (int)size.Y; break; default: x = GetTextCenter(rect.Width, size.X); y = GetTextCenter(rect.Height, size.Y); break; } pos.X = (int)(pos.X + x); pos.Y = (int)(pos.Y + y); DrawString(font, text, (int)pos.X + offsetX, (int)pos.Y + offsetY, color); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private static int GetTextCenter(float size1, float size2) { return (int)Math.Ceiling((size1 / 2) - (size2 / 2)); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawLayer(SkinLayer layer, Rectangle rect, Color color, int index) { Size imageSize = new Size(layer.Image.Resource.Width, layer.Image.Resource.Height); Size partSize = new Size(layer.Width, layer.Height); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.TopLeft), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.TopLeft, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.TopCenter), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.TopCenter, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.TopRight), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.TopRight, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.MiddleLeft), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.MiddleLeft, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.MiddleCenter), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.MiddleCenter, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.MiddleRight), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.MiddleRight, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.BottomLeft), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.BottomLeft, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.BottomCenter), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.BottomCenter, index), color); Draw(layer.Image.Resource, GetDestinationArea(rect, layer.SizingMargins, Alignment.BottomRight), GetSourceArea(imageSize, partSize, layer.SizingMargins, Alignment.BottomRight, index), color); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private static Rectangle GetSourceArea(Size imageSize, Size partSize, Margins margins, Alignment alignment, int index) { Rectangle rect = new Rectangle(); int xc = (int)((float)imageSize.Width / partSize.Width); int yc = (int)((float)imageSize.Height / partSize.Height); int xm = (index) % xc; int ym = (index) / xc; int adj = 1; margins.Left += margins.Left > 0 ? adj : 0; margins.Top += margins.Top > 0 ? adj : 0; margins.Right += margins.Right > 0 ? adj : 0; margins.Bottom += margins.Bottom > 0 ? adj : 0; margins = new Margins(margins.Left, margins.Top, margins.Right, margins.Bottom); switch (alignment) { case Alignment.TopLeft: { rect = new Rectangle((0 + (xm * partSize.Width)), (0 + (ym * partSize.Height)), margins.Left, margins.Top); break; } case Alignment.TopCenter: { rect = new Rectangle((0 + (xm * partSize.Width)) + margins.Left, (0 + (ym * partSize.Height)), partSize.Width - margins.Left - margins.Right, margins.Top); break; } case Alignment.TopRight: { rect = new Rectangle((partSize.Width + (xm * partSize.Width)) - margins.Right, (0 + (ym * partSize.Height)), margins.Right, margins.Top); break; } case Alignment.MiddleLeft: { rect = new Rectangle((0 + (xm * partSize.Width)), (0 + (ym * partSize.Height)) + margins.Top, margins.Left, partSize.Height - margins.Top - margins.Bottom); break; } case Alignment.MiddleCenter: { rect = new Rectangle((0 + (xm * partSize.Width)) + margins.Left, (0 + (ym * partSize.Height)) + margins.Top, partSize.Width - margins.Left - margins.Right, partSize.Height - margins.Top - margins.Bottom); break; } case Alignment.MiddleRight: { rect = new Rectangle((partSize.Width + (xm * partSize.Width)) - margins.Right, (0 + (ym * partSize.Height)) + margins.Top, margins.Right, partSize.Height - margins.Top - margins.Bottom); break; } case Alignment.BottomLeft: { rect = new Rectangle((0 + (xm * partSize.Width)), (partSize.Height + (ym * partSize.Height)) - margins.Bottom, margins.Left, margins.Bottom); break; } case Alignment.BottomCenter: { rect = new Rectangle((0 + (xm * partSize.Width)) + margins.Left, (partSize.Height + (ym * partSize.Height)) - margins.Bottom, partSize.Width - margins.Left - margins.Right, margins.Bottom); break; } case Alignment.BottomRight: { rect = new Rectangle((partSize.Width + (xm * partSize.Width)) - margins.Right, (partSize.Height + (ym * partSize.Height)) - margins.Bottom, margins.Right, margins.Bottom); break; } } return rect; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public static Rectangle GetDestinationArea(Rectangle area, Margins margins, Alignment alignment) { Rectangle rect = new Rectangle(); int adj = 1; margins.Left += margins.Left > 0 ? adj : 0; margins.Top += margins.Top > 0 ? adj : 0; margins.Right += margins.Right > 0 ? adj : 0; margins.Bottom += margins.Bottom > 0 ? adj : 0; margins = new Margins(margins.Left, margins.Top, margins.Right, margins.Bottom); switch (alignment) { case Alignment.TopLeft: { rect = new Rectangle(area.Left + 0, area.Top + 0, margins.Left, margins.Top); break; } case Alignment.TopCenter: { rect = new Rectangle(area.Left + margins.Left, area.Top + 0, area.Width - margins.Left - margins.Right, margins.Top); break; } case Alignment.TopRight: { rect = new Rectangle(area.Left + area.Width - margins.Right, area.Top + 0, margins.Right, margins.Top); break; } case Alignment.MiddleLeft: { rect = new Rectangle(area.Left + 0, area.Top + margins.Top, margins.Left, area.Height - margins.Top - margins.Bottom); break; } case Alignment.MiddleCenter: { rect = new Rectangle(area.Left + margins.Left, area.Top + margins.Top, area.Width - margins.Left - margins.Right, area.Height - margins.Top - margins.Bottom); break; } case Alignment.MiddleRight: { rect = new Rectangle(area.Left + area.Width - margins.Right, area.Top + margins.Top, margins.Right, area.Height - margins.Top - margins.Bottom); break; } case Alignment.BottomLeft: { rect = new Rectangle(area.Left + 0, area.Top + area.Height - margins.Bottom, margins.Left, margins.Bottom); break; } case Alignment.BottomCenter: { rect = new Rectangle(area.Left + margins.Left, area.Top + area.Height - margins.Bottom, area.Width - margins.Left - margins.Right, margins.Bottom); break; } case Alignment.BottomRight: { rect = new Rectangle(area.Left + area.Width - margins.Right, area.Top + area.Height - margins.Bottom, margins.Right, margins.Bottom); break; } } return rect; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public void DrawGlyph(Glyph glyph, Rectangle rect) { Size imageSize = new Size(glyph.Image.Width, glyph.Image.Height); if (!glyph.SourceRect.IsEmpty) { imageSize = new Size(glyph.SourceRect.Width, glyph.SourceRect.Height); } if (glyph.SizeMode == SizeMode.Centered) { rect = new Rectangle((rect.X + (rect.Width - imageSize.Width) / 2) + glyph.Offset.X, (rect.Y + (rect.Height - imageSize.Height) / 2) + glyph.Offset.Y, imageSize.Width, imageSize.Height); } else if (glyph.SizeMode == SizeMode.Normal) { rect = new Rectangle(rect.X + glyph.Offset.X, rect.Y + glyph.Offset.Y, imageSize.Width, imageSize.Height); } else if (glyph.SizeMode == SizeMode.Auto) { rect = new Rectangle(rect.X + glyph.Offset.X, rect.Y + glyph.Offset.Y, imageSize.Width, imageSize.Height); } if (glyph.SourceRect.IsEmpty) { Draw(glyph.Image, rect, glyph.Color); } else { Draw(glyph.Image, rect, glyph.SourceRect, glyph.Color); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawLayer(Control control, SkinLayer layer, Rectangle rect) { DrawLayer(control, layer, rect, control.ControlState); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void DrawLayer(Control control, SkinLayer layer, Rectangle rect, ControlState state) { Color c = Color.White; Color oc = Color.White; int i = 0; int oi = -1; SkinLayer l = layer; if (state == ControlState.Hovered && (layer.States.Hovered.Index != -1)) { c = l.States.Hovered.Color; i = l.States.Hovered.Index; if (l.States.Hovered.Overlay) { oc = l.Overlays.Hovered.Color; oi = l.Overlays.Hovered.Index; } } else if (state == ControlState.Focused || (control.Focused && state == ControlState.Hovered && layer.States.Hovered.Index == -1)) { c = l.States.Focused.Color; i = l.States.Focused.Index; if (l.States.Focused.Overlay) { oc = l.Overlays.Focused.Color; oi = l.Overlays.Focused.Index; } } else if (state == ControlState.Pressed) { c = l.States.Pressed.Color; i = l.States.Pressed.Index; if (l.States.Pressed.Overlay) { oc = l.Overlays.Pressed.Color; oi = l.Overlays.Pressed.Index; } } else if (state == ControlState.Disabled) { c = l.States.Disabled.Color; i = l.States.Disabled.Index; if (l.States.Disabled.Overlay) { oc = l.Overlays.Disabled.Color; oi = l.Overlays.Disabled.Index; } } else { c = l.States.Enabled.Color; i = l.States.Enabled.Index; if (l.States.Enabled.Overlay) { oc = l.Overlays.Enabled.Color; oi = l.Overlays.Enabled.Index; } } if (control.Color != Control.UndefinedColor) c = control.Color * (control.Color.A / 255f); DrawLayer(l, rect, c, i); if (oi != -1) { DrawLayer(l, rect, oc, oi); } } //////////////////////////////////////////////////////////////////////////// #endregion } }
using UnityEngine; namespace Zenject { // Zero parameters public class MonoPoolableMemoryPool<TValue> : MemoryPool<TValue> where TValue : Component, IPoolable { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TValue item) { item.gameObject.SetActive(true); item.OnSpawned(); } } // One parameters public class MonoPoolableMemoryPool<TParam1, TValue> : MemoryPool<TParam1, TValue> where TValue : Component, IPoolable<TParam1> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1); } } // Two parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TValue> : MemoryPool<TParam1, TParam2, TValue> where TValue : Component, IPoolable<TParam1, TParam2> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2); } } // Three parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TParam3, TValue> : MemoryPool<TParam1, TParam2, TParam3, TValue> where TValue : Component, IPoolable<TParam1, TParam2, TParam3> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2, p3); } } // Four parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> : MemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> where TValue : Component, IPoolable<TParam1, TParam2, TParam3, TParam4> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2, p3, p4); } } // Five parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> where TValue : Component, IPoolable<TParam1, TParam2, TParam3, TParam4, TParam5> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2, p3, p4, p5); } } // Six parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> where TValue : Component, IPoolable<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2, p3, p4, p5, p6); } } // Seven parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> : MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> where TValue : Component, IPoolable<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2, p3, p4, p5, p6, p7); } } // Eight parameters public class MonoPoolableMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TValue> : MemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TValue> where TValue : Component, IPoolable<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8> { Transform _originalParent; [Inject] public MonoPoolableMemoryPool() { } protected override void OnCreated(TValue item) { item.gameObject.SetActive(false); _originalParent = item.transform.parent; } protected override void OnDestroyed(TValue item) { GameObject.Destroy(item.gameObject); } protected override void OnDespawned(TValue item) { item.OnDespawned(); item.gameObject.SetActive(false); if (item.transform.parent != _originalParent) { item.transform.SetParent(_originalParent, false); } } protected override void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7, TParam8 p8, TValue item) { item.gameObject.SetActive(true); item.OnSpawned(p1, p2, p3, p4, p5, p6, p7, p8); } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// namespace CallButler.ExceptionManagement.Dialogs { partial class ErrorCaptureDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.pnlHeader = new System.Windows.Forms.Panel(); this.lblHeader = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.btnSend = new System.Windows.Forms.Button(); this.btnDontSend = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.lnkShowErrorContent = new System.Windows.Forms.LinkLabel(); this.pnlHeader.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // pnlHeader // this.pnlHeader.BackColor = System.Drawing.Color.White; this.pnlHeader.Controls.Add(this.lblHeader); this.pnlHeader.Controls.Add(this.pictureBox1); this.pnlHeader.Dock = System.Windows.Forms.DockStyle.Top; this.pnlHeader.Location = new System.Drawing.Point(0, 0); this.pnlHeader.Name = "pnlHeader"; this.pnlHeader.Size = new System.Drawing.Size(470, 77); this.pnlHeader.TabIndex = 2; // // lblHeader // this.lblHeader.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblHeader.Location = new System.Drawing.Point(66, 20); this.lblHeader.Name = "lblHeader"; this.lblHeader.Size = new System.Drawing.Size(382, 37); this.lblHeader.TabIndex = 1; this.lblHeader.Text = "{0} has encountered a problem and needs to close. We are sorry for the inconveni" + "ence."; this.lblHeader.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // pictureBox1 // this.pictureBox1.Image = global::CallButler.ExceptionManagement.Properties.Resources.doctor; this.pictureBox1.Location = new System.Drawing.Point(12, 14); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(48, 48); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // btnSend // this.btnSend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSend.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnSend.Location = new System.Drawing.Point(231, 179); this.btnSend.Name = "btnSend"; this.btnSend.Size = new System.Drawing.Size(146, 23); this.btnSend.TabIndex = 3; this.btnSend.Text = "Send Error Report"; this.btnSend.UseVisualStyleBackColor = true; this.btnSend.Click += new System.EventHandler(this.btnSend_Click); // // btnDontSend // this.btnDontSend.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnDontSend.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnDontSend.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnDontSend.Location = new System.Drawing.Point(383, 179); this.btnDontSend.Name = "btnDontSend"; this.btnDontSend.Size = new System.Drawing.Size(75, 23); this.btnDontSend.TabIndex = 4; this.btnDontSend.Text = "Don\'t Send"; this.btnDontSend.UseVisualStyleBackColor = true; this.btnDontSend.Click += new System.EventHandler(this.btnDontSend_Click); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(22, 95); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(194, 13); this.label2.TabIndex = 6; this.label2.Text = "Please tell us about this problem."; // // label3 // this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(22, 117); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(426, 18); this.label3.TabIndex = 7; this.label3.Text = "We have created an error report that you can send to help us improve our products" + "."; // // lnkShowErrorContent // this.lnkShowErrorContent.ActiveLinkColor = System.Drawing.Color.RoyalBlue; this.lnkShowErrorContent.AutoSize = true; this.lnkShowErrorContent.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.lnkShowErrorContent.LinkColor = System.Drawing.Color.RoyalBlue; this.lnkShowErrorContent.Location = new System.Drawing.Point(22, 142); this.lnkShowErrorContent.Name = "lnkShowErrorContent"; this.lnkShowErrorContent.Size = new System.Drawing.Size(207, 13); this.lnkShowErrorContent.TabIndex = 29; this.lnkShowErrorContent.TabStop = true; this.lnkShowErrorContent.Text = "What data does this error report contain?"; this.lnkShowErrorContent.VisitedLinkColor = System.Drawing.Color.RoyalBlue; this.lnkShowErrorContent.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkShowErrorContent_LinkClicked); // // ErrorCaptureDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.WhiteSmoke; this.ClientSize = new System.Drawing.Size(470, 214); this.Controls.Add(this.lnkShowErrorContent); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.btnDontSend); this.Controls.Add(this.btnSend); this.Controls.Add(this.pnlHeader); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83))))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ErrorCaptureDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Error"; this.pnlHeader.ResumeLayout(false); this.pnlHeader.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel pnlHeader; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button btnDontSend; private System.Windows.Forms.Label lblHeader; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.LinkLabel lnkShowErrorContent; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // try/catch, try/finally using System; using System.Runtime.CompilerServices; class Test4 { public static string teststr1 = null; public static string[] teststr2 = new string[3]; public static string teststr3 = null; public const string teststr4 = "const string\""; // special case for DiffObjRef public const string testgenstr4 = "GenC const string\""; // special case for DiffObjRef public static string teststr5 = null; // special case for DiffObjRef public static bool TestSameObjRef() { Console.WriteLine(); Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); Console.WriteLine("When JIT'ed, two strings always have same object reference"); Console.WriteLine(); Console.WriteLine("Testing SameObjRef"); bool passed = true; string b = null; try { teststr1 = "static \uC09C\u7B8B field"; b = C.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 != (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr1 == (object) b is expected"); } try { teststr2[0] = "\u3F2Aarray element 0"; b = C.teststr2[0]; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] != (object)C.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)C.teststr2[0] is expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "array element 1\uCB53"; b = C.teststr2[1]; } if ((object)teststr2[1] != (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object) b is expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "array \u47BBelement 2"; } if ((object)teststr2[2] != (object)C.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)C.teststr2[2] is expected"); } try { teststr3 = @"method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 != (object)C.teststr3()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)C.teststr3() is expected"); } try { } finally { if ((object)teststr4 != (object)C.teststr4) { passed = false; Console.WriteLine("FAILED, (object)teststr4 != (object)C.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; if ((object)teststr5 != (object)C.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 != (object)C.teststr5 is expected"); } } } } // Generic Class try { teststr1 = "GenC static \uC09C\u7B8B field"; b = GenC<string>.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 != (object)b) { passed = false; Console.WriteLine("FAILED, (object)teststr1 == (object)GenC<string>.teststr1 is expected"); } try { teststr2[0] = "GenC \u3F2Aarray element 0"; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] != (object)GenC<string>.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)GenC<string>.teststr2[0] is expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "GenC array element 1\uCB53"; b = GenC<string>.teststr2[1]; } if ((object)teststr2[1] != (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object)GenC<string>.teststr2[1] is expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "GenC array \u47BBelement 2"; } if ((object)teststr2[2] != (object)GenC<string>.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)GenC<string>.teststr2[2] is expected"); } try { teststr3 = @"GenC method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 != (object)GenC<string>.teststr3<int>()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)GenC<string>.teststr3<int>() is expected"); } try { } finally { if ((object)testgenstr4 != (object)GenC<string>.teststr4) { passed = false; Console.WriteLine("FAILED, (object)testgenstr4 != (object)GenC<string>.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; if ((object)teststr5 != (object)GenC<string>.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 != (object)GenC<string>.teststr5 is expected"); } } } } return passed; } public static bool TestDiffObjRef() { Console.WriteLine(); Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); Console.WriteLine("When JIT'ed, two strings always have same object reference"); Console.WriteLine(); Console.WriteLine("Testing DiffObjRef"); bool passed = true; string b = null; try { teststr1 = "static \uC09C\u7B8B field"; b = C.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 == (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr1 == (object) b is NOT expected"); } try { teststr2[0] = "\u3F2Aarray element 0"; b = C.teststr2[0]; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] == (object)C.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)C.teststr2[0] is NOT expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "array element 1\uCB53"; b = C.teststr2[1]; } if ((object)teststr2[1] == (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object) b is NOT expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "array \u47BBelement 2"; } if ((object)teststr2[2] == (object)C.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)C.teststr2[2] is NOT expected"); } try { teststr3 = @"method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 == (object)C.teststr3()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)C.teststr3() is NOT expected"); } try { } finally { // Special case for const literal teststr4 // two consecutive LDSTR is emitted by C# compiler for the following statement // as a result, both are interned in the same module and object comparison returns true if ((object)teststr4 != (object)C.teststr4) { passed = false; Console.WriteLine("FAILED, (object)teststr4 == (object)C.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; // Special case for String.Empty // String.Empty is loaded using LDSFLD, rather than LDSTR in any module // as a result, it is always the same reference to [mscorlib]System.String::Empty, // and object comparison return true if ((object)teststr5 != (object)C.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 == (object)C.teststr5 is expected"); } } } } // Generic Class try { teststr1 = "GenC static \uC09C\u7B8B field"; b = GenC<string>.teststr1; throw new Exception(); } catch (System.Exception) { } if ((object)teststr1 == (object)b) { passed = false; Console.WriteLine("FAILED, (object)teststr1 == (object)GenC<string>.teststr1 is NOT expected"); } try { teststr2[0] = "GenC \u3F2Aarray element 0"; throw new Exception(); } catch (System.Exception) { if ((object)teststr2[0] == (object)GenC<string>.teststr2[0]) { passed = false; Console.WriteLine("FAILED, (object) teststr2[0] == (object)GenC<string>.teststr2[0] is NOT expected"); } } try { throw new Exception(); } catch (System.Exception) { teststr2[1] = "GenC array element 1\uCB53"; b = GenC<string>.teststr2[1]; } if ((object)teststr2[1] == (object)b) { passed = false; Console.WriteLine("FAILED, (object) teststr2[1] == (object)GenC<string>.teststr2[1] is NOT expected"); } try { throw new Exception(); } catch (System.Exception) { } finally { teststr2[2] = "GenC array \u47BBelement 2"; } if ((object)teststr2[2] == (object)GenC<string>.teststr2[2]) { passed = false; Console.WriteLine("FAILED, (object)teststr2[2] == (object)GenC<string>.teststr2[2] is NOT expected"); } try { teststr3 = @"GenC method return\\"; throw new Exception(); } catch (System.Exception) { if ((object)teststr3 == (object)GenC<string>.teststr3<int>()) { passed = false; Console.WriteLine("FAILED, (object) teststr3 == (object)GenC<string>.teststr3<int>() is NOT expected"); } try { } finally { // Special case for const literal teststr4 // two consecutive LDSTR is emitted by C# compiler for the following statement // as a result, both are interned in the same module and object comparison returns true if ((object)testgenstr4 != (object)GenC<string>.teststr4) { passed = false; Console.WriteLine("FAILED, (object)testgenstr4 == (object)GenC<string>.teststr4 is expected"); } try { throw new Exception(); } catch { } finally { teststr5 = String.Empty; // Special case for String.Empty // String.Empty is loaded using LDSFLD, rather than LDSTR in any module // as a result, it is always the same reference to [mscorlib]System.String::Empty, // and object comparison return true if ((object)teststr5 != (object)GenC<string>.teststr5) { passed = false; Console.WriteLine("FAILED, (object) teststr5 == (object)GenC<string>.teststr5 is expected"); } } } } return passed; } public static int Main(string[] args) { bool passed = false; if ((args.Length < 1) || (args[0].ToUpper() == "SAMEOBJREF")) passed = TestSameObjRef(); else if (args[0].ToUpper() == "DIFFOBJREF") passed = TestDiffObjRef(); else { Console.WriteLine("Usage: Test4.exe [SameObjRef|DiffObjRef]"); Console.WriteLine(); Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); Console.WriteLine("When JIT'ed, two strings always have same object reference"); Console.WriteLine(); return 9; } Console.WriteLine(); if (passed) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return 1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; #pragma warning disable 618 // ignore obsolete warning about XmlDataDocument namespace System.Xml { internal abstract class BaseRegionIterator : BaseTreeIterator { internal BaseRegionIterator(DataSetMapper mapper) : base(mapper) { } } // Iterates over non-attribute nodes internal sealed class RegionIterator : BaseRegionIterator { private XmlBoundElement _rowElement; private XmlNode _currentNode; internal RegionIterator(XmlBoundElement rowElement) : base(((XmlDataDocument)(rowElement.OwnerDocument)).Mapper) { Debug.Assert(rowElement != null && rowElement.Row != null); _rowElement = rowElement; _currentNode = rowElement; } internal override void Reset() { _currentNode = _rowElement; } internal override XmlNode CurrentNode => _currentNode; internal override bool Next() { XmlNode nextNode; ElementState oldState = _rowElement.ElementState; // We do not want to cause any foliation w/ this iterator or use this iterator once the region was defoliated Debug.Assert(oldState != ElementState.None); // Try to move to the first child nextNode = _currentNode.FirstChild; // No children, try next sibling if (nextNode != null) { _currentNode = nextNode; // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; return true; } return NextRight(); } internal override bool NextRight() { // Make sure we do not get past the rowElement if we call NextRight on a just initialized iterator and rowElement has no children if (_currentNode == _rowElement) { _currentNode = null; return false; } ElementState oldState = _rowElement.ElementState; // We do not want to cause any foliation w/ this iterator or use this iterator once the region was defoliated Debug.Assert(oldState != ElementState.None); XmlNode nextNode = _currentNode.NextSibling; if (nextNode != null) { _currentNode = nextNode; // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; return true; } // No next sibling, try the first sibling of from the parent chain nextNode = _currentNode; while (nextNode != _rowElement && nextNode.NextSibling == null) { nextNode = nextNode.ParentNode; } if (nextNode == _rowElement) { _currentNode = null; // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; return false; } _currentNode = nextNode.NextSibling; Debug.Assert(_currentNode != null); // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; return true; } // Get the initial text value for the current node. You should be positioned on the node (element) for // which to get the initial text value, not on the text node. internal bool NextInitialTextLikeNodes(out string value) { Debug.Assert(CurrentNode != null); Debug.Assert(CurrentNode.NodeType == XmlNodeType.Element); #if DEBUG // It's not OK to try to read the initial text value for sub-regions, because we do not know how to revert their initial state if (CurrentNode.NodeType == XmlNodeType.Element && mapper.GetTableSchemaForElement((XmlElement)(CurrentNode)) != null) { if (CurrentNode != _rowElement) { Debug.Assert(false); } } #endif ElementState oldState = _rowElement.ElementState; // We do not want to cause any foliation w/ this iterator or use this iterator once the region was defoliated Debug.Assert(oldState != ElementState.None); XmlNode n = CurrentNode.FirstChild; value = GetInitialTextFromNodes(ref n); if (n == null) { // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback eventual foliation _rowElement.ElementState = oldState; return NextRight(); } Debug.Assert(!XmlDataDocument.IsTextLikeNode(n)); _currentNode = n; // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback eventual foliation _rowElement.ElementState = oldState; return true; } private static string GetInitialTextFromNodes(ref XmlNode n) { string value = null; if (n != null) { // don't consider whitespace while (n.NodeType == XmlNodeType.Whitespace) { n = n.NextSibling; if (n == null) { return string.Empty; } } if (XmlDataDocument.IsTextLikeNode(n) && (n.NextSibling == null || !XmlDataDocument.IsTextLikeNode(n.NextSibling))) { // don't use string builder if only one text node exists value = n.Value; n = n.NextSibling; } else { StringBuilder sb = new StringBuilder(); while (n != null && XmlDataDocument.IsTextLikeNode(n)) { // Ignore non-significant whitespace nodes if (n.NodeType != XmlNodeType.Whitespace) { sb.Append(n.Value); } n = n.NextSibling; } value = sb.ToString(); } } return value ?? string.Empty; } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService { using System.Runtime.Serialization; using System; [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="VirtualMachineProvisioningRequest", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] [System.SerializableAttribute()] public partial class VirtualMachineProvisioningRequest : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string AdminPasswordField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ComputerNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DestinationPathField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string DnsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string GatewayField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string IPAddressField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long MemorySizeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NotesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OSProductKeyField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string SubnetmaskField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string TemplateVirtualImageField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string VirtualMachineNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string VirtualSwitchNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string AdminPassword { get { return this.AdminPasswordField; } set { if ((object.ReferenceEquals(this.AdminPasswordField, value) != true)) { this.AdminPasswordField = value; this.RaisePropertyChanged("AdminPassword"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string ComputerName { get { return this.ComputerNameField; } set { if ((object.ReferenceEquals(this.ComputerNameField, value) != true)) { this.ComputerNameField = value; this.RaisePropertyChanged("ComputerName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string DestinationPath { get { return this.DestinationPathField; } set { if ((object.ReferenceEquals(this.DestinationPathField, value) != true)) { this.DestinationPathField = value; this.RaisePropertyChanged("DestinationPath"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Dns { get { return this.DnsField; } set { if ((object.ReferenceEquals(this.DnsField, value) != true)) { this.DnsField = value; this.RaisePropertyChanged("Dns"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Gateway { get { return this.GatewayField; } set { if ((object.ReferenceEquals(this.GatewayField, value) != true)) { this.GatewayField = value; this.RaisePropertyChanged("Gateway"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string IPAddress { get { return this.IPAddressField; } set { if ((object.ReferenceEquals(this.IPAddressField, value) != true)) { this.IPAddressField = value; this.RaisePropertyChanged("IPAddress"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long MemorySize { get { return this.MemorySizeField; } set { if ((this.MemorySizeField.Equals(value) != true)) { this.MemorySizeField = value; this.RaisePropertyChanged("MemorySize"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Notes { get { return this.NotesField; } set { if ((object.ReferenceEquals(this.NotesField, value) != true)) { this.NotesField = value; this.RaisePropertyChanged("Notes"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string OSProductKey { get { return this.OSProductKeyField; } set { if ((object.ReferenceEquals(this.OSProductKeyField, value) != true)) { this.OSProductKeyField = value; this.RaisePropertyChanged("OSProductKey"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Subnetmask { get { return this.SubnetmaskField; } set { if ((object.ReferenceEquals(this.SubnetmaskField, value) != true)) { this.SubnetmaskField = value; this.RaisePropertyChanged("Subnetmask"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string TemplateVirtualImage { get { return this.TemplateVirtualImageField; } set { if ((object.ReferenceEquals(this.TemplateVirtualImageField, value) != true)) { this.TemplateVirtualImageField = value; this.RaisePropertyChanged("TemplateVirtualImage"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string VirtualMachineName { get { return this.VirtualMachineNameField; } set { if ((object.ReferenceEquals(this.VirtualMachineNameField, value) != true)) { this.VirtualMachineNameField = value; this.RaisePropertyChanged("VirtualMachineName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string VirtualSwitchName { get { return this.VirtualSwitchNameField; } set { if ((object.ReferenceEquals(this.VirtualSwitchNameField, value) != true)) { this.VirtualSwitchNameField = value; this.RaisePropertyChanged("VirtualSwitchName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] [System.SerializableAttribute()] public partial class HostingServiceFault : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string ErrorMessageField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string OperationField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public string ErrorMessage { get { return this.ErrorMessageField; } set { if ((object.ReferenceEquals(this.ErrorMessageField, value) != true)) { this.ErrorMessageField = value; this.RaisePropertyChanged("ErrorMessage"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Operation { get { return this.OperationField; } set { if ((object.ReferenceEquals(this.OperationField, value) != true)) { this.OperationField = value; this.RaisePropertyChanged("Operation"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="MemorySettingInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] [System.SerializableAttribute()] public partial class MemorySettingInfo : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long AllocatedRAMField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualDeviceTypeInfo DeviceTypeField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public long AllocatedRAM { get { return this.AllocatedRAMField; } set { if ((this.AllocatedRAMField.Equals(value) != true)) { this.AllocatedRAMField = value; this.RaisePropertyChanged("AllocatedRAM"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualDeviceTypeInfo DeviceType { get { return this.DeviceTypeField; } set { if ((this.DeviceTypeField.Equals(value) != true)) { this.DeviceTypeField = value; this.RaisePropertyChanged("DeviceType"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="VirtualDeviceTypeInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] public enum VirtualDeviceTypeInfo : int { [System.Runtime.Serialization.EnumMemberAttribute()] Unknown = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Memory = 1, [System.Runtime.Serialization.EnumMemberAttribute()] Processor = 2, [System.Runtime.Serialization.EnumMemberAttribute()] EthernetPortEmulated = 3, [System.Runtime.Serialization.EnumMemberAttribute()] EthernetPortSynthetic = 4, [System.Runtime.Serialization.EnumMemberAttribute()] SerialController = 5, [System.Runtime.Serialization.EnumMemberAttribute()] SerialPort = 6, [System.Runtime.Serialization.EnumMemberAttribute()] IDEController = 7, [System.Runtime.Serialization.EnumMemberAttribute()] SCSISyntheticController = 8, [System.Runtime.Serialization.EnumMemberAttribute()] DisketteController = 9, [System.Runtime.Serialization.EnumMemberAttribute()] DisketteSyntheticDrive = 10, [System.Runtime.Serialization.EnumMemberAttribute()] HardDiskSyntheticDirve = 11, [System.Runtime.Serialization.EnumMemberAttribute()] HardDiskPhysicalDrive = 12, [System.Runtime.Serialization.EnumMemberAttribute()] DVDSyntheticDrive = 13, [System.Runtime.Serialization.EnumMemberAttribute()] TimeSync = 14, [System.Runtime.Serialization.EnumMemberAttribute()] Heartbeat = 15, [System.Runtime.Serialization.EnumMemberAttribute()] DataExchange = 16, [System.Runtime.Serialization.EnumMemberAttribute()] Shutdown = 17, [System.Runtime.Serialization.EnumMemberAttribute()] VSSIntegration = 18, [System.Runtime.Serialization.EnumMemberAttribute()] HardDisk = 19, [System.Runtime.Serialization.EnumMemberAttribute()] ISODisk = 20, [System.Runtime.Serialization.EnumMemberAttribute()] FloppyDisk = 21, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="ProcessorSettingInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] [System.SerializableAttribute()] public partial class ProcessorSettingInfo : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualDeviceTypeInfo DeviceTypeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int LimitField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int ProcessorPerSocketField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int ReservationField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int SocketCountField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int VirtualQuantityField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int WeightField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualDeviceTypeInfo DeviceType { get { return this.DeviceTypeField; } set { if ((this.DeviceTypeField.Equals(value) != true)) { this.DeviceTypeField = value; this.RaisePropertyChanged("DeviceType"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Limit { get { return this.LimitField; } set { if ((this.LimitField.Equals(value) != true)) { this.LimitField = value; this.RaisePropertyChanged("Limit"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int ProcessorPerSocket { get { return this.ProcessorPerSocketField; } set { if ((this.ProcessorPerSocketField.Equals(value) != true)) { this.ProcessorPerSocketField = value; this.RaisePropertyChanged("ProcessorPerSocket"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Reservation { get { return this.ReservationField; } set { if ((this.ReservationField.Equals(value) != true)) { this.ReservationField = value; this.RaisePropertyChanged("Reservation"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int SocketCount { get { return this.SocketCountField; } set { if ((this.SocketCountField.Equals(value) != true)) { this.SocketCountField = value; this.RaisePropertyChanged("SocketCount"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int VirtualQuantity { get { return this.VirtualQuantityField; } set { if ((this.VirtualQuantityField.Equals(value) != true)) { this.VirtualQuantityField = value; this.RaisePropertyChanged("VirtualQuantity"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int Weight { get { return this.WeightField; } set { if ((this.WeightField.Equals(value) != true)) { this.WeightField = value; this.RaisePropertyChanged("Weight"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="VirtualComputerSystemSettingInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] [System.SerializableAttribute()] public partial class VirtualComputerSystemSettingInfo : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool BiosNumLockField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.BootDeviceTypeInfo[] BootOrderField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime CreationTimeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InstanceIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NotesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo ParentSnapshotField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo SettingTypeField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public bool BiosNumLock { get { return this.BiosNumLockField; } set { if ((this.BiosNumLockField.Equals(value) != true)) { this.BiosNumLockField = value; this.RaisePropertyChanged("BiosNumLock"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.BootDeviceTypeInfo[] BootOrder { get { return this.BootOrderField; } set { if ((object.ReferenceEquals(this.BootOrderField, value) != true)) { this.BootOrderField = value; this.RaisePropertyChanged("BootOrder"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime CreationTime { get { return this.CreationTimeField; } set { if ((this.CreationTimeField.Equals(value) != true)) { this.CreationTimeField = value; this.RaisePropertyChanged("CreationTime"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InstanceId { get { return this.InstanceIdField; } set { if ((object.ReferenceEquals(this.InstanceIdField, value) != true)) { this.InstanceIdField = value; this.RaisePropertyChanged("InstanceId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Notes { get { return this.NotesField; } set { if ((object.ReferenceEquals(this.NotesField, value) != true)) { this.NotesField = value; this.RaisePropertyChanged("Notes"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo ParentSnapshot { get { return this.ParentSnapshotField; } set { if ((object.ReferenceEquals(this.ParentSnapshotField, value) != true)) { this.ParentSnapshotField = value; this.RaisePropertyChanged("ParentSnapshot"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo SettingType { get { return this.SettingTypeField; } set { if ((object.ReferenceEquals(this.SettingTypeField, value) != true)) { this.SettingTypeField = value; this.RaisePropertyChanged("SettingType"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="BootDeviceTypeInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] public enum BootDeviceTypeInfo : int { [System.Runtime.Serialization.EnumMemberAttribute()] Floppy = 0, [System.Runtime.Serialization.EnumMemberAttribute()] CDROM = 1, [System.Runtime.Serialization.EnumMemberAttribute()] IDEHardDrive = 2, [System.Runtime.Serialization.EnumMemberAttribute()] PXEBoot = 3, [System.Runtime.Serialization.EnumMemberAttribute()] SCSIHardDrive = 4, } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="VirtualComputerSystemInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] [System.SerializableAttribute()] public partial class VirtualComputerSystemInfo : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private bool BiosNumLockField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.BootDeviceTypeInfo[] BootOrderField; [System.Runtime.Serialization.OptionalFieldAttribute()] private System.DateTime CreationTimeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualSystemHealthStateInfo HealthStateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string HostServerNameField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string InstanceIdField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.MemorySettingInfo MemorySettingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private long MemoryUsageField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string NotesField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int ProcessorLoadField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.ProcessorSettingInfo ProcessorSettingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo[] SnapshotsField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.EnabledStateInfo StateField; [System.Runtime.Serialization.OptionalFieldAttribute()] private WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo SystemSettingField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string UpTimeField; [System.Runtime.Serialization.OptionalFieldAttribute()] private string VirtualMachineNameField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public bool BiosNumLock { get { return this.BiosNumLockField; } set { if ((this.BiosNumLockField.Equals(value) != true)) { this.BiosNumLockField = value; this.RaisePropertyChanged("BiosNumLock"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.BootDeviceTypeInfo[] BootOrder { get { return this.BootOrderField; } set { if ((object.ReferenceEquals(this.BootOrderField, value) != true)) { this.BootOrderField = value; this.RaisePropertyChanged("BootOrder"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public System.DateTime CreationTime { get { return this.CreationTimeField; } set { if ((this.CreationTimeField.Equals(value) != true)) { this.CreationTimeField = value; this.RaisePropertyChanged("CreationTime"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualSystemHealthStateInfo HealthState { get { return this.HealthStateField; } set { if ((this.HealthStateField.Equals(value) != true)) { this.HealthStateField = value; this.RaisePropertyChanged("HealthState"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string HostServerName { get { return this.HostServerNameField; } set { if ((object.ReferenceEquals(this.HostServerNameField, value) != true)) { this.HostServerNameField = value; this.RaisePropertyChanged("HostServerName"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string InstanceId { get { return this.InstanceIdField; } set { if ((object.ReferenceEquals(this.InstanceIdField, value) != true)) { this.InstanceIdField = value; this.RaisePropertyChanged("InstanceId"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.MemorySettingInfo MemorySetting { get { return this.MemorySettingField; } set { if ((object.ReferenceEquals(this.MemorySettingField, value) != true)) { this.MemorySettingField = value; this.RaisePropertyChanged("MemorySetting"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public long MemoryUsage { get { return this.MemoryUsageField; } set { if ((this.MemoryUsageField.Equals(value) != true)) { this.MemoryUsageField = value; this.RaisePropertyChanged("MemoryUsage"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string Notes { get { return this.NotesField; } set { if ((object.ReferenceEquals(this.NotesField, value) != true)) { this.NotesField = value; this.RaisePropertyChanged("Notes"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public int ProcessorLoad { get { return this.ProcessorLoadField; } set { if ((this.ProcessorLoadField.Equals(value) != true)) { this.ProcessorLoadField = value; this.RaisePropertyChanged("ProcessorLoad"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.ProcessorSettingInfo ProcessorSetting { get { return this.ProcessorSettingField; } set { if ((object.ReferenceEquals(this.ProcessorSettingField, value) != true)) { this.ProcessorSettingField = value; this.RaisePropertyChanged("ProcessorSetting"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo[] Snapshots { get { return this.SnapshotsField; } set { if ((object.ReferenceEquals(this.SnapshotsField, value) != true)) { this.SnapshotsField = value; this.RaisePropertyChanged("Snapshots"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.EnabledStateInfo State { get { return this.StateField; } set { if ((this.StateField.Equals(value) != true)) { this.StateField = value; this.RaisePropertyChanged("State"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo SystemSetting { get { return this.SystemSettingField; } set { if ((object.ReferenceEquals(this.SystemSettingField, value) != true)) { this.SystemSettingField = value; this.RaisePropertyChanged("SystemSetting"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string UpTime { get { return this.UpTimeField; } set { if ((object.ReferenceEquals(this.UpTimeField, value) != true)) { this.UpTimeField = value; this.RaisePropertyChanged("UpTime"); } } } [System.Runtime.Serialization.DataMemberAttribute()] public string VirtualMachineName { get { return this.VirtualMachineNameField; } set { if ((object.ReferenceEquals(this.VirtualMachineNameField, value) != true)) { this.VirtualMachineNameField = value; this.RaisePropertyChanged("VirtualMachineName"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="VirtualSystemHealthStateInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] public enum VirtualSystemHealthStateInfo : int { [System.Runtime.Serialization.EnumMemberAttribute()] CriticalFailure = 25, [System.Runtime.Serialization.EnumMemberAttribute()] Ok = 5, } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="EnabledStateInfo", Namespace="http://Microsoft.Hosting.Virtualization.DataContracts/2007/04")] public enum EnabledStateInfo : int { [System.Runtime.Serialization.EnumMemberAttribute()] Unknown = 0, [System.Runtime.Serialization.EnumMemberAttribute()] Enabled = 2, [System.Runtime.Serialization.EnumMemberAttribute()] Disabled = 3, [System.Runtime.Serialization.EnumMemberAttribute()] ShuttingDown = 4, [System.Runtime.Serialization.EnumMemberAttribute()] Reset = 10, [System.Runtime.Serialization.EnumMemberAttribute()] Paused = 32768, [System.Runtime.Serialization.EnumMemberAttribute()] Saved = 32769, [System.Runtime.Serialization.EnumMemberAttribute()] Starting = 32770, [System.Runtime.Serialization.EnumMemberAttribute()] Snapshotting = 32771, [System.Runtime.Serialization.EnumMemberAttribute()] Migrating = 32772, [System.Runtime.Serialization.EnumMemberAttribute()] Saving = 32773, [System.Runtime.Serialization.EnumMemberAttribute()] Stopping = 32774, [System.Runtime.Serialization.EnumMemberAttribute()] Deleted = 32775, [System.Runtime.Serialization.EnumMemberAttribute()] Pausing = 32776, [System.Runtime.Serialization.EnumMemberAttribute()] Resuming = 32777, } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04", ConfigurationName="VirtualizationWebService.IVirtualizationProvisioningService")] public interface IVirtualizationProvisioningService { [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/CreateVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/CreateVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/CreateVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool CreateVirtualSystem(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualMachineProvisioningRequest request, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/MountVirtualHardDisk", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/MountVirtualHardDiskResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/MountVirtualHardDiskHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] string MountVirtualHardDisk(string virtualDiskPath, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/UnmountVirtualHardDisk", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/UnmountVirtualHardDiskResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/UnmountVirtualHardDiskHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool UnmountVirtualHardDisk(string virtualDiskPath, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/DefineVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/DefineVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/DefineVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool DefineVirtualSystem(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualMachineProvisioningRequest request, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/RemoveVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/RemoveVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/RemoveVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool RemoveVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/StartVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/StartVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/StartVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool StartVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/TurnoffVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/TurnoffVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/TurnoffVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool TurnoffVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/PauseVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/PauseVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/PauseVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool PauseVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ResumeVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ResumeVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ResumeVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool ResumeVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/SnapshotVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/SnapshotVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/SnapshotVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool SnapshotVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/SaveVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/SaveVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/SaveVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool SaveVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ResetVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ResetVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ResetVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool ResetVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ShutdownVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ShutdownVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ShutdownVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool ShutdownVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemMemorySetting", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemMemorySettingResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemMemorySettingHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool ChangeVirtualSystemMemorySetting(string systemName, string serverName, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.MemorySettingInfo setting, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemProcessorSetting", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemProcessorSettingResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemProcessorSettingHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool ChangeVirtualSystemProcessorSetting(string systemName, string serverName, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.ProcessorSettingInfo setting, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemSetting", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemSettingResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/ChangeVirtualSystemSettingHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] bool ChangeVirtualSystemSetting(string systemName, string serverName, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo setting, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystems", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemsResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemsHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemInfo[] GetVirtualSystems(string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystem", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemInfo GetVirtualSystem(string systemName, string serverName, string domain, string userName, string password); [System.ServiceModel.OperationContractAttribute(Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemThumbnailImage", ReplyAction="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemThumbnailImageResponse")] [System.ServiceModel.FaultContractAttribute(typeof(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.HostingServiceFault), Action="http://Microsoft.Hosting.Virtualization.ServiceContracts/2007/04/IVirtualizationP" + "rovisioningService/GetVirtualSystemThumbnailImageHostingServiceFaultFault", Name="HostingServiceFault", Namespace="http://Microsoft.Hosting.FaultContracts/2007/04")] byte[] GetVirtualSystemThumbnailImage(int imgWidth, int imgHeight, string systemName, string serverName, string domain, string userName, string password); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface IVirtualizationProvisioningServiceChannel : WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.IVirtualizationProvisioningService, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class VirtualizationProvisioningServiceClient : System.ServiceModel.ClientBase<WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.IVirtualizationProvisioningService>, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.IVirtualizationProvisioningService { public VirtualizationProvisioningServiceClient() { } public VirtualizationProvisioningServiceClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public VirtualizationProvisioningServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public VirtualizationProvisioningServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public VirtualizationProvisioningServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public bool CreateVirtualSystem(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualMachineProvisioningRequest request, string serverName, string domain, string userName, string password) { return base.Channel.CreateVirtualSystem(request, serverName, domain, userName, password); } public string MountVirtualHardDisk(string virtualDiskPath, string serverName, string domain, string userName, string password) { return base.Channel.MountVirtualHardDisk(virtualDiskPath, serverName, domain, userName, password); } public bool UnmountVirtualHardDisk(string virtualDiskPath, string serverName, string domain, string userName, string password) { return base.Channel.UnmountVirtualHardDisk(virtualDiskPath, serverName, domain, userName, password); } public bool DefineVirtualSystem(WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualMachineProvisioningRequest request, string serverName, string domain, string userName, string password) { return base.Channel.DefineVirtualSystem(request, serverName, domain, userName, password); } public bool RemoveVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.RemoveVirtualSystem(systemName, serverName, domain, userName, password); } public bool StartVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.StartVirtualSystem(systemName, serverName, domain, userName, password); } public bool TurnoffVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.TurnoffVirtualSystem(systemName, serverName, domain, userName, password); } public bool PauseVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.PauseVirtualSystem(systemName, serverName, domain, userName, password); } public bool ResumeVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.ResumeVirtualSystem(systemName, serverName, domain, userName, password); } public bool SnapshotVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.SnapshotVirtualSystem(systemName, serverName, domain, userName, password); } public bool SaveVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.SaveVirtualSystem(systemName, serverName, domain, userName, password); } public bool ResetVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.ResetVirtualSystem(systemName, serverName, domain, userName, password); } public bool ShutdownVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.ShutdownVirtualSystem(systemName, serverName, domain, userName, password); } public bool ChangeVirtualSystemMemorySetting(string systemName, string serverName, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.MemorySettingInfo setting, string domain, string userName, string password) { return base.Channel.ChangeVirtualSystemMemorySetting(systemName, serverName, setting, domain, userName, password); } public bool ChangeVirtualSystemProcessorSetting(string systemName, string serverName, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.ProcessorSettingInfo setting, string domain, string userName, string password) { return base.Channel.ChangeVirtualSystemProcessorSetting(systemName, serverName, setting, domain, userName, password); } public bool ChangeVirtualSystemSetting(string systemName, string serverName, WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemSettingInfo setting, string domain, string userName, string password) { return base.Channel.ChangeVirtualSystemSetting(systemName, serverName, setting, domain, userName, password); } public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemInfo[] GetVirtualSystems(string serverName, string domain, string userName, string password) { return base.Channel.GetVirtualSystems(serverName, domain, userName, password); } public WebsitePanel.Providers.VirtualizationForPC.VirtualizationWebService.VirtualComputerSystemInfo GetVirtualSystem(string systemName, string serverName, string domain, string userName, string password) { return base.Channel.GetVirtualSystem(systemName, serverName, domain, userName, password); } public byte[] GetVirtualSystemThumbnailImage(int imgWidth, int imgHeight, string systemName, string serverName, string domain, string userName, string password) { return base.Channel.GetVirtualSystemThumbnailImage(imgWidth, imgHeight, systemName, serverName, domain, userName, password); } } }
/* * Copyright (c) 2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.InteropServices; using System.Globalization; namespace OpenMetaverse { [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector4 : IComparable<Vector4>, IEquatable<Vector4> { /// <summary>X value</summary> public float X; /// <summary>Y value</summary> public float Y; /// <summary>Z value</summary> public float Z; /// <summary>W value</summary> public float W; #region Constructors public Vector4(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Vector4(Vector2 value, float z, float w) { X = value.X; Y = value.Y; Z = z; W = w; } public Vector4(Vector3 value, float w) { X = value.X; Y = value.Y; Z = value.Z; W = w; } public Vector4(float value) { X = value; Y = value; Z = value; W = value; } /// <summary> /// Constructor, builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing four four-byte floats</param> /// <param name="pos">Beginning position in the byte array</param> public Vector4(byte[] byteArray, int pos) { X = Y = Z = W = 0f; FromBytes(byteArray, pos); } public Vector4(Vector4 value) { X = value.X; Y = value.Y; Z = value.Z; W = value.W; } #endregion Constructors #region Public Methods public float Length() { return (float)Math.Sqrt(DistanceSquared(this, Zero)); } public float LengthSquared() { return DistanceSquared(this, Zero); } public void Normalize() { this = Normalize(this); } /// <summary> /// Test if this vector is equal to another vector, within a given /// tolerance range /// </summary> /// <param name="vec">Vector to test against</param> /// <param name="tolerance">The acceptable magnitude of difference /// between the two vectors</param> /// <returns>True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false</returns> public bool ApproxEquals(Vector4 vec, float tolerance) { Vector4 diff = this - vec; return (diff.Length() <= tolerance); } /// <summary> /// IComparable.CompareTo implementation /// </summary> public int CompareTo(Vector4 vector) { return Length().CompareTo(vector.Length()); } /// <summary> /// Test if this vector is composed of all finite numbers /// </summary> public bool IsFinite() { return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z) && Utils.IsFinite(W)); } /// <summary> /// Builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte vector</param> /// <param name="pos">Beginning position in the byte array</param> public void FromBytes(byte[] byteArray, int pos) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[16]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); Array.Reverse(conversionBuffer, 12, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); W = BitConverter.ToSingle(conversionBuffer, 12); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); W = BitConverter.ToSingle(byteArray, pos + 12); } } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <returns>A 16 byte array containing X, Y, Z, and W</returns> public byte[] GetBytes() { byte[] byteArray = new byte[16]; Buffer.BlockCopy(BitConverter.GetBytes(X), 0, byteArray, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, byteArray, 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, byteArray, 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(W), 0, byteArray, 12, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(byteArray, 0, 4); Array.Reverse(byteArray, 4, 4); Array.Reverse(byteArray, 8, 4); Array.Reverse(byteArray, 12, 4); } return byteArray; } #endregion Public Methods #region Static Methods public static Vector4 Add(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { return new Vector4( Utils.Clamp(value1.X, min.X, max.X), Utils.Clamp(value1.Y, min.Y, max.Y), Utils.Clamp(value1.Z, min.Z, max.Z), Utils.Clamp(value1.W, min.W, max.W)); } public static float Distance(Vector4 value1, Vector4 value2) { return (float)Math.Sqrt(DistanceSquared(value1, value2)); } public static float DistanceSquared(Vector4 value1, Vector4 value2) { return (value1.W - value2.W) * (value1.W - value2.W) + (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } public static Vector4 Divide(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector4 Divide(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } public static float Dot(Vector4 vector1, Vector4 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W; } public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount) { return new Vector4( Utils.Lerp(value1.X, value2.X, amount), Utils.Lerp(value1.Y, value2.Y, amount), Utils.Lerp(value1.Z, value2.Z, amount), Utils.Lerp(value1.W, value2.W, amount)); } public static Vector4 Max(Vector4 value1, Vector4 value2) { return new Vector4( Math.Max(value1.X, value2.X), Math.Max(value1.Y, value2.Y), Math.Max(value1.Z, value2.Z), Math.Max(value1.W, value2.W)); } public static Vector4 Min(Vector4 value1, Vector4 value2) { return new Vector4( Math.Min(value1.X, value2.X), Math.Min(value1.Y, value2.Y), Math.Min(value1.Z, value2.Z), Math.Min(value1.W, value2.W)); } public static Vector4 Multiply(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector4 Multiply(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector4 Negate(Vector4 value) { value.X = -value.X; value.Y = -value.Y; value.Z = -value.Z; value.W = -value.W; return value; } public static Vector4 Normalize(Vector4 vector) { const float MAG_THRESHOLD = 0.0000001f; float factor = DistanceSquared(vector, Zero); if (factor > MAG_THRESHOLD) { factor = 1f / (float)Math.Sqrt(factor); vector.X *= factor; vector.Y *= factor; vector.Z *= factor; vector.W *= factor; } else { vector.X = 0f; vector.Y = 0f; vector.Z = 0f; vector.W = 0f; } return vector; } public static Vector4 SmoothStep(Vector4 value1, Vector4 value2, float amount) { return new Vector4( Utils.SmoothStep(value1.X, value2.X, amount), Utils.SmoothStep(value1.Y, value2.Y, amount), Utils.SmoothStep(value1.Z, value2.Z, amount), Utils.SmoothStep(value1.W, value2.W, amount)); } public static Vector4 Subtract(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector4 Transform(Vector2 position, Matrix4 matrix) { return new Vector4( (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + matrix.M44); } public static Vector4 Transform(Vector3 position, Matrix4 matrix) { return new Vector4( (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + (position.Z * matrix.M34) + matrix.M44); } public static Vector4 Transform(Vector4 vector, Matrix4 matrix) { return new Vector4( (vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + (vector.W * matrix.M41), (vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + (vector.W * matrix.M42), (vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + (vector.W * matrix.M43), (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44)); } public static Vector4 Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector4( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture), float.Parse(split[3].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector4 result) { try { result = Parse(val); return true; } catch (Exception) { result = new Vector4(); return false; } } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Vector4) ? this == (Vector4)obj : false; } public bool Equals(Vector4 other) { return W == other.W && X == other.X && Y == other.Y && Z == other.Z; } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode(); } public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); } /// <summary> /// Get a string representation of the vector elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the vector</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W); } #endregion Overrides #region Operators public static bool operator ==(Vector4 value1, Vector4 value2) { return value1.W == value2.W && value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } public static bool operator !=(Vector4 value1, Vector4 value2) { return !(value1 == value2); } public static Vector4 operator +(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector4 operator -(Vector4 value) { return new Vector4(-value.X, -value.Y, -value.Z, -value.W); } public static Vector4 operator -(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector4 operator *(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector4 operator *(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector4 operator /(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector4 operator /(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } #endregion Operators /// <summary>A vector with a value of 0,0,0,0</summary> public readonly static Vector4 Zero = new Vector4(); /// <summary>A vector with a value of 1,1,1,1</summary> public readonly static Vector4 One = new Vector4(1f, 1f, 1f, 1f); /// <summary>A vector with a value of 1,0,0,0</summary> public readonly static Vector4 UnitX = new Vector4(1f, 0f, 0f, 0f); /// <summary>A vector with a value of 0,1,0,0</summary> public readonly static Vector4 UnitY = new Vector4(0f, 1f, 0f, 0f); /// <summary>A vector with a value of 0,0,1,0</summary> public readonly static Vector4 UnitZ = new Vector4(0f, 0f, 1f, 0f); /// <summary>A vector with a value of 0,0,0,1</summary> public readonly static Vector4 UnitW = new Vector4(0f, 0f, 0f, 1f); } }
using System; using System.Linq; using NetGore.IO; using NUnit.Framework; // ReSharper disable UnusedMember.Local namespace NetGore.Tests.NetGore { [TestFixture] public class EnumHelperTests { static readonly SafeRandom r = new SafeRandom(); static string CreateRandomString() { var length = r.Next(2, 10); var ret = new char[length]; for (var i = 0; i < ret.Length; i++) { int j; if (i == 0) j = r.Next(1, 3); // Don't let the first character be numeric else j = r.Next(0, 3); int min; int max; // ReSharper disable RedundantCast switch (j) { case 0: min = (int)'0'; max = (int)'9'; break; case 1: min = (int)'a'; max = (int)'z'; break; default: min = (int)'A'; max = (int)'Z'; break; } // ReSharper restore RedundantCast ret[i] = (char)r.Next(min, max + 1); } return new string(ret); } #region Unit tests [Test] public void BitsRequiredTest() { Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum1>.MaxValue), EnumHelper<BitsReqEnum1>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum2>.MaxValue), EnumHelper<BitsReqEnum2>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum3>.MaxValue), EnumHelper<BitsReqEnum3>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum4>.MaxValue), EnumHelper<BitsReqEnum4>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum5>.MaxValue), EnumHelper<BitsReqEnum5>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum6>.MaxValue), EnumHelper<BitsReqEnum6>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum7>.MaxValue), EnumHelper<BitsReqEnum7>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum8>.MaxValue), EnumHelper<BitsReqEnum8>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum9>.MaxValue), EnumHelper<BitsReqEnum9>.BitsRequired); Assert.AreEqual(BitOps.RequiredBits((uint)EnumHelper<BitsReqEnum10>.MaxValue), EnumHelper<BitsReqEnum10>.BitsRequired); } [Test] public void ExceptionWhenNotSupportsCastOperationsTest() { #pragma warning disable 219 object o; #pragma warning restore 219 var bs = new BitStream(128); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.BitsRequired); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.MaxValue); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.MinValue); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.GetToIntFunc()); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.GetFromIntFunc()); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.FromInt(1)); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.ToInt(EVULong.A)); Assert.Throws<MethodAccessException>(() => EnumHelper<EVULong>.WriteValue(bs, EVULong.A)); Assert.Throws<MethodAccessException>(() => EnumHelper<EVULong>.WriteValue(bs, "test", EVULong.A)); bs.PositionBits = 0; Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.ReadValue(bs)); Assert.Throws<MethodAccessException>(() => o = EnumHelper<EVULong>.ReadValue(bs, "test")); } [Test] public void FromIntTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.AreEqual(v, EnumHelper<EVByte>.FromInt((int)v)); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.AreEqual(v, EnumHelper<EVSByte>.FromInt((int)v)); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.AreEqual(v, EnumHelper<EVShort>.FromInt((int)v)); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.AreEqual(v, EnumHelper<EVUShort>.FromInt((int)v)); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.AreEqual(v, EnumHelper<EVInt>.FromInt((int)v)); } } [Test] public void InvalidEnumTypeTest() { #pragma warning disable 219 bool b; #pragma warning restore 219 Assert.Throws<TypeInitializationException>(() => b = EnumHelper<int>.Values != null); } [Test] public void IsDefinedInvalidValuesTest() { for (var i = 50; i < 80; i++) { Assert.IsFalse(EnumHelper<EVByte>.IsDefined((EVByte)i)); Assert.IsFalse(EnumHelper<EVSByte>.IsDefined((EVSByte)i)); Assert.IsFalse(EnumHelper<EVShort>.IsDefined((EVShort)i)); Assert.IsFalse(EnumHelper<EVUShort>.IsDefined((EVUShort)i)); Assert.IsFalse(EnumHelper<EVInt>.IsDefined((EVInt)i)); Assert.IsFalse(EnumHelper<EVUInt>.IsDefined((EVUInt)i)); Assert.IsFalse(EnumHelper<EVLong>.IsDefined((EVLong)i)); Assert.IsFalse(EnumHelper<EVULong>.IsDefined((EVULong)i)); } } [Test] public void IsDefinedValidValuesTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.IsTrue(EnumHelper<EVByte>.IsDefined(v)); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.IsTrue(EnumHelper<EVSByte>.IsDefined(v)); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.IsTrue(EnumHelper<EVShort>.IsDefined(v)); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.IsTrue(EnumHelper<EVUShort>.IsDefined(v)); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.IsTrue(EnumHelper<EVInt>.IsDefined(v)); } foreach (var v in EnumHelper<EVLong>.Values) { Assert.IsTrue(EnumHelper<EVLong>.IsDefined(v)); } foreach (var v in EnumHelper<EVULong>.Values) { Assert.IsTrue(EnumHelper<EVULong>.IsDefined(v)); } foreach (var v in EnumHelper<EVUInt>.Values) { Assert.IsTrue(EnumHelper<EVUInt>.IsDefined(v)); } } [Test] public void MaxValueTest() { Assert.AreEqual((int)BitsReqEnum1.a, EnumHelper<BitsReqEnum1>.MaxValue); Assert.AreEqual((int)BitsReqEnum2.b, EnumHelper<BitsReqEnum2>.MaxValue); Assert.AreEqual((int)BitsReqEnum3.c, EnumHelper<BitsReqEnum3>.MaxValue); Assert.AreEqual((int)BitsReqEnum4.d, EnumHelper<BitsReqEnum4>.MaxValue); Assert.AreEqual((int)BitsReqEnum5.e, EnumHelper<BitsReqEnum5>.MaxValue); Assert.AreEqual((int)BitsReqEnum6.f, EnumHelper<BitsReqEnum6>.MaxValue); Assert.AreEqual((int)BitsReqEnum7.g, EnumHelper<BitsReqEnum7>.MaxValue); Assert.AreEqual((int)BitsReqEnum8.h, EnumHelper<BitsReqEnum8>.MaxValue); Assert.AreEqual((int)BitsReqEnum9.i, EnumHelper<BitsReqEnum9>.MaxValue); Assert.AreEqual((int)BitsReqEnum10.j, EnumHelper<BitsReqEnum10>.MaxValue); } [Test] public void MinValueTest() { Assert.AreEqual((int)BitsReqEnum1.a, EnumHelper<BitsReqEnum1>.MinValue); Assert.AreEqual((int)BitsReqEnum2.a, EnumHelper<BitsReqEnum2>.MinValue); Assert.AreEqual((int)BitsReqEnum3.a, EnumHelper<BitsReqEnum3>.MinValue); Assert.AreEqual((int)BitsReqEnum4.a, EnumHelper<BitsReqEnum4>.MinValue); Assert.AreEqual((int)BitsReqEnum5.a, EnumHelper<BitsReqEnum5>.MinValue); Assert.AreEqual((int)BitsReqEnum6.a, EnumHelper<BitsReqEnum6>.MinValue); Assert.AreEqual((int)BitsReqEnum7.a, EnumHelper<BitsReqEnum7>.MinValue); Assert.AreEqual((int)BitsReqEnum8.a, EnumHelper<BitsReqEnum8>.MinValue); Assert.AreEqual((int)BitsReqEnum9.a, EnumHelper<BitsReqEnum9>.MinValue); Assert.AreEqual((int)BitsReqEnum10.a, EnumHelper<BitsReqEnum10>.MinValue); } [Test] public void ParseValidValuesIgnoreCaseLowerTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.AreEqual(v, EnumHelper<EVByte>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.AreEqual(v, EnumHelper<EVSByte>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.AreEqual(v, EnumHelper<EVShort>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.AreEqual(v, EnumHelper<EVUShort>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.AreEqual(v, EnumHelper<EVInt>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVLong>.Values) { Assert.AreEqual(v, EnumHelper<EVLong>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVULong>.Values) { Assert.AreEqual(v, EnumHelper<EVULong>.Parse(v.ToString().ToLower(), true)); } foreach (var v in EnumHelper<EVUInt>.Values) { Assert.AreEqual(v, EnumHelper<EVUInt>.Parse(v.ToString().ToLower(), true)); } } [Test] public void ParseValidValuesIgnoreCaseUpperTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.AreEqual(v, EnumHelper<EVByte>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.AreEqual(v, EnumHelper<EVSByte>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.AreEqual(v, EnumHelper<EVShort>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.AreEqual(v, EnumHelper<EVUShort>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.AreEqual(v, EnumHelper<EVInt>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVLong>.Values) { Assert.AreEqual(v, EnumHelper<EVLong>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVULong>.Values) { Assert.AreEqual(v, EnumHelper<EVULong>.Parse(v.ToString().ToUpper(), true)); } foreach (var v in EnumHelper<EVUInt>.Values) { Assert.AreEqual(v, EnumHelper<EVUInt>.Parse(v.ToString().ToUpper(), true)); } } [Test] public void ParseValidValuesInvalidCaseTest() { foreach (var v in EnumHelper<EVByte>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVByte>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVSByte>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVSByte>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVShort>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVShort>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVUShort>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVUShort>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVInt>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVInt>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVLong>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVLong>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVULong>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVULong>.Parse(b.ToString().ToLower())); } foreach (var v in EnumHelper<EVUInt>.Values) { var b = v; Assert.Throws<ArgumentException>(() => EnumHelper<EVUInt>.Parse(b.ToString().ToLower())); } } [Test] public void ParseValidValuesTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.AreEqual(v, EnumHelper<EVByte>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.AreEqual(v, EnumHelper<EVSByte>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.AreEqual(v, EnumHelper<EVShort>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.AreEqual(v, EnumHelper<EVUShort>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.AreEqual(v, EnumHelper<EVInt>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVLong>.Values) { Assert.AreEqual(v, EnumHelper<EVLong>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVULong>.Values) { Assert.AreEqual(v, EnumHelper<EVULong>.Parse(v.ToString())); } foreach (var v in EnumHelper<EVUInt>.Values) { Assert.AreEqual(v, EnumHelper<EVUInt>.Parse(v.ToString())); } } [Test] public void SupportsCastOperationsTest() { Assert.IsTrue(EnumHelper<EVByte>.SupportsCastOperations); Assert.IsTrue(EnumHelper<EVSByte>.SupportsCastOperations); Assert.IsTrue(EnumHelper<EVShort>.SupportsCastOperations); Assert.IsTrue(EnumHelper<EVUShort>.SupportsCastOperations); Assert.IsTrue(EnumHelper<EVInt>.SupportsCastOperations); Assert.IsFalse(EnumHelper<EVUInt>.SupportsCastOperations); Assert.IsFalse(EnumHelper<EVLong>.SupportsCastOperations); Assert.IsFalse(EnumHelper<EVULong>.SupportsCastOperations); } [Test] public void ToIntTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.AreEqual((int)v, EnumHelper<EVByte>.ToInt(v)); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.AreEqual((int)v, EnumHelper<EVSByte>.ToInt(v)); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.AreEqual((int)v, EnumHelper<EVShort>.ToInt(v)); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.AreEqual((int)v, EnumHelper<EVUShort>.ToInt(v)); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.AreEqual((int)v, EnumHelper<EVInt>.ToInt(v)); } } [Test] public void ToNameTest() { foreach (var v in EnumHelper<EVByte>.Values) { Assert.AreEqual(v, EnumHelper<EVByte>.Parse(EnumHelper<EVByte>.ToName(v))); } foreach (var v in EnumHelper<EVSByte>.Values) { Assert.AreEqual(v, EnumHelper<EVSByte>.Parse(EnumHelper<EVSByte>.ToName(v))); } foreach (var v in EnumHelper<EVShort>.Values) { Assert.AreEqual(v, EnumHelper<EVShort>.Parse(EnumHelper<EVShort>.ToName(v))); } foreach (var v in EnumHelper<EVUShort>.Values) { Assert.AreEqual(v, EnumHelper<EVUShort>.Parse(EnumHelper<EVUShort>.ToName(v))); } foreach (var v in EnumHelper<EVInt>.Values) { Assert.AreEqual(v, EnumHelper<EVInt>.Parse(EnumHelper<EVInt>.ToName(v))); } foreach (var v in EnumHelper<EVLong>.Values) { Assert.AreEqual(v, EnumHelper<EVLong>.Parse(EnumHelper<EVLong>.ToName(v))); } foreach (var v in EnumHelper<EVULong>.Values) { Assert.AreEqual(v, EnumHelper<EVULong>.Parse(EnumHelper<EVULong>.ToName(v))); } foreach (var v in EnumHelper<EVUInt>.Values) { Assert.AreEqual(v, EnumHelper<EVUInt>.Parse(EnumHelper<EVUInt>.ToName(v))); } } [Test] public void TryParseCaseInsensitiveTests() { var names = Enum.GetNames(typeof(TestEnum)); foreach (var name in names) { TestEnum outValue; Assert.IsTrue(EnumHelper<TestEnum>.TryParse(name, true, out outValue)); Assert.AreEqual(EnumHelper<TestEnum>.Parse(name), outValue); Assert.AreEqual((TestEnum)Enum.Parse(typeof(TestEnum), name, true), outValue); } foreach (var name in names.Select(x => x.ToUpper())) { TestEnum outValue; Assert.IsTrue(EnumHelper<TestEnum>.TryParse(name, true, out outValue)); Assert.AreEqual(EnumHelper<TestEnum>.Parse(name, true), outValue); Assert.AreEqual((TestEnum)Enum.Parse(typeof(TestEnum), name, true), outValue); } foreach (var name in names.Select(x => x.ToLower())) { TestEnum outValue; Assert.IsTrue(EnumHelper<TestEnum>.TryParse(name, true, out outValue)); Assert.AreEqual(EnumHelper<TestEnum>.Parse(name, true), outValue); Assert.AreEqual((TestEnum)Enum.Parse(typeof(TestEnum), name, true), outValue); } } [Test] public void TryParseCaseSensitiveTests() { var names = Enum.GetNames(typeof(TestEnum)); foreach (var name in names) { TestEnum outValue; Assert.IsTrue(EnumHelper<TestEnum>.TryParse(name, false, out outValue)); Assert.AreEqual(EnumHelper<TestEnum>.Parse(name, false), outValue); Assert.AreEqual((TestEnum)Enum.Parse(typeof(TestEnum), name, false), outValue); } foreach (var name in names) { var nameUpper = name.ToUpper(); if (name.Equals(nameUpper, StringComparison.CurrentCulture)) continue; TestEnum outValue; Assert.IsFalse(EnumHelper<TestEnum>.TryParse(nameUpper, false, out outValue)); } foreach (var name in names) { var nameLower = name.ToLower(); if (name.Equals(nameLower, StringComparison.CurrentCulture)) continue; TestEnum outValue; Assert.IsFalse(EnumHelper<TestEnum>.TryParse(nameLower, false, out outValue)); } } [Test] public void TryParseRandomStrings() { var names = Enum.GetNames(typeof(TestEnum)); for (var i = 0; i < 1000; i++) { var s = CreateRandomString(); if (names.Contains(s, StringComparer.OrdinalIgnoreCase)) continue; TestEnum outValue; Assert.IsFalse(EnumHelper<TestEnum>.TryParse(s, true, out outValue), "String: " + s); Assert.IsFalse(EnumHelper<TestEnum>.TryParse(s, false, out outValue), "String: " + s); } } [Test] public void TryParseValidValuesIgnoreCaseLowerTest() { foreach (var v in EnumHelper<EVByte>.Values) { EVByte o; Assert.IsTrue(EnumHelper<EVByte>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVSByte>.Values) { EVSByte o; Assert.IsTrue(EnumHelper<EVSByte>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVShort>.Values) { EVShort o; Assert.IsTrue(EnumHelper<EVShort>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVUShort>.Values) { EVUShort o; Assert.IsTrue(EnumHelper<EVUShort>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVInt>.Values) { EVInt o; Assert.IsTrue(EnumHelper<EVInt>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVLong>.Values) { EVLong o; Assert.IsTrue(EnumHelper<EVLong>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVULong>.Values) { EVULong o; Assert.IsTrue(EnumHelper<EVULong>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVUInt>.Values) { EVUInt o; Assert.IsTrue(EnumHelper<EVUInt>.TryParse(v.ToString().ToLower(), true, out o)); Assert.AreEqual(v, o); } } [Test] public void TryParseValidValuesIgnoreCaseUpperTest() { foreach (var v in EnumHelper<EVByte>.Values) { EVByte o; Assert.IsTrue(EnumHelper<EVByte>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVSByte>.Values) { EVSByte o; Assert.IsTrue(EnumHelper<EVSByte>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVShort>.Values) { EVShort o; Assert.IsTrue(EnumHelper<EVShort>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVUShort>.Values) { EVUShort o; Assert.IsTrue(EnumHelper<EVUShort>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVInt>.Values) { EVInt o; Assert.IsTrue(EnumHelper<EVInt>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVLong>.Values) { EVLong o; Assert.IsTrue(EnumHelper<EVLong>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVULong>.Values) { EVULong o; Assert.IsTrue(EnumHelper<EVULong>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVUInt>.Values) { EVUInt o; Assert.IsTrue(EnumHelper<EVUInt>.TryParse(v.ToString().ToUpper(), true, out o)); Assert.AreEqual(v, o); } } [Test] public void TryParseValidValuesTest() { foreach (var v in EnumHelper<EVByte>.Values) { EVByte o; Assert.IsTrue(EnumHelper<EVByte>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVSByte>.Values) { EVSByte o; Assert.IsTrue(EnumHelper<EVSByte>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVShort>.Values) { EVShort o; Assert.IsTrue(EnumHelper<EVShort>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVUShort>.Values) { EVUShort o; Assert.IsTrue(EnumHelper<EVUShort>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVInt>.Values) { EVInt o; Assert.IsTrue(EnumHelper<EVInt>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVLong>.Values) { EVLong o; Assert.IsTrue(EnumHelper<EVLong>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVULong>.Values) { EVULong o; Assert.IsTrue(EnumHelper<EVULong>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } foreach (var v in EnumHelper<EVUInt>.Values) { EVUInt o; Assert.IsTrue(EnumHelper<EVUInt>.TryParse(v.ToString(), out o)); Assert.AreEqual(v, o); } } #endregion enum BitsReqEnum1 { a } ; enum BitsReqEnum10 { a, b, c, d, e, f, g, h, i, j } ; enum BitsReqEnum2 { a, b } ; enum BitsReqEnum3 { a, b, c } ; enum BitsReqEnum4 { a, b, c, d } ; enum BitsReqEnum5 { a, b, c, d, e } ; enum BitsReqEnum6 { a, b, c, d, e, f } ; enum BitsReqEnum7 { a, b, c, d, e, f, g } ; enum BitsReqEnum8 { a, b, c, d, e, f, g, h } ; enum BitsReqEnum9 { a, b, c, d, e, f, g, h, i } ; enum EVByte : byte { A, B, C, D, E, F, G, H } enum EVInt { A = -100, B = 0, C, D, E, F = 100, G, H } enum EVLong : long { A, B, C, D, E, F, G, H } enum EVSByte : byte { A, B, C, D, E, F, G, H } enum EVShort : byte { A, B, C, D, E, F, G, H } enum EVUInt : uint { A = 0, B = 1, C, D, E, F = 100, G, H } enum EVULong : ulong { A, B, C, D, E, F, G, H } enum EVUShort : byte { A, B, C, D, E, F, G, H } enum TestEnum { A, B, C, D, E, F, G, h, i, jk, lmno, p } } }
// String.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; namespace System { /// <summary> /// Equivalent to the String type in Javascript. /// </summary> [IgnoreNamespace] [Imported(ObeysTypeSystem = true)] public sealed class String : IComparable<String>, IEquatable<String> { [ScriptName("")] public String() {} [ScriptName("")] public String(String other) {} [InlineCode("{$System.Script}.stringFromChar({$System.String}.fromCharCode({ch}), {count})")] public String(char ch, int count) {} [IndexerName("Chars")] public char this[int index] { [InlineCode("{this}.charCodeAt({index})")] get { return '\0'; } } [NonScriptable] public IEnumerator<char> GetEnumerator() { return null; } /// <summary> /// An empty zero-length string. /// </summary> [InlineConstant] public const String Empty = ""; /// <summary> /// The number of characters in the string. /// </summary> [IntrinsicProperty] public int Length { get { return 0; } } /// <summary> /// Retrieves the character at the specified position. /// </summary> /// <param name="index">The specified 0-based position.</param> /// <returns>The character within the string.</returns> public string CharAt(int index) { return null; } /// <summary> /// Retrieves the character code of the character at the specified position. /// </summary> /// <param name="index">The specified 0-based position.</param> /// <returns>The character code of the character within the string.</returns> public char CharCodeAt(int index) { return '\0'; } [InlineCode("{$System.Script}.compareStrings({s1}, {s2})")] public static int Compare(string s1, string s2) { return 0; } [InlineCode("{$System.Script}.compareStrings({s1}, {s2}, {ignoreCase})")] public static int Compare(string s1, string s2, bool ignoreCase) { return 0; } [InlineCode("{$System.Script}.compareStrings({this}, {s}, {ignoreCase})")] public int CompareTo(string s, bool ignoreCase) { return 0; } [InlineCode("{$System.Script}.concatStrings({s1}, {s2})")] public static string Concat(string s1, string s2) { return null; } [InlineCode("{$System.Script}.concatStrings({s1}, {s2}, {s3})")] public static string Concat(string s1, string s2, string s3) { return null; } [InlineCode("{$System.Script}.concatStrings({s1}, {s2}, {s3}, {s4})")] public static string Concat(string s1, string s2, string s3, string s4) { return null; } /// <summary> /// Concatenates a set of individual strings into a single string. /// </summary> /// <param name="strings">The sequence of strings</param> /// <returns>The concatenated string.</returns> [InlineCode("{$System.Script}.concatStrings({*strings})")] public static string Concat(params string[] strings) { return null; } [InlineCode("{$System.Script}.concatStrings({o1}, {o2})")] public static string Concat(object o1, object o2) { return null; } [EditorBrowsable(EditorBrowsableState.Never)] [InlineCode("{$System.Script}.concatStrings({o1}, {o2}, {o3})")] public static string Concat(object o1, object o2, object o3) { return null; } [EditorBrowsable(EditorBrowsableState.Never)] [InlineCode("{$System.Script}.concatStrings({o1}, {o2}, {o3}, {o4})")] public static string Concat(object o1, object o2, object o3, object o4) { return null; } [EditorBrowsable(EditorBrowsableState.Never)] [InlineCode("{$System.Script}.concatStrings({*o})")] public static string Concat(params object[] o) { return null; } /// <summary> /// Returns the unencoded version of a complete encoded URI. /// </summary> /// <returns>The unencoded string.</returns> [ScriptAlias("decodeURI")] public static string DecodeUri(string s) { return null; } /// <summary> /// Returns the unencoded version of a single part or component of an encoded URI. /// </summary> /// <returns>The unencoded string.</returns> [ScriptAlias("decodeURIComponent")] public static string DecodeUriComponent(string s) { return null; } /// <summary> /// Encodes the complete URI. /// </summary> /// <returns>The encoded string.</returns> [ScriptAlias("encodeURI")] public static string EncodeUri(string s) { return null; } /// <summary> /// Encodes a single part or component of a URI. /// </summary> /// <returns>The encoded string.</returns> [ScriptAlias("encodeURIComponent")] public static string EncodeUriComponent(string s) { return null; } /// <summary> /// Determines if the string ends with the specified character. /// </summary> /// <param name="ch">The character to test for.</param> /// <returns>true if the string ends with the character; false otherwise.</returns> [InlineCode("{$System.Script}.endsWithString({this}, {$System.String}.fromCharCode({ch}))")] public bool EndsWith(char ch) { return false; } /// <summary> /// Determines if the string ends with the specified substring or suffix. /// </summary> /// <param name="suffix">The string to test for.</param> /// <returns>true if the string ends with the suffix; false otherwise.</returns> [InlineCode("{$System.Script}.endsWithString({this}, {suffix})")] public bool EndsWith(string suffix) { return false; } /// <summary> /// Determines if the strings are equal. /// </summary> /// <returns>true if the string s1 = s2; false otherwise.</returns> [InlineCode("{$System.Script}.compareStrings({s1}, {s2}, {ignoreCase}) === 0)")] public static bool Equals(string s1, string s2, bool ignoreCase) { return false; } /// <summary> /// Encodes a string by replacing punctuation, spaces etc. with their escaped equivalents. /// </summary> /// <returns>The escaped string.</returns> [ScriptAlias("escape") ] public static string Escape(string s) { return null; } [InlineCode("{$System.Script}.formatString({format}, {*values})")] public static string Format(string format, params object[] values) { return null; } [ExpandParams] public static string FromCharCode(params char[] charCode) { return null; } [InlineCode("{$System.Script}.htmlDecode({this})")] public string HtmlDecode() { return null; } [InlineCode("{$System.Script}.htmlEncode({this})")] public string HtmlEncode() { return null; } [InlineCode("{this}.indexOf({$System.String}.fromCharCode({ch}))")] public int IndexOf(char ch) { return 0; } public int IndexOf(string subString) { return 0; } [InlineCode("{this}.indexOf({$System.String}.fromCharCode({ch}), {startIndex})")] public int IndexOf(char ch, int startIndex) { return 0; } public int IndexOf(string ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch})")] public int IndexOfAny(params char[] ch) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch}, {startIndex})")] public int IndexOfAny(char[] ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch}, {startIndex}, {count})")] public int IndexOfAny(char[] ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.insertString({this}, {index}, {value})")] public string Insert(int index, string value) { return null; } [InlineCode("{$System.Script}.isNullOrEmptyString({s})")] public static bool IsNullOrEmpty(string s) { return false; } [InlineCode("{this}.lastIndexOf({$System.String}.fromCharCode({ch}))")] public int LastIndexOf(char ch) { return 0; } public int LastIndexOf(string subString) { return 0; } public int LastIndexOf(string subString, int startIndex) { return 0; } [InlineCode("{this}.lastIndexOf({$System.String}.fromCharCode({ch}), {startIndex})")] public int LastIndexOf(char ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch})")] public int LastIndexOfAny(params char[] ch) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch}, {startIndex})")] public int LastIndexOfAny(char[] ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch}, {startIndex}, {count})")] public int LastIndexOfAny(char[] ch, int startIndex, int count) { return 0; } public int LocaleCompare(string string2) { return 0; } [ExpandParams] public static string LocaleFormat(string format, params object[] values) { return null; } public string[] Match(Regex regex) { return null; } [InlineCode("{$System.Script}.padLeftString({this}, {totalWidth})")] public string PadLeft(int totalWidth) { return null; } [InlineCode("{$System.Script}.padLeftString({this}, {totalWidth}, {ch})")] public string PadLeft(int totalWidth, char ch) { return null; } [InlineCode("{$System.Script}.padRightString({this}, {totalWidth})")] public string PadRight(int totalWidth) { return null; } [InlineCode("{$System.Script}.padRightString({this}, {totalWidth}, {ch})")] public string PadRight(int totalWidth, char ch) { return null; } [InlineCode("{$System.Script}.removeString({this}, {index})")] public string Remove(int index) { return null; } [InlineCode("{$System.Script}.removeString({this}, {index}, {count})")] public string Remove(int index, int count) { return null; } [InlineCode("{$System.Script}.replaceAllString({this}, {oldText}, {replaceText})")] public string Replace(string oldText, string replaceText) { return null; } [ScriptName("replace")] public string ReplaceFirst(string oldText, string replaceText) { return null; } [ScriptName("replace")] public string Replace(Regex regex, string replaceText) { return null; } [ScriptName("replace")] public string Replace(Regex regex, StringReplaceCallback callback) { return null; } public int Search(Regex regex) { return 0; } public string[] Split(string separator) { return null; } [InlineCode("{this}.split({$System.String}.fromCharCode({separator}))")] public string[] Split(char separator) { return null; } public string[] Split(string separator, int limit) { return null; } [InlineCode("{this}.split({$System.String}.fromCharCode({separator}), {limit})")] public string[] Split(char separator, int limit) { return null; } public string[] Split(Regex regex) { return null; } public string[] Split(Regex regex, int limit) { return null; } [InlineCode("{$System.Script}.startsWithString({this}, {$System.String}.fromCharCode({ch}))")] public bool StartsWith(char ch) { return false; } [InlineCode("{$System.Script}.startsWithString({this}, {prefix})")] public bool StartsWith(string prefix) { return false; } public string Substr(int startIndex) { return null; } public string Substr(int startIndex, int length) { return null; } public string Substring(int startIndex) { return null; } [ScriptName("substr")] public string Substring(int startIndex, int length) { return null; } [ScriptName("substring")] public string JsSubstring(int startIndex, int end) { return null; } public string ToLocaleLowerCase() { return null; } public string ToLocaleUpperCase() { return null; } public string ToLowerCase() { return null; } [ScriptName("toLowerCase")] public string ToLower() { return null; } public string ToUpperCase() { return null; } [ScriptName("toUpperCase")] public string ToUpper() { return null; } public string Trim() { return null; } [InlineCode("{$System.Script}.trimStartString({this})")] public string TrimStart() { return null; } [InlineCode("{$System.Script}.trimEndString({this})")] public string TrimEnd() { return null; } /// <summary> /// Decodes a string by replacing escaped parts with their equivalent textual representation. /// </summary> /// <returns>The unescaped string.</returns> [ScriptAlias("unescape")] public static string Unescape(string s) { return null; } [IntrinsicOperator] public static bool operator ==(string s1, string s2) { return false; } [IntrinsicOperator] public static bool operator !=(string s1, string s2) { return false; } [InlineCode("{$System.Script}.compare({this}, {other})")] public int CompareTo(string other) { return 0; } [InlineCode("{$System.Script}.equalsT({this}, {other})")] public bool Equals(string other) { return false; } } }
using System; using System.Runtime.InteropServices; namespace ManagedBass.Vst { /// <summary> /// BassVst allows the usage of VST effect plugins as well as VST instruments (VSTi plugins) with BASS. /// </summary> public static class BassVst { const string DllName = "bass_vst"; /// <summary> /// Creates a new BASS stream based on any VST instrument plugin (VSTi). /// </summary> /// <param name="Frequency">The sample rate of the VSTi output (e.g. 44100).</param> /// <param name="Channels">The number of channels... 1 = mono, 2 = stereo, 4 = quadraphonic, 6 = 5.1, 8 = 7.1.</param> /// <param name="DllFile">The fully qualified path and file name to the VSTi plugin (a DLL file name).</param> /// <param name="Flags">A combination of <see cref="BassFlags"/>.</param> /// <returns>If successful, the new vst handle is returned, else 0 is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// On success, the function returns the new vstHandle that must be given to the other functions. /// The returned VST handle can also be given to the typical Bass.Channel* functions. /// Use <see cref="ChannelFree" /> to delete and free a VST instrument channel. /// </remarks> public static int ChannelCreate(int Frequency, int Channels, string DllFile, BassFlags Flags) { return BASS_VST_ChannelCreate(Frequency, Channels, DllFile, Flags | BassFlags.Unicode); } [DllImport(DllName, CharSet = CharSet.Unicode)] static extern int BASS_VST_ChannelCreate(int Frequency, int Channels, string DllFile, BassFlags Flags); /// <summary> /// Deletes and frees a VST instrument channel. /// </summary> /// <param name="VstHandle">The VSTi channel to delete (as created by <see cref="ChannelCreate" />).</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// Note, that you cannot delete VST effects assigned to this channels this way; for this purpose, please call <see cref="ChannelRemoveDSP" />. /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_ChannelFree")] public static extern bool ChannelFree(int VstHandle); /// <summary> /// Removes a VST effect from a channel and destroys the VST instance. /// </summary> /// <param name="Channels">The channel handle from which to remove the VST effect... a HSTREAM, HMUSIC, or HRECORD.</param> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// <para>If you do not call <see cref="ChannelRemoveDSP" /> explicitly and you have assigned a channel to the effect, the effect is removed automatically when the channel handle is deleted by BASS (like for any other DSP as well).</para> /// <para>For various reasons, the underlying DLL is unloaded from memory with a little delay, however, this has also the advantage that subsequent adding/removing of DLLs to channels has no bad performance impact.</para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_ChannelRemoveDSP")] public static extern bool ChannelRemoveDSP(int Channels, int VstHandle); /// <summary> /// Assigns a VST effects (defined by a DLL file name) to any BASS channels. /// <para>This overload implements the Unicode overload for the dllFile name, so the BASS_UNICODE flag will automatically be added if not already set.</para> /// </summary> /// <param name="Channels">The channel handle... a HSTREAM, HMUSIC, or HRECORD. Or 0, if you want to test, if the dll is a valid VST plugin.</param> /// <param name="DllFile">The fully qualified path and file name to the VST effect plugin (a DLL file name).</param> /// <param name="Flags">A combination of <see cref="BassVstDsp"/></param> /// <param name="Priority">Same meaning as for <see cref="Bass.ChannelSetDSP" /> - DSPs with higher priority are called before those with lower.</param> /// <returns>On success, the method returns the new vstHandle that must be given to all the other functions, else 0 is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// The VST plugin is implemented via a DSP callback on the channel. /// That means when you play the channel (or call <see cref="Bass.ChannelGetData(int,IntPtr,int)" /> if it's a decoding channel), the sample data will be sent to the VST effect at the same time. /// If the channel is freed all DSPs are removed automatically, also all VST DSPs are removed as well. /// If you want or need to free the VST DSP manually you can call <see cref="ChannelRemoveDSP" />. /// <para>For testing if a DLL is a valid VST effect, you can set Channels to 0 - however, do not forget to call <see cref="ChannelRemoveDSP" /> even in this case.</para> /// <para> /// You may safely assign the same DLL to different channels at the same time - the library makes sure, every channel is processed indepeningly. /// But take care to use the correct vstHandles in this case. /// </para> /// <para> /// Finally, you can use any number of VST effects on a channel. /// They are processed alongside with all other BASS DSPs in the order of it's priority. /// </para> /// <para> /// To set or get the parameters of a VST effect you might use <see cref="GetParamCount" /> alongside with <see cref="GetParam" /> and <see cref="SetParam" /> to enumerate over the total number of effect parameters. /// To retrieve details about an individual parameter you might use <see cref="GetParamInfo(int,int,out BassVstParamInfo)" />. /// If the VST effect supports an embedded editor you might also invoke this one with <see cref="EmbedEditor" />. /// If the embedded editor also supports localization you might set the language in advance with <see cref="SetLanguage" />. /// </para> /// <para>If you need to temporarily bypass the VST effect you might call <see cref="SetBypass" /> - <see cref="GetBypass" /> will tell you the current bypass status though.</para> /// <para>Use <see cref="GetInfo" /> to get even more details about a loaded VST plugin.</para> /// </remarks> public static int ChannelSetDSP(int Channels, string DllFile, BassVstDsp Flags, int Priority) { return BASS_VST_ChannelSetDSP(Channels, DllFile, Flags | BassVstDsp.Unicode, Priority); } [DllImport(DllName, CharSet = CharSet.Unicode)] static extern int BASS_VST_ChannelSetDSP(int Channels, string DllFile, BassVstDsp Flags, int Priority); /// <summary> /// Many VST effects come along with an graphical parameters editor; with the following function, you can embed these editors to your user interface. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ParentWindow">The IntPtr to the window handle (HWND) of the parents window in which the editor should be embedded (e.g. use a new modeless dialog or user control).</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// <para> /// To embed the editor to another window, call this function with parentWindow set to the HWND of the parent window. /// To check, if an effect has an editor, see the hasEditor flag set by <see cref="GetInfo" />. /// </para> /// <para>To "unembed" the editor, call this function with <paramref name="ParentWindow"/> set to <see langword="null" />.</para> /// <para> /// If you create the editor window independently of a real channel (by skipping the channel parameter when calling <see cref="ChannelSetDSP" />) and the editor displays any spectrums, VU-meters or such, /// the data for this come from the most recent channel using the same effect and the same scope. /// The scope can be set by <see cref="SetScope" /> to any ID, the default is 0. /// </para> /// <para>In order to create a new window in which the editor should be embedded, it is a good idea to call <see cref="GetInfo" /> in order to retrieve the editors height and width.</para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_EmbedEditor")] public static extern bool EmbedEditor(int VstHandle, IntPtr ParentWindow); /// <summary> /// Gets the current bypasses state of the the effect processing. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> [DllImport(DllName, EntryPoint = "BASS_VST_GetBypass")] public static extern bool GetBypass(int VstHandle); [DllImport(DllName)] static extern IntPtr BASS_VST_GetChunk(int VstHandle, bool IsPreset, ref int Length); /// <summary> /// Gets the VST plug-in state as a plain byte array (memory chunk storage). /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="IsPreset"><see langword="true" /> when saving a single program; <see langword="false" /> for all programs.</param> /// <returns>The array of bytes representing the VST plug-in state - or <see langword="null" /> if the VST doesn't support the chunk data mode.</returns> /// <remarks> /// There are two ways to store the current state of a VST plug-In: /// Either trough the parameter interfaces (<see cref="GetParam" /> and <see cref="SetParam" />) or as an opaque memory block (chunk mode). /// <para> /// You might first queries this method to see, if the VST supports the chunk mode. /// If it is not implemented (<see langword="null" /> is returned), the values of all parameters might be used to save the plug-in state. /// </para> /// <para> /// Chunk storage allows to save additional data (besides the parameter state) which is specific to the VST plug-in. /// Please note, that if you decide to use the chunk storage, you have to take care of saving and loading parameter states on your own (see <see cref="SetChunk(int,bool,byte[],int)" /> for details)! /// </para> /// </remarks> public static byte[] GetChunk(int VstHandle, bool IsPreset) { var num = 0; var intPtr = BASS_VST_GetChunk(VstHandle, IsPreset, ref num); if (intPtr == IntPtr.Zero || num <= 0) return null; var numArray = new byte[num]; Marshal.Copy(intPtr, numArray, 0, num); return numArray; } /// <summary> /// Gets general information about a VST effect plugin. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="Info">An instance of the <see cref="BassVstInfo" /> where to store the parameter information at.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// <para> /// VST effects that have no input channels (so called "Instruments") are not loaded by BASS_VST. /// So you can assume chansIn and chansOut to be at least 1. /// </para> /// <para> /// Multi-channel streams should work correctly, if supported by a effect. /// If not, only the first chansIn channels are processed by the effect, the other ones stay unaffected. /// The opposite, eg. assigning multi-channel effects to stereo channels, should be no problem at all. /// </para> /// <para> /// If mono effects are assigned to stereo channels, the result will be mono, expanded to both channels. /// This behaviour can be switched of using the <see cref="BassVstDsp.KeepChannels"/> in <see cref="ChannelSetDSP" />. /// </para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_GetInfo")] public static extern bool GetInfo(int VstHandle, out BassVstInfo Info); /// <summary> /// Gets general information about a VST effect plugin. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>If successful, an instance of <see cref="BassVstInfo" /> is returned, else <see langword="null" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// <para> /// VST effects that have no input channels (so called "Instruments") are not loaded by BASS_VST. /// So you can assume chansIn and chansOut to be at least 1. /// </para> /// <para> /// Multi-channel streams should work correctly, if supported by a effect. /// If not, only the first chansIn channels are processed by the effect, the other ones stay unaffected. /// The opposite, eg. assigning multi-channel effects to stereo channels, should be no problem at all. /// </para> /// <para> /// If mono effects are assigned to stereo channels, the result will be mono, expanded to both channels. /// This behaviour can be switched of using the <see cref="BassVstDsp.KeepChannels"/> in <see cref="ChannelSetDSP" />. /// </para> /// </remarks> public static BassVstInfo BASS_VST_GetInfo(int VstHandle) { if (!GetInfo(VstHandle, out var info)) throw new BassException(); return info; } /// <summary> /// Get the value of a single VST effect parameter. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ParamIndex">The index of the parameter (must be smaller than <see cref="GetParamCount" />).</param> /// <returns><see langword="true" /> on success.</returns> /// <remarks> /// <para> /// All VST effect parameters are in the range from 0.0 to 1.0 (float), however, from the view of a VST effect, they may represent completely different values. /// E.g. some might represent a multiplier to some internal constants and will result in number of samples or some might represent a value in dB etc. /// </para> /// <para>You can use <see cref="GetParamInfo(int,int,out BassVstParamInfo)" /> to get further information about a single parameter, which will also present you with the current value in a readable format.</para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_GetParam")] public static extern float GetParam(int VstHandle, int ParamIndex); /// <summary> /// Returns the number of editable parameters for the VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>The number of editable parameters or if the effect has no editable parameters, 0 is returned.</returns> /// <remarks> /// To set or get the individual parameters of a VST effect you might use <see cref="GetParamCount" /> alongside with <see cref="GetParam" /> and <see cref="SetParam" /> to enumerate over the total number of effect parameters. /// To retrieve details about an individual parameter you might use <see cref="GetParamInfo(int,int,out BassVstParamInfo)" />. /// If the VST effect supports an embedded editor you might also invoke this one with <see cref="EmbedEditor" />. /// If the embedded editor also supports localization you might set the language in advance with <see cref="SetLanguage" />. /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_GetParamCount")] public static extern int GetParamCount(int VstHandle); /// <summary> /// Get some common information about an editable parameter to a <see cref="BassVstParamInfo" /> object. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ParamIndex">The index of the parameter (must be smaller than <see cref="GetParamCount" />).</param> /// <param name="Info">An instance of the <see cref="BassVstParamInfo" /> where to store the parameter information at.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> [DllImport(DllName, EntryPoint = "BASS_VST_GetParamInfo")] public static extern bool GetParamInfo(int VstHandle, int ParamIndex, out BassVstParamInfo Info); /// <summary> /// Get some common information about an editable parameter to a <see cref="BassVstParamInfo" /> class. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ParamIndex">The index of the parameter (must be smaller than <see cref="GetParamCount" />).</param> /// <returns>If successful, an instance of the <see cref="BassVstParamInfo" /> is returned, else <see langword="null" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> public static BassVstParamInfo GetParamInfo(int VstHandle, int ParamIndex) { if (!GetParamInfo(VstHandle, ParamIndex, out var info)) throw new BassException(); return info; } /// <summary> /// Returns the currently selected program for the VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>The currect selected program number. Valid program numbers are between 0 and <see cref="GetProgramCount" /> minus 1.</returns> /// <remarks> /// After construction (using <see cref="ChannelSetDSP" />), always the first program (0) is selected. /// <para> /// With <see cref="SetProgram" /> you can change the selected program. /// Functions as <see cref="SetParam" /> will always change the selected program's settings. /// </para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_GetProgram")] public static extern int GetProgram(int VstHandle); /// <summary> /// Returns the number of editable programs for the VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>The number of available programs or 0 if no program is available.</returns> /// <remarks> /// Many (not all!) effects have more than one "program" that can hold a complete set of parameters each. /// Moreover, some of these programs may be initialized to some useful "factory defaults". /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_GetProgramCount")] public static extern int GetProgramCount(int VstHandle); /// <summary> /// Gets the name of any program of a VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ProgramIndex">The program number for which to get the name, must be smaller than <see cref="GetProgramCount" />.</param> /// <returns>The name of the program given or <see langword="null" /> if not valid.</returns> /// <remarks>The names are limited to 24 characters. This function does not change the selected program!</remarks> public static string GetProgramName(int VstHandle, int ProgramIndex) { return Marshal.PtrToStringAnsi(BASS_VST_GetProgramName(VstHandle, ProgramIndex)); } [DllImport(DllName)] static extern IntPtr BASS_VST_GetProgramName(int VstHandle, int ProgramIndex); /// <summary> /// Returns a list of all available program names. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>An array of strings representing the list of available program names. The index corresponds to the program numbers.</returns> /// <remarks>This function does not change the selected program!</remarks> public static string[] GetProgramNames(int VstHandle) { var num = GetProgramCount(VstHandle); if (num <= 0) return null; var strArrays = new string[num]; for (var i = 0; i < num; i++) strArrays[i] = GetProgramName(VstHandle, i); return strArrays; } /// <summary> /// Returns the parameters of a given program. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ProgramIndex">The program number for which to query the parameter values, must be smaller than <see cref="GetProgramCount" />.</param> /// <returns>An array of float values representing the parameter values of the given program or <see langword="null" /> if the program (VST effect) has no parameters or an error occurred.</returns> /// <remarks> /// <para>The parameters of the currently selected program can also be queried by <see cref="GetParam" />.</para> /// <para> /// The function returns the parameters as an array of floats. /// The number of elements in the returned array is equal to <see cref="GetParamCount" />. /// </para> /// <para>This function does not change the selected program!</para> /// </remarks> public static float[] GetProgramParam(int VstHandle, int ProgramIndex) { var num = 0; var intPtr = BASS_VST_GetProgramParam(VstHandle, ProgramIndex, ref num); if (intPtr == IntPtr.Zero || num <= 0) return null; var singleArray = new float[num]; Marshal.Copy(intPtr, singleArray, 0, num); return singleArray; } [DllImport(DllName)] static extern IntPtr BASS_VST_GetProgramParam(int VstHandle, int ProgramIndex, ref int Length); /// <summary> /// Sends a MIDI message/event to the VSTi plugin. /// </summary> /// <param name="VstHandle">The VSTi channel to send a MIDI message to (as created by <see cref="ChannelCreate" />).</param> /// <param name="MidiChannel">The Midi channel number to use (0 to 15).</param> /// <param name="EventType">The Midi event/status value to use (see MidiEventType for details).</param> /// <param name="Param">The data bytes to send with the message to compose a data byte 1 and 2.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// Use one of the MidiEventType commands similar to BassMidi.StreamEvent(int,int,MidiEventType,int). /// <para> /// Set <paramref name="MidiChannel" /> to 0xFFFF and <paramref name="EventType" /> to the raw command to send. /// The raw command must be encoded as 0x00xxyyzz with xx=MIDI command, yy=MIDI databyte #1, zz=MIDI databyte #2. /// <paramref name="Param" /> should be set to 0 in this case. /// </para> /// <para> /// Send SysEx commands by setting <paramref name="MidiChannel" /> to 0xEEEE. /// <paramref name="EventType" /> will denote the type of event to send (see MidiEventType about possible values for <paramref name="Param" /> in such case). /// </para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_ProcessEvent")] public static extern bool ProcessEvent(int VstHandle, int MidiChannel, int EventType, int Param); /// <summary> /// Sends a SysEx or MIDI (short)message/event to the VSTi plugin. /// </summary> /// <param name="VstHandle">The VSTi channel to send a MIDI message to (as created by <see cref="ChannelCreate" />).</param> /// <param name="Message">The pointer to your Midi message data to send (byte[]).</param> /// <param name="Length">The length of a SysEx message or 0 in case of a normal Midi (short)message.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// <para> /// To send a Midi (short)message : /// The raw message must be encoded as 0x00xxyyzz with xx=MIDI command, yy=MIDI databyte #1, zz=MIDI databyte #2. /// <paramref name="Length" /> should be set to 0 in this case. /// </para> /// <para> /// To send a SysEx message: /// <paramref name="Message" /> must be set to a pointer to the bytes to send and <paramref name="Length" /> must be set to the number of bytes to send. /// </para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_ProcessEventRaw")] public static extern bool ProcessEventRaw(int VstHandle, IntPtr Message, int Length); /// <summary> /// Sends a SysEx or MIDI (short)message/event to the VSTi plugin. /// </summary> /// <param name="VstHandle">The VSTi channel to send a MIDI message to (as created by <see cref="ChannelCreate" />).</param> /// <param name="Message">The byte array containing your Midi message data to send.</param> /// <param name="Length">The length of a SysEx message or 0 in case of a normal Midi (short)message.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// <para> /// To send a Midi (short)message : /// The raw message must be encoded as 0x00xxyyzz with xx=MIDI command, yy=MIDI databyte #1, zz=MIDI databyte #2. /// <paramref name="Length" /> should be set to 0 in this case. /// </para> /// <para> /// To send a SysEx message: /// <paramref name="Message" /> must be set to a pointer to the bytes to send and <paramref name="Length" /> must be set to the number of bytes to send. /// </para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_ProcessEventRaw")] public static extern bool ProcessEventRaw(int VstHandle, byte[] Message, int Length); /// <summary> /// Call this function after position changes or sth. like that. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// Some VST effects will use an internal buffer for effect calculation and handling. /// This will reset the internal VST buffers which may remember some "old" data. /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_Resume")] public static extern bool Resume(int VstHandle); /// <summary> /// Bypasses the effect processing (state=<see langword="true" />) or switch back to normal processing (state=<see langword="false" />). /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="State"><see langword="true" /> to bypasses the effect processing; <see langword="false" /> to switch back to normal processing.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// By default bypassing is OFF and the effect will be processed normally. /// Use <see cref="GetBypass" /> returns the current state. /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetBypass")] public static extern bool SetBypass(int VstHandle, bool State); /// <summary> /// Assign a callback function to a vstHandle. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="Procedure">The user defined callback delegate (see <see cref="VstProcedure" />).</param> /// <param name="User">User instance data to pass to the callback function.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks>Unless defined otherwise, the callback function should always return 0.</remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetCallback")] public static extern bool SetCallback(int VstHandle, VstProcedure Procedure, IntPtr User); /// <summary> /// Sets the VST plug-in state with a plain byte array (memory chunk storage). /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="IsPreset"><see langword="true" /> when restoring a single program; <see langword="false" /> for all programs.</param> /// <param name="Chunk">The byte array containing the memory chunk storage to set.</param> /// <param name="Length">The number of bytes to write.</param> /// <returns>The number of bytes written.</returns> /// <remarks> /// Might be used to restore a VST plug-in state which was previously saved via <see cref="GetChunk" />. /// <para>After restoring a plug-in state you might need to retrieve the program names again (see <see cref="GetProgramName" /> and <see cref="GetProgramCount" />) as they might have changed.</para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetChunk")] public static extern int SetChunk(int VstHandle, bool IsPreset, byte[] Chunk, int Length); /// <summary> /// Sets the VST plug-in state with a plain byte array (memory chunk storage). /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="IsPreset"><see langword="true" /> when restoring a single program; <see langword="false" /> for all programs.</param> /// <param name="Chunk">The byte array containing the memory chunk storage to set.</param> /// <returns>The number of bytes written.</returns> /// <remarks> /// Might be used to restore a VST plug-in state which was previously saved via <see cref="GetChunk" />. /// <para>After restoring a plug-in state you might need to retrieve the program names again (see <see cref="GetProgramName" /> and <see cref="GetProgramCount" />) as they might have changed.</para> /// </remarks> public static int SetChunk(int VstHandle, bool IsPreset, byte[] Chunk) { return SetChunk(VstHandle, IsPreset, Chunk, Chunk.Length); } /// <summary> /// Set the VST language to be used by any plugins. /// </summary> /// <param name="Language">The desired language as ISO 639.1, e.g. "en", "de", "es"...</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// Some VST effects come along localized. /// With this function you can set the desired language as ISO 639.1 -- eg. "en" for english, "de" for german, "es" for spanish and so on. /// The default language is english. /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetLanguage", CharSet = CharSet.Unicode)] public static extern bool SetLanguage(string Language); /// <summary> /// Set a value of a single VST effect parameter. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ParamIndex">The index of the parameter (must be smaller than <see cref="GetParamCount" />).</param> /// <param name="NewValue">The new value to set in the range from 0.0 to 1.0 (float). See the documentation of the actual VST implementation for details of the effective value representation.</param> /// <returns><see langword="true" /> on success.</returns> /// <remarks> /// <para> /// All VST effect parameters are in the range from 0.0 to 1.0 (float), however, from the view of a VST effect, they may represent completely different values. /// E.g. some might represent a multiplier to some internal constants and will result in number of samples or some might represent a value in dB etc. /// </para> /// <para>So it is a good idea to call <see cref="GetParamInfo(int,int,out BassVstParamInfo)" /> after you modified a parameter, in order to to get further information about the parameter in question, which will also present you with the current value in a readable format.</para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetParam")] public static extern bool SetParam(int VstHandle, int ParamIndex, float NewValue); /// <summary> /// Sets (changes) the selected program for the VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ProgramIndex">The program number to set (between 0 and <see cref="GetProgramCount" /> minus 1.).</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks>You might call <see cref="GetProgramCount" /> to check, if the VST effect has any editable programs available. /// <para> /// With <see cref="GetProgram" /> you can check, which is the current selected program. /// Functions as as <see cref="SetParam" /> will always change the selected program's settings. /// </para> /// </remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetProgram")] public static extern bool SetProgram(int VstHandle, int ProgramIndex); /// <summary> /// Sets the name of any program of a VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ProgramIndex">The program number for which to set the name, must be smaller than <see cref="GetProgramCount" />.</param> /// <param name="Name">The new name to use. Names are limited to 24 characters, BASS_VST truncates the names, if needed.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks>This function does not change the selected program!</remarks> [DllImport(DllName, EntryPoint = "BASS_VST_SetProgramName", CharSet = CharSet.Unicode)] public static extern bool SetProgramName(int VstHandle, int ProgramIndex, string Name); [DllImport(DllName)] static extern bool BASS_VST_SetProgramParam(int VstHandle, int ProgramIndex, float[] Param, int Length); /// <summary> /// Set all parameters of any program in a VST effect. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="ProgramIndex">The program number for which to set the parameter values, must be smaller than <see cref="GetProgramCount" />.</param> /// <param name="Param">An array with the parameter values to set. The array needs to have as many elements as defined by <see cref="GetParamCount" /> or as returned be <see cref="GetProgramParam" />.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> /// <remarks> /// This function does not change the selected program! /// <para>If you use <see cref="SetCallback" />, the <see cref="BassVstAction.ParametersChanged"/> event is only posted if you select a program with parameters different from the prior.</para> /// </remarks> public static bool SetProgramParam(int VstHandle, int ProgramIndex, float[] Param) { return BASS_VST_SetProgramParam(VstHandle, ProgramIndex, Param, Param.Length); } /// <summary> /// Sets the scope of an Editor to a given ID. /// </summary> /// <param name="VstHandle">The VST effect handle as returned by <see cref="ChannelSetDSP" />.</param> /// <param name="Scope">The ID to set the scope to.</param> /// <returns>If successful, <see langword="true" /> is returned, else <see langword="false" /> is returned. Use <see cref="Bass.LastError" /> to get the error code.</returns> [DllImport(DllName, EntryPoint = "BASS_VST_SetScope")] public static extern bool SetScope(int VstHandle, int Scope); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SubnetsOperations operations. /// </summary> internal partial class SubnetsOperations : IServiceOperations<NetworkManagementClient>, ISubnetsOperations { /// <summary> /// Initializes a new instance of the SubnetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubnetsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified subnet by virtual network and resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (subnetParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(subnetParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Xml; namespace Apache.Geode.DUnitFramework { /// <summary> /// Interface for sending commands from server to client. /// </summary> public interface IClientComm { /// <summary> /// Synchronously call a function on the client without any return value. /// </summary> /// <param name="objectId"> /// The ID of the object on which the method has to be invoked. /// </param> /// <param name="assemblyName"> /// The name of the assembly where the type is defined. /// </param> /// <param name="typeName">The type name (class) of the object.</param> /// <param name="methodName"> /// The name of the method to be invoked for the object. /// </param> /// <param name="paramList">The list of parameters for the method.</param> void Call(int objectId, string assemblyName, string typeName, string methodName, params object[] paramList); /// <summary> /// Synchronously call a function on the client returning some value. /// </summary> /// <param name="objectId"> /// The ID of the object on which the method has to be invoked. /// </param> /// <param name="assemblyName"> /// The name of the assembly where the type is defined. /// </param> /// <param name="typeName">The type name (class) of the object.</param> /// <param name="methodName"> /// The name of the method to be invoked for the object. /// </param> /// <param name="paramList">The list of parameters for the method.</param> /// <returns>The result of the invocation of the method.</returns> object CallR(int objectId, string assemblyName, string typeName, string methodName, params object[] paramList); /// <summary> /// End the persistence of the object with the given ID. /// </summary> /// <param name="objectId">The ID of the object.</param> void RemoveObjectID(int objectId); /// <summary> /// Set path of the log file for the client. /// </summary> /// <param name="logPath">The path of the log file.</param> void SetLogFile(string logPath); /// <summary> /// Set logging level for the client. /// </summary> /// <param name="logLevel">The logging level to set.</param> void SetLogLevel(Util.LogLevel logLevel); /// <summary> /// Create a new client on the same host as of the running process /// with the given clientId and port. /// </summary> /// <param name="clientId">The ID of the new client.</param> /// <param name="port">The port of the new client.</param> /// <returns>Whether the process successfully started.</returns> bool CreateNew(string clientId, int port); /// <summary> /// Dump the stack trace of the process. /// Usually invoked before exiting when a timeout has occurred. /// </summary> void DumpStackTrace(); /// <summary> /// Any cleanup to be performed at the end of a test. /// </summary> void TestCleanup(); /// <summary> /// Signal that the client should exit. /// </summary> void Exit(bool force); /// <summary> /// Gets the process object of the client process /// </summary> /// <returns>Process object</returns> System.Diagnostics.Process GetClientProcess(); } public interface IClientCommV2 : IClientComm { /// <summary> /// Launches a client on the same host as of the running process /// with the given arguments. /// </summary> /// <param name="clientPath">Location and name of the client to be launched.</param> /// <param name="args">Arguments that are to be passed to the client.</param> /// <param name="proc">Process object of the started process.</param> /// <returns>Whether the process successfully started.</returns> bool LaunchNewClient(string clientPath, string args, out System.Diagnostics.Process proc); } /// <summary> /// Interface for sending commands from client to server. /// </summary> public interface IDriverComm { /// <summary> /// Log a message on the main server thread. /// </summary> /// <param name="clientId">The ID of the client.</param> /// <param name="prefix">A string to be prefixed in the log line.</param> /// <param name="message">The log message.</param> void Log(string clientId, string prefix, string message); /// <summary> /// Signal that the client is up and running, so that the server /// can initiate connection to the client. /// </summary> /// <param name="clientId">The ID of the client.</param> void ClientListening(string clientId); /// <summary> /// Client callback to request server to start a task on another Windows machine. /// </summary> /// <param name="clientId">The ID of the client.</param> /// <param name="hostName"> /// The host name where the task is to be started. /// </param> /// <param name="taskSpec"> /// A specification of the task to be executed on the new client. /// </param> /// <returns>Whether the task successfully executed.</returns> bool RunWinTask(string clientId, string hostName, string taskSpec); /// <summary> /// Client callback to request server to run a shell command on another machine. /// </summary> /// <param name="clientId">The ID of the client.</param> /// <param name="hostName"> /// The host name where the task is to be started. /// </param> /// <param name="shellCmd"> /// Command to be executed using the shell. /// </param> /// <param name="envVars"> /// An optional list of environment variables to be set in the shell. /// </param> /// <returns>The standard output of the task.</returns> string RunShellTask(string clientId, string hostName, string shellCmd, Dictionary<string, string> envVars); /// <summary> /// Send the TERM signal to the driver, that will cleanup clients and exit. /// </summary> void Term(); } /// <summary> /// Interface for the blackboard for reading/writing values. /// </summary> public interface IBBComm { /// Write an object with a given key on the server. Useful for /// communication between different client processes. There is intentionally /// no data protection i.e. any client can (over-)write any object. /// The value should be Serializable i.e. the class (and all the types /// that it contains) should be marked with [Serializable] attribute. /// </summary> /// <param name="key">The key of the object to write.</param> /// <param name="value">The value of the object.</param> void WriteObject(string key, object value); /// <summary> /// Add a given value to an integer given the key on the server and return /// the new value; if the key does not exist or the type of object is not /// integer then it throws a <c>KeyNotFoundException</c>. /// </summary> /// <param name="key">The key of the integer to change.</param> /// <param name="incValue"> /// The value to be added to the existing value. /// </param> /// <returns> /// The modified value if the key exists and value is an integer. /// </returns> /// <exception cref="KeyNotFoundException"> /// When the current object associated with the key is not an integer, /// or the key does not exist. /// </exception> int AddInt(string key, int incValue); /// <summary> /// Add a given value to an integer given the key on the server and return /// the new value; if the key does not exist or the type of object is not /// integer then it sets the value to the given value. /// </summary> /// <param name="key">The key of the integer to change.</param> /// <param name="incValue"> /// The value to be added to the existing value, or the value to be /// set if the key is not found or the type of object is not integer. /// </param> /// <returns> /// The modified value or created value when key does not exist or type /// of object is not integer. /// </returns> int AddOrSetInt(string key, int val); /// <summary> /// Read the value of an object for the given key from the server. /// Useful for communication between different client processes. /// </summary> /// <param name="key">The key of the object to write.</param> /// <returns>The value of the object with the given key.</returns> /// <exception cref="KeyNotFoundException"> /// When the key does not exist. /// </exception> object ReadObject(string key); /// <summary> /// Remove the object with the given key from the server. /// </summary> /// <param name="key">The key of the object to remove.</param> void RemoveObject(string key); /// <summary> /// Clear all the keys/values from the blackboard server. /// </summary> void Clear(); /// <summary> /// Exit the blackboard server. /// </summary> void Exit(); } public static class CommConstants { public const string ClientService = "Client"; public const string ClientIPC = "localClientIPCPort"; public const string DriverService = "Driver"; public const string ServerIPC = "localServerIPCPort"; public const string BBService = "BlackBoard"; public const string BBAddrEnvVar = "CSFWK_BBADDR"; public const string DriverAddrEnvVar = "CSFWK_DRIVERADDR"; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ReplicationLogicalNetworksOperations operations. /// </summary> internal partial class ReplicationLogicalNetworksOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationLogicalNetworksOperations { /// <summary> /// Initializes a new instance of the ReplicationLogicalNetworksOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ReplicationLogicalNetworksOperations(SiteRecoveryManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SiteRecoveryManagementClient /// </summary> public SiteRecoveryManagementClient Client { get; private set; } /// <summary> /// Gets the list of logical networks under a fabric. /// </summary> /// <remarks> /// Lists all the logical networks of the Azure Site Recovery fabric /// </remarks> /// <param name='fabricName'> /// Server Id. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LogicalNetwork>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationFabrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationLogicalNetworks").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LogicalNetwork>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LogicalNetwork>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a logical network with specified server id and logical network name. /// </summary> /// <remarks> /// Gets the details of a logical network. /// </remarks> /// <param name='fabricName'> /// Server Id. /// </param> /// <param name='logicalNetworkName'> /// Logical network name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LogicalNetwork>> GetWithHttpMessagesAsync(string fabricName, string logicalNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (logicalNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "logicalNetworkName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("logicalNetworkName", logicalNetworkName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationLogicalNetworks/{logicalNetworkName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{logicalNetworkName}", System.Uri.EscapeDataString(logicalNetworkName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LogicalNetwork>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LogicalNetwork>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the list of logical networks under a fabric. /// </summary> /// <remarks> /// Lists all the logical networks of the Azure Site Recovery fabric /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LogicalNetwork>>> ListByReplicationFabricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationFabricsNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LogicalNetwork>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LogicalNetwork>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; namespace System.Net.Http.Headers { // According to the RFC, in places where a "parameter" is required, the value is mandatory // (e.g. Media-Type, Accept). However, we don't introduce a dedicated type for it. So NameValueHeaderValue supports // name-only values in addition to name/value pairs. public class NameValueHeaderValue : ICloneable { private static readonly Func<NameValueHeaderValue> s_defaultNameValueCreator = CreateNameValue; private string _name; private string _value; public string Name { get { return _name; } } public string Value { get { return _value; } set { CheckValueFormat(value); _value = value; } } internal NameValueHeaderValue() { } public NameValueHeaderValue(string name) : this(name, null) { } public NameValueHeaderValue(string name, string value) { CheckNameValueFormat(name, value); _name = name; _value = value; } protected NameValueHeaderValue(NameValueHeaderValue source) { Contract.Requires(source != null); _name = source._name; _value = source._value; } public override int GetHashCode() { Debug.Assert(_name != null); int nameHashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(_name); if (!string.IsNullOrEmpty(_value)) { // If we have a quoted-string, then just use the hash code. If we have a token, convert to lowercase // and retrieve the hash code. if (_value[0] == '"') { return nameHashCode ^ _value.GetHashCode(); } return nameHashCode ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_value); } return nameHashCode; } public override bool Equals(object obj) { NameValueHeaderValue other = obj as NameValueHeaderValue; if (other == null) { return false; } if (!string.Equals(_name, other._name, StringComparison.OrdinalIgnoreCase)) { return false; } // RFC2616: 14.20: unquoted tokens should use case-INsensitive comparison; quoted-strings should use // case-sensitive comparison. The RFC doesn't mention how to compare quoted-strings outside the "Expect" // header. We treat all quoted-strings the same: case-sensitive comparison. if (string.IsNullOrEmpty(_value)) { return string.IsNullOrEmpty(other._value); } if (_value[0] == '"') { // We have a quoted string, so we need to do case-sensitive comparison. return string.Equals(_value, other._value, StringComparison.Ordinal); } else { return string.Equals(_value, other._value, StringComparison.OrdinalIgnoreCase); } } public static NameValueHeaderValue Parse(string input) { int index = 0; return (NameValueHeaderValue)GenericHeaderParser.SingleValueNameValueParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out NameValueHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueNameValueParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (NameValueHeaderValue)output; return true; } return false; } public override string ToString() { if (!string.IsNullOrEmpty(_value)) { return _name + "=" + _value; } return _name; } internal static void ToString(ICollection<NameValueHeaderValue> values, char separator, bool leadingSeparator, StringBuilder destination) { Debug.Assert(destination != null); if ((values == null) || (values.Count == 0)) { return; } foreach (var value in values) { if (leadingSeparator || (destination.Length > 0)) { destination.Append(separator); destination.Append(' '); } destination.Append(value.ToString()); } } internal static string ToString(ICollection<NameValueHeaderValue> values, char separator, bool leadingSeparator) { if ((values == null) || (values.Count == 0)) { return null; } StringBuilder sb = new StringBuilder(); ToString(values, separator, leadingSeparator, sb); return sb.ToString(); } internal static int GetHashCode(ICollection<NameValueHeaderValue> values) { if ((values == null) || (values.Count == 0)) { return 0; } int result = 0; foreach (var value in values) { result = result ^ value.GetHashCode(); } return result; } internal static int GetNameValueLength(string input, int startIndex, out NameValueHeaderValue parsedValue) { return GetNameValueLength(input, startIndex, s_defaultNameValueCreator, out parsedValue); } internal static int GetNameValueLength(string input, int startIndex, Func<NameValueHeaderValue> nameValueCreator, out NameValueHeaderValue parsedValue) { Contract.Requires(input != null); Contract.Requires(startIndex >= 0); Contract.Requires(nameValueCreator != null); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the name, i.e. <name> in name/value string "<name>=<value>". Caller must remove // leading whitespaces. int nameLength = HttpRuleParser.GetTokenLength(input, startIndex); if (nameLength == 0) { return 0; } string name = input.Substring(startIndex, nameLength); int current = startIndex + nameLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the separator between name and value if ((current == input.Length) || (input[current] != '=')) { // We only have a name and that's OK. Return. parsedValue = nameValueCreator(); parsedValue._name = name; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespaces return current - startIndex; } current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); // Parse the value, i.e. <value> in name/value string "<name>=<value>" int valueLength = GetValueLength(input, current); if (valueLength == 0) { return 0; // We have an invalid value. } // Use parameterless ctor to avoid double-parsing of name and value, i.e. skip public ctor validation. parsedValue = nameValueCreator(); parsedValue._name = name; parsedValue._value = input.Substring(current, valueLength); current = current + valueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // skip whitespaces return current - startIndex; } // Returns the length of a name/value list, separated by 'delimiter'. E.g. "a=b, c=d, e=f" adds 3 // name/value pairs to 'nameValueCollection' if 'delimiter' equals ','. internal static int GetNameValueListLength(string input, int startIndex, char delimiter, ICollection<NameValueHeaderValue> nameValueCollection) { Contract.Requires(nameValueCollection != null); Contract.Requires(startIndex >= 0); if ((string.IsNullOrEmpty(input)) || (startIndex >= input.Length)) { return 0; } int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex); while (true) { NameValueHeaderValue parameter = null; int nameValueLength = NameValueHeaderValue.GetNameValueLength(input, current, s_defaultNameValueCreator, out parameter); if (nameValueLength == 0) { return 0; } nameValueCollection.Add(parameter); current = current + nameValueLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); if ((current == input.Length) || (input[current] != delimiter)) { // We're done and we have at least one valid name/value pair. return current - startIndex; } // input[current] is 'delimiter'. Skip the delimiter and whitespaces and try to parse again. current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } } internal static NameValueHeaderValue Find(ICollection<NameValueHeaderValue> values, string name) { Contract.Requires((name != null) && (name.Length > 0)); if ((values == null) || (values.Count == 0)) { return null; } foreach (var value in values) { if (string.Equals(value.Name, name, StringComparison.OrdinalIgnoreCase)) { return value; } } return null; } internal static int GetValueLength(string input, int startIndex) { Contract.Requires(input != null); if (startIndex >= input.Length) { return 0; } int valueLength = HttpRuleParser.GetTokenLength(input, startIndex); if (valueLength == 0) { // A value can either be a token or a quoted string. Check if it is a quoted string. if (HttpRuleParser.GetQuotedStringLength(input, startIndex, out valueLength) != HttpParseResult.Parsed) { // We have an invalid value. Reset the name and return. return 0; } } return valueLength; } private static void CheckNameValueFormat(string name, string value) { HeaderUtilities.CheckValidToken(name, "name"); CheckValueFormat(value); } private static void CheckValueFormat(string value) { // Either value is null/empty or a valid token/quoted string if (!(string.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length))) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } private static NameValueHeaderValue CreateNameValue() { return new NameValueHeaderValue(); } // Implement ICloneable explicitly to allow derived types to "override" the implementation. object ICloneable.Clone() { return new NameValueHeaderValue(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System; using System.IO; using System.Xml; using System.Xml.Schema; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_GlobalTypes", Desc = "")] public class TC_SchemaSet_GlobalTypes { private ITestOutputHelper _output; public TC_SchemaSet_GlobalTypes(ITestOutputHelper output) { _output = output; } public XmlSchema GetSchema(string ns, string type1, string type2) { string xsd = String.Empty; if (ns.Equals(String.Empty)) xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; else xsd = "<schema xmlns='http://www.w3.org/2001/XMLSchema' targetNamespace='" + ns + "'><complexType name='" + type1 + "'><sequence><element name='local'/></sequence></complexType><simpleType name='" + type2 + "'><restriction base='int'/></simpleType></schema>"; XmlSchema schema = XmlSchema.Read(new StringReader(xsd), null); return schema; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - GlobalTypes on empty collection")] [InlineData()] [Theory] public void v1() { XmlSchemaSet sc = new XmlSchemaSet(); XmlSchemaObjectTable table = sc.GlobalTypes; CError.Compare(table == null, false, "Count"); return; } //----------------------------------------------------------------------------------- // params is a pair of the following info: (namaespace, type1 type2) two schemas are made from this info //[Variation(Desc = "v2.1 - GlobalTypes with set with two schemas, both without NS", Params = new object[] { "", "t1", "t2", "", "t3", "t4" })] [InlineData("", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, one without NS one with NS", Params = new object[] { "a", "t1", "t2", "", "t3", "t4" })] [InlineData("a", "t1", "t2", "", "t3", "t4")] //[Variation(Desc = "v2.2 - GlobalTypes with set with two schemas, both with NS", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4" })] [InlineData("a", "t1", "t2", "b", "t3", "t4")] [Theory] public void v2(object param0, object param1, object param2, object param3, object param4, object param5) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss = new XmlSchemaSet(); ss.Add(s1); CError.Compare(ss.GlobalTypes.Count, 0, "Types Count after add"); ss.Compile(); ss.Add(s2); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after add/compile"); //+1 for anyType ss.Compile(); //Verify CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after add/compile/add/compile"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss.Reprocess(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after repr"); //+1 for anyType ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 5, "Types Count after repr/comp"); //+1 for anyType //Now Remove one schema and check ss.Remove(s1); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove"); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count after remove/comp"); return; } // params is a pair of the following info: (namaespace, type1 type2)*, doCompile? //[Variation(Desc = "v3.1 - GlobalTypes with a set having schema (nons) to another set with schema(nons)", Params = new object[] { "", "t1", "t2", "", "t3", "t4", true })] [InlineData("", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.2 - GlobalTypes with a set having schema (ns) to another set with schema(nons)", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", true })] [InlineData("a", "t1", "t2", "", "t3", "t4", true)] //[Variation(Desc = "v3.3 - GlobalTypes with a set having schema (nons) to another set with schema(ns)", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", true })] [InlineData("", "t1", "t2", "a", "t3", "t4", true)] //[Variation(Desc = "v3.4 - GlobalTypes with a set having schema (ns) to another set with schema(ns)", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", true })] [InlineData("a", "t1", "t2", "b", "t3", "t4", true)] //[Variation(Desc = "v3.5 - GlobalTypes with a set having schema (nons) to another set with schema(nons), no compile", Params = new object[] { "", "t1", "t2", "", "t3", "t4", false })] [InlineData("", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.6 - GlobalTypes with a set having schema (ns) to another set with schema(nons), no compile", Params = new object[] { "a", "t1", "t2", "", "t3", "t4", false })] [InlineData("a", "t1", "t2", "", "t3", "t4", false)] //[Variation(Desc = "v3.7 - GlobalTypes with a set having schema (nons) to another set with schema(ns), no compile", Params = new object[] { "", "t1", "t2", "a", "t3", "t4", false })] [InlineData("", "t1", "t2", "a", "t3", "t4", false)] //[Variation(Desc = "v3.8 - GlobalTypes with a set having schema (ns) to another set with schema(ns), no compile", Params = new object[] { "a", "t1", "t2", "b", "t3", "t4", false })] [InlineData("a", "t1", "t2", "b", "t3", "t4", false)] [Theory] public void v3(object param0, object param1, object param2, object param3, object param4, object param5, object param6) { string ns1 = param0.ToString(); string ns2 = param3.ToString(); string type1 = param1.ToString(); string type2 = param2.ToString(); string type3 = param4.ToString(); string type4 = param5.ToString(); bool doCompile = (bool)param6; XmlSchema s1 = GetSchema(ns1, type1, type2); XmlSchema s2 = GetSchema(ns2, type3, type4); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(s1); ss1.Compile(); ss2.Add(s2); if (doCompile) ss2.Compile(); // add one schemaset to another ss1.Add(ss2); if (!doCompile) ss1.Compile(); //Verify CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count after add/comp"); //+1 for anyType CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type2, ns1)), true, "Contains2"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type3, ns2)), true, "Contains3"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName(type4, ns2)), true, "Contains4"); //Now reprocess one schema and check ss1.Reprocess(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count repr"); //+1 for anyType ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Types Count repr/comp"); //+1 for anyType //Now Remove one schema and check ss1.Remove(s1); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after remove"); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 3, "Types Count after rem/comp"); return; } //----------------------------------------------------------------------------------- //[Variation(Desc = "v4.1 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v4.2 - GlobalTypes with set having one which imports another, remove one", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v4(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); XmlSchema schema1 = ss.Add(null, TestData._Root + uri1); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); //get the SOM for the imported schema foreach (XmlSchema s in ss.Schemas(ns2)) { ss.Remove(s); } ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 2, "Types Count after Remove"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //[Variation(Desc = "v5.1 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B" })] [InlineData("import_v1_a.xsd", "ns-a", "ct-A", "", "ct-B")] //[Variation(Desc = "v5.2 - GlobalTypes with set having one which imports another, then removerecursive", Priority = 1, Params = new object[] { "import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B" })] [InlineData("import_v2_a.xsd", "ns-a", "ct-A", "ns-b", "ct-B")] [Theory] public void v5(object param0, object param1, object param2, object param3, object param4) { string uri1 = param0.ToString(); string ns1 = param1.ToString(); string type1 = param2.ToString(); string ns2 = param3.ToString(); string type2 = param4.ToString(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, TestData._Root + "xsdauthor.xsd"); XmlSchema schema1 = ss.Add(null, TestData._Root + uri1); ss.Compile(); CError.Compare(ss.GlobalTypes.Count, 3, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), true, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), true, "Contains2"); ss.RemoveRecursive(schema1); // should not need to compile for RemoveRecursive to take effect CError.Compare(ss.GlobalTypes.Count, 1, "Types Count"); //+1 for anyType CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type1, ns1)), false, "Contains1"); CError.Compare(ss.GlobalTypes.Contains(new XmlQualifiedName(type2, ns2)), false, "Contains2"); return; } //----------------------------------------------------------------------------------- //REGRESSIONS //[Variation(Desc = "v100 - XmlSchemaSet: Components are not added to the global tabels if it is already compiled", Priority = 1)] [InlineData()] [Theory] public void v100() { try { // anytype t1 t2 XmlSchema schema1 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='a'><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t1'/><xs:complexType name='t2'/></xs:schema>"), null); // anytype t3 t4 XmlSchema schema2 = XmlSchema.Read(new StringReader("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' ><xs:element name='e1' type='xs:anyType'/><xs:complexType name='t3'/><xs:complexType name='t4'/></xs:schema>"), null); XmlSchemaSet ss1 = new XmlSchemaSet(); XmlSchemaSet ss2 = new XmlSchemaSet(); ss1.Add(schema1); ss2.Add(schema2); ss2.Compile(); ss1.Add(ss2); ss1.Compile(); CError.Compare(ss1.GlobalTypes.Count, 5, "Count"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t1", "a")), true, "Contains"); CError.Compare(ss1.GlobalTypes.Contains(new XmlQualifiedName("t2", "a")), true, "Contains"); } catch (Exception e) { _output.WriteLine(e.Message); Assert.True(false); } return; } } } //todo: add sanity test for include //todo: copy count checks from element
/* ### # # ######### _______ _ _ ______ _ _ ## ######## @ ## |______ | | | ____ | | ################## | |_____| |_____| |_____| ## ############# f r a m e w o r k # # ######### ### (c) 2015 - 2018 FUGU framework 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. */ using Fugu.Linq; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Fugu.IO { public class Glob { public String Pattern { get; set; } public Action<String> ErrorLog { get; set; } public Boolean Cancelled { get; private set; } public Boolean ThrowOnError { get; set; } public Boolean IgnoreCase { get; set; } public Boolean DirectoriesOnly { get; set; } public Boolean CacheRegexes { get; set; } public void Cancel() { Cancelled = true; } private void Log(String s, params object[] args) { if (ErrorLog != null) ErrorLog(String.Format(s, args)); } public Glob() { IgnoreCase = true; CacheRegexes = true; } public Glob(String pattern) : this() { Pattern = pattern; } public static IEnumerable<String> ExpandNames(String pattern, Boolean ignoreCase = true, Boolean dirOnly = false) { return new Glob(pattern) { IgnoreCase = ignoreCase, DirectoriesOnly = dirOnly }.ExpandNames(); } public static IEnumerable<FileSystemInfo> Expand(String pattern, Boolean ignoreCase = true, Boolean dirOnly = false) { return new Glob(pattern) { IgnoreCase = ignoreCase, DirectoriesOnly = dirOnly }.Expand(); } public IEnumerable<String> ExpandNames() { return Expand(Pattern, DirectoriesOnly).Select(f => f.FullName); } public IEnumerable<FileSystemInfo> Expand() { return Expand(Pattern, DirectoriesOnly); } class RegexOrString { public Regex Regex { get; set; } public String Pattern { get; set; } public Boolean IgnoreCase { get; set; } public RegexOrString(String pattern, String rawString, Boolean ignoreCase, Boolean compileRegex) { IgnoreCase = ignoreCase; try { Regex = new Regex(pattern, RegexOptions.CultureInvariant | (ignoreCase ? RegexOptions.IgnoreCase : 0) | (compileRegex ? RegexOptions.Compiled : 0)); Pattern = pattern; } catch { Pattern = rawString; } } public Boolean IsMatch(String input) { return Regex != null ? Regex.IsMatch(input) : Pattern.Equals(input, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } private static ConcurrentDictionary<String, RegexOrString> RegexOrStringCache = new ConcurrentDictionary<String, RegexOrString>(); private RegexOrString CreateRegexOrString(String pattern) { if (!CacheRegexes) return new RegexOrString(GlobToRegex(pattern), pattern, IgnoreCase, compileRegex: false); RegexOrString regexOrString; if (!RegexOrStringCache.TryGetValue(pattern, out regexOrString)) { regexOrString = new RegexOrString(GlobToRegex(pattern), pattern, IgnoreCase, compileRegex: true); RegexOrStringCache[pattern] = regexOrString; } return regexOrString; } private static char[] GlobCharacters = "*?[]{}".ToCharArray(); private IEnumerable<FileSystemInfo> Expand(String path, Boolean dirOnly) { if (Cancelled) yield break; if (String.IsNullOrEmpty(path)) { yield break; } // stop looking if there are no more glob characters in the path. // but only if ignoring case because FileSystemInfo.Exists always ignores case. if (IgnoreCase && path.IndexOfAny(GlobCharacters) < 0) { FileSystemInfo fsi = null; Boolean exists = false; try { fsi = dirOnly ? (FileSystemInfo)new DirectoryInfo(path) : new FileInfo(path); exists = fsi.Exists; } catch (Exception ex) { Log("Error getting FileSystemInfo for '{0}': {1}", path, ex); if (ThrowOnError) throw; } if (exists) yield return fsi; yield break; } String parent = null; try { parent = Path.GetDirectoryName(path); } catch (Exception ex) { Log("Error getting directory name for '{0}': {1}", path, ex); if (ThrowOnError) throw; yield break; } if (parent == null) { DirectoryInfo dir = null; try { dir = new DirectoryInfo(path); } catch (Exception ex) { Log("Error getting DirectoryInfo for '{0}': {1}", path, ex); if (ThrowOnError) throw; } if (dir != null) yield return dir; yield break; } if (parent == "") { try { parent = Directory.GetCurrentDirectory(); } catch (Exception ex) { Log("Error getting current working directory: {1}", ex); if (ThrowOnError) throw; } } var child = Path.GetFileName(path); // handle groups that contain folders // child will contain unmatched closing brace if (child.Count(c => c == '}') > child.Count(c => c == '{')) { foreach (var group in Ungroup(path)) { foreach (var item in Expand(group, dirOnly)) { yield return item; } } yield break; } if (child == "**") { foreach (DirectoryInfo dir in Expand(parent, true).DistinctBy(d => d.FullName)) { DirectoryInfo[] recursiveDirectories; try { recursiveDirectories = GetDirectories(dir).ToArray(); } catch (Exception ex) { Log("Error finding recursive directory in {0}: {1}.", dir, ex); if (ThrowOnError) throw; continue; } yield return dir; foreach (var subDir in recursiveDirectories) { yield return subDir; } } yield break; } var childRegexes = Ungroup(child).Select(s => CreateRegexOrString(s)).ToList(); foreach (DirectoryInfo parentDir in Expand(parent, true).DistinctBy(d => d.FullName)) { IEnumerable<FileSystemInfo> fileSystemEntries; try { fileSystemEntries = dirOnly ? parentDir.GetDirectories() : parentDir.GetFileSystemInfos(); } catch (Exception ex) { Log("Error finding file system entries in {0}: {1}.", parentDir, ex); if (ThrowOnError) throw; continue; } foreach (var fileSystemEntry in fileSystemEntries) { if (childRegexes.Any(r => r.IsMatch(fileSystemEntry.Name))) { yield return fileSystemEntry; } } if (childRegexes.Any(r => r.Pattern == @"^\.\.$")) yield return parentDir.Parent ?? parentDir; if (childRegexes.Any(r => r.Pattern == @"^\.$")) yield return parentDir; } } private static HashSet<char> RegexSpecialChars = new HashSet<char>(new[] { '[', '\\', '^', '$', '.', '|', '?', '*', '+', '(', ')' }); private static String GlobToRegex(String glob) { StringBuilder regex = new StringBuilder(); Boolean characterClass = false; regex.Append("^"); foreach (var c in glob) { if (characterClass) { if (c == ']') characterClass = false; regex.Append(c); continue; } switch (c) { case '*': regex.Append(".*"); break; case '?': regex.Append("."); break; case '[': characterClass = true; regex.Append(c); break; default: if (RegexSpecialChars.Contains(c)) regex.Append('\\'); regex.Append(c); break; } } regex.Append("$"); return regex.ToString(); } private static Regex GroupRegex = new Regex(@"{([^}]*)}"); private static IEnumerable<String> Ungroup(String path) { if (!path.Contains('{')) { yield return path; yield break; } int level = 0; String option = ""; String prefix = ""; String postfix = ""; List<String> options = new List<String>(); for (int i = 0; i < path.Length; i++) { var c = path[i]; switch (c) { case '{': level++; if (level == 1) { prefix = option; option = ""; } else option += c; break; case ',': if (level == 1) { options.Add(option); option = ""; } else option += c; break; case '}': level--; if (level == 0) { options.Add(option); break; } else option += c; break; default: option += c; break; } if (level == 0 && c == '}' && (i + 1) < path.Length) { postfix = path.Substring(i + 1); break; } } if (level > 0) // invalid grouping { yield return path; yield break; } var postGroups = Ungroup(postfix); foreach (var opt in options.SelectMany(o => Ungroup(o))) { foreach (var postGroup in postGroups) { var s = prefix + opt + postGroup; yield return s; } } } public override String ToString() { return Pattern; } public override int GetHashCode() { return Pattern.GetHashCode(); } public override Boolean Equals(object obj) { //Check for null and compare run-time types. if (obj == null || GetType() != obj.GetType()) return false; Glob g = (Glob)obj; return Pattern == g.Pattern; } private static IEnumerable<DirectoryInfo> GetDirectories(DirectoryInfo root) { DirectoryInfo[] subDirs = null; try { subDirs = root.GetDirectories(); } catch (Exception) { yield break; } foreach (DirectoryInfo dirInfo in subDirs) { yield return dirInfo; foreach (var recursiveDir in GetDirectories(dirInfo)) { yield return recursiveDir; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; using System.IO; using System.Text; using XmlCoreTest.Common; namespace System.Xml.Tests { [InheritRequired()] public abstract partial class TCReadContentAsBinHex : TCXMLReaderBaseGeneral { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public static string BinHexXml = "BinHex.xml"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.BINHEX_TEST); return ret; } public override int Terminate(object objParam) { if (DataReader.Internal != null) { while (DataReader.Read()) ; DataReader.Close(); } return base.Terminate(objParam); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return true; try { DataReader.ReadContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { CError.WriteLine("Actual exception:{0}", e.GetType().ToString()); CError.WriteLine("Expected exception:{0}", exceptionType.ToString()); bPassed = (e.GetType().ToString() == exceptionType.ToString()); } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } [Variation("ReadBinHex Element with all valid value")] public int TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } CError.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Num value", Pri = 0)] public int TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME3); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Text value")] public int TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); return TEST_PASS; } public void Dump(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { CError.WriteLineIgnore("Byte" + i + ": " + bytes[i]); } } [Variation("ReadBinHex Element on CDATA", Pri = 0)] public int TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; string xmlStr = "<root><![CDATA[ABCDEF]]></root>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("root"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 3, "BinHex"); BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 0, "BinHex"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0")] public int TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME5); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all long valid value (from concatenation)")] public int TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME6); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); CError.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex with count > buffer size")] public int TestReadBinHex_7() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with count < 0")] public int TestReadBinHex_8() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index > buffer size")] public int vReadBinHex_9() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index < 0")] public int TestReadBinHex_10() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index + count exceeds buffer")] public int TestReadBinHex_11() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex index & count =0")] public int TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0); } catch (Exception e) { CError.WriteLine(e.ToString()); return TEST_FAIL; } CError.Compare(iCount, 0, "has to be zero"); return TEST_PASS; } [Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0")] public int TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); CError.WriteLine("Actual: " + strActbinhex + " Exp: " + strTextBinHex); CError.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } return TEST_PASS; } [Variation("ReadBinHex with buffer == null")] public int TestReadBinHex_14() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return TEST_PASS; } return TEST_FAIL; } [Variation("Read after partial ReadBinHex")] public int TestReadBinHex_16() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[10]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8); CError.Compare(nRead, 8, "0"); DataReader.Read(); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "ElemText", String.Empty), "1vn"); return TEST_PASS; } [Variation("Current node on multiple calls")] public int TestReadBinHex_17() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[30]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2); CError.Compare(nRead, 2, "0"); nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19); CError.Compare(nRead, 18, "1"); CError.Compare(DataReader.VerifyNode(XmlNodeType.EndElement, "ElemNum", String.Empty), "1vn"); return TEST_PASS; } [Variation("ReadBinHex with whitespaces")] public int TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex with odd number of chars")] public int TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex when end tag doesn't exist")] public int TestTextReadBinHex_23() { if (IsRoundTrippedReader()) return TEST_SKIPPED; byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("B"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadContentAsBinHex(buffer, 0, 5000); CError.WriteLine("Accepted incomplete element"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } return TEST_PASS; } [Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")] public int TestTextReadBinHex_24() { string filename = TestData + "Common/Bug99148.xml"; ReloadSource(filename); DataReader.MoveToContent(); int bytes = -1; DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { CError.Write(bbb[i].ToString()); output.AppendFormat(bbb[i].ToString()); } } CError.WriteLine(); CError.WriteLine("Length of the output : " + output.ToString().Length); return (CError.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) ? TEST_PASS : TEST_FAIL; } } [InheritRequired()] public abstract partial class TCReadElementContentAsBinHex : TCXMLReaderBaseGeneral { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public static string BinHexXml = "BinHex.xml"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.BINHEX_TEST); return ret; } public override int Terminate(object objParam) { DataReader.Close(); return base.Terminate(objParam); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return true; try { DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { CError.WriteLine("Actual exception:{0}", e.GetType().ToString()); CError.WriteLine("Expected exception:{0}", exceptionType.ToString()); bPassed = (e.GetType().ToString() == exceptionType.ToString()); } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } [Variation("ReadBinHex Element with all valid value")] public int TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return TEST_PASS; binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } CError.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Num value", Pri = 0)] public int TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME3); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Text value")] public int TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with Comments and PIs", Pri = 0)] public int TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; ReloadSource(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>")); DataReader.PositionOnElement("root"); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 3, "BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0")] public int TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME5); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all long valid value (from concatenation)")] public int TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME6); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); CError.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex with count > buffer size")] public int TestReadBinHex_7() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with count < 0")] public int TestReadBinHex_8() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index > buffer size")] public int vReadBinHex_9() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index < 0")] public int TestReadBinHex_10() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index + count exceeds buffer")] public int TestReadBinHex_11() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex index & count =0")] public int TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return TEST_PASS; try { iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0); } catch (Exception e) { CError.WriteLine(e.ToString()); return TEST_FAIL; } CError.Compare(iCount, 0, "has to be zero"); return TEST_PASS; } [Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0")] public int TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadElementContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); CError.WriteLine("Actual: " + strActbinhex + " Exp: " + strTextBinHex); CError.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } return TEST_PASS; } [Variation("ReadBinHex with buffer == null")] public int TestReadBinHex_14() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return TEST_PASS; } return TEST_FAIL; } [Variation("Read after partial ReadBinHex")] public int TestReadBinHex_16() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[10]; int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8); CError.Compare(nRead, 8, "0"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node"); return TEST_PASS; } [Variation("No op node types")] public int TestReadBinHex_18() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; TestInvalidNodeType(XmlNodeType.Text); TestInvalidNodeType(XmlNodeType.Attribute); TestInvalidNodeType(XmlNodeType.Whitespace); TestInvalidNodeType(XmlNodeType.ProcessingInstruction); TestInvalidNodeType(XmlNodeType.CDATA); if (!(IsCoreReader() || IsRoundTrippedReader())) { TestInvalidNodeType(XmlNodeType.EndEntity); TestInvalidNodeType(XmlNodeType.EntityReference); } return TEST_PASS; } [Variation("ReadBinHex with whitespaces")] public int TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex with odd number of chars")] public int TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex when end tag doesn't exist")] public int TestTextReadBinHex_23() { if (IsRoundTrippedReader()) return TEST_SKIPPED; byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("B"); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(buffer, 0, 5000); CError.WriteLine("Accepted incomplete element"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } return TEST_PASS; } [Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")] public int TestTextReadBinHex_24() { string filename = TestData + "Common/Bug99148.xml"; ReloadSource(filename); DataReader.MoveToContent(); if (CheckCanReadBinaryContent()) return TEST_PASS; int bytes = -1; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { CError.Write(bbb[i].ToString()); output.AppendFormat(bbb[i].ToString()); } } CError.WriteLine(); CError.WriteLine("Length of the output : " + output.ToString().Length); return (CError.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) ? TEST_PASS : TEST_FAIL; } [Variation("430329: SubtreeReader inserted attributes don't work with ReadContentAsBinHex")] public int TestReadBinHex_430329() { if (IsCustomReader() || IsXsltReader() || IsBinaryReader()) return TEST_SKIPPED; string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>"; ReloadSource(new StringReader(strxml)); DataReader.Read(); DataReader.Read(); using (XmlReader sr = DataReader.ReadSubtree()) { sr.Read(); sr.MoveToFirstAttribute(); sr.MoveToFirstAttribute(); byte[] bytes = new byte[4]; while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } } DataReader.Close(); return TEST_PASS; } [Variation("ReadBinHex with = in the middle")] public int TestReadBinHex_27() { byte[] buffer = new byte[1]; string strxml = "<abc>1=2</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(buffer, 0, 1); CError.Compare(false, "ReadBinHex with = in the middle succeeded"); } catch (XmlException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("ReadBinHex runs into an Overflow", Params = new object[] { "1000000" })] //[Variation("ReadBinHex runs into an Overflow", Params = new object[] { "10000000" })] public int TestReadBinHex_105376() { int totalfilesize = Convert.ToInt32(CurVariation.Params[0].ToString()); CError.WriteLine(" totalfilesize = " + totalfilesize); string ascii = new string('c', totalfilesize); byte[] bits = Encoding.Unicode.GetBytes(ascii); CError.WriteLineIgnore("Count = " + bits.Length); string base64str = Convert.ToBase64String(bits); string fileName = "bug105376c_" + CurVariation.Params[0].ToString() + ".xml"; MemoryStream mems = new MemoryStream(); StreamWriter sw = new StreamWriter(mems); sw.Write("<root><base64>"); sw.Write(base64str); sw.Write("</base64></root>"); sw.Flush();//sw.Close(); FilePathUtil.addStream(fileName, mems); ReloadSource(fileName); int SIZE = (totalfilesize - 30); int SIZE64 = SIZE * 3 / 4; DataReader.PositionOnElement("base64"); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] base64 = new byte[SIZE64]; try { DataReader.ReadElementContentAsBinHex(base64, 0, 4096); return TEST_FAIL; } catch (XmlException) { DataReader.Close(); return TEST_PASS; } finally { DataReader.Close(); } } [Variation("call ReadContentAsBinHex on two or more nodes")] public int TestReadBinHex_28() { string xml = "<elem0> 11B <elem1> 11B <elem2> 11B </elem2> 11B </elem1> 11B </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)17, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } [Variation("read BinHex over invalid text node")] public int TestReadBinHex_29() { string xml = "<elem0>12%45<elem1>12%45<elem2>12%45</elem2>12%45</elem1>12%45</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[5]; int currentSize = 0; while (DataReader.Read()) { DataReader.Read(); try { currentSize = DataReader.ReadContentAsBinHex(buffer, 0, 5); if (!(IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader())) return TEST_FAIL; } catch (XmlException) { CError.Compare(currentSize, 0, "size"); } } DataReader.Close(); return TEST_PASS; } [Variation("goto to text node, ask got.Value, readcontentasBinHex")] public int TestReadBinHex_30() { string xml = "<elem0>123</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; DataReader.Read(); DataReader.Read(); CError.Compare(DataReader.Value, "123", "value"); CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 1), 1, "size"); DataReader.Close(); return TEST_PASS; } [Variation("goto to text node, readcontentasBinHex, ask got.Value")] public int TestReadBinHex_31() { string xml = "<elem0>123</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; DataReader.Read(); DataReader.Read(); CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 1), 1, "size"); CError.Compare(DataReader.Value, (IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader()) ? "123" : "3", "value"); DataReader.Close(); return TEST_PASS; } [Variation("goto to huge text node, read several chars with ReadContentAsBinHex and Move forward with .Read()")] public int TestReadBinHex_32() { string xml = "<elem0>1234567 89 1234 123345 5676788 5567712 34567 89 1234 123345 5676788 55677</elem0>"; ReloadSource(new StringReader(xml)); byte[] buffer = new byte[5]; DataReader.Read(); DataReader.Read(); try { CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 5), 5, "size"); } catch (NotSupportedException) { return TEST_PASS; } DataReader.Read(); DataReader.Close(); return TEST_PASS; } [Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBinHex and Move forward with .Read()")] public int TestReadBinHex_33() { string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>"; ReloadSource(new StringReader(xml)); byte[] buffer = new byte[5]; DataReader.Read(); DataReader.Read(); try { CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 5), 5, "size"); DataReader.Read(); } catch (XmlException) { return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("ReadContentAsBinHex on an xmlns attribute", Param = "<foo xmlns='default'> <bar > id='1'/> </foo>")] //[Variation("ReadContentAsBinHex on an xmlns:k attribute", Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>")] //[Variation("ReadContentAsBinHex on an xml:space attribute", Param = "<foo xml:space='default'> <bar > id='1'/> </foo>")] //[Variation("ReadContentAsBinHex on an xml:lang attribute", Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>")] public int TestBinHex_34() { string xml = (string)CurVariation.Param; byte[] buffer = new byte[8]; try { ReloadSource(new StringReader(xml)); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); DataReader.MoveToAttribute(0); CError.Compare(DataReader.Value, "default", "value"); CError.Equals(DataReader.ReadContentAsBinHex(buffer, 0, 8), 5, "size"); CError.Equals(false, "No exception"); } catch (XmlException) { return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } [Variation("call ReadContentAsBinHex on two or more nodes and whitespace")] public int TestReadBinHex_35() { string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123 <elem2> 123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)18, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } [Variation("call ReadContentAsBinHex on two or more nodes and whitespace after call Value")] public int TestReadBinHex_36() { string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123 <elem2> 123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { CError.Equals(DataReader.Value.Contains("123"), "Value"); currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)18, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } } }
namespace CSharpChartExplorer { partial class FrmRealTimeZoomScroll { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmRealTimeZoomScroll)); this.winChartViewer1 = new ChartDirector.WinChartViewer(); this.leftPanel = new System.Windows.Forms.Panel(); this.savePB = new System.Windows.Forms.Button(); this.pointerPB = new System.Windows.Forms.RadioButton(); this.zoomInPB = new System.Windows.Forms.RadioButton(); this.zoomOutPB = new System.Windows.Forms.RadioButton(); this.samplePeriod = new System.Windows.Forms.NumericUpDown(); this.valueC = new System.Windows.Forms.Label(); this.valueB = new System.Windows.Forms.Label(); this.valueA = new System.Windows.Forms.Label(); this.valueCLabel = new System.Windows.Forms.Label(); this.valueBLabel = new System.Windows.Forms.Label(); this.valueALabel = new System.Windows.Forms.Label(); this.simulatedMachineLabel = new System.Windows.Forms.Label(); this.separator = new System.Windows.Forms.Label(); this.updatePeriodLabel = new System.Windows.Forms.Label(); this.topLabel = new System.Windows.Forms.Label(); this.hScrollBar1 = new System.Windows.Forms.HScrollBar(); this.chartUpdateTimer = new System.Windows.Forms.Timer(this.components); this.dataRateTimer = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.winChartViewer1)).BeginInit(); this.leftPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.samplePeriod)).BeginInit(); this.SuspendLayout(); // // winChartViewer1 // this.winChartViewer1.Location = new System.Drawing.Point(124, 27); this.winChartViewer1.Name = "winChartViewer1"; this.winChartViewer1.Size = new System.Drawing.Size(640, 350); this.winChartViewer1.TabIndex = 27; this.winChartViewer1.TabStop = false; this.winChartViewer1.ViewPortChanged += new ChartDirector.WinViewPortEventHandler(this.winChartViewer1_ViewPortChanged); this.winChartViewer1.MouseMovePlotArea += new System.Windows.Forms.MouseEventHandler(this.winChartViewer1_MouseMovePlotArea); // // leftPanel // this.leftPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); this.leftPanel.Controls.Add(this.savePB); this.leftPanel.Controls.Add(this.pointerPB); this.leftPanel.Controls.Add(this.zoomInPB); this.leftPanel.Controls.Add(this.zoomOutPB); this.leftPanel.Controls.Add(this.samplePeriod); this.leftPanel.Controls.Add(this.valueC); this.leftPanel.Controls.Add(this.valueB); this.leftPanel.Controls.Add(this.valueA); this.leftPanel.Controls.Add(this.valueCLabel); this.leftPanel.Controls.Add(this.valueBLabel); this.leftPanel.Controls.Add(this.valueALabel); this.leftPanel.Controls.Add(this.simulatedMachineLabel); this.leftPanel.Controls.Add(this.separator); this.leftPanel.Controls.Add(this.updatePeriodLabel); this.leftPanel.Dock = System.Windows.Forms.DockStyle.Left; this.leftPanel.Location = new System.Drawing.Point(0, 24); this.leftPanel.Name = "leftPanel"; this.leftPanel.Size = new System.Drawing.Size(120, 371); this.leftPanel.TabIndex = 25; // // savePB // this.savePB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.savePB.Image = ((System.Drawing.Image)(resources.GetObject("savePB.Image"))); this.savePB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.savePB.Location = new System.Drawing.Point(0, 109); this.savePB.Name = "savePB"; this.savePB.Size = new System.Drawing.Size(120, 28); this.savePB.TabIndex = 3; this.savePB.Text = " Save"; this.savePB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.savePB.Click += new System.EventHandler(this.savePB_Click); // // pointerPB // this.pointerPB.Appearance = System.Windows.Forms.Appearance.Button; this.pointerPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.pointerPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.pointerPB.Image = ((System.Drawing.Image)(resources.GetObject("pointerPB.Image"))); this.pointerPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.pointerPB.Location = new System.Drawing.Point(0, -1); this.pointerPB.Name = "pointerPB"; this.pointerPB.Size = new System.Drawing.Size(120, 28); this.pointerPB.TabIndex = 0; this.pointerPB.Text = " Pointer"; this.pointerPB.CheckedChanged += new System.EventHandler(this.pointerPB_CheckedChanged); // // zoomInPB // this.zoomInPB.Appearance = System.Windows.Forms.Appearance.Button; this.zoomInPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.zoomInPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.zoomInPB.Image = ((System.Drawing.Image)(resources.GetObject("zoomInPB.Image"))); this.zoomInPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.zoomInPB.Location = new System.Drawing.Point(0, 26); this.zoomInPB.Name = "zoomInPB"; this.zoomInPB.Size = new System.Drawing.Size(120, 28); this.zoomInPB.TabIndex = 1; this.zoomInPB.Text = " Zoom In"; this.zoomInPB.CheckedChanged += new System.EventHandler(this.zoomInPB_CheckedChanged); // // zoomOutPB // this.zoomOutPB.Appearance = System.Windows.Forms.Appearance.Button; this.zoomOutPB.FlatAppearance.CheckedBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.zoomOutPB.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.zoomOutPB.Image = ((System.Drawing.Image)(resources.GetObject("zoomOutPB.Image"))); this.zoomOutPB.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.zoomOutPB.Location = new System.Drawing.Point(0, 53); this.zoomOutPB.Name = "zoomOutPB"; this.zoomOutPB.Size = new System.Drawing.Size(120, 28); this.zoomOutPB.TabIndex = 2; this.zoomOutPB.Text = " Zoom Out"; this.zoomOutPB.CheckedChanged += new System.EventHandler(this.zoomOutPB_CheckedChanged); // // samplePeriod // this.samplePeriod.Increment = new decimal(new int[] { 250, 0, 0, 0}); this.samplePeriod.Location = new System.Drawing.Point(5, 190); this.samplePeriod.Maximum = new decimal(new int[] { 2000, 0, 0, 0}); this.samplePeriod.Minimum = new decimal(new int[] { 250, 0, 0, 0}); this.samplePeriod.Name = "samplePeriod"; this.samplePeriod.Size = new System.Drawing.Size(112, 20); this.samplePeriod.TabIndex = 4; this.samplePeriod.Value = new decimal(new int[] { 1000, 0, 0, 0}); this.samplePeriod.ValueChanged += new System.EventHandler(this.samplePeriod_ValueChanged); // // valueC // this.valueC.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.valueC.Location = new System.Drawing.Point(56, 328); this.valueC.Name = "valueC"; this.valueC.Size = new System.Drawing.Size(60, 22); this.valueC.TabIndex = 45; this.valueC.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // valueB // this.valueB.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.valueB.Location = new System.Drawing.Point(56, 306); this.valueB.Name = "valueB"; this.valueB.Size = new System.Drawing.Size(60, 22); this.valueB.TabIndex = 44; this.valueB.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // valueA // this.valueA.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.valueA.Location = new System.Drawing.Point(56, 285); this.valueA.Name = "valueA"; this.valueA.Size = new System.Drawing.Size(60, 22); this.valueA.TabIndex = 43; this.valueA.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // valueCLabel // this.valueCLabel.Location = new System.Drawing.Point(4, 328); this.valueCLabel.Name = "valueCLabel"; this.valueCLabel.Size = new System.Drawing.Size(48, 22); this.valueCLabel.TabIndex = 42; this.valueCLabel.Text = "Gamma"; this.valueCLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // valueBLabel // this.valueBLabel.Location = new System.Drawing.Point(4, 306); this.valueBLabel.Name = "valueBLabel"; this.valueBLabel.Size = new System.Drawing.Size(48, 22); this.valueBLabel.TabIndex = 41; this.valueBLabel.Text = "Beta"; this.valueBLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // valueALabel // this.valueALabel.Location = new System.Drawing.Point(4, 285); this.valueALabel.Name = "valueALabel"; this.valueALabel.Size = new System.Drawing.Size(48, 22); this.valueALabel.TabIndex = 40; this.valueALabel.Text = "Alpha"; this.valueALabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // simulatedMachineLabel // this.simulatedMachineLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.simulatedMachineLabel.Location = new System.Drawing.Point(4, 266); this.simulatedMachineLabel.Name = "simulatedMachineLabel"; this.simulatedMachineLabel.Size = new System.Drawing.Size(112, 17); this.simulatedMachineLabel.TabIndex = 38; this.simulatedMachineLabel.Text = "Simulated Machine"; // // separator // this.separator.BackColor = System.Drawing.Color.Black; this.separator.Dock = System.Windows.Forms.DockStyle.Right; this.separator.Location = new System.Drawing.Point(119, 0); this.separator.Name = "separator"; this.separator.Size = new System.Drawing.Size(1, 371); this.separator.TabIndex = 31; // // updatePeriodLabel // this.updatePeriodLabel.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.updatePeriodLabel.Location = new System.Drawing.Point(5, 173); this.updatePeriodLabel.Name = "updatePeriodLabel"; this.updatePeriodLabel.Size = new System.Drawing.Size(112, 17); this.updatePeriodLabel.TabIndex = 1; this.updatePeriodLabel.Text = "Update Period (ms)"; // // topLabel // this.topLabel.BackColor = System.Drawing.Color.Navy; this.topLabel.Dock = System.Windows.Forms.DockStyle.Top; this.topLabel.Font = new System.Drawing.Font("Arial", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.topLabel.ForeColor = System.Drawing.Color.Yellow; this.topLabel.Location = new System.Drawing.Point(0, 0); this.topLabel.Name = "topLabel"; this.topLabel.Size = new System.Drawing.Size(768, 24); this.topLabel.TabIndex = 26; this.topLabel.Text = "Advanced Software Engineering"; this.topLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // hScrollBar1 // this.hScrollBar1.BackColor = System.Drawing.Color.White; this.hScrollBar1.Cursor = System.Windows.Forms.Cursors.Default; this.hScrollBar1.Dock = System.Windows.Forms.DockStyle.Bottom; this.hScrollBar1.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.hScrollBar1.Location = new System.Drawing.Point(120, 379); this.hScrollBar1.Maximum = 1000000000; this.hScrollBar1.Name = "hScrollBar1"; this.hScrollBar1.Size = new System.Drawing.Size(648, 16); this.hScrollBar1.TabIndex = 5; this.hScrollBar1.ValueChanged += new System.EventHandler(this.hScrollBar1_ValueChanged); // // chartUpdateTimer // this.chartUpdateTimer.Enabled = true; this.chartUpdateTimer.Interval = 250; this.chartUpdateTimer.Tick += new System.EventHandler(this.chartUpdateTimer_Tick); // // dataRateTimer // this.dataRateTimer.Enabled = true; this.dataRateTimer.Interval = 250; this.dataRateTimer.Tick += new System.EventHandler(this.dataRateTimer_Tick); // // FrmRealTimeZoomScroll // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(768, 395); this.Controls.Add(this.hScrollBar1); this.Controls.Add(this.winChartViewer1); this.Controls.Add(this.leftPanel); this.Controls.Add(this.topLabel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.Name = "FrmRealTimeZoomScroll"; this.Text = "Realtime Chart with Zoom/Scroll and Track Line"; this.Load += new System.EventHandler(this.FrmRealtimeZoomScroll_Load); ((System.ComponentModel.ISupportInitialize)(this.winChartViewer1)).EndInit(); this.leftPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.samplePeriod)).EndInit(); this.ResumeLayout(false); } #endregion private ChartDirector.WinChartViewer winChartViewer1; private System.Windows.Forms.Panel leftPanel; private System.Windows.Forms.NumericUpDown samplePeriod; private System.Windows.Forms.Label valueC; private System.Windows.Forms.Label valueB; private System.Windows.Forms.Label valueA; private System.Windows.Forms.Label valueCLabel; private System.Windows.Forms.Label valueBLabel; private System.Windows.Forms.Label valueALabel; private System.Windows.Forms.Label simulatedMachineLabel; private System.Windows.Forms.Label separator; private System.Windows.Forms.Label updatePeriodLabel; private System.Windows.Forms.Label topLabel; private System.Windows.Forms.HScrollBar hScrollBar1; private System.Windows.Forms.RadioButton pointerPB; private System.Windows.Forms.RadioButton zoomInPB; private System.Windows.Forms.RadioButton zoomOutPB; internal System.Windows.Forms.Timer chartUpdateTimer; internal System.Windows.Forms.Timer dataRateTimer; private System.Windows.Forms.Button savePB; } }
// FileSystemScanner.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> public class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> public class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> public class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base (name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> public class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a directory. /// </summary> public delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> public class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { //fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { //fileFilter_ = new PathFilter(fileFilter); //directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { //fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { //fileFilter_ = fileFilter; //directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public ProcessDirectoryHandler ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); handler(this, args); //alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if ( result ){ ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); //alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if ( handler!= null ) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); //alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); //alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { ProcessDirectoryHandler handler = ProcessDirectory; if ( handler != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); //alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> //public void Scan(string directory, bool recurse) //{ // alive_ = true; // ScanDir(directory, recurse); //} //void ScanDir(string directory, bool recurse) //{ // try { // string[] names = System.IO.Directory.GetFiles(directory); // bool hasMatch = false; // for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { // if ( !fileFilter_.IsMatch(names[fileIndex]) ) { // names[fileIndex] = null; // } else { // hasMatch = true; // } // } // OnProcessDirectory(directory, hasMatch); // if ( alive_ && hasMatch ) { // foreach (string fileName in names) { // try { // if ( fileName != null ) { // OnProcessFile(fileName); // if ( !alive_ ) { // break; // } // } // } // catch (Exception e) { // if (!OnFileFailure(fileName, e)) { // throw; // } // } // } // } // } // catch (Exception e) { // if (!OnDirectoryFailure(directory, e)) { // throw; // } // } // if ( alive_ && recurse ) { // try { // string[] names = System.IO.Directory.GetDirectories(directory); // foreach (string fulldir in names) { // if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { // ScanDir(fulldir, true); // if ( !alive_ ) { // break; // } // } // } // } // catch (Exception e) { // if (!OnDirectoryFailure(directory, e)) { // throw; // } // } // } //} #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> //IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> //IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> //bool alive_; #endregion } }
///////////////////////////////////////////////////////////////////////// // Copyright (C) 2002-2011 Aspose Pty Ltd. All rights reserved. // // This file is part of Aspose.Pdf. The source code in this file // is only intended as a supplement to the documentation, and is provided // "as is", without warranty of any kind, either expressed or implied. ///////////////////////////////////////////////////////////////////////// using System; using Aspose.Pdf.Generator; using System.Globalization; using System.Data; namespace FlyNowAirlineBookingService { /// <summary> /// creates ticket /// </summary> public class Ticket { string path; System.Globalization.CultureInfo locale = new System.Globalization.CultureInfo("en-US"); public Ticket(string curPath) { path = curPath; Aspose.Pdf.License lic = new Aspose.Pdf.License(); lic.SetLicense(@"c:\tempfiles\Aspose.Total.lic"); } public Aspose.Pdf.Generator.Pdf GetTicket(PassengerInfo passengerInfo, FlightInfo flightInfo, BookingInfo bookingInfo) { Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf(); pdf.IsTruetypeFontMapCached = false; pdf.Sections.Add(); MarginInfo marginInfo = new MarginInfo(); marginInfo.Top = 50; marginInfo.Left = 50; marginInfo.Right = 50; pdf.Sections[0].PageInfo.Margin = marginInfo; PutOrder(pdf, passengerInfo, flightInfo, bookingInfo); return pdf; } private void PutOrder(Aspose.Pdf.Generator.Pdf pdf, PassengerInfo passengerInfo, FlightInfo flightInfo, BookingInfo bookingInfo) { //ticket for leaving PutSummary(pdf, passengerInfo, bookingInfo, flightInfo, false); //ticket for returning PutSummary(pdf, passengerInfo, bookingInfo, flightInfo, true); } private void PutSummary(Aspose.Pdf.Generator.Pdf pdf, PassengerInfo passengerInfo, BookingInfo bookingInfo, FlightInfo flightInfo, bool isReturn) { //create table structure for the ticket Table summaryTable = new Table(); Aspose.Pdf.Generator.Color color = new Aspose.Pdf.Generator.Color(111, 146, 188); summaryTable.Margin.Top = 20; summaryTable.ColumnWidths = "80 80 80 80"; summaryTable.DefaultCellTextInfo.FontSize = 10; summaryTable.DefaultCellPadding.Bottom = summaryTable.DefaultCellPadding.Top = 3; summaryTable.Border = new BorderInfo((int)BorderSide.Box, 0.5f ,color); summaryTable.BackgroundColor = new Color(173, 202, 225); //add table to the PDF page Section section = pdf.Sections[0]; section.Paragraphs.Add(summaryTable); //declare temporary variables Aspose.Pdf.Generator.TextInfo textInfo = new Aspose.Pdf.Generator.TextInfo(); Cell tempCell; //add logo and barcode images Row row1SummaryTable = summaryTable.Rows.Add(); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); Cell cell1 = new Cell(row1SummaryTable); cell1.ColumnsSpan = 2; cell1.DefaultCellTextInfo = textInfo; Aspose.Pdf.Generator.Image img = new Aspose.Pdf.Generator.Image(); img.ImageInfo.File = path + "\\FlyNowLogoOnly.jpg"; img.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg; img.ImageInfo.FixWidth = 90; img.ImageInfo.FixHeight = 30; cell1.Paragraphs.Add(img); row1SummaryTable.Cells.Add(cell1); Cell cell2 = new Cell(row1SummaryTable); cell2.ColumnsSpan = 2; cell2.DefaultCellTextInfo = textInfo; cell2.Alignment = AlignmentType.Right; img = new Aspose.Pdf.Generator.Image(); if(!isReturn) img.ImageInfo.File = path + "\\barcodeleave.jpg"; else img.ImageInfo.File = path + "\\barcodereturn.jpg"; img.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg; img.ImageInfo.FixWidth = 160; img.ImageInfo.FixHeight = 30; cell2.Paragraphs.Add(img); row1SummaryTable.Cells.Add(cell2); Row row2SummaryTable = summaryTable.Rows.Add(); textInfo = SetTextInfo("Times-Roman", 9, "Black", true); tempCell = AddTextToCell("Class:", row2SummaryTable, textInfo, true); row2SummaryTable.Cells.Add(tempCell); //cell2 = new Cell(row2SummaryTable); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); tempCell = AddTextToCell("Economy", row2SummaryTable, textInfo, false); row2SummaryTable.Cells.Add(tempCell); //add emptry cells Cell cell3 = new Cell(row2SummaryTable); row2SummaryTable.Cells.Add(cell3); Cell cell4 = new Cell(row2SummaryTable); row2SummaryTable.Cells.Add(cell4); //add flight details Row row3SummaryTable = summaryTable.Rows.Add(); textInfo = SetTextInfo("Times-Roman", 9, "Black", true); tempCell = AddTextToCell("Flight: ", row3SummaryTable, textInfo,true); row3SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); if(!isReturn) tempCell = AddTextToCell(flightInfo.FlightNumberLeave, row3SummaryTable, textInfo, false); else tempCell = AddTextToCell(flightInfo.FlightNumberReturn, row3SummaryTable, textInfo, false); row3SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", true); tempCell = AddTextToCell("Seat Number: ", row3SummaryTable, textInfo, true); row3SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); tempCell = AddTextToCell(passengerInfo.SeatNumber, row3SummaryTable, textInfo, false); row3SummaryTable.Cells.Add(tempCell); Row row4SummaryTable = summaryTable.Rows.Add(); textInfo = SetTextInfo("Times-Roman", 9, "Black", true); tempCell = AddTextToCell("From: ", row3SummaryTable, textInfo, true); row4SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); if(!isReturn) tempCell = AddTextToCell(flightInfo.DepartureLocation, row3SummaryTable, textInfo, false); else tempCell = AddTextToCell(flightInfo.Destination, row3SummaryTable, textInfo, false); row4SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", true); tempCell = AddTextToCell("To: ", row3SummaryTable, textInfo, true); row4SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); if(!isReturn) tempCell = AddTextToCell(flightInfo.Destination, row3SummaryTable, textInfo, false); else tempCell = AddTextToCell(flightInfo.DepartureLocation, row3SummaryTable, textInfo, false); row4SummaryTable.Cells.Add(tempCell); Row row5SummaryTable = summaryTable.Rows.Add(); textInfo = SetTextInfo("Times-Roman",9, "Black", true); tempCell = AddTextToCell("Departure:", row5SummaryTable, textInfo, true); row5SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); if(!isReturn) tempCell = AddTextToCell(flightInfo.DepartureDateandTime.ToString(), row5SummaryTable, textInfo, false); else tempCell = AddTextToCell(flightInfo.ReturnDateandTime.ToString(), row5SummaryTable, textInfo, false); row5SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", true); tempCell = AddTextToCell("Arrival:", row5SummaryTable, textInfo, true); row5SummaryTable.Cells.Add(tempCell); textInfo = SetTextInfo("Times-Roman", 9, "Black", false); if(!isReturn) tempCell = AddTextToCell(flightInfo.ArrivalDateandTimeDest.ToString(), row5SummaryTable, textInfo, false); else tempCell = AddTextToCell(flightInfo.ArrivalDateandTimeBack.ToString(), row5SummaryTable, textInfo, false); row5SummaryTable.Cells.Add(tempCell); } //create object with text styling information private Aspose.Pdf.Generator.TextInfo SetTextInfo(string fontName, float fontSize, string fontColor, bool isBold) { Aspose.Pdf.Generator.TextInfo textInfo = new Aspose.Pdf.Generator.TextInfo(); textInfo.FontSize = fontSize; textInfo.Color = new Aspose.Pdf.Generator.Color(fontColor); textInfo.Alignment = AlignmentType.Center; textInfo.IsTrueTypeFontBold = isBold; textInfo.TruetypeFontFileName = fontName; return textInfo; } //create a new cell private Cell AddTextToCell(string strText, Row currentRow, Aspose.Pdf.Generator.TextInfo textInfo, bool isRightAligned) { Cell tempCell = new Cell(currentRow); Text text = new Text(strText); text.TextInfo = textInfo; if (isRightAligned) text.TextInfo.Alignment = AlignmentType.Right; else text.TextInfo.Alignment = AlignmentType.Left; tempCell.Paragraphs.Add(text); return tempCell; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace SqliteSharp { static class Sqlite3 { const string dllname = "sqlite3"; public const int SQLITE_OK = 0; public const int SQLITE_ROW = 100; public const int SQLITE_DONE = 101; public const int SQLITE_INTEGER = 1; public const int SQLITE_FLOAT = 2; public const int SQLITE_TEXT = 3; public const int SQLITE_BLOB = 4; public const int SQLITE_NULL = 5; [DllImport(dllname, EntryPoint = "sqlite3_open")] static extern int sqlite3_open(string filename, out IntPtr ppDb); public static IntPtr Open(string filename) { IntPtr db; if(sqlite3_open(filename, out db) != SQLITE_OK){ throw new Exception("Could not open database file: " + filename); } return db; } [DllImport(dllname, EntryPoint = "sqlite3_close")] static extern int sqlite3_close(IntPtr db); public static int Close(IntPtr db) { return sqlite3_close(db); } [DllImport(dllname, EntryPoint = "sqlite3_errmsg")] static extern IntPtr sqlite3_errmsg(IntPtr db); public static string Errmsg(IntPtr db) { IntPtr err = sqlite3_errmsg(db); return Marshal.PtrToStringAnsi(err); } [DllImport(dllname, EntryPoint = "sqlite3_prepare_v2")] static extern int sqlite3_prepare_v2(IntPtr db, string zSql, int nByte, out IntPtr ppStmt, IntPtr pzTail); public static IntPtr Prepare(IntPtr db, string sql) { IntPtr stmt; int len = Encoding.UTF8.GetByteCount(sql); if(sqlite3_prepare_v2(db, sql, len, out stmt, IntPtr.Zero) != SQLITE_OK){ throw new Exception(sqlite3_errmsg(db)); } return stmt; } [DllImport(dllname, EntryPoint = "sqlite3_finalize")] static extern int sqlite3_finalize(IntPtr pStmt); public static int Finalize(IntPtr pStmt) { return sqlite3_finalize(pStmt); } [DllImport(dllname, EntryPoint = "sqlite3_reset")] static extern int sqlite3_reset(IntPtr pStmt); public static int Reset(IntPtr pStmt) { return sqlite3_reset(pStmt); } public static void Reset(IntPtr db, IntPtr pStmt) { if(Reset(pStmt) != SQLITE_OK){ throw new Exception(Errmsg(db)); } } [DllImport(dllname, EntryPoint = "sqlite3_clear_bindings")] static extern int sqlite3_clear_bindings(IntPtr pStmt); public static int ClearBindings(IntPtr pStmt) { return sqlite3_clear_bindings(pStmt); } public static void ClearBindings(IntPtr db, IntPtr pStmt) { if(ClearBindings(pStmt) != SQLITE_OK){ throw new Exception(Errmsg(db)); } } [DllImport(dllname, EntryPoint = "sqlite3_bind_parameter_index")] static extern int sqlite3_bind_parameter_index(IntPtr pStmt, string zName); public static int BindParameterIndex(IntPtr pStmt, string name) { return sqlite3_bind_parameter_index(pStmt, name); } public static void BindParameterIndex(IntPtr db, IntPtr pStmt, string name) { int index = BindParameterIndex(pStmt, name); if(index == 0){ throw new Exception(Errmsg(db)); } } [DllImport(dllname, EntryPoint = "sqlite3_bind_blob")] static extern int sqlite3_bind_blob(IntPtr pStmt, int i, byte[] data, int len , IntPtr func); public static int BindBlob(IntPtr pStmt, int i, byte[] value) { var len = value.Length; return sqlite3_bind_blob(pStmt, i, value, len, IntPtr.Zero); } [DllImport(dllname, EntryPoint = "sqlite3_bind_double")] static extern int sqlite3_bind_double(IntPtr pStmt, int i, double value); public static int BindDouble(IntPtr pStmt, int i, double value) { return sqlite3_bind_double(pStmt, i, value); } [DllImport(dllname, EntryPoint = "sqlite3_bind_int")] static extern int sqlite3_bind_int(IntPtr pStmt, int i, int value); public static int BindInt(IntPtr pStmt, int i, int value) { return sqlite3_bind_int(pStmt, i, value); } [DllImport(dllname, EntryPoint = "sqlite3_bind_null")] static extern int sqlite3_bind_null(IntPtr pStmt, int i); public static int BindNull(IntPtr pStmt, int i) { return sqlite3_bind_null(pStmt, i); } [DllImport(dllname, EntryPoint = "sqlite3_bind_text")] static extern int sqlite3_bind_text(IntPtr pStmt, int i, byte[] value, int nByte, IntPtr func); public static int BindText(IntPtr pStmt, int i, string value) { var len = Encoding.UTF8.GetByteCount(value)+1; var data = new byte[len]; len = Encoding.UTF8.GetBytes(value, 0, value.Length, data, 0); return sqlite3_bind_text(pStmt, i, data, len, IntPtr.Zero); } //[DllImport(dllname, EntryPoint = "sqlite3_bind_value")] //static extern int sqlite3_bind_value(IntPtr pStmt, int i, IntPtr pValue); [DllImport(dllname, EntryPoint = "sqlite3_bind_zeroblob")] static extern int sqlite3_bind_zeroblob(IntPtr pStmt, int i, int n); public static int BindZeroBlob(IntPtr pStmt, int i, int n) { return sqlite3_bind_zeroblob(pStmt, i, n); } public static void Bind(IntPtr db, IntPtr pStmt, int i, object value) { int result; if(value == null){ result = Sqlite3.BindNull(pStmt, i); } else if(value is int || value is long || value is short){ result = BindInt(pStmt, i, (int)value); } else if(value is string){ result = BindText(pStmt, i, (string)value); } else if(value is float || value is double){ result = BindDouble(pStmt, i, (double)value); } else if(value is byte[]){ result = BindBlob(pStmt, i, (byte[])value); } else{ throw new Exception("invalid binding parameter type: ("+i+") "+value.GetType()); } if(result != SQLITE_OK){ throw new Exception(Errmsg(db)); } } [DllImport(dllname, EntryPoint = "sqlite3_step")] static extern int sqlite3_step(IntPtr pStmt); public static bool Step(IntPtr db, IntPtr pStmt) { int result = sqlite3_step(pStmt); if(result != SQLITE_ROW && result != SQLITE_DONE){ throw new Exception(Errmsg(db)); } return result == SQLITE_ROW; } [DllImport(dllname, EntryPoint = "sqlite3_column_count")] static extern int sqlite3_column_count(IntPtr pStmt); public static int ColumnCount(IntPtr pStmt) { return sqlite3_column_count(pStmt); } [DllImport(dllname, EntryPoint = "sqlite3_column_name")] static extern IntPtr sqlite3_column_name(IntPtr pStmt, int iCol); public static string ColumnName(IntPtr pStmt, int iCol) { var pStr = sqlite3_column_name(pStmt, iCol); return Marshal.PtrToStringAnsi(pStr); } public static List<string> ColumnNames(IntPtr pStmt) { int cc = ColumnCount(pStmt); var names = new List<string>(cc); for(var i=0; i<cc; ++i){ names.Add(ColumnName(pStmt, i)); } return names; } [DllImport(dllname, EntryPoint = "sqlite3_column_type")] static extern int sqlite3_column_type(IntPtr pStmt, int iCol); public static int ColumnType(IntPtr pStmt, int iCol) { return sqlite3_column_type(pStmt, iCol); } [DllImport(dllname, EntryPoint = "sqlite3_column_int")] static extern int sqlite3_column_int(IntPtr pStmt, int iCol); public static int ColumnInt(IntPtr pStmt, int iCol) { return sqlite3_column_int(pStmt, iCol); } [DllImport(dllname, EntryPoint = "sqlite3_column_text")] static extern IntPtr sqlite3_column_text(IntPtr pStmt, int iCol); public static string ColumnText(IntPtr pStmt, int iCol) { var pStr = sqlite3_column_text(pStmt, iCol); return Marshal.PtrToStringAnsi(pStr); } [DllImport(dllname, EntryPoint = "sqlite3_column_double")] static extern double sqlite3_column_double(IntPtr pStmt, int iCol); public static double ColumnDouble(IntPtr pStmt, int iCol) { return sqlite3_column_double(pStmt, iCol); } [DllImport(dllname, EntryPoint = "sqlite3_column_bytes")] static extern int sqlite3_column_bytes(IntPtr pStmt, int iCol); public static int ColumnBytes(IntPtr pStmt, int iCol) { return sqlite3_column_bytes(pStmt, iCol); } [DllImport(dllname, EntryPoint = "sqlite3_column_blob")] static extern IntPtr sqlite3_column_blob(IntPtr pStmt, int iCol); public static byte[] ColumnBlob(IntPtr pStmt, int iCol) { int size = ColumnBytes(pStmt, iCol); var pBlob = sqlite3_column_blob(pStmt, iCol); var data = new byte[size]; Marshal.Copy(pBlob, data, 0, size); return data; } public static object Column(IntPtr pStmt, int iCol) { switch(ColumnType(pStmt, iCol)){ case SQLITE_INTEGER: return ColumnInt(pStmt, iCol); case SQLITE_FLOAT: return ColumnDouble(pStmt, iCol); case SQLITE_TEXT: return ColumnText(pStmt, iCol); case SQLITE_BLOB: return ColumnBlob(pStmt, iCol); case SQLITE_NULL: default: return null; } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 3/8/2010 11:54:49 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.IO; namespace DotSpatial.Data { /// <summary> /// Stream extensions /// </summary> public static class StreamExt { /// <summary> /// Attempts to read count of bytes from stream. /// </summary> /// <param name="stream">Input stream.</param> /// <param name="count">Count of bytes.</param> /// <returns>Bytes array.</returns> public static byte[] ReadBytes(this Stream stream, int count) { var bytes = new byte[count]; stream.Read(bytes, 0, bytes.Length); return bytes; } /// <summary> /// Attempts to read the specified T. If this system is /// doesn't match the specified endian, then this will reverse the array of bytes, /// so that it corresponds with the big-endian format. /// </summary> /// <param name="stream">The stream to read the value from</param> /// <param name="endian">Specifies what endian property should be used.</param> /// <returns>The integer value</returns> public static int ReadInt32(this Stream stream, Endian endian = Endian.LittleEndian) { var val = new byte[4]; stream.Read(val, 0, 4); if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian) { Array.Reverse(val); } return BitConverter.ToInt32(val, 0); } /// <summary> /// Reads the specified number of integers. If a value other than the /// systems endian format is specified the values will be reversed. /// </summary> /// <param name="stream">The stream to read from</param> /// <param name="count">The integer count of integers to read</param> /// <param name="endian">The endian order of the bytes.</param> /// <returns>The array of integers that will have count integers.</returns> public static int[] ReadInt32(this Stream stream, int count, Endian endian = Endian.LittleEndian) { var result = new int[count]; var val = new byte[4 * count]; stream.Read(val, 0, val.Length); if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian) { for (var i = 0; i < count; i++) { var temp = new byte[4]; Array.Copy(val, i * 4, temp, 0, 4); Array.Reverse(temp); Array.Copy(temp, 0, val, i * 4, 4); } } Buffer.BlockCopy(val, 0, result, 0, count * 4); return result; } /// <summary> /// Reads a double precision value from the stream. If this system /// is not little endian, it will reverse the individual memebrs. /// </summary> /// <param name="stream">The stream to read the values from.</param> /// <returns>A double precision value</returns> public static double ReadDouble(this Stream stream) { return ReadDouble(stream, 1)[0]; } /// <summary> /// Reads the specified number of double precision values. If this system /// does not match the specified endian, the bytes will be reversed. /// </summary> /// <param name="stream">The stream to read the values from.</param> /// <param name="count">The integer count of doubles to read.</param> /// <param name="endian">The endian to use.</param> /// <returns></returns> public static double[] ReadDouble(this Stream stream, int count, Endian endian = Endian.LittleEndian) { var val = new byte[count * 8]; stream.Read(val, 0, count * 8); if ((endian == Endian.LittleEndian) != BitConverter.IsLittleEndian) { for (var i = 0; i < count; i++) { var temp = new byte[8]; Array.Copy(val, i * 8, temp, 0, 8); Array.Reverse(temp); Array.Copy(temp, 0, val, i * 8, 8); } } var result = new double[count]; Buffer.BlockCopy(val, 0, result, 0, count * 8); return result; } /// <summary> /// Writes the integer as big endian /// </summary> /// <param name="stream">The IO stream </param> /// <param name="value"></param> public static void WriteBe(this Stream stream, int value) { var val = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) Array.Reverse(val); stream.Write(val, 0, 4); } /// <summary> /// Writes the endian as little endian /// </summary> /// <param name="stream"></param> /// <param name="value"></param> public static void WriteLe(this Stream stream, int value) { var val = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(val); stream.Write(val, 0, 4); } /// <summary> /// Checks that the endian order is ok for integers and then writes /// the entire array to the stream. /// </summary> /// <param name="stream"></param> /// <param name="values"></param> /// <param name="startIndex"></param> /// <param name="count"></param> public static void WriteLe(this Stream stream, int[] values, int startIndex, int count) { var bytes = new byte[count * 4]; Buffer.BlockCopy(values, startIndex * 4, bytes, 0, bytes.Length); if (!BitConverter.IsLittleEndian) { // Reverse to little endian if this is a big endian machine var temp = bytes; bytes = new byte[temp.Length]; Array.Reverse(temp); for (var i = 0; i < count; i++) { Array.Copy(temp, i * 4, bytes, (count - i - 1) * 4, 4); } } stream.Write(bytes, 0, bytes.Length); } /// <summary> /// Writes the specified double value to the stream as little endian /// </summary> /// <param name="stream"></param> /// <param name="value"></param> public static void WriteLe(this Stream stream, double value) { var val = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) Array.Reverse(val); stream.Write(val, 0, 8); } /// <summary> /// Checks that the endian order is ok for doubles and then writes /// the entire array to the stream. /// </summary> /// <param name="stream">The stream to write to</param> /// <param name="values">The double values to write in little endian form</param> /// <param name="startIndex">The integer start index in the double array to begin writing</param> /// <param name="count">The integer count of doubles to write.</param> public static void WriteLe(this Stream stream, double[] values, int startIndex, int count) { var bytes = new byte[count * 8]; Buffer.BlockCopy(values, startIndex * 8, bytes, 0, bytes.Length); if (!BitConverter.IsLittleEndian) { // Reverse to little endian if this is a big endian machine var temp = bytes; bytes = new byte[temp.Length]; Array.Reverse(temp); for (var i = 0; i < count; i++) { Array.Copy(temp, i * 8, bytes, (count - i - 1) * 8, 8); } } stream.Write(bytes, 0, bytes.Length); } } }
//------------------------------------------------------------------------------ // <copyright file="ListGeneralPage.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls { using System; using System.Globalization; using System.CodeDom; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Data; using System.Diagnostics; using System.Drawing; using System.Web.UI; using System.Web.UI.MobileControls; using System.Web.UI.WebControls; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Web.UI.Design.MobileControls.Util; using DataBinding = System.Web.UI.DataBinding; using DataList = System.Web.UI.WebControls.DataList; using TextBox = System.Windows.Forms.TextBox; using CheckBox = System.Windows.Forms.CheckBox; using ComboBox = System.Windows.Forms.ComboBox; using Control = System.Windows.Forms.Control; using Label = System.Windows.Forms.Label; using PropertyDescriptor = System.ComponentModel.PropertyDescriptor; /// <summary> /// The General page for the DataList control. /// </summary> /// <internalonly/> [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class ListGeneralPage : MobileComponentEditorPage { private const int IDX_DECORATION_NONE = 0; private const int IDX_DECORATION_BULLETED = 1; private const int IDX_DECORATION_NUMBERED = 2; private const int IDX_SELECTTYPE_DROPDOWN = 0; private const int IDX_SELECTTYPE_LISTBOX = 1; private const int IDX_SELECTTYPE_RADIO = 2; private const int IDX_SELECTTYPE_MULTISELECTLISTBOX = 3; private const int IDX_SELECTTYPE_CHECKBOX = 4; private ComboBox _decorationCombo; private ComboBox _selectTypeCombo; private TextBox _itemCountTextBox; private TextBox _itemsPerPageTextBox; private TextBox _rowsTextBox; private bool _isBaseControlList; protected override String HelpKeyword { get { if (_isBaseControlList) { return "net.Mobile.ListProperties.General"; } else { return "net.Mobile.SelectionListProperties.General"; } } } /// <summary> /// Initializes the UI of the form. /// </summary> private void InitForm() { Debug.Assert(GetBaseControl() != null); _isBaseControlList = (GetBaseControl() is List); // SelectionList otherwise. GroupLabel appearanceGroup = new GroupLabel(); GroupLabel pagingGroup = null; Label itemCountLabel = null; Label itemsPerPageLabel = null; Label rowsLabel = null; Label decorationLabel = null; Label selectTypeLabel = null; if (_isBaseControlList) { pagingGroup = new GroupLabel(); itemCountLabel = new Label(); _itemCountTextBox = new TextBox(); itemsPerPageLabel = new Label(); _itemsPerPageTextBox = new TextBox(); decorationLabel = new Label(); _decorationCombo = new ComboBox(); } else { rowsLabel = new Label(); _rowsTextBox = new TextBox(); selectTypeLabel = new Label(); _selectTypeCombo = new ComboBox(); } appearanceGroup.SetBounds(4, 4, 372, 16); appearanceGroup.Text = SR.GetString(SR.ListGeneralPage_AppearanceGroupLabel); appearanceGroup.TabIndex = 0; appearanceGroup.TabStop = false; if (_isBaseControlList) { decorationLabel.SetBounds(8, 24, 200, 16); decorationLabel.Text = SR.GetString(SR.ListGeneralPage_DecorationCaption); decorationLabel.TabStop = false; decorationLabel.TabIndex = 1; _decorationCombo.SetBounds(8, 40, 161, 21); _decorationCombo.DropDownStyle = ComboBoxStyle.DropDownList; _decorationCombo.SelectedIndexChanged += new EventHandler(this.OnSetPageDirty); _decorationCombo.Items.AddRange(new object[] { SR.GetString(SR.ListGeneralPage_DecorationNone), SR.GetString(SR.ListGeneralPage_DecorationBulleted), SR.GetString(SR.ListGeneralPage_DecorationNumbered) }); _decorationCombo.TabIndex = 2; pagingGroup.SetBounds(4, 77, 372, 16); pagingGroup.Text = SR.GetString(SR.ListGeneralPage_PagingGroupLabel); pagingGroup.TabIndex = 3; pagingGroup.TabStop = false; itemCountLabel.SetBounds(8, 97, 161, 16); itemCountLabel.Text = SR.GetString(SR.ListGeneralPage_ItemCountCaption); itemCountLabel.TabStop = false; itemCountLabel.TabIndex = 4; _itemCountTextBox.SetBounds(8, 113, 161, 20); _itemCountTextBox.TextChanged += new EventHandler(this.OnSetPageDirty); _itemCountTextBox.KeyPress += new KeyPressEventHandler(this.OnKeyPressNumberTextBox); _itemCountTextBox.TabIndex = 5; itemsPerPageLabel.SetBounds(211, 97, 161, 16); itemsPerPageLabel.Text = SR.GetString(SR.ListGeneralPage_ItemsPerPageCaption); itemsPerPageLabel.TabStop = false; itemsPerPageLabel.TabIndex = 6; _itemsPerPageTextBox.SetBounds(211, 113, 161, 20); _itemsPerPageTextBox.TextChanged += new EventHandler(this.OnSetPageDirty); _itemsPerPageTextBox.KeyPress += new KeyPressEventHandler(this.OnKeyPressNumberTextBox); _itemsPerPageTextBox.TabIndex = 7; } else { selectTypeLabel.SetBounds(8, 24, 161, 16); selectTypeLabel.Text = SR.GetString(SR.ListGeneralPage_SelectTypeCaption); selectTypeLabel.TabStop = false; selectTypeLabel.TabIndex = 1; _selectTypeCombo.SetBounds(8, 40, 161, 21); _selectTypeCombo.DropDownStyle = ComboBoxStyle.DropDownList; _selectTypeCombo.SelectedIndexChanged += new EventHandler(this.OnSetPageDirty); _selectTypeCombo.Items.AddRange(new object[] { SR.GetString(SR.ListGeneralPage_SelectTypeDropDown), SR.GetString(SR.ListGeneralPage_SelectTypeListBox), SR.GetString(SR.ListGeneralPage_SelectTypeRadio), SR.GetString(SR.ListGeneralPage_SelectTypeMultiSelectListBox), SR.GetString(SR.ListGeneralPage_SelectTypeCheckBox) }); _selectTypeCombo.TabIndex = 2; rowsLabel.SetBounds(211, 24, 161, 16); rowsLabel.Text = SR.GetString(SR.ListGeneralPage_RowsCaption); rowsLabel.TabStop = false; rowsLabel.TabIndex = 3; _rowsTextBox.SetBounds(211, 40, 161, 20); _rowsTextBox.TextChanged += new EventHandler(this.OnSetPageDirty); _rowsTextBox.KeyPress += new KeyPressEventHandler(this.OnKeyPressNumberTextBox); _rowsTextBox.TabIndex = 4; } this.Text = SR.GetString(SR.ListGeneralPage_Title); this.Size = new Size(382, 270); this.CommitOnDeactivate = true; this.Icon = new Icon( typeof(System.Web.UI.Design.MobileControls.MobileControlDesigner), "General.ico" ); this.Controls.AddRange(new Control[] { appearanceGroup }); if (_isBaseControlList) { this.Controls.AddRange(new Control[] { _itemsPerPageTextBox, itemsPerPageLabel, _itemCountTextBox, itemCountLabel, pagingGroup, decorationLabel, _decorationCombo }); } else { this.Controls.AddRange(new Control[] { _rowsTextBox, rowsLabel, selectTypeLabel, _selectTypeCombo }); } } protected override void LoadComponent() { IListDesigner listDesigner = (IListDesigner)GetBaseDesigner(); if (_isBaseControlList) { List list = (List)GetBaseControl(); _itemCountTextBox.Text = list.ItemCount.ToString(CultureInfo.InvariantCulture); _itemsPerPageTextBox.Text = list.ItemsPerPage.ToString(CultureInfo.InvariantCulture); switch (list.Decoration) { case ListDecoration.None: _decorationCombo.SelectedIndex = IDX_DECORATION_NONE; break; case ListDecoration.Bulleted: _decorationCombo.SelectedIndex = IDX_DECORATION_BULLETED; break; case ListDecoration.Numbered: _decorationCombo.SelectedIndex = IDX_DECORATION_NUMBERED; break; } } else { SelectionList selectionList = (SelectionList)GetBaseControl(); switch (selectionList.SelectType) { case ListSelectType.DropDown: _selectTypeCombo.SelectedIndex = IDX_SELECTTYPE_DROPDOWN; break; case ListSelectType.ListBox: _selectTypeCombo.SelectedIndex = IDX_SELECTTYPE_LISTBOX; break; case ListSelectType.Radio: _selectTypeCombo.SelectedIndex = IDX_SELECTTYPE_RADIO; break; case ListSelectType.MultiSelectListBox: _selectTypeCombo.SelectedIndex = IDX_SELECTTYPE_MULTISELECTLISTBOX; break; case ListSelectType.CheckBox: _selectTypeCombo.SelectedIndex = IDX_SELECTTYPE_CHECKBOX; break; } _rowsTextBox.Text = selectionList.Rows.ToString(CultureInfo.InvariantCulture); } } private void OnSetPageDirty(Object source, EventArgs e) { if (IsLoading()) { return; } SetDirty(); } private void OnKeyPressNumberTextBox(Object source, KeyPressEventArgs e) { if (!((e.KeyChar >='0' && e.KeyChar <= '9') || e.KeyChar == 8)) { e.Handled = true; SafeNativeMethods.MessageBeep(unchecked((int)0xFFFFFFFF)); } } /// <summary> /// Saves the component loaded into the page. /// </summary> /// <seealso cref="System.Windows.Forms.Design.ComponentEditorPage"/> protected override void SaveComponent() { IListDesigner listDesigner = (IListDesigner)GetBaseDesigner(); if (_isBaseControlList) { List list = (List)GetBaseControl(); switch (_decorationCombo.SelectedIndex) { case IDX_DECORATION_NONE: list.Decoration = ListDecoration.None; break; case IDX_DECORATION_BULLETED: list.Decoration = ListDecoration.Bulleted; break; case IDX_DECORATION_NUMBERED: list.Decoration = ListDecoration.Numbered; break; } try { int itemCount = 0; if (_itemCountTextBox.Text.Length != 0) { itemCount = Int32.Parse(_itemCountTextBox.Text, CultureInfo.InvariantCulture); } list.ItemCount = itemCount; } catch (Exception) { _itemCountTextBox.Text = list.ItemCount.ToString(CultureInfo.InvariantCulture); } try { int itemsPerPage = 0; if (_itemsPerPageTextBox.Text.Length != 0) { itemsPerPage = Int32.Parse(_itemsPerPageTextBox.Text, CultureInfo.InvariantCulture); } list.ItemsPerPage = itemsPerPage; } catch (Exception) { _itemsPerPageTextBox.Text = list.ItemsPerPage.ToString(CultureInfo.InvariantCulture); } TypeDescriptor.Refresh(list); } else { // SelectionList selectionList = (SelectionList)GetBaseControl(); switch (_selectTypeCombo.SelectedIndex) { case IDX_SELECTTYPE_DROPDOWN: selectionList.SelectType = ListSelectType.DropDown; break; case IDX_SELECTTYPE_LISTBOX: selectionList.SelectType = ListSelectType.ListBox; break; case IDX_SELECTTYPE_RADIO: selectionList.SelectType = ListSelectType.Radio; break; case IDX_SELECTTYPE_MULTISELECTLISTBOX: selectionList.SelectType = ListSelectType.MultiSelectListBox; break; case IDX_SELECTTYPE_CHECKBOX: selectionList.SelectType = ListSelectType.CheckBox; break; } try { int rows = 4; if (_rowsTextBox.Text.Length != 0) { rows = Int32.Parse(_rowsTextBox.Text, CultureInfo.InvariantCulture); } selectionList.Rows = rows; } catch (Exception) { _rowsTextBox.Text = selectionList.Rows.ToString(CultureInfo.InvariantCulture); } TypeDescriptor.Refresh(selectionList); } } /// <summary> /// Sets the component that is to be edited in the page. /// </summary> /// <seealso cref="System.Windows.Forms.Design.ComponentEditorPage"/> public override void SetComponent(IComponent component) { base.SetComponent(component); InitForm(); } } }
/** * Project: emergetk: stateful web framework for the masses * File name: .cs * Description: * * @author Ben Joldersma, All-In-One Creations, Ltd. http://all-in-one-creations.net, Copyright (C) 2006. * * @see The GNU Public License (GPL) */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Web; using Boo.Lang.Compiler; using Boo.Lang.Interpreter; namespace EmergeTk { /// <summary> /// Summary description for Util. /// </summary> public static class Util { private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(Util)); public static string RootPath { get { return HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "\\"); } } public static string Join(this IList list, string sep) { return Join( list, sep, false ); } /*public static string Join(IList list, string sep) { return Join( list, sep, false ); }*/ public static string Join(IList list, string sep, bool formatForClient) { return Join(list, sep, formatForClient, 0); } public static string Join(IList list, string sep, bool formatForClient, int startIndex) { if( list != null ) return Join(list, sep, formatForClient, startIndex, list.Count - 1); else return null; } public static string Join(IList list, string sep, bool formatForClient, int startIndex, int finishIndex) { if (list == null || list.Count == 0) return null; StringBuilder sb = new StringBuilder(); for (int i = startIndex; i < finishIndex; i++) { string val; val = prepareValue(list, formatForClient, i); sb.Append(val); sb.Append(sep); } sb.Append(prepareValue( list, formatForClient, finishIndex )); return sb.ToString(); } private static string prepareValue(IList list, bool formatForClient, int i) { string val; if (formatForClient) val = FormatForClient(list[i] as string); else { if (list[i] != null) val = list[i].ToString(); else val = string.Empty; } return val; } public static string Join<T>(T[] cols) { return Join(cols, ","); } public static string Join<T>(List<T> cols) { return Join(cols, ","); } public static string JoinToString<T>(this IEnumerable<T> list, string sep) { StringBuilder sb = new StringBuilder(); foreach( T t in list ) { sb.Append(t); sb.Append(sep); } string result = sb.ToString(); return result.Substring( 0, result.Length-sep.Length ); } public static void ForEach<T>(this IEnumerable<T> list, Action<T> func) { foreach( T t in list ) func(t); } public static void Times(this int count, Action<int> func) { for( int i = 0; i < count; i++ ) func(i); } public static string Quotize(string s) { if (s == null || s == string.Empty) { return "\"\""; } //s = s.Replace("</script>", "</scr' + 'ipt>"); //s = s.Replace("</SCRIPT>", "</scr' + 'ipt>"); return "\"" + s + "\""; //return Surround(s, "\""); } public static string Surround( string inner, string surrounder ) { return string.Format("{0}{1}{0}",surrounder, inner); } public static string SurroundTag(string inner, string tag) { return string.Format("<{0}>{1}</{0}>", tag, inner); } public static string FormatForClient( string input ) { if( input == null ) return string.Empty; StringBuilder sb = new StringBuilder (input.Length * 2); for (int i = 0; i < input.Length; i++) { char c = input[i]; switch(c) { case '\t': sb.Append ("\\t"); break; case '\r': sb.Append ("\\r"); break; case '\n': sb.Append ("\\n"); break; case '\"': sb.Append ("\\\""); break; case '\\': sb.Append ("\\\\"); break; default: sb.Append(c); break; } } return sb.ToString(); } public static string ToJavaScriptString(string input) { return Quotize(FormatForClient(input)); } public static string Coalesce(params string[] args) { for (int i = 0; i < args.Length; i++) { if (args[i] != null) return args[i]; } return null; } public static string Textalize(string source) { Regex newLineRemoveReg = new Regex(@"(==|\>)\n"); source = newLineRemoveReg.Replace(source,"$1"); Regex r = new Regex(@"(?<tag>====|===|==|--|'''|\''|\|)(?<inner>.*?)\k<tag>",RegexOptions.Singleline); MatchEvaluator me = new MatchEvaluator( matchTag ); source = r.Replace( source, me ); source = matchLists( source ); source = source.Replace("\r\n\r\n", "<br><br>"); source = source.Replace("\n\n", "<br><br>"); source = source.Replace("\\n", "<br>"); source = source.Replace("\\n", "<br>"); return source; } static private string matchLists( string source ) { Regex numReg = new Regex(@"((^#+)(.*)\n)+([^#]?)",RegexOptions.Compiled|RegexOptions.Multiline); MatchEvaluator me = new MatchEvaluator( matchListOL ); source = numReg.Replace( source,me ); Regex bulletReg = new Regex(@"((^\*+)(.*)\n)+([^#]?)",RegexOptions.Compiled|RegexOptions.Multiline); me = new MatchEvaluator( matchListUL ); source = bulletReg.Replace( source,me ); return source; } static private string matchListOL( Match m ) { return matchList( m, "OL" ); } static private string matchListUL( Match m ) { return matchList( m, "UL" ); } static private string matchList( Match m, string tag ) { //group 0 is <OL>, group n-1 is </OL> //all groups in between are <LI> string open = "<" + tag + ">", close = "</" + tag + ">"; string s = open; int numOpen = 1; int line = 0; foreach( Capture c in m.Groups[2].Captures ) { Capture c2 = m.Groups[3].Captures[line++]; string hashes = c.Value; if( hashes.Length > numOpen ) { numOpen++; s += open; } else if( hashes.Length < numOpen ) { numOpen--; s += close; } s += "<LI>" + c2.Value + "</LI>"; } s += close + m.Groups[4].Value; return s; } static private string matchTag( Match m ) { string tag = string.Empty; string atts = string.Empty; string inner = m.Groups["inner"].Value; switch( m.Groups["tag"].Captures[0].Value ) { case "'''": tag = "B"; break; case "--": tag = "DEL"; break; case "''": tag = "I"; break; case "|": tag = "A"; string[] parts = m.Groups["inner"].Value.Split(new char[]{' '}, 2, StringSplitOptions.RemoveEmptyEntries); atts = " HREF='" + parts[0] + "'"; inner = parts.Length == 2 ? parts[1] : parts[0]; break; case "##": tag = "OL"; inner = inner.Replace("#.", "<LI>"); break; case "**": tag = "UL"; inner = inner.Replace("*.", "<LI>"); break; case "====": tag = "H3"; break; case "===": tag = "H2"; break; case "==": tag = "H1"; break; } return string.Format("<{0}{2}>{1}</{0}>", tag, Util.Textalize(inner), atts); } static public string PascalToHuman( string p ) { if( p == "_" ) return p; Regex r = new Regex("([a-z0-9][A-Z]|[a-z][0-9])"); MatchCollection matches = r.Matches(p); foreach( Match m in matches ) p = p.Replace(m.Groups[0].Value, m.Groups[0].Value.Insert(1," ")); p = p.Replace("_", " "); p = p.Trim(); return p; } // Convert MakeFoo to makeFoo, CTR to CTR, HTMLInput to HTMLInput, HtmlInput to htmlInput. static public string PascalToCamel(string input) { if( input.Length > 1 && char.IsUpper(input[1]) ) return input; return input[0].ToString().ToLower() + input.Substring(1); } //makeFoo to MakeFoo, CTR to CTR, htmlInput to HtmlInput static public string Capitalize (string input) { return CamelToPascal (input); } static public string CamelToPascal(string input) { if (input == null) return null; var c = input.ToCharArray (); c[0] = char.ToUpper (c[0]); return new string (c); } static public object Coalesce( params object[] values ) { for( int i = 0; i < values.Length; i++ ) if( values[i] != null ) return values[ i ]; return null; } static InteractiveInterpreter booInterpreter = null; public static object Eval(string eval) { eval = '(' + eval + ')'; if( booInterpreter == null ) { booInterpreter = new InteractiveInterpreter(); booInterpreter.RememberLastValue = true; } try { log.Debug("Boo Eval'ing ", eval ); booInterpreter.Reset(); booInterpreter.Eval(eval); log.Debug("Boo Result: ", booInterpreter.LastValue ); return booInterpreter.LastValue; } catch (Exception e) { log.Error(string.Format("=====\n\njscript eval error: {0} eval'ing: {1}\n=====\n\n", e.Message, eval) ); return null; } } public static string HashToMime(Dictionary<string, string> input) { List<string> pairs = new List<string>(); foreach( string key in input.Keys ) { pairs.Add(key + "=" + input[key]); } return Join(pairs, "&"); } public static string BuildExceptionOutput(Exception e) { List<string> outputs = new List<string>(); while( e != null ) { outputs.Add( string.Format( "{0} ({1})\n\nStackTrace:\n{2}\n\n", e.Message, e.GetType(), e.StackTrace ) ); e = e.InnerException; } outputs.Reverse(); return Util.Join(outputs,"\n\n"); } public static long ConvertFromBase32(string base32number) { char[] base32 = new char[] { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v' }; long n = 0; foreach (char d in base32number.ToLowerInvariant()) { n = n << 5; int idx = Array.IndexOf(base32, d); if (idx == -1) throw new Exception("Provided number contains invalid characters"); n += idx; } return n; } static char[] base32 = new char[] { 'A','B','C','D','E','F','G','H', 'I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X', 'Y','Z','a','b','c','d','e','f' }; public static string ConvertToBase32( long x ) { string v; if( x > 0 ) v = string.Empty; else v = "A"; while( x > 0 ) { v = base32[ x % 32 ] + v; x /= 32; } return v; } public static string ConvertToBase32( byte[] bytes ) { string v = string.Empty; foreach( byte b in bytes ) { if( b > 0 ) { int x = b; while( x > 0 ) { v += base32[ x % 32 ]; x /= 32; } } else v += "0"; } return v; } public static string GetBase32Guid() { return ConvertToBase32( Guid.NewGuid().ToByteArray() ).Replace("=","").Replace("+",""); } public static string FriendlyTimeSpan( TimeSpan s ) { return string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}", s.Days, s.Hours, s.Minutes, s.Seconds); } public static string Shorten(this string s, int length ) { //shorten to first space inside of length. if(s== null || s.Length <=length ) return s; s = s.Substring(0,length); if( s.Contains( " " ) ) { s = s.Substring(0, s.LastIndexOf(' ')); } s += "..."; return s; } public static IEnumerable<int> Range(this int max) { for (int i = 0; i < max; i++) yield return i; } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i <= end; i++) yield return i; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; // from http://answers.unity3d.com/questions/754873/c-how-to-make-a-job-queue-for-noise-function.html public abstract class JobPool<JOBTYPE> { class TJob { public JOBTYPE job; public ManualResetEvent doneEvent; // a flag to signal when the work is complete public JobPool<JOBTYPE> parent; public TJob(JOBTYPE _job,JobPool<JOBTYPE> _parent) { job = _job; parent = _parent; doneEvent = new ManualResetEvent(false); doneEvent.Reset(); } public void ThreadPoolCallback (System.Object o) { doneEvent.Reset(); parent.DoExecuteJob (this.job); parent.RemoveJob (this); doneEvent.Set (); } }; public bool debug = true; public float jobProgress { get { return jobsCompleted / (float)Mathf.Max(1,jobsPending+jobsCompleted); } } public int jobsCompleted { get { return jobsCompletedCount + jobsExceptionCount; } } public int jobsPending { get { return (jobs!=null) ? jobs.Count : 0; } } int jobsCompletedCount = 0; int jobsExceptionCount = 0; List<TJob> jobs = new List<TJob>(); List<ManualResetEvent> jobDoneEvents = new List<ManualResetEvent> (); //bool run = true; //Thread thread; protected abstract void ExecuteJob (JOBTYPE Job); private void DoExecuteJob(JOBTYPE Job) { try { ExecuteJob (Job); jobsCompletedCount++; } catch { jobsExceptionCount++; } } public void PushJob(JOBTYPE Job) { var NewJob = new TJob (Job, this); lock (jobDoneEvents) { jobs.Add (NewJob); jobDoneEvents.Add (NewJob.doneEvent); } ThreadPool.QueueUserWorkItem ( NewJob.ThreadPoolCallback ); } private void RemoveJob(TJob Job) { lock (jobDoneEvents) { jobDoneEvents.Remove (Job.doneEvent); jobs.Remove (Job); } } public void WaitForJobs(int TimeoutMs) { var NonNullEvents = new List<ManualResetEvent> (); int NullCount = 0; lock (jobDoneEvents) { foreach (var e in jobDoneEvents) { if (e != null) NonNullEvents.Add (e); NullCount++; } } var WaitHandles = NonNullEvents.ToArray (); Debug.Log ("Wait for jobs x" + WaitHandles.Length + " (" + NullCount + " nulls"); if (WaitHandles == null) return; if ( TimeoutMs == -1 ) WaitHandle.WaitAll (WaitHandles); else WaitHandle.WaitAll (WaitHandles,TimeoutMs); } public void Shutdown() { WaitForJobs (-1); } }; public class JobPool_Action : JobPool<System.Action> { protected override void ExecuteJob (System.Action Job) { if (Job != null) Job.Invoke (); } } public abstract class JobThread_Base<JOBTYPE> { public bool debug = true; public float jobProgress { get { return jobsCompleted / (float)Mathf.Max(1,jobsPending+jobsCompleted); } } public int jobsCompleted { get { return jobsCompletedCount; } } public int jobsPending { get { return (jobs!=null) ? jobs.Count : 0; } } int jobsCompletedCount = 0; List<JOBTYPE> jobs = new List<JOBTYPE>(); bool run = true; Thread thread; ManualResetEvent IsIdle = new ManualResetEvent(true); public abstract void ExecuteJob (JOBTYPE Job); public JobThread_Base() { } public void PushJob(JOBTYPE Job) { jobs.Add (Job); IsIdle.Reset (); // no longer idle Wake(); } public void Shutdown() { run = false; if (thread != null) { Debug.Log ("Shutdown Worker thread joining..."); thread.Join (); thread = null; Debug.Log ("Shutdown Worker thread null'd"); } } void Wake() { // thread has finished or thrown exception if ( thread != null && !thread.IsAlive) { // hiccup? mark as idle so WaitFor doesn't block OnIdle(); if ( debug ) Debug.Log ("Worker thread not alive: " + jobs.Count + " jobs"); if ( debug ) Debug.Log ("Worker thread joining..."); thread.Join (); thread = null; if ( debug ) Debug.Log ("Worker thread null'd"); } if ( thread == null && run ) { thread = new Thread (new ThreadStart (Iterator)); thread.Start(); // spin to startup thread while (!thread.IsAlive) { if ( debug ) Debug.Log ("Spinning to startup thread"); } } } void Iterator() { try { while ( run ) //while (true) { if (jobs.Count == 0) { OnIdle (); // wait for job notification here Thread.Sleep (1); continue; } // run through all the jobs, lock so we know they're busy if ( debug ) Debug.Log(jobs.Count + " Jobs todo"); while (jobs.Count > 0) { var Job0 = jobs [0]; ExecuteJob( Job0 ); jobsCompletedCount++; jobs.RemoveAt (0); } } } catch(System.Exception e) { Debug.Log ("Worker thread exception... clearing " + jobs.Count + " jobs"); Debug.LogException (e); jobs.Clear (); OnIdle (); } } void OnIdle() { IsIdle.Set (); } public void WaitForJobs(int TimeoutMs=0) { Wake (); if ( debug ) Debug.Log ("Waiting for " + jobs.Count + " jobs."); if (jobs.Count > 0) { if ( TimeoutMs == 0 ) IsIdle.WaitOne (); else IsIdle.WaitOne (TimeoutMs); } } } public class JobThread : JobThread_Base<System.Action> { public override void ExecuteJob (System.Action Job) { if (Job != null) Job.Invoke (); } }
// // 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.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.RecoveryServices.Backup; using Microsoft.Azure.Management.RecoveryServices.Backup.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices.Backup { /// <summary> /// The Resource Manager API includes operations for managing the /// protectable objects registered to your Recovery Services Vault. /// </summary> internal partial class ProtectableObjectOperations : IServiceOperations<RecoveryServicesBackupManagementClient>, IProtectableObjectOperations { /// <summary> /// Initializes a new instance of the ProtectableObjectOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ProtectableObjectOperations(RecoveryServicesBackupManagementClient client) { this._client = client; } private RecoveryServicesBackupManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.Backup.RecoveryServicesBackupManagementClient. /// </summary> public RecoveryServicesBackupManagementClient Client { get { return this._client; } } /// <summary> /// Lists all the protectable objects within your subscription /// according to the query filter and the pagination parameters. /// </summary> /// <param name='resourceGroupName'> /// Required. Resource group name of your recovery services vault. /// </param> /// <param name='resourceName'> /// Required. Name of your recovery services vault. /// </param> /// <param name='queryFilter'> /// Optional. /// </param> /// <param name='paginationParams'> /// Optional. Pagination parameters for controlling the response. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of protectable object resonses as returned by the list /// protectable objects API. /// </returns> public async Task<ProtectableObjectListResponse> ListAsync(string resourceGroupName, string resourceName, ProtectableObjectListQueryParameters queryFilter, PaginationRequest paginationParams, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("queryFilter", queryFilter); tracingParameters.Add("paginationParams", paginationParams); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId.ToString()); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/backupProtectableItems"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); List<string> odataFilter = new List<string>(); if (queryFilter != null && queryFilter.BackupManagementType != null) { odataFilter.Add("backupManagementType eq '" + Uri.EscapeDataString(queryFilter.BackupManagementType) + "'"); } if (queryFilter != null && queryFilter.Status != null) { odataFilter.Add("status eq '" + Uri.EscapeDataString(queryFilter.Status) + "'"); } if (queryFilter != null && queryFilter.FriendlyName != null) { odataFilter.Add("friendlyName eq '" + Uri.EscapeDataString(queryFilter.FriendlyName) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(" and ", odataFilter)); } if (paginationParams != null && paginationParams.SkipToken != null) { queryParameters.Add("$skiptoken=" + Uri.EscapeDataString(paginationParams.SkipToken)); } if (paginationParams != null && paginationParams.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(paginationParams.Top)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // 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 ProtectableObjectListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProtectableObjectListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ProtectableObjectResourceList itemListInstance = new ProtectableObjectResourceList(); result.ItemList = itemListInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ProtectableObjectResource protectableObjectResourceInstance = new ProtectableObjectResource(); itemListInstance.ProtectableObjects.Add(protectableObjectResourceInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["protectableItemType"]); if (typeName == "ProtectableItem") { ProtectableItem protectableItemInstance = new ProtectableItem(); JToken friendlyNameValue = propertiesValue["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); protectableItemInstance.FriendlyName = friendlyNameInstance; } JToken protectionStateValue = propertiesValue["protectionState"]; if (protectionStateValue != null && protectionStateValue.Type != JTokenType.Null) { string protectionStateInstance = ((string)protectionStateValue); protectableItemInstance.ProtectionState = protectionStateInstance; } JToken protectableItemTypeValue = propertiesValue["protectableItemType"]; if (protectableItemTypeValue != null && protectableItemTypeValue.Type != JTokenType.Null) { string protectableItemTypeInstance = ((string)protectableItemTypeValue); protectableItemInstance.ProtectableItemType = protectableItemTypeInstance; } JToken backupManagementTypeValue = propertiesValue["backupManagementType"]; if (backupManagementTypeValue != null && backupManagementTypeValue.Type != JTokenType.Null) { string backupManagementTypeInstance = ((string)backupManagementTypeValue); protectableItemInstance.BackupManagementType = backupManagementTypeInstance; } protectableObjectResourceInstance.Properties = protectableItemInstance; } if (typeName == "IaaSVMProtectableItem") { AzureIaaSVMProtectableItem azureIaaSVMProtectableItemInstance = new AzureIaaSVMProtectableItem(); JToken virtualMachineIdValue = propertiesValue["virtualMachineId"]; if (virtualMachineIdValue != null && virtualMachineIdValue.Type != JTokenType.Null) { string virtualMachineIdInstance = ((string)virtualMachineIdValue); azureIaaSVMProtectableItemInstance.VirtualMachineId = virtualMachineIdInstance; } JToken friendlyNameValue2 = propertiesValue["friendlyName"]; if (friendlyNameValue2 != null && friendlyNameValue2.Type != JTokenType.Null) { string friendlyNameInstance2 = ((string)friendlyNameValue2); azureIaaSVMProtectableItemInstance.FriendlyName = friendlyNameInstance2; } JToken protectionStateValue2 = propertiesValue["protectionState"]; if (protectionStateValue2 != null && protectionStateValue2.Type != JTokenType.Null) { string protectionStateInstance2 = ((string)protectionStateValue2); azureIaaSVMProtectableItemInstance.ProtectionState = protectionStateInstance2; } JToken protectableItemTypeValue2 = propertiesValue["protectableItemType"]; if (protectableItemTypeValue2 != null && protectableItemTypeValue2.Type != JTokenType.Null) { string protectableItemTypeInstance2 = ((string)protectableItemTypeValue2); azureIaaSVMProtectableItemInstance.ProtectableItemType = protectableItemTypeInstance2; } JToken backupManagementTypeValue2 = propertiesValue["backupManagementType"]; if (backupManagementTypeValue2 != null && backupManagementTypeValue2.Type != JTokenType.Null) { string backupManagementTypeInstance2 = ((string)backupManagementTypeValue2); azureIaaSVMProtectableItemInstance.BackupManagementType = backupManagementTypeInstance2; } protectableObjectResourceInstance.Properties = azureIaaSVMProtectableItemInstance; } if (typeName == "Microsoft.ClassicCompute/virtualMachines") { AzureIaaSClassicComputeVMProtectableItem azureIaaSClassicComputeVMProtectableItemInstance = new AzureIaaSClassicComputeVMProtectableItem(); JToken virtualMachineIdValue2 = propertiesValue["virtualMachineId"]; if (virtualMachineIdValue2 != null && virtualMachineIdValue2.Type != JTokenType.Null) { string virtualMachineIdInstance2 = ((string)virtualMachineIdValue2); azureIaaSClassicComputeVMProtectableItemInstance.VirtualMachineId = virtualMachineIdInstance2; } JToken friendlyNameValue3 = propertiesValue["friendlyName"]; if (friendlyNameValue3 != null && friendlyNameValue3.Type != JTokenType.Null) { string friendlyNameInstance3 = ((string)friendlyNameValue3); azureIaaSClassicComputeVMProtectableItemInstance.FriendlyName = friendlyNameInstance3; } JToken protectionStateValue3 = propertiesValue["protectionState"]; if (protectionStateValue3 != null && protectionStateValue3.Type != JTokenType.Null) { string protectionStateInstance3 = ((string)protectionStateValue3); azureIaaSClassicComputeVMProtectableItemInstance.ProtectionState = protectionStateInstance3; } JToken protectableItemTypeValue3 = propertiesValue["protectableItemType"]; if (protectableItemTypeValue3 != null && protectableItemTypeValue3.Type != JTokenType.Null) { string protectableItemTypeInstance3 = ((string)protectableItemTypeValue3); azureIaaSClassicComputeVMProtectableItemInstance.ProtectableItemType = protectableItemTypeInstance3; } JToken backupManagementTypeValue3 = propertiesValue["backupManagementType"]; if (backupManagementTypeValue3 != null && backupManagementTypeValue3.Type != JTokenType.Null) { string backupManagementTypeInstance3 = ((string)backupManagementTypeValue3); azureIaaSClassicComputeVMProtectableItemInstance.BackupManagementType = backupManagementTypeInstance3; } protectableObjectResourceInstance.Properties = azureIaaSClassicComputeVMProtectableItemInstance; } if (typeName == "Microsoft.Compute/virtualMachines") { AzureIaaSComputeVMProtectableItem azureIaaSComputeVMProtectableItemInstance = new AzureIaaSComputeVMProtectableItem(); JToken virtualMachineIdValue3 = propertiesValue["virtualMachineId"]; if (virtualMachineIdValue3 != null && virtualMachineIdValue3.Type != JTokenType.Null) { string virtualMachineIdInstance3 = ((string)virtualMachineIdValue3); azureIaaSComputeVMProtectableItemInstance.VirtualMachineId = virtualMachineIdInstance3; } JToken friendlyNameValue4 = propertiesValue["friendlyName"]; if (friendlyNameValue4 != null && friendlyNameValue4.Type != JTokenType.Null) { string friendlyNameInstance4 = ((string)friendlyNameValue4); azureIaaSComputeVMProtectableItemInstance.FriendlyName = friendlyNameInstance4; } JToken protectionStateValue4 = propertiesValue["protectionState"]; if (protectionStateValue4 != null && protectionStateValue4.Type != JTokenType.Null) { string protectionStateInstance4 = ((string)protectionStateValue4); azureIaaSComputeVMProtectableItemInstance.ProtectionState = protectionStateInstance4; } JToken protectableItemTypeValue4 = propertiesValue["protectableItemType"]; if (protectableItemTypeValue4 != null && protectableItemTypeValue4.Type != JTokenType.Null) { string protectableItemTypeInstance4 = ((string)protectableItemTypeValue4); azureIaaSComputeVMProtectableItemInstance.ProtectableItemType = protectableItemTypeInstance4; } JToken backupManagementTypeValue4 = propertiesValue["backupManagementType"]; if (backupManagementTypeValue4 != null && backupManagementTypeValue4.Type != JTokenType.Null) { string backupManagementTypeInstance4 = ((string)backupManagementTypeValue4); azureIaaSComputeVMProtectableItemInstance.BackupManagementType = backupManagementTypeInstance4; } protectableObjectResourceInstance.Properties = azureIaaSComputeVMProtectableItemInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); protectableObjectResourceInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); protectableObjectResourceInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); protectableObjectResourceInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); protectableObjectResourceInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); protectableObjectResourceInstance.Tags.Add(tagsKey, tagsValue); } } JToken eTagValue = valueValue["eTag"]; if (eTagValue != null && eTagValue.Type != JTokenType.Null) { string eTagInstance = ((string)eTagValue); protectableObjectResourceInstance.ETag = eTagInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); itemListInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.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 gagvc = Google.Ads.GoogleAds.V9.Common; 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 GeneratedCampaignBidModifierServiceClientTest { [Category("Autogenerated")][Test] public void GetCampaignBidModifierRequestObject() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); GetCampaignBidModifierRequest request = new GetCampaignBidModifierRequest { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), }; gagvr::CampaignBidModifier expectedResponse = new gagvr::CampaignBidModifier { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), InteractionType = new gagvc::InteractionTypeInfo(), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, }; mockGrpcClient.Setup(x => x.GetCampaignBidModifier(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignBidModifier response = client.GetCampaignBidModifier(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignBidModifierRequestObjectAsync() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); GetCampaignBidModifierRequest request = new GetCampaignBidModifierRequest { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), }; gagvr::CampaignBidModifier expectedResponse = new gagvr::CampaignBidModifier { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), InteractionType = new gagvc::InteractionTypeInfo(), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, }; mockGrpcClient.Setup(x => x.GetCampaignBidModifierAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignBidModifier>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignBidModifier responseCallSettings = await client.GetCampaignBidModifierAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignBidModifier responseCancellationToken = await client.GetCampaignBidModifierAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignBidModifier() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); GetCampaignBidModifierRequest request = new GetCampaignBidModifierRequest { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), }; gagvr::CampaignBidModifier expectedResponse = new gagvr::CampaignBidModifier { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), InteractionType = new gagvc::InteractionTypeInfo(), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, }; mockGrpcClient.Setup(x => x.GetCampaignBidModifier(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignBidModifier response = client.GetCampaignBidModifier(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignBidModifierAsync() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); GetCampaignBidModifierRequest request = new GetCampaignBidModifierRequest { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), }; gagvr::CampaignBidModifier expectedResponse = new gagvr::CampaignBidModifier { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), InteractionType = new gagvc::InteractionTypeInfo(), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, }; mockGrpcClient.Setup(x => x.GetCampaignBidModifierAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignBidModifier>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignBidModifier responseCallSettings = await client.GetCampaignBidModifierAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignBidModifier responseCancellationToken = await client.GetCampaignBidModifierAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignBidModifierResourceNames() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); GetCampaignBidModifierRequest request = new GetCampaignBidModifierRequest { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), }; gagvr::CampaignBidModifier expectedResponse = new gagvr::CampaignBidModifier { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), InteractionType = new gagvc::InteractionTypeInfo(), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, }; mockGrpcClient.Setup(x => x.GetCampaignBidModifier(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignBidModifier response = client.GetCampaignBidModifier(request.ResourceNameAsCampaignBidModifierName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignBidModifierResourceNamesAsync() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); GetCampaignBidModifierRequest request = new GetCampaignBidModifierRequest { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), }; gagvr::CampaignBidModifier expectedResponse = new gagvr::CampaignBidModifier { ResourceNameAsCampaignBidModifierName = gagvr::CampaignBidModifierName.FromCustomerCampaignCriterion("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[CRITERION_ID]"), InteractionType = new gagvc::InteractionTypeInfo(), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, }; mockGrpcClient.Setup(x => x.GetCampaignBidModifierAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignBidModifier>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignBidModifier responseCallSettings = await client.GetCampaignBidModifierAsync(request.ResourceNameAsCampaignBidModifierName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignBidModifier responseCancellationToken = await client.GetCampaignBidModifierAsync(request.ResourceNameAsCampaignBidModifierName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignBidModifiersRequestObject() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); MutateCampaignBidModifiersRequest request = new MutateCampaignBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignBidModifierOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignBidModifiersResponse expectedResponse = new MutateCampaignBidModifiersResponse { Results = { new MutateCampaignBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignBidModifiers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignBidModifiersResponse response = client.MutateCampaignBidModifiers(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignBidModifiersRequestObjectAsync() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); MutateCampaignBidModifiersRequest request = new MutateCampaignBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignBidModifierOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignBidModifiersResponse expectedResponse = new MutateCampaignBidModifiersResponse { Results = { new MutateCampaignBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignBidModifiersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignBidModifiersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignBidModifiersResponse responseCallSettings = await client.MutateCampaignBidModifiersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignBidModifiersResponse responseCancellationToken = await client.MutateCampaignBidModifiersAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignBidModifiers() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); MutateCampaignBidModifiersRequest request = new MutateCampaignBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignBidModifierOperation(), }, }; MutateCampaignBidModifiersResponse expectedResponse = new MutateCampaignBidModifiersResponse { Results = { new MutateCampaignBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignBidModifiers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignBidModifiersResponse response = client.MutateCampaignBidModifiers(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignBidModifiersAsync() { moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient> mockGrpcClient = new moq::Mock<CampaignBidModifierService.CampaignBidModifierServiceClient>(moq::MockBehavior.Strict); MutateCampaignBidModifiersRequest request = new MutateCampaignBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignBidModifierOperation(), }, }; MutateCampaignBidModifiersResponse expectedResponse = new MutateCampaignBidModifiersResponse { Results = { new MutateCampaignBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignBidModifiersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignBidModifiersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignBidModifierServiceClient client = new CampaignBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignBidModifiersResponse responseCallSettings = await client.MutateCampaignBidModifiersAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignBidModifiersResponse responseCancellationToken = await client.MutateCampaignBidModifiersAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Copyright (c) 2007-2008, the libsecondlife development 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.IO; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace libsecondlife.Imaging { #if !NO_UNSAFE /// <summary> /// A Wrapper around openjpeg to encode and decode images to and from byte arrays /// </summary> public class OpenJPEG { /// <summary>TGA Header size</summary> public const int TGA_HEADER_SIZE = 32; // This structure is used to marshal both encoded and decoded images // MUST MATCH THE STRUCT IN libsl.h! [StructLayout(LayoutKind.Sequential, Pack = 4)] private struct MarshalledImage { public IntPtr encoded; // encoded image data public int length; // encoded image length public int dummy; // padding for 64-bit alignment public IntPtr decoded; // decoded image, contiguous components public int width; // width of decoded image public int height; // height of decoded image public int components; // component count } // allocate encoded buffer based on length field [DllImport("openjpeg-libsl.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool LibslAllocEncoded(ref MarshalledImage image); // allocate decoded buffer based on width and height fields [DllImport("openjpeg-libsl.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool LibslAllocDecoded(ref MarshalledImage image); // free buffers [DllImport("openjpeg-libsl.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool LibslFree(ref MarshalledImage image); // encode raw to jpeg2000 [DllImport("openjpeg-libsl.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool LibslEncode(ref MarshalledImage image, bool lossless); // decode jpeg2000 to raw [DllImport("openjpeg-libsl.dll", CallingConvention = CallingConvention.Cdecl)] private static extern bool LibslDecode(ref MarshalledImage image); /// <summary> /// Encode a <seealso cref="ManagedImage"/> object into a byte array /// </summary> /// <param name="image">The <seealso cref="ManagedImage"/> object to encode</param> /// <param name="lossless">true to enable lossless conversion, only useful for small images ie: sculptmaps</param> /// <returns>A byte array containing the encoded Image object</returns> public static byte[] Encode(ManagedImage image, bool lossless) { if ( (image.Channels & ManagedImage.ImageChannels.Color) == 0 || ((image.Channels & ManagedImage.ImageChannels.Bump) != 0 && (image.Channels & ManagedImage.ImageChannels.Alpha) == 0)) throw new ArgumentException("JPEG2000 encoding is not supported for this channel combination"); MarshalledImage marshalled = new MarshalledImage(); // allocate and copy to input buffer marshalled.width = image.Width; marshalled.height = image.Height; marshalled.components = 3; if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) marshalled.components++; if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) marshalled.components++; if (!LibslAllocDecoded(ref marshalled)) throw new Exception("LibslAllocDecoded failed"); int n = image.Width * image.Height; if ((image.Channels & ManagedImage.ImageChannels.Color) != 0) { Marshal.Copy(image.Red, 0, marshalled.decoded, n); Marshal.Copy(image.Green, 0, (IntPtr)(marshalled.decoded.ToInt64() + n), n); Marshal.Copy(image.Blue, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 2), n); } if ((image.Channels & ManagedImage.ImageChannels.Alpha) != 0) Marshal.Copy(image.Alpha, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 3), n); if ((image.Channels & ManagedImage.ImageChannels.Bump) != 0) Marshal.Copy(image.Bump, 0, (IntPtr)(marshalled.decoded.ToInt64() + n * 4), n); // codec will allocate output buffer if (!LibslEncode(ref marshalled, lossless)) throw new Exception("LibslEncode failed"); // copy output buffer byte[] encoded = new byte[marshalled.length]; Marshal.Copy(marshalled.encoded, encoded, 0, marshalled.length); // free buffers LibslFree(ref marshalled); return encoded; } /// <summary> /// Encode a <seealso cref="ManagedImage"/> object into a byte array /// </summary> /// <param name="image">The <seealso cref="ManagedImage"/> object to encode</param> /// <returns>a byte array of the encoded image</returns> public static byte[] Encode(ManagedImage image) { return Encode(image, false); } /// <summary> /// Decode JPEG2000 data to an <seealso cref="System.Drawing.Image"/> and /// <seealso cref="ManagedImage"/> /// </summary> /// <param name="encoded">JPEG2000 encoded data</param> /// <param name="managedImage">ManagedImage object to decode to</param> /// <param name="image">Image object to decode to</param> /// <returns>True if the decode succeeds, otherwise false</returns> public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage, out Image image) { managedImage = null; image = null; if (DecodeToImage(encoded, out managedImage)) { try { image = LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA())); return true; } catch (Exception ex) { Logger.Log("Failed to export and load TGA data from decoded image", Helpers.LogLevel.Error, ex); return false; } } else { return false; } } /// <summary> /// /// </summary> /// <param name="encoded"></param> /// <param name="managedImage"></param> /// <returns></returns> public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage) { MarshalledImage marshalled = new MarshalledImage(); // Allocate and copy to input buffer marshalled.length = encoded.Length; LibslAllocEncoded(ref marshalled); Marshal.Copy(encoded, 0, marshalled.encoded, encoded.Length); // Codec will allocate output buffer LibslDecode(ref marshalled); int n = marshalled.width * marshalled.height; switch (marshalled.components) { case 1: // Grayscale managedImage = new ManagedImage(marshalled.width, marshalled.height, ManagedImage.ImageChannels.Color); Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n); Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n); break; case 2: // Grayscale + alpha managedImage = new ManagedImage(marshalled.width, marshalled.height, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); Buffer.BlockCopy(managedImage.Red, 0, managedImage.Green, 0, n); Buffer.BlockCopy(managedImage.Red, 0, managedImage.Blue, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Alpha, 0, n); break; case 3: // RGB managedImage = new ManagedImage(marshalled.width, marshalled.height, ManagedImage.ImageChannels.Color); Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n); break; case 4: // RGBA managedImage = new ManagedImage(marshalled.width, marshalled.height, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Alpha, 0, n); break; case 5: // RGBBA managedImage = new ManagedImage(marshalled.width, marshalled.height, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump); Marshal.Copy(marshalled.decoded, managedImage.Red, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)n), managedImage.Green, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 2)), managedImage.Blue, 0, n); // Bump comes before alpha in 5 channel encode Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 3)), managedImage.Bump, 0, n); Marshal.Copy((IntPtr)(marshalled.decoded.ToInt64() + (long)(n * 4)), managedImage.Alpha, 0, n); break; default: Logger.Log("Decoded image with unhandled number of components: " + marshalled.components, Helpers.LogLevel.Error); LibslFree(ref marshalled); managedImage = null; return false; } LibslFree(ref marshalled); return true; } /// <summary> /// Encode a <seealso cref="System.Drawing.Bitmap"/> object into a byte array /// </summary> /// <param name="bitmap">The source <seealso cref="System.Drawing.Bitmap"/> object to encode</param> /// <param name="lossless">true to enable lossless decoding</param> /// <returns>A byte array containing the source Bitmap object</returns> public unsafe static byte[] EncodeFromImage(Bitmap bitmap, bool lossless) { BitmapData bd; ManagedImage decoded; int bitmapWidth = bitmap.Width; int bitmapHeight = bitmap.Height; int pixelCount = bitmapWidth * bitmapHeight; int i; if ((bitmap.PixelFormat & PixelFormat.Alpha) != 0 || (bitmap.PixelFormat & PixelFormat.PAlpha) != 0) { // Four layers, RGBA decoded = new ManagedImage(bitmapWidth, bitmapHeight, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte* pixel = (byte*)bd.Scan0; for (i = 0; i < pixelCount; i++) { // GDI+ gives us BGRA and we need to turn that in to RGBA decoded.Blue[i] = *(pixel++); decoded.Green[i] = *(pixel++); decoded.Red[i] = *(pixel++); decoded.Alpha[i] = *(pixel++); } } else if (bitmap.PixelFormat == PixelFormat.Format16bppGrayScale) { // One layer decoded = new ManagedImage(bitmapWidth, bitmapHeight, ManagedImage.ImageChannels.Color); bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight), ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale); byte* pixel = (byte*)bd.Scan0; for (i = 0; i < pixelCount; i++) { // Normalize 16-bit data down to 8-bit ushort origVal = (byte)(*(pixel) + (*(pixel + 1) << 8)); byte val = (byte)(((double)origVal / (double)UInt32.MaxValue) * (double)Byte.MaxValue); decoded.Red[i] = val; decoded.Green[i] = val; decoded.Blue[i] = val; pixel += 2; } } else { // Three layers, RGB decoded = new ManagedImage(bitmapWidth, bitmapHeight, ManagedImage.ImageChannels.Color); bd = bitmap.LockBits(new Rectangle(0, 0, bitmapWidth, bitmapHeight), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); byte* pixel = (byte*)bd.Scan0; for (i = 0; i < pixelCount; i++) { decoded.Blue[i] = *(pixel++); decoded.Green[i] = *(pixel++); decoded.Red[i] = *(pixel++); } } bitmap.UnlockBits(bd); byte[] encoded = Encode(decoded, lossless); return encoded; } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net.Cache; using System.Net.Test.Common; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Net.Tests { public class WebClientTest { [Fact] public static void DefaultCtor_PropertiesReturnExpectedValues() { var wc = new WebClient(); Assert.Empty(wc.BaseAddress); Assert.Null(wc.CachePolicy); Assert.Null(wc.Credentials); Assert.Equal(Encoding.Default, wc.Encoding); Assert.Empty(wc.Headers); Assert.False(wc.IsBusy); Assert.NotNull(wc.Proxy); Assert.Empty(wc.QueryString); Assert.False(wc.UseDefaultCredentials); } [Fact] public static void Properties_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentException>("value", () => { wc.BaseAddress = "http::/invalid url"; }); Assert.Throws<ArgumentNullException>("Encoding", () => { wc.Encoding = null; }); } [Fact] public static void DownloadData_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((Uri)null); }); } [Fact] public static void DownloadFile_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((string)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFile((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileAsync((Uri)null, "", null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((string)null, ""); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadFileTaskAsync((Uri)null, ""); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFile(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.DownloadFileTaskAsync(new Uri("http://localhost"), null); }); } [Fact] public static void DownloadString_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((Uri)null); }); } [Fact] public static void UploadData_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadData((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadDataTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadData(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadDataTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void UploadFile_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFile((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadFileTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFile(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("fileName", () => { wc.UploadFileTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void UploadString_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadString((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadStringTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadString(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadStringTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void UploadValues_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValues((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesAsync((Uri)null, null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((string)null, null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.UploadValuesTaskAsync((Uri)null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValues(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesAsync(new Uri("http://localhost"), null, null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync("http://localhost", null, null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null); }); Assert.Throws<ArgumentNullException>("data", () => { wc.UploadValuesTaskAsync(new Uri("http://localhost"), null, null); }); } [Fact] public static void OpenWrite_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((Uri)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenWrite((Uri)null, null); }); } [Fact] public static void OpenRead_InvalidArguments_ThrowExceptions() { var wc = new WebClient(); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenRead((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { wc.OpenRead((Uri)null); }); } [Fact] public static void BaseAddress_Roundtrips() { var wc = new WebClient(); wc.BaseAddress = "http://localhost/"; Assert.Equal("http://localhost/", wc.BaseAddress); wc.BaseAddress = null; Assert.Equal(string.Empty, wc.BaseAddress); } [Fact] public static void CachePolicy_Roundtrips() { var wc = new WebClient(); var c = new RequestCachePolicy(RequestCacheLevel.BypassCache); wc.CachePolicy = c; Assert.Same(c, wc.CachePolicy); } [Fact] public static void Credentials_Roundtrips() { var wc = new WebClient(); var c = new DummyCredentials(); wc.Credentials = c; Assert.Same(c, wc.Credentials); wc.Credentials = null; Assert.Null(wc.Credentials); } private sealed class DummyCredentials : ICredentials { public NetworkCredential GetCredential(Uri uri, string authType) => null; } [Fact] public static void Proxy_Roundtrips() { var wc = new WebClient(); Assert.Same(WebRequest.DefaultWebProxy, wc.Proxy); var p = new DummyProxy(); wc.Proxy = p; Assert.Same(p, wc.Proxy); wc.Proxy = null; Assert.Null(wc.Proxy); } private sealed class DummyProxy : IWebProxy { public ICredentials Credentials { get; set; } public Uri GetProxy(Uri destination) => null; public bool IsBypassed(Uri host) => false; } [Fact] public static void Encoding_Roundtrips() { var wc = new WebClient(); Encoding e = Encoding.UTF8; wc.Encoding = e; Assert.Same(e, wc.Encoding); } [Fact] public static void Headers_Roundtrips() { var wc = new WebClient(); Assert.NotNull(wc.Headers); Assert.Empty(wc.Headers); wc.Headers = null; Assert.NotNull(wc.Headers); Assert.Empty(wc.Headers); var whc = new WebHeaderCollection(); wc.Headers = whc; Assert.Same(whc, wc.Headers); } [Fact] public static void QueryString_Roundtrips() { var wc = new WebClient(); Assert.NotNull(wc.QueryString); Assert.Empty(wc.QueryString); wc.QueryString = null; Assert.NotNull(wc.QueryString); Assert.Empty(wc.QueryString); var nvc = new NameValueCollection(); wc.QueryString = nvc; Assert.Same(nvc, wc.QueryString); } [Fact] public static void UseDefaultCredentials_Roundtrips() { var wc = new WebClient(); for (int i = 0; i < 2; i++) { wc.UseDefaultCredentials = true; Assert.True(wc.UseDefaultCredentials); wc.UseDefaultCredentials = false; Assert.False(wc.UseDefaultCredentials); } } [Fact] public static async Task ResponseHeaders_ContainsHeadersAfterOperation() { var wc = new DerivedWebClient(); // verify we can use a derived type as well Assert.Null(wc.ResponseHeaders); await LoopbackServer.CreateServerAsync(async (server, url) => { Task<string> download = wc.DownloadStringTaskAsync(url.ToString()); Assert.Null(wc.ResponseHeaders); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: 0\r\n" + "ArbitraryHeader: ArbitraryValue\r\n" + "\r\n"); await download; }); Assert.NotNull(wc.ResponseHeaders); Assert.Equal("ArbitraryValue", wc.ResponseHeaders["ArbitraryHeader"]); } [Fact] public static async Task RequestHeaders_SpecialHeaders_RequestSucceeds() { var wc = new WebClient(); wc.Headers["Accept"] = "text/html"; wc.Headers["Connection"] = "close"; wc.Headers["ContentType"] = "text/html; charset=utf-8"; wc.Headers["Expect"] = "100-continue"; wc.Headers["Referer"] = "http://localhost"; wc.Headers["User-Agent"] = ".NET"; wc.Headers["Host"] = "http://localhost"; await LoopbackServer.CreateServerAsync(async (server, url) => { Task<string> download = wc.DownloadStringTaskAsync(url.ToString()); Assert.Null(wc.ResponseHeaders); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: 0\r\n" + "\r\n"); await download; }); } [Fact] public static async Task ConcurrentOperations_Throw() { await LoopbackServer.CreateServerAsync((server, url) => { var wc = new WebClient(); Task ignored = wc.DownloadDataTaskAsync(url); // won't complete Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); }); Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); }); Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); }); return Task.CompletedTask; }); } private sealed class DerivedWebClient : WebClient { } } public abstract class WebClientTestBase { public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers; const string ExpectedText = "To be, or not to be, that is the question:" + "Whether 'tis Nobler in the mind to suffer" + "The Slings and Arrows of outrageous Fortune," + "Or to take Arms against a Sea of troubles," + "And by opposing end them:"; protected abstract bool IsAsync { get; } protected abstract Task<byte[]> DownloadDataAsync(WebClient wc, string address); protected abstract Task DownloadFileAsync(WebClient wc, string address, string fileName); protected abstract Task<string> DownloadStringAsync(WebClient wc, string address); protected abstract Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data); protected abstract Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName); protected abstract Task<string> UploadStringAsync(WebClient wc, string address, string data); protected abstract Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data); protected abstract Task<Stream> OpenReadAsync(WebClient wc, string address); protected abstract Task<Stream> OpenWriteAsync(WebClient wc, string address); [Theory] [InlineData(null)] [InlineData("text/html; charset=utf-8")] [InlineData("text/html; charset=us-ascii")] public async Task DownloadString_Success(string contentType) { await LoopbackServer.CreateServerAsync(async (server, url) => { var wc = new WebClient(); if (contentType != null) { wc.Headers[HttpRequestHeader.ContentType] = contentType; } Task<string> download = DownloadStringAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); Assert.Equal(ExpectedText, await download); }); } [Fact] public async Task DownloadData_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { var wc = new WebClient(); var downloadProgressInvoked = new TaskCompletionSource<bool>(); wc.DownloadProgressChanged += (s, e) => downloadProgressInvoked.TrySetResult(true); Task<byte[]> download = DownloadDataAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); Assert.Equal(ExpectedText, Encoding.ASCII.GetString(await download)); Assert.True(!IsAsync || await downloadProgressInvoked.Task, "Expected download progress callback to be invoked"); }); } [Theory] public async Task DownloadData_LargeData_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { string largeText = GetRandomText(1024 * 1024); var wc = new WebClient(); Task<byte[]> download = DownloadDataAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {largeText.Length}\r\n" + "\r\n" + $"{largeText}"); Assert.Equal(largeText, Encoding.ASCII.GetString(await download)); }); } [Fact] public async Task DownloadFile_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { string tempPath = Path.GetTempFileName(); try { var wc = new WebClient(); Task download = DownloadFileAsync(wc, url.ToString(), tempPath); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); await download; Assert.Equal(ExpectedText, File.ReadAllText(tempPath)); } finally { File.Delete(tempPath); } }); } [Fact] public async Task OpenRead_Success() { await LoopbackServer.CreateServerAsync(async (server, url) => { var wc = new WebClient(); Task<Stream> download = OpenReadAsync(wc, url.ToString()); await LoopbackServer.ReadRequestAndSendResponseAsync(server, "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Content-Length: {ExpectedText.Length}\r\n" + "\r\n" + $"{ExpectedText}"); using (var reader = new StreamReader(await download)) { Assert.Equal(ExpectedText, await reader.ReadToEndAsync()); } }); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task OpenWrite_Success(Uri echoServer) { var wc = new WebClient(); using (Stream s = await OpenWriteAsync(wc, echoServer.ToString())) { byte[] data = Encoding.UTF8.GetBytes(ExpectedText); await s.WriteAsync(data, 0, data.Length); } } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadData_Success(Uri echoServer) { var wc = new WebClient(); var uploadProgressInvoked = new TaskCompletionSource<bool>(); wc.UploadProgressChanged += (s, e) => uploadProgressInvoked.TrySetResult(true); // to enable chunking of the upload byte[] result = await UploadDataAsync(wc, echoServer.ToString(), Encoding.UTF8.GetBytes(ExpectedText)); Assert.Contains(ExpectedText, Encoding.UTF8.GetString(result)); Assert.True(!IsAsync || await uploadProgressInvoked.Task, "Expected upload progress callback to be invoked"); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadData_LargeData_Success(Uri echoServer) { var wc = new WebClient(); string largeText = GetRandomText(512 * 1024); byte[] result = await UploadDataAsync(wc, echoServer.ToString(), Encoding.UTF8.GetBytes(largeText)); Assert.Contains(largeText, Encoding.UTF8.GetString(result)); } private static string GetRandomText(int length) { var rand = new Random(); return new string(Enumerable.Range(0, 512 * 1024).Select(_ => (char)('a' + rand.Next(0, 26))).ToArray()); } [OuterLoop("Networking test talking to remote server: issue #11345")] [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201 [MemberData(nameof(EchoServers))] public async Task UploadFile_Success(Uri echoServer) { string tempPath = Path.GetTempFileName(); try { File.WriteAllBytes(tempPath, Encoding.UTF8.GetBytes(ExpectedText)); var wc = new WebClient(); byte[] result = await UploadFileAsync(wc, echoServer.ToString(), tempPath); Assert.Contains(ExpectedText, Encoding.UTF8.GetString(result)); } finally { File.Delete(tempPath); } } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadString_Success(Uri echoServer) { var wc = new WebClient(); string result = await UploadStringAsync(wc, echoServer.ToString(), ExpectedText); Assert.Contains(ExpectedText, result); } [OuterLoop("Networking test talking to remote server: issue #11345")] [Theory] [MemberData(nameof(EchoServers))] public async Task UploadValues_Success(Uri echoServer) { var wc = new WebClient(); byte[] result = await UploadValuesAsync(wc, echoServer.ToString(), new NameValueCollection() { { "Data", ExpectedText } }); Assert.Contains(WebUtility.UrlEncode(ExpectedText), Encoding.UTF8.GetString(result)); } } public class SyncWebClientTest : WebClientTestBase { protected override bool IsAsync => false; protected override Task<byte[]> DownloadDataAsync(WebClient wc, string address) => Task.Run(() => wc.DownloadData(address)); protected override Task DownloadFileAsync(WebClient wc, string address, string fileName) => Task.Run(() => wc.DownloadFile(address, fileName)); protected override Task<string> DownloadStringAsync(WebClient wc, string address) => Task.Run(() => wc.DownloadString(address)); protected override Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data) => Task.Run(() => wc.UploadData(address, data)); protected override Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName) => Task.Run(() => wc.UploadFile(address, fileName)); protected override Task<string> UploadStringAsync(WebClient wc, string address, string data) => Task.Run(() => wc.UploadString(address, data)); protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => Task.Run(() => wc.UploadValues(address, data)); protected override Task<Stream> OpenReadAsync(WebClient wc, string address) => Task.Run(() => wc.OpenRead(address)); protected override Task<Stream> OpenWriteAsync(WebClient wc, string address) => Task.Run(() => wc.OpenWrite(address)); } // NOTE: Today the XxTaskAsync APIs are implemented as wrappers for the XxAsync APIs. // If that changes, we should add an EapWebClientTest here that targets those directly. // In the meantime, though, there's no benefit to the extra testing it would provide. public class TaskWebClientTest : WebClientTestBase { protected override bool IsAsync => true; protected override Task<byte[]> DownloadDataAsync(WebClient wc, string address) => wc.DownloadDataTaskAsync(address); protected override Task DownloadFileAsync(WebClient wc, string address, string fileName) => wc.DownloadFileTaskAsync(address, fileName); protected override Task<string> DownloadStringAsync(WebClient wc, string address) => wc.DownloadStringTaskAsync(address); protected override Task<byte[]> UploadDataAsync(WebClient wc, string address, byte[] data) => wc.UploadDataTaskAsync(address, data); protected override Task<byte[]> UploadFileAsync(WebClient wc, string address, string fileName) => wc.UploadFileTaskAsync(address, fileName); protected override Task<string> UploadStringAsync(WebClient wc, string address, string data) => wc.UploadStringTaskAsync(address, data); protected override Task<byte[]> UploadValuesAsync(WebClient wc, string address, NameValueCollection data) => wc.UploadValuesTaskAsync(address, data); protected override Task<Stream> OpenReadAsync(WebClient wc, string address) => wc.OpenReadTaskAsync(address); protected override Task<Stream> OpenWriteAsync(WebClient wc, string address) => wc.OpenWriteTaskAsync(address); } }
#region File Description //----------------------------------------------------------------------------- // GameplayScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Xml.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; #endregion namespace HoneycombRush { /// <summary> /// This is the class the handle the entire game /// </summary> public class GameplayScreen : GameScreen { #region Fields/Properties SpriteFont font16px; SpriteFont font36px; Texture2D arrowTexture; Texture2D background; Texture2D controlstickBoundary; Texture2D controlstick; Texture2D beehiveTexture; Texture2D smokeButton; ScoreBar smokeButtonScorebar; Vector2 controlstickStartupPosition; Vector2 controlstickBoundaryPosition; Vector2 smokeButtonPosition; Vector2 lastTouchPosition; bool isSmokebuttonClicked; bool drawArrow; bool drawArrowInterval; bool isInMotion; bool isAtStartupCountDown; bool isLevelEnd; bool levelEnded; bool isUserWon; bool userTapToExit; Dictionary<string, Animation> animations; int amountOfSoldierBee; int amountOfWorkerBee; int arrowCounter; List<Beehive> beehives = new List<Beehive>(); List<Bee> bees = new List<Bee>(); const string SmokeText = "Smoke"; TimeSpan gameElapsed; TimeSpan startScreenTime; BeeKeeper beeKeeper; HoneyJar jar; Vat vat; DifficultyMode gameDifficultyLevel; public bool IsStarted { get { return !isAtStartupCountDown && !levelEnded; } } private bool IsInMotion { get { return isInMotion; } set { isInMotion = value; if (beeKeeper != null) { beeKeeper.IsInMotion = isInMotion; } } } private int Score { get { int highscoreFactor = ConfigurationManager.ModesConfiguration[gameDifficultyLevel].HighScoreFactor; return highscoreFactor * (int)gameElapsed.TotalMilliseconds; } } #endregion #region Initializations /// <summary> /// Creates a new gameplay screen. /// </summary> /// <param name="gameDifficultyMode">The desired game difficulty.</param> public GameplayScreen(DifficultyMode gameDifficultyMode) { TransitionOnTime = TimeSpan.FromSeconds(0.0); TransitionOffTime = TimeSpan.FromSeconds(0.0); startScreenTime = TimeSpan.FromSeconds(3); //Loads configuration ConfigurationManager.LoadConfiguration(XDocument.Load("Content/Configuration/Configuration.xml")); ConfigurationManager.DifficultyMode = gameDifficultyMode; gameDifficultyLevel = gameDifficultyMode; gameElapsed = ConfigurationManager.ModesConfiguration[gameDifficultyLevel].GameElapsed; amountOfSoldierBee = 4; amountOfWorkerBee = 16; controlstickBoundaryPosition = new Vector2(34, 347); smokeButtonPosition = new Vector2(664, 346); controlstickStartupPosition = new Vector2(55, 369); IsInMotion = false; isAtStartupCountDown = true; isLevelEnd = false; EnabledGestures = GestureType.Tap; } #endregion #region Loading and Unloading /// <summary> /// Loads content and assets. /// </summary> public void LoadAssets() { // Loads the animation dictionary from an xml file animations = new Dictionary<string, Animation>(); LoadAnimationFromXML(); // Loads all textures that are required LoadTextures(); // Create all game components CreateGameComponents(); AudioManager.PlayMusic("InGameSong_Loop"); } /// <summary> /// Unloads game components which are no longer needed once the game ends. /// </summary> public override void UnloadContent() { var componentList = ScreenManager.Game.Components; for (int index = 0; index < componentList.Count; index++) { if (componentList[index] != this && componentList[index] != ScreenManager && !(componentList[index] is AudioManager)) { componentList.RemoveAt(index); index--; } } base.UnloadContent(); } #endregion #region Update /// <summary> /// Handle the player's input. /// </summary> /// <param name="input"></param> public override void HandleInput(GameTime gameTime, InputState input) { if (IsActive) { if (input == null) { throw new ArgumentNullException("input"); } VirtualThumbsticks.Update(input); if (input.IsPauseGame(null)) { PauseCurrentGame(); } } if (input.TouchState.Count > 0) { foreach (TouchLocation touch in input.TouchState) { lastTouchPosition = touch.Position; } } isSmokebuttonClicked = false; PlayerIndex player; // If there was any touch if (VirtualThumbsticks.RightThumbstickCenter.HasValue) { // Button Bounds Rectangle buttonRectangle = new Rectangle((int)smokeButtonPosition.X, (int)smokeButtonPosition.Y, smokeButton.Width / 2, smokeButton.Height); // Touch Bounds Rectangle touchRectangle = new Rectangle((int)VirtualThumbsticks.RightThumbstickCenter.Value.X, (int)VirtualThumbsticks.RightThumbstickCenter.Value.Y, 1, 1); // If the touch is in the button if (buttonRectangle.Contains(touchRectangle) && !beeKeeper.IsCollectingHoney && !beeKeeper.IsStung) { isSmokebuttonClicked = true; } } if (input.IsKeyDown(Keys.Space, ControllingPlayer, out player) && !beeKeeper.IsCollectingHoney && !beeKeeper.IsStung) { isSmokebuttonClicked = true; } if (input.Gestures.Count > 0) { if (isLevelEnd) { if (input.Gestures[0].GestureType == GestureType.Tap) { userTapToExit = true; } } } } /// <summary> /// Perform the game's update logic. /// </summary> /// <param name="gameTime">Game time information.</param> /// <param name="otherScreenHasFocus">Whether or not another screen currently has the focus.</param> /// <param name="coveredByOtherScreen">Whether or not this screen is covered by another.</param> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { // When the game starts the first thing the user sees is the count down before the game actually begins if (isAtStartupCountDown) { startScreenTime -= gameTime.ElapsedGameTime; } // Check for and handle a game over if (CheckIfCurrentGameFinished()) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); return; } if (!(IsActive && IsStarted)) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); return; } gameElapsed -= gameTime.ElapsedGameTime; HandleThumbStick(); HandleSmoke(); beeKeeper.SetDirection(VirtualThumbsticks.LeftThumbstick); HandleCollision(gameTime); HandleVatHoneyArrow(); beeKeeper.DrawOrder = 1; int beeKeeperY = (int)(beeKeeper.Position.Y + beeKeeper.Bounds.Height - 2); // We want to determine the draw order of the beekeeper, // if the beekeeper is under half the height of the beehive // it should be drawn over the beehive. foreach (Beehive beehive in beehives) { if (beeKeeperY > beehive.Bounds.Y) { if (beehive.Bounds.Y + beehive.Bounds.Height / 2 < beeKeeperY) { beeKeeper.DrawOrder = Math.Max(beeKeeper.DrawOrder, beehive.Bounds.Y + 1); } } } if (gameElapsed.Minutes == 0 && gameElapsed.Seconds == 10) { AudioManager.PlaySound("10SecondCountDown"); } if (gameElapsed.Minutes == 0 && gameElapsed.Seconds == 30) { AudioManager.PlaySound("30SecondWarning"); } // Update the time remaining displayed on the vat vat.DrawTimeLeft(gameElapsed); base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); } #endregion #region Render /// <summary> /// Draw the game screen. /// </summary> /// <param name="gameTime">Game time information.</param> public override void Draw(GameTime gameTime) { ScreenManager.SpriteBatch.Begin(); // Draw the background ScreenManager.SpriteBatch.Draw(background, new Rectangle(0, 0, ScreenManager.Game.GraphicsDevice.Viewport.Width, ScreenManager.Game.GraphicsDevice.Viewport.Height), null, Color.White, 0f, Vector2.Zero, SpriteEffects.None, 1); // Draw count down screen if (isAtStartupCountDown) { DrawStartupString(); } if (IsActive && IsStarted) { DrawSmokeButton(); ScreenManager.SpriteBatch.Draw(controlstickBoundary, controlstickBoundaryPosition, Color.White); ScreenManager.SpriteBatch.Draw(controlstick, controlstickStartupPosition, Color.White); ScreenManager.SpriteBatch.DrawString(font16px, SmokeText, new Vector2(684, 456), Color.White); DrawVatHoneyArrow(); } DrawLevelEndIfNecessary(); ScreenManager.SpriteBatch.End(); base.Draw(gameTime); } #endregion #region Private Methods /// <summary> /// If the level is over, draws text describing the level's outocme. /// </summary> private void DrawLevelEndIfNecessary() { if (isLevelEnd) { string stringToDisplay = string.Empty; if (isUserWon) { if (CheckIsInHighScore()) { stringToDisplay = "It's a new\nHigh-Score!"; } else { stringToDisplay = "You Win!"; } } else { stringToDisplay = "Time Is Up!"; } var stringVector = font36px.MeasureString(stringToDisplay); ScreenManager.SpriteBatch.DrawString(font36px, stringToDisplay, new Vector2(ScreenManager.GraphicsDevice.Viewport.Width / 2 - stringVector.X / 2, ScreenManager.GraphicsDevice.Viewport.Height / 2 - stringVector.Y / 2), Color.White); } } /// <summary> /// Checks if the user's score is a high score. /// </summary> /// <returns>True if the user has a high score, false otherwise.</returns> private bool CheckIsInHighScore() { // User can be at high score only if he is at Hard level. return gameDifficultyLevel == DifficultyMode.Hard && HighScoreScreen.IsInHighscores(Score); } /// <summary> /// Advances to the next screen based on the current difficulty and whether or not the user has won. /// </summary> /// <param name="isWon">Whether or not the user has won the current level.</param> private void MoveToNextScreen(bool isWon) { ScreenManager.AddScreen(new BackgroundScreen("pauseBackground"), null); if (isWon) { switch (gameDifficultyLevel) { case DifficultyMode.Easy: case DifficultyMode.Medium: ScreenManager.AddScreen( new LevelOverScreen("You Finished Level: " + gameDifficultyLevel.ToString(), ++gameDifficultyLevel), null); break; case DifficultyMode.Hard: ScreenManager.AddScreen(new LevelOverScreen("You Win", null), null); break; } } else { ScreenManager.AddScreen(new LevelOverScreen("You Lose", null), null); } AudioManager.StopMusic(); AudioManager.StopSound("BeeBuzzing_Loop"); } /// <summary> /// Pause the game. /// </summary> private void PauseCurrentGame() { // Pause sounds AudioManager.PauseResumeSounds(false); // Set pause screen ScreenManager.AddScreen(new BackgroundScreen("pauseBackground"), null); ScreenManager.AddScreen(new PauseScreen(), null); } /// <summary> /// Loads animation settings from an xml file. /// </summary> private void LoadAnimationFromXML() { XDocument doc = XDocument.Load("Content/Textures/AnimationsDefinition.xml"); XName name = XName.Get("Definition"); var definitions = doc.Document.Descendants(name); // Loop over all definitions in the XML foreach (var animationDefinition in definitions) { // Get the name of the animation string animationAlias = animationDefinition.Attribute("Alias").Value; Texture2D texture = ScreenManager.Game.Content.Load<Texture2D>(animationDefinition.Attribute("SheetName").Value); // Get the frame size (width & height) Point frameSize = new Point(); frameSize.X = int.Parse(animationDefinition.Attribute("FrameWidth").Value); frameSize.Y = int.Parse(animationDefinition.Attribute("FrameHeight").Value); // Get the frames sheet dimensions Point sheetSize = new Point(); sheetSize.X = int.Parse(animationDefinition.Attribute("SheetColumns").Value); sheetSize.Y = int.Parse(animationDefinition.Attribute("SheetRows").Value); Animation animation = new Animation(texture, frameSize, sheetSize); // Checks for sub-animation definition if (animationDefinition.Element("SubDefinition") != null) { int startFrame = int.Parse( animationDefinition.Element("SubDefinition").Attribute("StartFrame").Value); int endFrame = int.Parse (animationDefinition.Element("SubDefinition").Attribute("EndFrame").Value); animation.SetSubAnimation(startFrame, endFrame); } if (animationDefinition.Attribute("Speed") != null) { animation.SetFrameInterval(TimeSpan.FromMilliseconds( double.Parse(animationDefinition.Attribute("Speed").Value))); } // If the definition has an offset defined - it should be // rendered relative to some element/animation if (null != animationDefinition.Attribute("OffsetX") && null != animationDefinition.Attribute("OffsetY")) { animation.Offset = new Vector2(int.Parse(animationDefinition.Attribute("OffsetX").Value), int.Parse(animationDefinition.Attribute("OffsetY").Value)); } animations.Add(animationAlias, animation); } } /// <summary> /// Create all the game components. /// </summary> private void CreateGameComponents() { ScoreBar scoreBar = new ScoreBar(ScreenManager.Game, 0, 100, new Vector2(8, 65), 10, 70, Color.Blue, ScoreBar.ScoreBarOrientation.Horizontal, 0, this, true); ScreenManager.Game.Components.Add(scoreBar); // Create the honey jar jar = new HoneyJar(ScreenManager.Game, this, new Vector2(20, 8), scoreBar); ScreenManager.Game.Components.Add(jar); // Create all the beehives and the bees CreateBeehives(); // Create the smoke gun's score bar int totalSmokeAmount = ConfigurationManager.ModesConfiguration[gameDifficultyLevel].TotalSmokeAmount; Vector2 smokeButtonPosition = new Vector2(664, 346) + new Vector2(22, smokeButton.Height - 8); smokeButtonScorebar = new ScoreBar(ScreenManager.Game, 0, totalSmokeAmount, smokeButtonPosition, 12, 70, Color.White, ScoreBar.ScoreBarOrientation.Horizontal, totalSmokeAmount, this, false); ScreenManager.Game.Components.Add(smokeButtonScorebar); // Creates the BeeKeeper beeKeeper = new BeeKeeper(ScreenManager.Game, this); beeKeeper.AnimationDefinitions = animations; beeKeeper.ThumbStickArea = new Rectangle((int)controlstickBoundaryPosition.X, (int)controlstickBoundaryPosition.Y, controlstickBoundary.Width, controlstickBoundary.Height); ScreenManager.Game.Components.Add(beeKeeper); // Create the vat's score bar scoreBar = new ScoreBar(ScreenManager.Game, 0, 300, new Vector2(306, 440), 10, 190, Color.White, ScoreBar.ScoreBarOrientation.Horizontal, 0, this, true); ScreenManager.Game.Components.Add(scoreBar); // Create the vat vat = new Vat(ScreenManager.Game, this, ScreenManager.Game.Content.Load<Texture2D>("Textures/vat"), new Vector2(294, 355), scoreBar); ScreenManager.Game.Components.Add(vat); scoreBar.DrawOrder = vat.DrawOrder + 1; } /// <summary> /// Creates all the beehives and bees. /// </summary> private void CreateBeehives() { // Init position parameters Vector2 scorebarPosition = new Vector2(18, beehiveTexture.Height - 15); Vector2[] beehivePositions = new Vector2[5] { new Vector2(83, 8), new Vector2(347, 8), new Vector2(661, 8), new Vector2(83, 201), new Vector2(661, 201) }; // Create the beehives for (int beehiveCounter = 0; beehiveCounter < beehivePositions.Length; beehiveCounter++) { ScoreBar scoreBar = new ScoreBar(ScreenManager.Game, 0, 100, beehivePositions[beehiveCounter] + scorebarPosition, 10, 68, Color.Green, ScoreBar.ScoreBarOrientation.Horizontal, 100, this, false); ScreenManager.Game.Components.Add(scoreBar); Beehive beehive = new Beehive(ScreenManager.Game, this, beehiveTexture, scoreBar, beehivePositions[beehiveCounter]); beehive.AnimationDefinitions = animations; ScreenManager.Game.Components.Add(beehive); beehives.Add(beehive); scoreBar.DrawOrder = beehive.DrawOrder; } for (int beehiveIndex = 0; beehiveIndex < beehivePositions.Length; beehiveIndex++) { // Create the Soldier bees for (int SoldierBeeCounter = 0; SoldierBeeCounter < amountOfSoldierBee; SoldierBeeCounter++) { SoldierBee bee = new SoldierBee(ScreenManager.Game, this, beehives[beehiveIndex]); bee.AnimationDefinitions = animations; ScreenManager.Game.Components.Add(bee); bees.Add(bee); } // Creates the worker bees for (int workerBeeCounter = 0; workerBeeCounter < amountOfWorkerBee; workerBeeCounter++) { WorkerBee bee = new WorkerBee(ScreenManager.Game, this, beehives[beehiveIndex]); bee.AnimationDefinitions = animations; ScreenManager.Game.Components.Add(bee); bees.Add(bee); } } } /// <summary> /// Loads all the necessary textures. /// </summary> private void LoadTextures() { beehiveTexture = ScreenManager.Game.Content.Load<Texture2D>("Textures/beehive"); background = ScreenManager.Game.Content.Load<Texture2D>("Textures/Backgrounds/GamePlayBackground"); controlstickBoundary = ScreenManager.Game.Content.Load<Texture2D>("Textures/controlstickBoundary"); controlstick = ScreenManager.Game.Content.Load<Texture2D>("Textures/controlstick"); smokeButton = ScreenManager.Game.Content.Load<Texture2D>("Textures/smokeBtn"); font16px = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/GameScreenFont16px"); arrowTexture = ScreenManager.Game.Content.Load<Texture2D>("Textures/arrow"); font16px = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/GameScreenFont16px"); font36px = ScreenManager.Game.Content.Load<SpriteFont>("Fonts/GameScreenFont36px"); } /// <summary> /// Handle thumbstick logic /// </summary> private void HandleThumbStick() { // Calculate the rectangle of the outer circle of the thumbstick Rectangle outerControlstick = new Rectangle(0, (int)controlstickBoundaryPosition.Y - 35, controlstickBoundary.Width + 60, controlstickBoundary.Height + 60); // Reset the thumbstick position when it is idle if (VirtualThumbsticks.LeftThumbstick == Vector2.Zero) { IsInMotion = false; beeKeeper.SetMovement(Vector2.Zero); controlstickStartupPosition = new Vector2(55, 369); } else { // If not in motion and the touch point is not in the control bounds - there is no movement Rectangle touchRectangle = new Rectangle((int)lastTouchPosition.X, (int)lastTouchPosition.Y, 1, 1); if (!outerControlstick.Contains(touchRectangle)) { controlstickStartupPosition = new Vector2(55, 369); IsInMotion = false; return; } // Move the beekeeper SetMotion(); // Moves the thumbstick's inner circle float radious = controlstick.Width / 2 + 35; controlstickStartupPosition = new Vector2(55, 369) + (VirtualThumbsticks.LeftThumbstick * radious); } } /// <summary> /// Moves the beekeeper. /// </summary> private void SetMotion() { // Calculate the beekeeper's location Vector2 leftThumbstick = Vector2.Zero; leftThumbstick = VirtualThumbsticks.LeftThumbstick; Vector2 tempVector = beeKeeper.Position + leftThumbstick * 12f; if (tempVector.X < 0 || tempVector.X + beeKeeper.Bounds.Width > ScreenManager.GraphicsDevice.Viewport.Width) { leftThumbstick.X = 0; } if (tempVector.Y < 0 || tempVector.Y + beeKeeper.Bounds.Height > ScreenManager.GraphicsDevice.Viewport.Height) { leftThumbstick.Y = 0; } if (leftThumbstick == Vector2.Zero) { isInMotion = false; } else { Vector2 beekeeperCalculatedPosition = new Vector2(beeKeeper.CentralCollisionArea.X, beeKeeper.CentralCollisionArea.Y) + leftThumbstick * 12; if (!CheckBeehiveCollision(beekeeperCalculatedPosition)) { beeKeeper.SetMovement(leftThumbstick * 12f); IsInMotion = true; } } } /// <summary> /// Checks if the beekeeper collides with a beehive. /// </summary> /// <param name="beekeeperPosition">The beekeeper's position.</param> /// <returns>True if the beekeeper collides with a beehive and false otherwise.</returns> private bool CheckBeehiveCollision(Vector2 beekeeperPosition) { // We do not use the beekeeper's collision area property as he has not actually moved at this point and // is still in his previous position Rectangle beekeeperTempCollisionArea = new Rectangle((int)beekeeperPosition.X, (int)beekeeperPosition.Y, beeKeeper.CentralCollisionArea.Width, beeKeeper.CentralCollisionArea.Height); foreach (Beehive currentBeehive in beehives) { if (beekeeperTempCollisionArea.Intersects(currentBeehive.CentralCollisionArea)) { return true; } } return false; } /// <summary> /// Check for any of the possible collisions. /// </summary> /// <param name="gameTime">Game time information.</param> private void HandleCollision(GameTime gameTime) { bool isCollectingHoney = HandleBeeKeeperBeehiveCollision(); HandleSmokeBeehiveCollision(); bool hasCollisionWithVat = HandleVatCollision(); HandleBeeInteractions(gameTime, hasCollisionWithVat, isCollectingHoney); } /// <summary> /// Handle the interaction of the bees with other game components. /// </summary> /// <param name="gameTime">Game time information.</param> private void HandleBeeInteractions(GameTime gameTime, bool isBeeKeeperCollideWithVat, bool isBeeKeeperCollideWithBeehive) { // Goes over all the bees foreach (Bee bee in bees) { // Check for smoke collisions SmokePuff intersectingPuff = beeKeeper.CheckSmokeCollision(bee.Bounds); if (intersectingPuff != null) { bee.HitBySmoke(intersectingPuff); } // Check for vat collision if (vat.Bounds.HasCollision(bee.Bounds)) { bee.Collide(vat.Bounds); } // Check for beekeeper collision if (beeKeeper.Bounds.HasCollision(bee.Bounds)) { if (!bee.IsBeeHit && !isBeeKeeperCollideWithVat && !beeKeeper.IsStung && !beeKeeper.IsFlashing && !isBeeKeeperCollideWithBeehive) { jar.DecreaseHoneyByPercent(20); beeKeeper.Stung(gameTime.TotalGameTime); AudioManager.PlaySound("HoneyPotBreak"); AudioManager.PlaySound("Stung"); } bee.Collide(beeKeeper.Bounds); } // Soldier bee chase logic if (bee is SoldierBee) { SoldierBee SoldierBee = bee as SoldierBee; SoldierBee.DistanceFromBeeKeeper = (Vector2.Distance(beeKeeper.Bounds.GetVector(), SoldierBee.Bounds.GetVector())); SoldierBee.BeeKeeperVector = beeKeeper.Bounds.GetVector() - SoldierBee.Bounds.GetVector(); } } } /// <summary> /// Handle the beekeeper's collision with the vat component. /// </summary> /// <returns>True if the beekeeper collides with the vat and false otherwise.</returns> private bool HandleVatCollision() { if (beeKeeper.Bounds.HasCollision(vat.VatDepositArea)) { if (jar.HasHoney && !beeKeeper.IsStung && !beeKeeper.IsDepositingHoney && VirtualThumbsticks.LeftThumbstick == Vector2.Zero) { beeKeeper.StartTransferHoney(4, EndHoneyDeposit); } return true; } beeKeeper.EndTransferHoney(); return false; } /// <summary> /// Handler for finalizing the honey deposit to the vat. /// </summary> /// <param name="result"></param> public void EndHoneyDeposit(IAsyncResult result) { int HoneyAmount = jar.DecreaseHoneyByPercent(100); vat.IncreaseHoney(HoneyAmount); AudioManager.StopSound("DepositingIntoVat_Loop"); } /// <summary> /// Handle the beekeeper's collision with beehive components. /// </summary> /// <returns>True if the beekeeper collides with a beehive and false otherwise.</returns> /// <remarks>This method is also responsible for allowing bees to regenerate when the beekeeper is not /// intersecting with a specific hive.</remarks> private bool HandleBeeKeeperBeehiveCollision() { bool isCollidingWithBeehive = false; Beehive collidedBeehive = null; // Goes over all the beehives foreach (Beehive beehive in beehives) { // If the beekeeper intersects with the beehive if (beeKeeper.Bounds.HasCollision(beehive.Bounds)) { if (VirtualThumbsticks.LeftThumbstick == Vector2.Zero) { collidedBeehive = beehive; isCollidingWithBeehive = true; } } else { beehive.AllowBeesToGenerate = true; } } if (collidedBeehive != null) { // The beehive has honey, the jar can carry more honey, and the beekeeper is not stung if (collidedBeehive.HasHoney && jar.CanCarryMore && !beeKeeper.IsStung) { // Take honey from the beehive and put it in the jar collidedBeehive.DecreaseHoney(1); jar.IncreaseHoney(1); beeKeeper.IsCollectingHoney = true; AudioManager.PlaySound("FillingHoneyPot_Loop"); } else { beeKeeper.IsCollectingHoney = false; } // Bees are not allowed to regenerate while the beekeeper is colliding with their beehive isCollidingWithBeehive = true; collidedBeehive.AllowBeesToGenerate = false; } else { beeKeeper.IsCollectingHoney = false; AudioManager.StopSound("FillingHoneyPot_Loop"); } return isCollidingWithBeehive; } /// <summary> /// Handle the smoke puff collision with beehive components. /// </summary> /// <remarks>Only disables bee regeneration, as it assumes that it will be enabled by /// <see cref="HandleBeeKeeperBeehiveCollision"/></remarks> private void HandleSmokeBeehiveCollision() { foreach (Beehive beehive in beehives) { foreach (SmokePuff smokePuff in beeKeeper.FiredSmokePuffs) { if (beehive.Bounds.HasCollision(smokePuff.CentralCollisionArea)) { beehive.AllowBeesToGenerate = false; } } } } /// <summary> /// Sets an internal value which determines whether or not to display an arrow above the vat. /// </summary> private void HandleVatHoneyArrow() { if (jar.HasHoney) { drawArrow = true; } else { drawArrow = false; } } /// <summary> /// Handle smoke logic. /// </summary> private void HandleSmoke() { // If not currently shooting, refill the gun if (!isSmokebuttonClicked) { smokeButtonScorebar.IncreaseCurrentValue( ConfigurationManager.ModesConfiguration[gameDifficultyLevel].IncreaseAmountSpeed); beeKeeper.IsShootingSmoke = false; } else { // Check that the gun is not empty if (smokeButtonScorebar.CurrentValue <= smokeButtonScorebar.MinValue) { beeKeeper.IsShootingSmoke = false; } else { beeKeeper.IsShootingSmoke = true; smokeButtonScorebar.DecreaseCurrentValue( ConfigurationManager.ModesConfiguration[gameDifficultyLevel].DecreaseAmountSpeed); } } } /// <summary> /// Checks whether the current game is over, and if so performs the necessary actions. /// </summary> /// <returns>True if the current game is over and false otherwise.</returns> private bool CheckIfCurrentGameFinished() { levelEnded = false; isUserWon = vat.CurrentVatCapacity >= vat.MaxVatCapacity; // If the vat is full, the player wins if (isUserWon || gameElapsed <= TimeSpan.Zero) { levelEnded = true; } // if true, game is over if (gameElapsed <= TimeSpan.Zero || levelEnded) { isLevelEnd = true; if (userTapToExit) { ScreenManager.RemoveScreen(this); if (isUserWon) // True - the user won { // If is in high score, gets is name if (CheckIsInHighScore()) { Guide.BeginShowKeyboardInput(PlayerIndex.One, "Player Name", "What is your name (max 15 characters)?", "Player", AfterPlayerEnterName, levelEnded); } AudioManager.PlaySound("Victory"); } else { AudioManager.PlaySound("Defeat"); } MoveToNextScreen(isUserWon); } } return false; } /// <summary> /// A handler invoked after the user has entered his name. /// </summary> /// <param name="result"></param> private void AfterPlayerEnterName(IAsyncResult result) { // Get the name entered by the user string playerName = Guide.EndShowKeyboardInput(result); if (!string.IsNullOrEmpty(playerName)) { // Ensure that it is valid if (playerName != null && playerName.Length > 15) { playerName = playerName.Substring(0, 15); } // Puts it in high score HighScoreScreen.PutHighScore(playerName, Score); } // Moves to the next screen MoveToNextScreen((bool)result.AsyncState); } /// <summary> /// Draws the arrow in intervals of 20 game update loops. /// </summary> private void DrawVatHoneyArrow() { // If the arrow needs to be drawn, and it is not invisible during the current interval if (drawArrow && drawArrowInterval) { ScreenManager.SpriteBatch.Draw(arrowTexture, new Vector2(370, 314), Color.White); if (arrowCounter == 20) { drawArrowInterval = false; arrowCounter = 0; } arrowCounter++; } else { if (arrowCounter == 20) { drawArrowInterval = true; arrowCounter = 0; } arrowCounter++; } } /// <summary> /// Draws the smoke button. /// </summary> private void DrawSmokeButton() { if (isSmokebuttonClicked) { ScreenManager.SpriteBatch.Draw( smokeButton, new Rectangle((int)smokeButtonPosition.X, (int)smokeButtonPosition.Y, 109, 109), new Rectangle(109, 0, 109, 109), Color.White); } else { ScreenManager.SpriteBatch.Draw( smokeButton, new Rectangle((int)smokeButtonPosition.X, (int)smokeButtonPosition.Y, 109, 109), new Rectangle(0, 0, 109, 109), Color.White); } } /// <summary> /// Draws the count down string. /// </summary> private void DrawStartupString() { // If needed if (isAtStartupCountDown) { string text = string.Empty; // If countdown is done if (startScreenTime.Seconds == 0) { text = "Go!"; isAtStartupCountDown = false; AudioManager.PlaySound("BeeBuzzing_Loop", true, .6f); } else { text = startScreenTime.Seconds.ToString(); } Vector2 size = font16px.MeasureString(text); Vector2 textPosition = (new Vector2(ScreenManager.GraphicsDevice.Viewport.Width, ScreenManager.GraphicsDevice.Viewport.Height) - size) / 2f; ScreenManager.SpriteBatch.DrawString(font36px, text, textPosition, Color.White); } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Parse.Abstractions.Internal; using Parse.Infrastructure; using Parse.Infrastructure.Control; using Parse.Infrastructure.Data; // TODO (hallucinogen): mock ParseACL, ParseObject, ParseUser once we have their Interfaces namespace Parse.Tests { [TestClass] public class EncoderTests { ParseClient Client { get; } = new ParseClient(new ServerConnectionData { Test = true }); /// <summary> /// A <see cref="ParseDataEncoder"/> that's used only for testing. This class is used to test /// <see cref="ParseDataEncoder"/>'s base methods. /// </summary> class ParseEncoderTestClass : ParseDataEncoder { public static ParseEncoderTestClass Instance { get; } = new ParseEncoderTestClass { }; protected override IDictionary<string, object> EncodeObject(ParseObject value) => null; } [TestMethod] public void TestIsValidType() { ParseObject corgi = new ParseObject("Corgi"); ParseRelation<ParseObject> corgiRelation = corgi.GetRelation<ParseObject>(nameof(corgi)); Assert.IsTrue(ParseDataEncoder.Validate(322)); Assert.IsTrue(ParseDataEncoder.Validate(0.3f)); Assert.IsTrue(ParseDataEncoder.Validate(new byte[] { 1, 2, 3, 4 })); Assert.IsTrue(ParseDataEncoder.Validate(nameof(corgi))); Assert.IsTrue(ParseDataEncoder.Validate(corgi)); Assert.IsTrue(ParseDataEncoder.Validate(new ParseACL { })); Assert.IsTrue(ParseDataEncoder.Validate(new ParseFile("Corgi", new byte[0]))); Assert.IsTrue(ParseDataEncoder.Validate(new ParseGeoPoint(1, 2))); Assert.IsTrue(ParseDataEncoder.Validate(corgiRelation)); Assert.IsTrue(ParseDataEncoder.Validate(new DateTime { })); Assert.IsTrue(ParseDataEncoder.Validate(new List<object> { })); Assert.IsTrue(ParseDataEncoder.Validate(new Dictionary<string, string> { })); Assert.IsTrue(ParseDataEncoder.Validate(new Dictionary<string, object> { })); Assert.IsFalse(ParseDataEncoder.Validate(new ParseAddOperation(new List<object> { }))); Assert.IsFalse(ParseDataEncoder.Validate(Task.FromResult(new ParseObject("Corgi")))); Assert.ThrowsException<MissingMethodException>(() => ParseDataEncoder.Validate(new Dictionary<object, object> { })); Assert.ThrowsException<MissingMethodException>(() => ParseDataEncoder.Validate(new Dictionary<object, string> { })); } [TestMethod] public void TestEncodeDate() { DateTime dateTime = new DateTime(1990, 8, 30, 12, 3, 59); IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(dateTime, Client) as IDictionary<string, object>; Assert.AreEqual("Date", value["__type"]); Assert.AreEqual("1990-08-30T12:03:59.000Z", value["iso"]); } [TestMethod] public void TestEncodeBytes() { byte[] bytes = new byte[] { 1, 2, 3, 4 }; IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(bytes, Client) as IDictionary<string, object>; Assert.AreEqual("Bytes", value["__type"]); Assert.AreEqual(Convert.ToBase64String(new byte[] { 1, 2, 3, 4 }), value["base64"]); } [TestMethod] public void TestEncodeParseObjectWithNoObjectsEncoder() { ParseObject obj = new ParseObject("Corgi"); Assert.ThrowsException<ArgumentException>(() => NoObjectsEncoder.Instance.Encode(obj, Client)); } [TestMethod] public void TestEncodeParseObjectWithPointerOrLocalIdEncoder() { // TODO (hallucinogen): we can't make an object with ID without saving for now. Let's revisit this after we make IParseObject } [TestMethod] public void TestEncodeParseFile() { ParseFile file1 = ParseFileExtensions.Create("Corgi.png", new Uri("http://corgi.xyz/gogo.png")); IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(file1, Client) as IDictionary<string, object>; Assert.AreEqual("File", value["__type"]); Assert.AreEqual("Corgi.png", value["name"]); Assert.AreEqual("http://corgi.xyz/gogo.png", value["url"]); ParseFile file2 = new ParseFile(null, new MemoryStream(new byte[] { 1, 2, 3, 4 })); Assert.ThrowsException<InvalidOperationException>(() => ParseEncoderTestClass.Instance.Encode(file2, Client)); } [TestMethod] public void TestEncodeParseGeoPoint() { ParseGeoPoint point = new ParseGeoPoint(3.22, 32.2); IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(point, Client) as IDictionary<string, object>; Assert.AreEqual("GeoPoint", value["__type"]); Assert.AreEqual(3.22, value["latitude"]); Assert.AreEqual(32.2, value["longitude"]); } [TestMethod] public void TestEncodeACL() { ParseACL acl1 = new ParseACL(); IDictionary<string, object> value1 = ParseEncoderTestClass.Instance.Encode(acl1, Client) as IDictionary<string, object>; Assert.IsNotNull(value1); Assert.AreEqual(0, value1.Keys.Count); ParseACL acl2 = new ParseACL { PublicReadAccess = true, PublicWriteAccess = true }; IDictionary<string, object> value2 = ParseEncoderTestClass.Instance.Encode(acl2, Client) as IDictionary<string, object>; Assert.AreEqual(1, value2.Keys.Count); IDictionary<string, object> publicAccess = value2["*"] as IDictionary<string, object>; Assert.AreEqual(2, publicAccess.Keys.Count); Assert.IsTrue((bool) publicAccess["read"]); Assert.IsTrue((bool) publicAccess["write"]); // TODO (hallucinogen): mock ParseUser and test SetReadAccess and SetWriteAccess } [TestMethod] public void TestEncodeParseRelation() { ParseObject obj = new ParseObject("Corgi"); ParseRelation<ParseObject> relation = ParseRelationExtensions.Create<ParseObject>(obj, "nano", "Husky"); IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(relation, Client) as IDictionary<string, object>; Assert.AreEqual("Relation", value["__type"]); Assert.AreEqual("Husky", value["className"]); } [TestMethod] public void TestEncodeParseFieldOperation() { ParseIncrementOperation incOps = new ParseIncrementOperation(1); IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(incOps, Client) as IDictionary<string, object>; Assert.AreEqual("Increment", value["__op"]); Assert.AreEqual(1, value["amount"]); // Other operations are tested in FieldOperationTests. } [TestMethod] public void TestEncodeList() { IList<object> list = new List<object> { new ParseGeoPoint(0, 0), "item", new byte[] { 1, 2, 3, 4 }, new string[] { "hikaru", "hanatan", "ultimate" }, new Dictionary<string, object>() { ["elements"] = new int[] { 1, 2, 3 }, ["mystic"] = "cage", ["listAgain"] = new List<object> { "xilia", "zestiria", "symphonia" } } }; IList<object> value = ParseEncoderTestClass.Instance.Encode(list, Client) as IList<object>; IDictionary<string, object> item0 = value[0] as IDictionary<string, object>; Assert.AreEqual("GeoPoint", item0["__type"]); Assert.AreEqual(0.0, item0["latitude"]); Assert.AreEqual(0.0, item0["longitude"]); Assert.AreEqual("item", value[1]); IDictionary<string, object> item2 = value[2] as IDictionary<string, object>; Assert.AreEqual("Bytes", item2["__type"]); IList<object> item3 = value[3] as IList<object>; Assert.AreEqual("hikaru", item3[0]); Assert.AreEqual("hanatan", item3[1]); Assert.AreEqual("ultimate", item3[2]); IDictionary<string, object> item4 = value[4] as IDictionary<string, object>; Assert.IsTrue(item4["elements"] is IList<object>); Assert.AreEqual("cage", item4["mystic"]); Assert.IsTrue(item4["listAgain"] is IList<object>); } [TestMethod] public void TestEncodeDictionary() { IDictionary<string, object> dict = new Dictionary<string, object>() { ["item"] = "random", ["list"] = new List<object> { "vesperia", "abyss", "legendia" }, ["array"] = new int[] { 1, 2, 3 }, ["geo"] = new ParseGeoPoint(0, 0), ["validDict"] = new Dictionary<string, object> { ["phantasia"] = "jbf" } }; IDictionary<string, object> value = ParseEncoderTestClass.Instance.Encode(dict, Client) as IDictionary<string, object>; Assert.AreEqual("random", value["item"]); Assert.IsTrue(value["list"] is IList<object>); Assert.IsTrue(value["array"] is IList<object>); Assert.IsTrue(value["geo"] is IDictionary<string, object>); Assert.IsTrue(value["validDict"] is IDictionary<string, object>); Assert.ThrowsException<MissingMethodException>(() => ParseEncoderTestClass.Instance.Encode(new Dictionary<object, string> { }, Client)); Assert.ThrowsException<MissingMethodException>(() => ParseEncoderTestClass.Instance.Encode(new Dictionary<string, object> { ["validDict"] = new Dictionary<object, string> { [new ParseACL()] = "jbf" } }, Client)); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Xml; using System.ComponentModel; using System.IO; using Axiom.MathLib; using Axiom.Core; using Multiverse.ToolBox; namespace Multiverse.Tools.WorldEditor { public class WorldRoot : IWorldObject, IWorldContainer, IObjectCollectionParent { protected String name; protected static WorldRoot instance = null; protected MultiSelectTreeView treeView; protected WorldTreeNode node = null; protected WorldTreeNode terrainNode = null; protected WorldEditor app; protected WorldTerrain worldTerrain; protected Ocean ocean; protected Skybox skybox; protected GlobalFog fog = null; protected GlobalAmbientLight ambientLight = null; protected GlobalDirectionalLight directionalLight = null; protected PathObjectTypeContainer pathObjectTypes = null; protected List<WorldObjectCollection> worldCollections; protected bool inTree = false; protected bool inScene = false; protected string worldFilePath = null; protected Vector3 cameraPosition = Vector3.Zero; protected Quaternion cameraOrientation = Quaternion.Identity; protected List<ToolStripButton> buttonBar; protected string path; protected bool loadCollections; public WorldRoot(String worldName, MultiSelectTreeView tree, WorldEditor worldEditor) { instance = this; name = worldName; treeView = tree; app = worldEditor; worldTerrain = new WorldTerrain(app); ocean = new Ocean(this, app); skybox = new Skybox(this, app); fog = new GlobalFog(this, app); ambientLight = new GlobalAmbientLight(this, app); directionalLight = new GlobalDirectionalLight(this, app); worldCollections = new List<WorldObjectCollection>(); pathObjectTypes = new PathObjectTypeContainer(this, app); } public WorldRoot(XmlReader r, String worldFilename, MultiSelectTreeView tree, WorldEditor worldEditor, bool loadCollections) { instance = this; treeView = tree; app = worldEditor; worldFilePath = worldFilename; this.loadCollections = loadCollections; worldCollections = new List<WorldObjectCollection>(); if (loadCollections) { FromXml(r); } else { FromXml(r, loadCollections); } // if the XML doesn't have ocean in it, then add it here if (ocean == null) { ocean = new Ocean(this, app); } if (skybox == null) { skybox = new Skybox(this, app); } if (fog == null) { fog = new GlobalFog(this, app); } if (ambientLight == null) { ambientLight = new GlobalAmbientLight(this, app); } if (directionalLight == null) { directionalLight = new GlobalDirectionalLight(this, app); } if (pathObjectTypes == null) { pathObjectTypes = new PathObjectTypeContainer(this, app); } } [DescriptionAttribute("The name of this world."), CategoryAttribute("Miscellaneous")] public string Name { get { return name; } set { name = value; UpdateNode(); } } [BrowsableAttribute(false)] public static WorldRoot Instance { get { return instance; } } protected void UpdateNode() { if (inTree) { node.Text = NodeName; } } [BrowsableAttribute(false)] protected string NodeName { get { string ret; if (app.Config.ShowTypeLabelsInTreeView) { ret = string.Format("{0}: {1}", ObjectType, name); } else { ret = name; } return ret; } } [BrowsableAttribute(false)] public Vector3 CameraPosition { get { return cameraPosition; } set { cameraPosition = value; } } [BrowsableAttribute(false)] public Quaternion CameraOrientation { get { return cameraOrientation; } set { cameraOrientation = value; } } [DescriptionAttribute("The type of this object."), CategoryAttribute("Miscellaneous")] public string ObjectType { get { return "World"; } } [BrowsableAttribute(false)] public WorldTerrain Terrain { get { return worldTerrain; } } [BrowsableAttribute(false)] public bool IsGlobal { get { return true; } } [BrowsableAttribute(false)] public bool IsTopLevel { get { return false; } } [BrowsableAttribute(false)] public bool AcceptObjectPlacement { get { return false; } set { //not implemented for this type of object } } public void Clone(IWorldContainer copyParent) { } protected void FromXml(XmlReader r) { string filename=""; string baseName = worldFilePath.Substring(0, worldFilePath.LastIndexOf('\\')); for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); switch (r.Name) { case "Name": name = r.Value; break; } } r.MoveToElement(); while (r.Read()) { // look for the start of an element if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.EndElement) { break; } if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "CameraPosition": cameraPosition = XmlHelperClass.ParseVectorAttributes(r); break; case "CameraOrientation": cameraOrientation = XmlHelperClass.ParseQuaternion(r); break; case "Terrain": worldTerrain = new WorldTerrain(app, r); break; case "TerrainDisplay": worldTerrain.DisplayParamsFromXml(r); break; case "Ocean": ocean = new Ocean(this, app, r); break; case "Skybox": skybox = new Skybox(this, app, r); break; case "GlobalFog": fog = new GlobalFog(this, app, r); break; case "GlobalAmbientLight": ambientLight = new GlobalAmbientLight(this, app, app.Scene, r); break; case "GlobalDirectionalLight": directionalLight = new GlobalDirectionalLight(this, app, r); break; case "PathObjectTypes": pathObjectTypes = new PathObjectTypeContainer(app, this, r); break; case "WorldCollection": string collectionName = null; filename = ""; for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); switch (r.Name) { case "Name": collectionName = r.Value; break; case "Filename": filename = r.Value; break; } } if (filename != "") { string filepath = String.Format("{0}\\{1}", baseName, filename); if (filename.EndsWith("~.mwc")) { string autofilepath = String.Format("{0}\\{1}", baseName, filename); string normalfilepath = String.Format("{0}\\{1}", baseName, filename.Remove(filename.LastIndexOf("~"), 1)); if ((File.Exists(autofilepath) && File.Exists(normalfilepath) && (new FileInfo(autofilepath)).LastWriteTime < (new FileInfo(normalfilepath).LastWriteTime)) || (!File.Exists(autofilepath) && File.Exists(normalfilepath))) { filename = filename.Remove(filename.LastIndexOf("~"), 1); filepath = normalfilepath; } else { filepath = autofilepath; } } XmlReader childReader = XmlReader.Create(filepath, app.XMLReaderSettings); WorldObjectCollection collection = new WorldObjectCollection(childReader, collectionName, this, app, baseName); collection.Filename = filename; while(collection.Filename.Contains("~")) { collection.Filename = collection.Filename.Remove(collection.Filename.LastIndexOf("~"), 1); } Add(collection); childReader.Close(); } else { XmlReader childReader = XmlReader.Create(String.Format("{0}\\{1}.mwc", baseName, collectionName), app.XMLReaderSettings); WorldObjectCollection collection = new WorldObjectCollection(childReader, collectionName, this, app, baseName); collection.Filename = filename; while(collection.Filename.Contains("~")) { collection.Filename = collection.Filename.Remove(collection.Filename.LastIndexOf("~"), 1); } Add(collection); childReader.Close(); } r.MoveToElement(); break; } } } } protected void FromXml(XmlReader r, bool loadCollections) { string filename = ""; string baseName = worldFilePath.Substring(0, worldFilePath.LastIndexOf('\\')); bool loadColl = loadCollections; for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); switch (r.Name) { case "Name": name = r.Value; break; } } r.MoveToElement(); while (r.Read()) { // look for the start of an element if (r.NodeType == XmlNodeType.Whitespace) { continue; } if (r.NodeType == XmlNodeType.EndElement) { break; } if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "CameraPosition": cameraPosition = XmlHelperClass.ParseVectorAttributes(r); break; case "CameraOrientation": cameraOrientation = XmlHelperClass.ParseQuaternion(r); break; case "Terrain": worldTerrain = new WorldTerrain(app, r); break; case "TerrainDisplay": worldTerrain.DisplayParamsFromXml(r); break; case "Ocean": ocean = new Ocean(this, app, r); break; case "Skybox": skybox = new Skybox(this, app, r); break; case "GlobalFog": fog = new GlobalFog(this, app, r); break; case "GlobalAmbientLight": ambientLight = new GlobalAmbientLight(this, app, app.Scene, r); break; case "GlobalDirectionalLight": directionalLight = new GlobalDirectionalLight(this, app, r); break; case "PathObjectTypes": pathObjectTypes = new PathObjectTypeContainer(app, this, r); break; case "WorldCollection": string collectionName = null; filename = ""; for (int i = 0; i < r.AttributeCount; i++) { r.MoveToAttribute(i); switch (r.Name) { case "Name": collectionName = r.Value; break; case "Filename": filename = r.Value; break; } } string filepath = String.Format("{0}\\{1}", baseName, filename); if (filename != "") { if (filename.EndsWith("~.mwc")) { string autofilepath = String.Format("{0}\\{1}", baseName, filename); string normalfilepath = String.Format("{0}\\{1}", baseName, filename.Remove(filename.LastIndexOf("~"), 1)); if ((File.Exists(autofilepath) && File.Exists(normalfilepath) && (new FileInfo(autofilepath)).LastWriteTime < (new FileInfo(normalfilepath).LastWriteTime)) || (!File.Exists(autofilepath) && File.Exists(normalfilepath))) { filename = filename.Remove(filename.LastIndexOf("~"), 1); filepath = normalfilepath; } else { filepath = autofilepath; } } XmlReader childReader = XmlReader.Create(filepath, app.XMLReaderSettings); WorldObjectCollection collection = new WorldObjectCollection(childReader, collectionName, this, app, baseName, loadColl); collection.Filename = filename; while (collection.Filename.Contains("~")) { collection.Filename = collection.Filename.Remove(collection.Filename.LastIndexOf("~"), 1); } Add(collection); childReader.Close(); } else { XmlReader childReader = XmlReader.Create(String.Format("{0}\\{1}.mwc", baseName, collectionName), app.XMLReaderSettings); WorldObjectCollection collection = new WorldObjectCollection(childReader, collectionName, this, app, baseName, loadColl); collection.Filename = filename; Add(collection); while (collection.Filename.Contains("~")) { collection.Filename = collection.Filename.Remove(collection.Filename.LastIndexOf("~"), 1); } childReader.Close(); } r.MoveToElement(); break; } } } } #region IObjectCollectionParent [BrowsableAttribute(false)] public string WorldFilePath { get { return worldFilePath; } set { worldFilePath = value; string temp = worldFilePath.Substring(0, worldFilePath.LastIndexOf("\\") + 1); Path = temp; } } [BrowsableAttribute(false)] public string Path { get { return path; } set { path = value; } } [BrowsableAttribute(false)] public List<WorldObjectCollection> CollectionList { get { List<WorldObjectCollection>list = new List<WorldObjectCollection>(); foreach (WorldObjectCollection col in worldCollections) { list.Add(col); } return list; } } #endregion IObjectCollectionParent [BrowsableAttribute(false)] public PathObjectTypeContainer PathObjectTypes { get { return pathObjectTypes; } } #region IWorldObject Members public void AddToTree(WorldTreeNode parentNode) { // add the world node node = app.MakeTreeNode(this, NodeName); treeView.Nodes.Add(node); // build the menu CommandMenuBuilder menuBuilder = new CommandMenuBuilder(); menuBuilder.Add("Create Object Collection", new CreateWorldCollectionCommandFactory(app,((IObjectCollectionParent) this)), app.DefaultCommandClickHandler); menuBuilder.Add("Copy Description", "", app.copyToClipboardMenuButton_Click); menuBuilder.Add("Help", "World_Root", app.HelpClickHandler); node.ContextMenuStrip = menuBuilder.Menu; // traverse children worldTerrain.AddToTree(node); ocean.AddToTree(node); skybox.AddToTree(node); fog.AddToTree(node); ambientLight.AddToTree(node); directionalLight.AddToTree(node); // pathObjectTypes.AddToTree(node); foreach (WorldObjectCollection child in worldCollections) { child.AddToTree(node); } inTree = true; buttonBar = menuBuilder.ButtonBar; } [BrowsableAttribute(false)] public string ObjectAsString { get { string objString = String.Format("Name:{0}\r\n", NodeName); objString += "\r\n"; return objString; } } [BrowsableAttribute(false)] public List<ToolStripButton> ButtonBar { get { return buttonBar; } } public void RemoveFromTree() { if (node.IsSelected) { node.UnSelect(); } worldTerrain.RemoveFromTree(); ocean.RemoveFromTree(); skybox.RemoveFromTree(); pathObjectTypes.RemoveFromTree(); foreach (WorldObjectCollection child in worldCollections) { child.RemoveFromTree(); } treeView.Nodes.Remove(node); node = null; inTree = false; } public void AddToScene() { inScene = true; worldTerrain.AddToScene(); ocean.AddToScene(); skybox.AddToScene(); fog.AddToScene(); ambientLight.AddToScene(); directionalLight.AddToScene(); // Iterate all children and have them add themselves to the tree foreach (IWorldObject child in worldCollections) { child.AddToScene(); } } public void UpdateScene(UpdateTypes type, UpdateHint hint) { foreach (WorldObjectCollection objCol in this.worldCollections) { objCol.UpdateScene(type, hint); } } public void RemoveFromScene() { inScene = false; worldTerrain.RemoveFromScene(); ocean.RemoveFromScene(); skybox.RemoveFromScene(); // Iterate all children and have them add themselves to the tree foreach (IWorldObject child in worldCollections) { child.RemoveFromScene(); } } public void RemoveCollectionsFromScene() { foreach (IWorldObject child in worldCollections) { child.RemoveFromScene(); } } public void CheckAssets() { worldTerrain.CheckAssets(); ocean.CheckAssets(); skybox.CheckAssets(); fog.CheckAssets(); ambientLight.CheckAssets(); directionalLight.CheckAssets(); foreach (IWorldObject child in worldCollections) { child.CheckAssets(); } } public void ToXml(XmlWriter w) { int pathEnd = worldFilePath.LastIndexOf('\\'); string pathName = worldFilePath.Substring(0, pathEnd); w.WriteStartElement("World"); w.WriteAttributeString("Name", name); w.WriteAttributeString("Version", app.Config.XmlSaveFileVersion.ToString()); w.WriteStartElement("CameraPosition"); w.WriteAttributeString("x", cameraPosition.x.ToString()); w.WriteAttributeString("y", cameraPosition.y.ToString()); w.WriteAttributeString("z", cameraPosition.z.ToString()); w.WriteEndElement(); w.WriteStartElement("CameraOrientation"); w.WriteAttributeString("x", cameraOrientation.x.ToString()); w.WriteAttributeString("y", cameraOrientation.y.ToString()); w.WriteAttributeString("z", cameraOrientation.z.ToString()); w.WriteAttributeString("w", cameraOrientation.w.ToString()); w.WriteEndElement(); worldTerrain.ToXml(w); ocean.ToXml(w); skybox.ToXml(w); fog.ToXml(w); ambientLight.ToXml(w); directionalLight.ToXml(w); pathObjectTypes.ToXml(w); foreach (WorldObjectCollection worldCollection in worldCollections) { // write the XML into the top level world file w.WriteStartElement("WorldCollection"); worldCollection.Path = pathName; if (worldCollection.Filename == "") { int startIndex = pathEnd + 1; worldCollection.Path = pathName; int subStringLength = worldFilePath.LastIndexOf(".mvw") - startIndex + 4; worldCollection.Filename = String.Format("{0}-{1}.mwc", worldFilePath.Substring(startIndex, subStringLength), worldCollection.Name); } w.WriteAttributeString("Name", worldCollection.Name); w.WriteAttributeString("Filename", worldCollection.Filename); w.WriteEndElement(); // create a file for the collection if (worldCollection.Loaded) { try { XmlWriter childWriter = XmlWriter.Create(String.Format("{0}\\{1}", pathName, worldCollection.Filename), app.XMLWriterSettings); worldCollection.ToXml(childWriter); childWriter.Close(); } catch (Exception e) { LogManager.Instance.Write(e.ToString()); MessageBox.Show(String.Format("Unable to open the file for writing. Use file menu \"Save As\" to save to another location. Error: {0}", e.Message), "Error Saving File", MessageBoxButtons.OK); } } } w.WriteEndElement(); } public void ToXml(XmlWriter w, bool backup) { if (!backup) { ToXml(w); } int pathEnd = worldFilePath.LastIndexOf('\\'); string pathName = worldFilePath.Substring(0, pathEnd); w.WriteStartElement("World"); w.WriteAttributeString("Name", name); w.WriteAttributeString("Version", app.Config.XmlSaveFileVersion.ToString()); w.WriteStartElement("CameraPosition"); w.WriteAttributeString("x", cameraPosition.x.ToString()); w.WriteAttributeString("y", cameraPosition.y.ToString()); w.WriteAttributeString("z", cameraPosition.z.ToString()); w.WriteEndElement(); w.WriteStartElement("CameraOrientation"); w.WriteAttributeString("x", cameraOrientation.x.ToString()); w.WriteAttributeString("y", cameraOrientation.y.ToString()); w.WriteAttributeString("z", cameraOrientation.z.ToString()); w.WriteAttributeString("w", cameraOrientation.w.ToString()); w.WriteEndElement(); worldTerrain.ToXml(w); ocean.ToXml(w); skybox.ToXml(w); fog.ToXml(w); ambientLight.ToXml(w); directionalLight.ToXml(w); pathObjectTypes.ToXml(w); foreach (WorldObjectCollection worldCollection in worldCollections) { if (worldCollection.Filename == "") { int startIndex = pathEnd + 1; int subStringLength = worldFilePath.LastIndexOf(".mvw") - startIndex + 4; worldCollection.Filename = String.Format("{0}-{1}.mwc", worldFilePath.Substring(startIndex, subStringLength), worldCollection.Name); } // write the XML into the top level world file w.WriteStartElement("WorldCollection"); w.WriteAttributeString("Name", worldCollection.Name); string filename = worldCollection.Filename.Insert((worldCollection.Filename.LastIndexOf(".")),"~"); w.WriteAttributeString("Filename", filename); w.WriteEndElement(); // create a file for the collection if (worldCollection.Loaded) { try { XmlWriter childWriter = XmlWriter.Create(String.Format("{0}\\{1}", pathName, filename), app.XMLWriterSettings); worldCollection.ToXml(childWriter, backup); childWriter.Close(); } catch (Exception e) { LogManager.Instance.Write(e.ToString()); MessageBox.Show(String.Format("Unable to open the file for writing. Use file menu \"Save As\" to save to another location. Error: {0}", e.Message), "Error Saving File", MessageBoxButtons.OK); } } int index = worldCollection.Filename.LastIndexOf('~'); if (index > 0) { worldCollection.Filename = worldCollection.Filename.Remove(worldCollection.Filename.LastIndexOf('~'),1); } } w.WriteEndElement(); } [BrowsableAttribute(false)] public bool WorldViewSelectable { get { return false; } set { // this property is not applicable to this object } } [BrowsableAttribute(false)] public Vector3 FocusLocation { get { Vector3 v = Vector3.Zero; if (worldCollections.Count != 0) { foreach (WorldObjectCollection worldCollection in worldCollections) { v += worldCollection.FocusLocation; } v = v / worldCollections.Count; } return v; } } [BrowsableAttribute(false)] public bool Highlight { get { return false; } set { // do nothing } } [BrowsableAttribute(false)] public WorldTreeNode Node { get { return node; } } public void ToManifest(System.IO.StreamWriter w) { if (worldCollections != null) { foreach (IWorldObject child in worldCollections) { child.ToManifest(w); } } // traverse children worldTerrain.ToManifest(w); ocean.ToManifest(w); skybox.ToManifest(w); fog.ToManifest(w); } #endregion [BrowsableAttribute(false)] public List<WorldObjectCollection> WorldObjectCollections { get { return this.worldCollections; } } #region IDisposable Members public void Dispose() { worldCollections.Clear(); } #endregion #region ICollection<IWorldObject> Members public void Add(IWorldObject item) { worldCollections.Add(item as WorldObjectCollection); if (inTree) { item.AddToTree(node); } if (inScene) { item.AddToScene(); } } public void Clear() { worldCollections.Clear(); } public bool Contains(IWorldObject item) { return worldCollections.Contains(item as WorldObjectCollection); } public void CopyTo(IWorldObject[] array, int arrayIndex) { worldCollections.CopyTo(array as WorldObjectCollection[], arrayIndex); } [BrowsableAttribute(false)] public bool DisplayOcean { get { return ocean.DisplayOcean; } } [BrowsableAttribute(false)] public int Count { get { return worldCollections.Count; } } [BrowsableAttribute(false)] public bool IsReadOnly { get { return false; } } public bool Remove(IWorldObject item) { if (inTree) { item.RemoveFromTree(); } if (inScene) { item.RemoveFromScene(); } return worldCollections.Remove(item as WorldObjectCollection); } #endregion #region IEnumerable<IWorldObject> Members public IEnumerator<IWorldObject> GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; using Microsoft.Data.Entity.SqlServer.Metadata; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] partial class AllReadyContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .Annotation("ProductVersion", "7.0.0-beta7-15540") .Annotation("SqlServer:ValueGenerationStrategy", SqlServerIdentityStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTime>("EndDateTimeUtc"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<string>("Name"); b.Property<string>("OrganizerId"); b.Property<DateTime>("StartDateTimeUtc"); b.Property<int>("TenantId"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<DateTime?>("CheckinDateTime"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("Description"); b.Property<DateTime?>("EndDateTimeUtc"); b.Property<string>("Name"); b.Property<DateTime?>("StartDateTimeUtc"); b.Property<int?>("TenantId"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<int?>("AssociatedTenantId"); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Email") .Annotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .Annotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .Annotation("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") .Annotation("MaxLength", 256); b.Key("Id"); b.Index("NormalizedEmail") .Annotation("Relational:Name", "EmailIndex"); b.Index("NormalizedUserName") .Annotation("Relational:Name", "UserNameIndex"); b.Annotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<DateTime>("EndDateTimeUtc"); b.Property<string>("ImageUrl"); b.Property<int>("ManagingTenantId"); b.Property<string>("Name") .Required(); b.Property<string>("OrganizerId"); b.Property<DateTime>("StartDateTimeUtc"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("TenantId"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCodePostalCode"); b.Property<string>("State"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode") .ValueGeneratedOnAdd(); b.Property<string>("City"); b.Property<string>("State"); b.Key("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.TaskUsers", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.Key("Id"); }); modelBuilder.Entity("AllReady.Models.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LogoUrl"); b.Property<string>("Name"); b.Property<string>("WebUrl"); b.Key("Id"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Name") .Annotation("MaxLength", 256); b.Property<string>("NormalizedName") .Annotation("MaxLength", 256); b.Key("Id"); b.Index("NormalizedName") .Annotation("Relational:Name", "RoleNameIndex"); b.Annotation("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"); b.Key("Id"); b.Annotation("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"); b.Key("Id"); b.Annotation("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"); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.Activity", b => { b.Reference("AllReady.Models.Campaign") .InverseCollection() .ForeignKey("CampaignId"); b.Reference("AllReady.Models.Location") .InverseCollection() .ForeignKey("LocationId"); b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("OrganizerId"); b.Reference("AllReady.Models.Tenant") .InverseCollection() .ForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.Reference("AllReady.Models.Activity") .InverseCollection() .ForeignKey("ActivityId"); b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Reference("AllReady.Models.Activity") .InverseCollection() .ForeignKey("ActivityId"); b.Reference("AllReady.Models.Tenant") .InverseCollection() .ForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Reference("AllReady.Models.Tenant") .InverseCollection() .ForeignKey("AssociatedTenantId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Reference("AllReady.Models.Tenant") .InverseCollection() .ForeignKey("ManagingTenantId"); b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Reference("AllReady.Models.Campaign") .InverseCollection() .ForeignKey("CampaignId"); b.Reference("AllReady.Models.Tenant") .InverseCollection() .ForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Reference("AllReady.Models.PostalCodeGeo") .InverseCollection() .ForeignKey("PostalCodePostalCode"); }); modelBuilder.Entity("AllReady.Models.TaskUsers", b => { b.Reference("AllReady.Models.AllReadyTask") .InverseCollection() .ForeignKey("TaskId"); b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("AllReady.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); } } }
using System; using System.Text; #if PSM using PssVector4 = Sce.PlayStation.Core.Vector4; #endif namespace CrossGraph.Math { public struct Vector4 : IEquatable<Vector4> { #region Private Fields private static Vector4 zeroVector = new Vector4(); private static Vector4 unitVector = new Vector4(1f, 1f, 1f, 1f); private static Vector4 unitXVector = new Vector4(1f, 0f, 0f, 0f); private static Vector4 unitYVector = new Vector4(0f, 1f, 0f, 0f); private static Vector4 unitZVector = new Vector4(0f, 0f, 1f, 0f); private static Vector4 unitWVector = new Vector4(0f, 0f, 0f, 1f); #endregion Private Fields #region Public Fields public float X; public float Y; public float Z; public float W; #endregion Public Fields #region Properties public static Vector4 Zero { get { return zeroVector; } } public static Vector4 One { get { return unitVector; } } public static Vector4 UnitX { get { return unitXVector; } } public static Vector4 UnitY { get { return unitYVector; } } public static Vector4 UnitZ { get { return unitZVector; } } public static Vector4 UnitW { get { return unitWVector; } } #endregion Properties #region Constructors public Vector4(float x, float y, float z, float w) { this.X = x; this.Y = y; this.Z = z; this.W = w; } public Vector4(Vector2 value, float z, float w) { this.X = value.X; this.Y = value.Y; this.Z = z; this.W = w; } public Vector4(Vector3 value, float w) { this.X = value.X; this.Y = value.Y; this.Z = value.Z; this.W = w; } public Vector4(float value) { this.X = value; this.Y = value; this.Z = value; this.W = value; } #endregion #region Public Methods public static Vector4 Add(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static void Add(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W + value2.W; result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; } public static Vector4 Barycentric(Vector4 value1, Vector4 value2, Vector4 value3, float amount1, float amount2) { #if(USE_FARSEER) return new Vector4( SilverSpriteMathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), SilverSpriteMathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), SilverSpriteMathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2), SilverSpriteMathHelper.Barycentric(value1.W, value2.W, value3.W, amount1, amount2)); #else return new Vector4( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), MathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2), MathHelper.Barycentric(value1.W, value2.W, value3.W, amount1, amount2)); #endif } public static void Barycentric(ref Vector4 value1, ref Vector4 value2, ref Vector4 value3, float amount1, float amount2, out Vector4 result) { #if(USE_FARSEER) result = new Vector4( SilverSpriteMathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), SilverSpriteMathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), SilverSpriteMathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2), SilverSpriteMathHelper.Barycentric(value1.W, value2.W, value3.W, amount1, amount2)); #else result = new Vector4( MathHelper.Barycentric(value1.X, value2.X, value3.X, amount1, amount2), MathHelper.Barycentric(value1.Y, value2.Y, value3.Y, amount1, amount2), MathHelper.Barycentric(value1.Z, value2.Z, value3.Z, amount1, amount2), MathHelper.Barycentric(value1.W, value2.W, value3.W, amount1, amount2)); #endif } public static Vector4 CatmullRom(Vector4 value1, Vector4 value2, Vector4 value3, Vector4 value4, float amount) { #if(USE_FARSEER) return new Vector4( SilverSpriteMathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), SilverSpriteMathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), SilverSpriteMathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount), SilverSpriteMathHelper.CatmullRom(value1.W, value2.W, value3.W, value4.W, amount)); #else return new Vector4( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), MathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount), MathHelper.CatmullRom(value1.W, value2.W, value3.W, value4.W, amount)); #endif } public static void CatmullRom(ref Vector4 value1, ref Vector4 value2, ref Vector4 value3, ref Vector4 value4, float amount, out Vector4 result) { #if(USE_FARSEER) result = new Vector4( SilverSpriteMathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), SilverSpriteMathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), SilverSpriteMathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount), SilverSpriteMathHelper.CatmullRom(value1.W, value2.W, value3.W, value4.W, amount)); #else result = new Vector4( MathHelper.CatmullRom(value1.X, value2.X, value3.X, value4.X, amount), MathHelper.CatmullRom(value1.Y, value2.Y, value3.Y, value4.Y, amount), MathHelper.CatmullRom(value1.Z, value2.Z, value3.Z, value4.Z, amount), MathHelper.CatmullRom(value1.W, value2.W, value3.W, value4.W, amount)); #endif } public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { return new Vector4( MathHelper.Clamp(value1.X, min.X, max.X), MathHelper.Clamp(value1.Y, min.Y, max.Y), MathHelper.Clamp(value1.Z, min.Z, max.Z), MathHelper.Clamp(value1.W, min.W, max.W)); } public static void Clamp(ref Vector4 value1, ref Vector4 min, ref Vector4 max, out Vector4 result) { result = new Vector4( MathHelper.Clamp(value1.X, min.X, max.X), MathHelper.Clamp(value1.Y, min.Y, max.Y), MathHelper.Clamp(value1.Z, min.Z, max.Z), MathHelper.Clamp(value1.W, min.W, max.W)); } public static float Distance(Vector4 value1, Vector4 value2) { return (float)System.Math.Sqrt(DistanceSquared(value1, value2)); } public static void Distance(ref Vector4 value1, ref Vector4 value2, out float result) { result = (float)System.Math.Sqrt(DistanceSquared(value1, value2)); } public static float DistanceSquared(Vector4 value1, Vector4 value2) { float result; DistanceSquared(ref value1, ref value2, out result); return result; } public static void DistanceSquared(ref Vector4 value1, ref Vector4 value2, out float result) { result = (value1.W - value2.W) * (value1.W - value2.W) + (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } public static Vector4 Divide(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector4 Divide(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } public static void Divide(ref Vector4 value1, float divider, out Vector4 result) { float factor = 1f / divider; result.W = value1.W * factor; result.X = value1.X * factor; result.Y = value1.Y * factor; result.Z = value1.Z * factor; } public static void Divide(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W / value2.W; result.X = value1.X / value2.X; result.Y = value1.Y / value2.Y; result.Z = value1.Z / value2.Z; } public static float Dot(Vector4 vector1, Vector4 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W; } public static void Dot(ref Vector4 vector1, ref Vector4 vector2, out float result) { result = vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W; } public override bool Equals(object obj) { return (obj is Vector4) ? this == (Vector4)obj : false; } public bool Equals(Vector4 other) { return this.W == other.W && this.X == other.X && this.Y == other.Y && this.Z == other.Z; } public override int GetHashCode() { return (int)(this.W + this.X + this.Y + this.Y); } public static Vector4 Hermite(Vector4 value1, Vector4 tangent1, Vector4 value2, Vector4 tangent2, float amount) { Vector4 result = new Vector4(); Hermite(ref value1, ref tangent1, ref value2, ref tangent2, amount, out result); return result; } public static void Hermite(ref Vector4 value1, ref Vector4 tangent1, ref Vector4 value2, ref Vector4 tangent2, float amount, out Vector4 result) { #if(USE_FARSEER) result.W = SilverSpriteMathHelper.Hermite(value1.W, tangent1.W, value2.W, tangent2.W, amount); result.X = SilverSpriteMathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); result.Y = SilverSpriteMathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); result.Z = SilverSpriteMathHelper.Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); #else result.W = MathHelper.Hermite(value1.W, tangent1.W, value2.W, tangent2.W, amount); result.X = MathHelper.Hermite(value1.X, tangent1.X, value2.X, tangent2.X, amount); result.Y = MathHelper.Hermite(value1.Y, tangent1.Y, value2.Y, tangent2.Y, amount); result.Z = MathHelper.Hermite(value1.Z, tangent1.Z, value2.Z, tangent2.Z, amount); #endif } public float Length() { float result; DistanceSquared(ref this, ref zeroVector, out result); return (float)System.Math.Sqrt(result); } public float LengthSquared() { float result; DistanceSquared(ref this, ref zeroVector, out result); return result; } public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount) { return new Vector4( MathHelper.Lerp(value1.X, value2.X, amount), MathHelper.Lerp(value1.Y, value2.Y, amount), MathHelper.Lerp(value1.Z, value2.Z, amount), MathHelper.Lerp(value1.W, value2.W, amount)); } public static void Lerp(ref Vector4 value1, ref Vector4 value2, float amount, out Vector4 result) { result = new Vector4( MathHelper.Lerp(value1.X, value2.X, amount), MathHelper.Lerp(value1.Y, value2.Y, amount), MathHelper.Lerp(value1.Z, value2.Z, amount), MathHelper.Lerp(value1.W, value2.W, amount)); } public static Vector4 Max(Vector4 value1, Vector4 value2) { return new Vector4( MathHelper.Max(value1.X, value2.X), MathHelper.Max(value1.Y, value2.Y), MathHelper.Max(value1.Z, value2.Z), MathHelper.Max(value1.W, value2.W)); } public static void Max(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result = new Vector4( MathHelper.Max(value1.X, value2.X), MathHelper.Max(value1.Y, value2.Y), MathHelper.Max(value1.Z, value2.Z), MathHelper.Max(value1.W, value2.W)); } public static Vector4 Min(Vector4 value1, Vector4 value2) { return new Vector4( MathHelper.Min(value1.X, value2.X), MathHelper.Min(value1.Y, value2.Y), MathHelper.Min(value1.Z, value2.Z), MathHelper.Min(value1.W, value2.W)); } public static void Min(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result = new Vector4( MathHelper.Min(value1.X, value2.X), MathHelper.Min(value1.Y, value2.Y), MathHelper.Min(value1.Z, value2.Z), MathHelper.Min(value1.W, value2.W)); } public static Vector4 Multiply(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector4 Multiply(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static void Multiply(ref Vector4 value1, float scaleFactor, out Vector4 result) { result.W = value1.W * scaleFactor; result.X = value1.X * scaleFactor; result.Y = value1.Y * scaleFactor; result.Z = value1.Z * scaleFactor; } public static void Multiply(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W * value2.W; result.X = value1.X * value2.X; result.Y = value1.Y * value2.Y; result.Z = value1.Z * value2.Z; } public static Vector4 Negate(Vector4 value) { value = new Vector4(-value.X, -value.Y, -value.Z, -value.W); return value; } public static void Negate(ref Vector4 value, out Vector4 result) { result = new Vector4(-value.X, -value.Y, -value.Z,-value.W); } public void Normalize() { Normalize(ref this, out this); } public static Vector4 Normalize(Vector4 vector) { Normalize(ref vector, out vector); return vector; } public static void Normalize(ref Vector4 vector, out Vector4 result) { float factor; DistanceSquared(ref vector, ref zeroVector, out factor); factor = 1f / (float)System.Math.Sqrt(factor); result.W = vector.W * factor; result.X = vector.X * factor; result.Y = vector.Y * factor; result.Z = vector.Z * factor; } public static Vector4 SmoothStep(Vector4 value1, Vector4 value2, float amount) { #if(USE_FARSEER) return new Vector4( SilverSpriteMathHelper.SmoothStep(value1.X, value2.X, amount), SilverSpriteMathHelper.SmoothStep(value1.Y, value2.Y, amount), SilverSpriteMathHelper.SmoothStep(value1.Z, value2.Z, amount), SilverSpriteMathHelper.SmoothStep(value1.W, value2.W, amount)); #else return new Vector4( MathHelper.SmoothStep(value1.X, value2.X, amount), MathHelper.SmoothStep(value1.Y, value2.Y, amount), MathHelper.SmoothStep(value1.Z, value2.Z, amount), MathHelper.SmoothStep(value1.W, value2.W, amount)); #endif } public static void SmoothStep(ref Vector4 value1, ref Vector4 value2, float amount, out Vector4 result) { #if(USE_FARSEER) result = new Vector4( SilverSpriteMathHelper.SmoothStep(value1.X, value2.X, amount), SilverSpriteMathHelper.SmoothStep(value1.Y, value2.Y, amount), SilverSpriteMathHelper.SmoothStep(value1.Z, value2.Z, amount), SilverSpriteMathHelper.SmoothStep(value1.W, value2.W, amount)); #else result = new Vector4( MathHelper.SmoothStep(value1.X, value2.X, amount), MathHelper.SmoothStep(value1.Y, value2.Y, amount), MathHelper.SmoothStep(value1.Z, value2.Z, amount), MathHelper.SmoothStep(value1.W, value2.W, amount)); #endif } public static Vector4 Subtract(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static void Subtract(ref Vector4 value1, ref Vector4 value2, out Vector4 result) { result.W = value1.W - value2.W; result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; } public static Vector4 Transform(Vector2 position, Matrix matrix) { Vector4 result; Transform(ref position, ref matrix, out result); return result; } public static Vector4 Transform(Vector3 position, Matrix matrix) { Vector4 result; Transform(ref position, ref matrix, out result); return result; } public static Vector4 Transform(Vector4 vector, Matrix matrix) { Transform(ref vector, ref matrix, out vector); return vector; } public static void Transform(ref Vector2 position, ref Matrix matrix, out Vector4 result) { result = new Vector4((position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + matrix.M44); } public static void Transform(ref Vector3 position, ref Matrix matrix, out Vector4 result) { result = new Vector4((position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + (position.Z * matrix.M34) + matrix.M44); } public static void Transform(ref Vector4 vector, ref Matrix matrix, out Vector4 result) { result = new Vector4((vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + (vector.W * matrix.M41), (vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + (vector.W * matrix.M42), (vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + (vector.W * matrix.M43), (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44)); } public override string ToString() { StringBuilder sb = new StringBuilder(32); sb.Append("{X:"); sb.Append(this.X); sb.Append(" Y:"); sb.Append(this.Y); sb.Append(" Z:"); sb.Append(this.Z); sb.Append(" W:"); sb.Append(this.W); sb.Append("}"); return sb.ToString(); } #endregion Public Methods #region Operators public static Vector4 operator -(Vector4 value) { return new Vector4(-value.X, -value.Y, -value.Z, -value.W); } public static bool operator ==(Vector4 value1, Vector4 value2) { return value1.W == value2.W && value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } public static bool operator !=(Vector4 value1, Vector4 value2) { return !(value1 == value2); } public static Vector4 operator +(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector4 operator -(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector4 operator *(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector4 operator *(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector4 operator *(float scaleFactor, Vector4 value1) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector4 operator /(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector4 operator /(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } #if PSM public static implicit operator PssVector4(Vector4 v) { return new PssVector4(v.X, v.Y, v.Z, v.W); } public static implicit operator Vector4(PssVector4 v) { return new Vector4(v.X, v.Y, v.Z, v.W); } #elif OPENTK public static implicit operator OpenTK.Vector4(Vector4 v) { return new OpenTK.Vector4(v.X, v.Y, v.Z, v.W); } public static implicit operator Vector4(OpenTK.Vector4 v) { return new Vector4(v.X, v.Y, v.Z, v.W); } #endif #endregion Operators } }
using UnityEngine; using System.Collections; public class sui_demo_ControllerOrbit : MonoBehaviour { //PUBLIC VARIABLES public bool isActive = false; public bool isControllable = true; public bool isExtraZoom = false; public Transform cameraTarget; public bool reverseYAxis = true; public bool reverseXAxis = false; public Vector2 mouseSensitivity = new Vector2(4.0f,4.0f); public float cameraFOV = 35.0f; public Vector3 cameraOffset = new Vector3(0.0f,0.0f,0.0f); public float cameraLean = 0.0f; public float rotationSensitivity = 6.0f; public Vector3 rotationLimits = new Vector3(0.0f,0.0f,0.0f); public float minZoomAmount = 1.25f; public float maxZoomAmount = 8.0f; public bool showDebug = false; public sui_demo_animCharacter targetAnimator; //PRIVATE VARIABLES private Transform cameraObject; //private float rotSense = 0.0f; private Vector2 axisSensitivity = new Vector2(4.0f,4.0f); private float followDistance = 10.0f; private float followHeight = 1.0f; private float followLat = 0.0f; private float camFOV = 35.0f; private float camRotation = 0.0f; private Vector3 camRot; private float camHeight = 4.0f; private bool isInWater = false; private bool isInWaterDeep = false; private bool isUnderWater = false; private Vector3 targetPosition; private float MouseRotationDistance = 0.0f; private float MouseVerticalDistance = 0.0f; private GameObject suimonoGameObject; private Suimono.Core.SuimonoModule suimonoModuleObject; private float followTgtDistance = 0.0f; private bool orbitView = false; private Quaternion targetRotation; private float MouseScrollDistance = 0.0f; //private Transform playerObject; //private float projEmitTimer = 0.0f; //private float camVRotation = 0.0f; //private float firingTime = 0.0f; //private float sightingTime = 0.0f; private float setFOV = 1.0f; //private float targetUseLean = 0.0f; //private float useSpeed = 0.0f; //private float useSideSpeed = 0.0f; //private float useVertSpeed = 0.0f; private float moveForward = 0.0f; private float moveSideways = 0.0f; //private float moveForwardTgt = 0.0f; //private float moveSidewaysTgt = 0.0f; //private float moveVert = 0.0f; private bool isWalking = false; private bool isRunning = false; private bool isSprinting = false; //private bool isMouseMove = false; //private float lastYPos = 0.0f; //private float propSpd = 0.0f; //private float engPos = 0.5f; //private Transform vehiclePosition; //private Transform vehicleExitPosition; //private float forwardAmt = 0.0f; //private float sidewaysAmt = 0.0f; //private float editorSensitivity = 1.0f; //private float button3time = 0.0f; private Vector3 savePos; private float oldMouseRotation; //private float oldMouseVRotation; private sui_demo_ControllerMaster MC; private sui_demo_InputController IC; //private float xMove = 0.0f; private float runButtonTime = 0.0f; private bool toggleRun = false; private float gSlope = 0.0f; private float useSlope = 0.0f; void Awake() { //get Suimono Specific Objects suimonoGameObject = GameObject.Find("SUIMONO_Module"); if (suimonoGameObject != null) suimonoModuleObject = suimonoGameObject.GetComponent<Suimono.Core.SuimonoModule>(); targetPosition = cameraTarget.position; targetRotation = cameraTarget.rotation; MC = this.gameObject.GetComponent<sui_demo_ControllerMaster>() as sui_demo_ControllerMaster; IC = this.gameObject.GetComponent<sui_demo_InputController>() as sui_demo_InputController; } void FixedUpdate () { if (isActive){ //------------------------------------ // GET DATA FROM MASTER CONTROLLER //------------------------------------ cameraObject = MC.cameraObject; //--------------------------------- // GET KEYBOARD AND MOUSE INPUTS //--------------------------------- if (isControllable){ //RESET MOVEMENT moveForward = 0.0f; moveSideways = 0.0f; //moveVert = 0.0f; // GET WASD MOVEMENT KEYS if (IC.inputKeyW) moveForward = 1.0f; if (IC.inputKeyS) moveForward = -1.0f; if (IC.inputKeyA) moveSideways = -1.0f; if (IC.inputKeyD) moveSideways = 1.0f; //if (IC.inputKeyQ) moveVert = -1.0f; //if (IC.inputKeyE) moveVert = 1.0f; //MOUSE BUTTON 0 //isMouseMove = IC.inputMouseKey0; //MOUSE BUTTON 1 isExtraZoom = IC.inputMouseKey1; if (isExtraZoom){ setFOV = 0.5f; } else { setFOV = 1.0f; } //SHIFT RUN/SPRINT // Tap Shift to toggle // hold shift to sprint isWalking = false; if (moveForward != 0.0f || moveSideways != 0.0f) isWalking = true; if (IC.inputKeySHIFTL){ runButtonTime += Time.deltaTime; if (runButtonTime > 0.2f){ isSprinting = true; } } else { if (runButtonTime > 0.0f){ if (runButtonTime < 0.2f){ isRunning = !isRunning; if (isRunning) toggleRun = true; } if (runButtonTime > 0.2f){ isRunning = false; } } if (isSprinting && toggleRun) isRunning = true; isSprinting = false; runButtonTime = 0.0f; } //SPACE if (Input.mousePosition.x > 325f || Input.mousePosition.y < 265f){ orbitView = IC.inputMouseKey0 || IC.inputMouseKey1; } else { orbitView = false; IC.inputMouseKey0 = false; IC.inputMouseKey1 = false; } } //CHECK FOR MOUSE INPUT targetPosition = cameraTarget.position; oldMouseRotation = MouseRotationDistance; //oldMouseVRotation = MouseVerticalDistance; //GET MOUSE MOVEMENT MouseRotationDistance = IC.inputMouseX; MouseVerticalDistance = IC.inputMouseY; MouseScrollDistance = IC.inputMouseWheel; if (reverseXAxis) MouseRotationDistance = -IC.inputMouseX; if (reverseYAxis) MouseVerticalDistance = -IC.inputMouseY; //--------------------------------- // HANDLE CAMERA VIEWS //--------------------------------- if (!isControllable){ //Zoom Settings used for the intro screen camFOV = 63.2f; followLat = Mathf.Lerp(followLat,-0.85f,Time.deltaTime*4.0f); followHeight = Mathf.Lerp(followHeight,1.8f,Time.deltaTime*4.0f); followDistance = Mathf.Lerp(followDistance,5.0f,Time.deltaTime*4.0f); axisSensitivity = new Vector2( Mathf.Lerp(axisSensitivity.x,mouseSensitivity.x,Time.deltaTime*4.0f), Mathf.Lerp(axisSensitivity.y,mouseSensitivity.y,Time.deltaTime*4.0f) ); cameraObject.GetComponent<Camera>().fieldOfView = camFOV; } //IDLE SETTINGS lerp camera back camFOV = Mathf.Lerp(camFOV,cameraFOV*setFOV,Time.deltaTime*4.0f); followLat = Mathf.Lerp(followLat,-0.4f,Time.deltaTime*4.0f); followHeight = Mathf.Lerp(followHeight,1.4f,Time.deltaTime*2.0f); axisSensitivity = new Vector2( Mathf.Lerp(axisSensitivity.x,mouseSensitivity.x,Time.deltaTime*4.0f), Mathf.Lerp(axisSensitivity.y,mouseSensitivity.y,Time.deltaTime*4.0f) ); //LOCK CURSOR Cursor.lockState = CursorLockMode.None; //--------------------------------- // SUIMONO SPECIFIC HANDLING //--------------------------------- // we use this to get the current Suimono plane water level (if applicable) from the // main Suimono Module object, then translate this into different walk / run speeds // based on water depth. //var waterLevel : float = suimonoModuleObject.GetWaterDepth(cameraTarget); if (suimonoModuleObject != null){ float waterLevel = suimonoModuleObject.SuimonoGetHeight(cameraTarget.position,"object depth"); isInWater = false; if (waterLevel < 0.0f) waterLevel = 0.0f; if (waterLevel > 0.0f){ isInWater = true; isInWaterDeep = false; isUnderWater = false; if (waterLevel >= 0.9f && waterLevel < 1.8f) isInWaterDeep = true; if (waterLevel >= 1.8f) isUnderWater = true; } } if (isControllable){ //--------------------------------- // CAMERA POSITIONING //--------------------------------- //Calculate Follow Distance float followLerpSpeed = 2.0f; followDistance -= (MouseScrollDistance*20.0f); followDistance = Mathf.Clamp(followDistance,minZoomAmount,maxZoomAmount); followTgtDistance = Mathf.Lerp(followTgtDistance,followDistance,Time.deltaTime*followLerpSpeed); // Calculate Rotation if (orbitView) camRotation = Mathf.Lerp(oldMouseRotation,MouseRotationDistance*axisSensitivity.x,Time.deltaTime); targetRotation.eulerAngles = new Vector3( targetRotation.eulerAngles.x, (targetRotation.eulerAngles.y+camRotation), targetRotation.eulerAngles.z ); cameraObject.transform.eulerAngles = new Vector3( targetRotation.eulerAngles.x, targetRotation.eulerAngles.y, cameraObject.transform.eulerAngles.z ); if (orbitView) camHeight = Mathf.Lerp(camHeight,camHeight+MouseVerticalDistance*axisSensitivity.y,Time.deltaTime); camHeight = Mathf.Clamp(camHeight,-45.0f,45.0f); // SET CAMERA POSITION and ROTATIONS cameraObject.transform.position = new Vector3( cameraTarget.transform.position.x+cameraOffset.x+(-cameraObject.transform.up.x*followTgtDistance), Mathf.Lerp(camHeight,cameraTarget.transform.position.y+cameraOffset.y+(-cameraObject.transform.up.y*followTgtDistance),Time.deltaTime*0.5f), cameraTarget.transform.position.z+cameraOffset.z+(-cameraObject.transform.up.z*followTgtDistance) ); cameraObject.transform.LookAt(new Vector3(targetPosition.x,targetPosition.y + followHeight,targetPosition.z)); } //--------------------------------- // SET CAMERA SETTINGS and FX //--------------------------------- if (isControllable){ //SET CAMERA SETTINGS cameraObject.GetComponent<Camera>().fieldOfView = camFOV; } } //------------------------------------ // SEND MODES TO CHARACTER ANIMATOR //------------------------------------ if (targetAnimator != null){ targetAnimator.isWalking = isWalking; targetAnimator.isRunning = isRunning; targetAnimator.isSprinting = isSprinting; targetAnimator.moveForward = moveForward; targetAnimator.moveSideways = moveSideways; targetAnimator.gSlope = gSlope; targetAnimator.useSlope = useSlope; targetAnimator.isInWater = isInWater; targetAnimator.isInWaterDeep = isInWaterDeep; targetAnimator.isUnderWater = isUnderWater; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net; using System.Reflection; using System.Threading.Tasks; using System.Threading; using NUnit.Framework; namespace Refit.Tests { [Headers("User-Agent: RefitTestClient", "Api-Version: 1")] public interface IRestMethodInfoTests { [Get("@)!@_!($_!@($\\\\|||::::")] Task<string> GarbagePath(); [Get("/foo/bar/{id}")] Task<string> FetchSomeStuffMissingParameters(); [Get("/foo/bar/{id}")] Task<string> FetchSomeStuff(int id); [Get("/foo/bar/{id}?baz=bamf")] Task<string> FetchSomeStuffWithHardcodedQueryParam(int id); [Get("/foo/bar/{id}?baz=bamf")] Task<string> FetchSomeStuffWithQueryParam(int id, string search); [Get("/foo/bar/{id}")] Task<string> FetchSomeStuffWithAlias([AliasAs("id")] int anId); [Get("/foo/bar/{width}x{height}")] Task<string> FetchAnImage(int width, int height); [Get("/foo/bar/{id}")] IObservable<string> FetchSomeStuffWithBody([AliasAs("id")] int anId, [Body] Dictionary<int, string> theData); [Post("/foo/bar/{id}")] IObservable<string> PostSomeUrlEncodedStuff([AliasAs("id")] int anId, [Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, string> theData); [Get("/foo/bar/{id}")] [Headers("Api-Version: 2 ")] Task<string> FetchSomeStuffWithHardcodedHeaders(int id); [Get("/foo/bar/{id}")] Task<string> FetchSomeStuffWithDynamicHeader(int id, [Header("Authorization")] string authorization); [Post("/foo/{id}")] Task<bool> OhYeahValueTypes(int id, [Body] int whatever); [Post("/foo/{id}")] Task VoidPost(int id); [Post("/foo/{id}")] string AsyncOnlyBuddy(int id); [Patch("/foo/{id}")] IObservable<string> PatchSomething(int id, [Body] string someAttribute); } [TestFixture] public class RestMethodInfoTests { [Test] public void GarbagePathsShouldThrow() { bool shouldDie = true; try { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "GarbagePath")); } catch (ArgumentException) { shouldDie = false; } Assert.IsFalse(shouldDie); } [Test] public void MissingParametersShouldBlowUp() { bool shouldDie = true; try { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffMissingParameters")); } catch (ArgumentException) { shouldDie = false; } Assert.IsFalse(shouldDie); } [Test] public void ParameterMappingSmokeTest() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuff")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.IsNull(fixture.BodyParameterInfo); } [Test] public void ParameterMappingWithQuerySmokeTest() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffWithQueryParam")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual("search", fixture.QueryParameterMap[1]); Assert.IsNull(fixture.BodyParameterInfo); } [Test] public void ParameterMappingWithHardcodedQuerySmokeTest() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffWithHardcodedQueryParam")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.IsNull(fixture.BodyParameterInfo); } [Test] public void AliasMappingShouldWork() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffWithAlias")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.IsNull(fixture.BodyParameterInfo); } [Test] public void MultipleParametersPerSegmentShouldWork() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchAnImage")); Assert.AreEqual("width", fixture.ParameterMap[0]); Assert.AreEqual("height", fixture.ParameterMap[1]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.IsNull(fixture.BodyParameterInfo); } [Test] public void FindTheBodyParameter() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffWithBody")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.IsNotNull(fixture.BodyParameterInfo); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.AreEqual(1, fixture.BodyParameterInfo.Item2); } [Test] public void AllowUrlEncodedContent() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "PostSomeUrlEncodedStuff")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.IsNotNull(fixture.BodyParameterInfo); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.AreEqual(BodySerializationMethod.UrlEncoded, fixture.BodyParameterInfo.Item1); } [Test] public void HardcodedHeadersShouldWork() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffWithHardcodedHeaders")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.IsNull(fixture.BodyParameterInfo); Assert.IsTrue(fixture.Headers.ContainsKey("Api-Version"), "Headers include Api-Version header"); Assert.AreEqual("2", fixture.Headers["Api-Version"]); Assert.IsTrue(fixture.Headers.ContainsKey("User-Agent"), "Headers include User-Agent header"); Assert.AreEqual("RefitTestClient", fixture.Headers["User-Agent"]); Assert.AreEqual(2, fixture.Headers.Count); } [Test] public void DynamicHeadersShouldWork() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "FetchSomeStuffWithDynamicHeader")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.IsNull(fixture.BodyParameterInfo); Assert.AreEqual("Authorization", fixture.HeaderParameterMap[1]); Assert.IsTrue(fixture.Headers.ContainsKey("User-Agent"), "Headers include User-Agent header"); Assert.AreEqual("RefitTestClient", fixture.Headers["User-Agent"]); Assert.AreEqual(2, fixture.Headers.Count); } [Test] public void ValueTypesDontBlowUp() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "OhYeahValueTypes")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(0, fixture.QueryParameterMap.Count); Assert.AreEqual(BodySerializationMethod.Json, fixture.BodyParameterInfo.Item1); Assert.AreEqual(1, fixture.BodyParameterInfo.Item2); Assert.AreEqual(typeof(bool), fixture.SerializedReturnType); } [Test] public void ReturningTaskShouldWork() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "VoidPost")); Assert.AreEqual("id", fixture.ParameterMap[0]); Assert.AreEqual(typeof(Task), fixture.ReturnType); Assert.AreEqual(typeof(void), fixture.SerializedReturnType); } [Test] public void SyncMethodsShouldThrow() { bool shouldDie = true; try { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "AsyncOnlyBuddy")); } catch (ArgumentException) { shouldDie = false; } Assert.IsFalse(shouldDie); } [Test] public void UsingThePatchAttributeSetsTheCorrectMethod() { var input = typeof(IRestMethodInfoTests); var fixture = new RestMethodInfo(input, input.GetMethods().First(x => x.Name == "PatchSomething")); Assert.AreEqual("PATCH", fixture.HttpMethod.Method); } } [Headers("User-Agent: RefitTestClient", "Api-Version: 1")] public interface IDummyHttpApi { [Get("/foo/bar/{id}")] Task<string> FetchSomeStuff(int id); [Get("/foo/bar/{id}?baz=bamf")] Task<string> FetchSomeStuffWithHardcodedQueryParameter(int id); [Get("/foo/bar/{id}?baz=bamf")] Task<string> FetchSomeStuffWithHardcodedAndOtherQueryParameters(int id, [AliasAs("search_for")] string searchQuery); [Get("/{id}/{width}x{height}/foo")] Task<string> FetchSomethingWithMultipleParametersPerSegment(int id, int width, int height); [Get("/foo/bar/{id}")] [Headers("Api-Version: 2")] Task<string> FetchSomeStuffWithHardcodedHeader(int id); [Get("/foo/bar/{id}")] [Headers("Api-Version")] Task<string> FetchSomeStuffWithNullHardcodedHeader(int id); [Get("/foo/bar/{id}")] [Headers("Api-Version: ")] Task<string> FetchSomeStuffWithEmptyHardcodedHeader(int id); [Post("/foo/bar/{id}")] [Headers("Content-Type: literally/anything")] Task<string> PostSomeStuffWithHardCodedContentTypeHeader(int id, [Body] string content); [Get("/foo/bar/{id}")] [Headers("Authorization: SRSLY aHR0cDovL2kuaW1ndXIuY29tL0NGRzJaLmdpZg==")] Task<string> FetchSomeStuffWithDynamicHeader(int id, [Header("Authorization")] string authorization); [Get("/foo/bar/{id}")] Task<string> FetchSomeStuffWithCustomHeader(int id, [Header("X-Emoji")] string custom); [Post("/foo/bar/{id}")] Task<string> PostSomeStuffWithCustomHeader(int id, [Body] object body, [Header("X-Emoji")] string emoji); [Get("/string")] Task<string> FetchSomeStuffWithoutFullPath(); [Get("/void")] Task FetchSomeStuffWithVoid(); [Post("/foo/bar/{id}")] Task<string> PostSomeUrlEncodedStuff(int id, [Body(BodySerializationMethod.UrlEncoded)] object content); [Post("/foo/bar/{id}")] Task<string> PostSomeAliasedUrlEncodedStuff(int id,[Body(BodySerializationMethod.UrlEncoded)] SomeRequestData content); string SomeOtherMethod(); [Put("/foo/bar/{id}")] Task PutSomeContentWithAuthorization(int id, [Body] object content, [Header("Authorization")] string authorization); [Put("/foo/bar/{id}")] Task<string> PutSomeStuffWithDynamicContentType(int id, [Body] string content, [Header("Content-Type")] string contentType); [Post("/foo/bar/{id}")] Task<bool> PostAValueType(int id, [Body] Guid? content); [Patch("/foo/bar/{id}")] IObservable<string> PatchSomething(int id, [Body] string someAttribute); } public class SomeRequestData { [AliasAs("rpn")] public int ReadablePropertyName { get; set; } } public class TestHttpMessageHandler : HttpMessageHandler { public HttpRequestMessage RequestMessage { get; private set; } public int MessagesSent { get; set; } public HttpContent Content { get; set; } public Func<HttpContent> ContentFactory { get; set; } public TestHttpMessageHandler(string content = "test") { Content = new StringContent(content); ContentFactory = () => Content; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { RequestMessage = request; MessagesSent++; return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = ContentFactory() }); } } public class TestUrlParameterFormatter : IUrlParameterFormatter { readonly string constantParameterOutput; public TestUrlParameterFormatter(string constantOutput) { constantParameterOutput = constantOutput; } public string Format(object value, ParameterInfo parameterInfo) { return constantParameterOutput; } } [TestFixture] public class RequestBuilderTests { [Test] public void HttpContentTest() { var fixture = new RequestBuilderImplementation(typeof(IHttpContentApi)); var factory = fixture.BuildRestResultFuncForMethod("PostFileUpload"); var testHttpMessageHandler = new TestHttpMessageHandler(); var retContent = new StreamContent(new MemoryStream()); testHttpMessageHandler.Content = retContent; var mpc = new MultipartContent("foosubtype"); var task = (Task<HttpContent>)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { mpc }); task.Wait(); Assert.AreEqual(testHttpMessageHandler.RequestMessage.Content, mpc); Assert.AreEqual(retContent, task.Result); } [Test] public void MethodsThatDontHaveAnHttpMethodShouldFail() { var failureMethods = new[] { "SomeOtherMethod", "weofjwoeijfwe", null, }; var successMethods = new[] { "FetchSomeStuff", }; foreach (var v in failureMethods) { bool shouldDie = true; try { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); fixture.BuildRequestFactoryForMethod(v); } catch (Exception) { shouldDie = false; } Assert.IsFalse(shouldDie); } foreach (var v in successMethods) { bool shouldDie = false; try { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); fixture.BuildRequestFactoryForMethod(v); } catch (Exception ex) { shouldDie = true; } Assert.IsFalse(shouldDie); } } [Test] public void HardcodedQueryParamShouldBeInUrl() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithHardcodedQueryParameter"); var output = factory(new object[] { 6 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.AreEqual("/foo/bar/6?baz=bamf", uri.PathAndQuery); } [Test] public void ParameterizedQueryParamsShouldBeInUrl() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithHardcodedAndOtherQueryParameters"); var output = factory(new object[] { 6, "foo" }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.AreEqual("/foo/bar/6?baz=bamf&search_for=foo", uri.PathAndQuery); } [Test] public void MultipleParametersInTheSameSegmentAreGeneratedProperly() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomethingWithMultipleParametersPerSegment"); var output = factory(new object[] { 6, 1024, 768 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.AreEqual("/6/1024x768/foo", uri.PathAndQuery); } [Test] public void HardcodedHeadersShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithHardcodedHeader"); var output = factory(new object[] { 6 }); Assert.IsTrue(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.AreEqual("RefitTestClient", output.Headers.UserAgent.ToString()); Assert.IsTrue(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); Assert.AreEqual("2", output.Headers.GetValues("Api-Version").Single()); } [Test] public void EmptyHardcodedHeadersShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithEmptyHardcodedHeader"); var output = factory(new object[] { 6 }); Assert.IsTrue(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.AreEqual("RefitTestClient", output.Headers.UserAgent.ToString()); Assert.IsTrue(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); Assert.AreEqual("", output.Headers.GetValues("Api-Version").Single()); } [Test] public void NullHardcodedHeadersShouldNotBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithNullHardcodedHeader"); var output = factory(new object[] { 6 }); Assert.IsTrue(output.Headers.Contains("User-Agent"), "Headers include User-Agent header"); Assert.AreEqual("RefitTestClient", output.Headers.UserAgent.ToString()); Assert.IsFalse(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); } [Test] public void ContentHeadersCanBeHardcoded() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PostSomeStuffWithHardCodedContentTypeHeader"); var output = factory(new object[] { 6, "stuff" }); Assert.IsTrue(output.Content.Headers.Contains("Content-Type"), "Content headers include Content-Type header"); Assert.AreEqual("literally/anything", output.Content.Headers.ContentType.ToString()); } [Test] public void DynamicHeaderShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithDynamicHeader"); var output = factory(new object[] { 6, "Basic RnVjayB5ZWFoOmhlYWRlcnMh" }); Assert.IsNotNull(output.Headers.Authorization, "Headers include Authorization header"); Assert.AreEqual("RnVjayB5ZWFoOmhlYWRlcnMh", output.Headers.Authorization.Parameter); } [Test] public void CustomDynamicHeaderShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithCustomHeader"); var output = factory(new object[] { 6, ":joy_cat:" }); Assert.IsTrue(output.Headers.Contains("X-Emoji"), "Headers include X-Emoji header"); Assert.AreEqual(":joy_cat:", output.Headers.GetValues("X-Emoji").First()); } [Test] public void EmptyDynamicHeaderShouldBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithCustomHeader"); var output = factory(new object[] { 6, "" }); Assert.IsTrue(output.Headers.Contains("X-Emoji"), "Headers include X-Emoji header"); Assert.AreEqual("", output.Headers.GetValues("X-Emoji").First()); } [Test] public void NullDynamicHeaderShouldNotBeInHeaders() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuffWithDynamicHeader"); var output = factory(new object[] { 6, null }); Assert.IsNull(output.Headers.Authorization, "Headers include Authorization header"); } [Test] public void AddCustomHeadersToRequestHeadersOnly() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PostSomeStuffWithCustomHeader"); var output = factory(new object[] { 6, new { Foo = "bar" }, ":smile_cat:" }); Assert.IsTrue(output.Headers.Contains("Api-Version"), "Headers include Api-Version header"); Assert.IsTrue(output.Headers.Contains("X-Emoji"), "Headers include X-Emoji header"); Assert.IsFalse(output.Content.Headers.Contains("Api-Version"), "Content headers include Api-Version header"); Assert.IsFalse(output.Content.Headers.Contains("X-Emoji"), "Content headers include X-Emoji header"); } [Test] public void HttpClientShouldPrefixedAbsolutePathToTheRequestUri() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStuffWithoutFullPath"); var testHttpMessageHandler = new TestHttpMessageHandler(); var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/foo/bar") }, new object[0]); task.Wait(); Assert.AreEqual("http://api/foo/bar/string", testHttpMessageHandler.RequestMessage.RequestUri.ToString()); } [Test] public void HttpClientForVoidMethodShouldPrefixedAbsolutePathToTheRequestUri() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStuffWithVoid"); var testHttpMessageHandler = new TestHttpMessageHandler(); var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/foo/bar") }, new object[0]); task.Wait(); Assert.AreEqual("http://api/foo/bar/void", testHttpMessageHandler.RequestMessage.RequestUri.ToString()); } [Test] public void HttpClientShouldNotPrefixEmptyAbsolutePathToTheRequestUri() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRestResultFuncForMethod("FetchSomeStuff"); var testHttpMessageHandler = new TestHttpMessageHandler(); var task = (Task)factory(new HttpClient(testHttpMessageHandler) { BaseAddress = new Uri("http://api/") }, new object[] { 42 }); task.Wait(); Assert.AreEqual("http://api/foo/bar/42", testHttpMessageHandler.RequestMessage.RequestUri.ToString()); } [Test] public void DontBlowUpWithDynamicAuthorizationHeaderAndContent() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PutSomeContentWithAuthorization"); var output = factory(new object[] { 7, new { Octocat = "Dunetocat" }, "Basic RnVjayB5ZWFoOmhlYWRlcnMh" }); Assert.IsNotNull(output.Headers.Authorization, "Headers include Authorization header"); Assert.AreEqual("RnVjayB5ZWFoOmhlYWRlcnMh", output.Headers.Authorization.Parameter); } [Test] public void SuchFlexibleContentTypeWow() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PutSomeStuffWithDynamicContentType"); var output = factory(new object[] { 7, "such \"refit\" is \"amaze\" wow", "text/dson" }); Assert.IsNotNull(output.Content, "Request has content"); Assert.IsNotNull(output.Content.Headers.ContentType, "Headers include Content-Type header"); Assert.AreEqual("text/dson", output.Content.Headers.ContentType.MediaType, "Content-Type header has the expected value"); } [Test] public async Task BodyContentGetsUrlEncoded() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PostSomeUrlEncodedStuff"); var output = factory( new object[] { 6, new { Foo = "Something", Bar = 100, Baz = default(string) } }); string content = await output.Content.ReadAsStringAsync(); Assert.AreEqual("Foo=Something&Bar=100&Baz=", content); } [Test] public async Task FormFieldGetsAliased() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PostSomeAliasedUrlEncodedStuff"); var output = factory( new object[] { 6, new SomeRequestData { ReadablePropertyName = 99 } }); string content = await output.Content.ReadAsStringAsync(); Assert.AreEqual("rpn=99", content); } [Test] public async Task CustomParmeterFormatter() { var settings = new RefitSettings { UrlParameterFormatter = new TestUrlParameterFormatter("custom-parameter") }; var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi), settings); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuff"); var output = factory(new object[] { 5 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.AreEqual("/foo/bar/custom-parameter", uri.PathAndQuery); } [Test] public async Task ICanPostAValueTypeIfIWantYoureNotTheBossOfMe() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PostAValueType"); var guid = Guid.NewGuid(); var expected = string.Format("\"{0}\"", guid); var output = factory(new object[] { 7, guid }); var content = await output.Content.ReadAsStringAsync(); Assert.AreEqual(expected, content); } [Test] public async Task SupportPATCHMethod() { var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi)); var factory = fixture.BuildRequestFactoryForMethod("PatchSomething"); var output = factory(new object[] { "testData" }); Assert.AreEqual("PATCH", output.Method.Method); } } }
/* The MIT License (MIT) Copyright (c) 2007 - 2020 Microting A/S Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microting.eForm.Infrastructure.Constants; using Microting.eForm.Infrastructure.Data.Entities; using NUnit.Framework; namespace eFormSDK.InSight.Tests { [TestFixture] public class QuestionsUTest : DbTestFixture { [Test] public async Task Questions_Create_DoesCreate() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSetForQuestion = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, ParentId = rnd.Next(1, 255), PossiblyDeployed = randomBool }; await questionSetForQuestion.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, ContinuousQuestionId = rnd.Next(1, 255), QuestionSetId = questionSetForQuestion.Id }; //Act await question.Create(DbContext).ConfigureAwait(false); List<Question> questions = DbContext.Questions.AsNoTracking().ToList(); List<QuestionVersion> questionVersions = DbContext.QuestionVersions.AsNoTracking().ToList(); Assert.NotNull(questions); Assert.NotNull(questionVersions); Assert.AreEqual(1,questions.Count()); Assert.AreEqual(1,questionVersions.Count()); Assert.AreEqual(question.CreatedAt.ToString(), questions[0].CreatedAt.ToString()); Assert.AreEqual(question.Version, questions[0].Version); // Assert.AreEqual(question.UpdatedAt.ToString(), questions[0].UpdatedAt.ToString()); Assert.AreEqual(questions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(question.Id, questionVersions[0].Id); Assert.AreEqual(question.Image, questions[0].Image); Assert.AreEqual(question.Maximum, questions[0].Maximum); Assert.AreEqual(question.Minimum, questions[0].Minimum); Assert.AreEqual(question.Prioritised, questions[0].Prioritised); Assert.AreEqual(question.Type, questions[0].Type); Assert.AreEqual(question.FontSize, questions[0].FontSize); Assert.AreEqual(question.ImagePosition, questions[0].ImagePosition); Assert.AreEqual(question.MaxDuration, questions[0].MaxDuration); Assert.AreEqual(question.MinDuration, questions[0].MinDuration); Assert.AreEqual(question.QuestionIndex, questions[0].QuestionIndex); Assert.AreEqual(question.QuestionType, questions[0].QuestionType); Assert.AreEqual(question.RefId, questions[0].RefId); Assert.AreEqual(question.ValidDisplay, questions[0].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questions[0].BackButtonEnabled); Assert.AreEqual(question.QuestionSetId, questionSetForQuestion.Id); //Versions Assert.AreEqual(question.CreatedAt.ToString(), questionVersions[0].CreatedAt.ToString()); Assert.AreEqual(1, questionVersions[0].Version); // Assert.AreEqual(question.UpdatedAt.ToString(), questionVersions[0].UpdatedAt.ToString()); Assert.AreEqual(questionVersions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(question.Id, questionVersions[0].QuestionId); Assert.AreEqual(question.Image, questionVersions[0].Image); Assert.AreEqual(question.Maximum, questionVersions[0].Maximum); Assert.AreEqual(question.Minimum, questionVersions[0].Minimum); Assert.AreEqual(question.Prioritised, questionVersions[0].Prioritised); Assert.AreEqual(question.Type, questionVersions[0].Type); Assert.AreEqual(question.FontSize, questionVersions[0].FontSize); Assert.AreEqual(question.ImagePosition, questionVersions[0].ImagePosition); Assert.AreEqual(question.MaxDuration, questionVersions[0].MaxDuration); Assert.AreEqual(question.MinDuration, questionVersions[0].MinDuration); Assert.AreEqual(question.QuestionIndex, questionVersions[0].QuestionIndex); Assert.AreEqual(question.QuestionType, questionVersions[0].QuestionType); Assert.AreEqual(question.RefId, questionVersions[0].RefId); Assert.AreEqual(question.ValidDisplay, questionVersions[0].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questionVersions[0].BackButtonEnabled); Assert.AreEqual(questionSetForQuestion.Id, questionVersions[0].QuestionSetId); } [Test] public async Task Questions_Update_DoesUpdate() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSetForQuestion = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, ParentId = rnd.Next(1, 255), PossiblyDeployed = randomBool }; await questionSetForQuestion.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, ContinuousQuestionId = rnd.Next(1, 255), QuestionSetId = questionSetForQuestion.Id }; await question.Create(DbContext).ConfigureAwait(false); //Act DateTime? oldUpdatedAt = question.UpdatedAt; bool oldImage = question.Image; int? oldMaximum = question.Maximum; int? oldMinimum = question.Minimum; bool oldPrioritised = question.Prioritised; string oldType = question.Type; string oldFontSize = question.FontSize; string oldImagePosition = question.ImagePosition; int? oldMaxDuration = question.MaxDuration; int? oldMinDuration = question.MinDuration; int? oldQuestionIndex = question.QuestionIndex; string oldQuestionType = question.QuestionType; int? oldRefId = question.RefId; bool oldValidDisplau = question.ValidDisplay; bool oldBackButtonEnabled = question.BackButtonEnabled; question.Image = randomBool; question.Maximum = rnd.Next(1, 255); question.Minimum = rnd.Next(1, 255); question.Prioritised = randomBool; question.Type = Guid.NewGuid().ToString(); question.FontSize = Guid.NewGuid().ToString(); question.ImagePosition = Guid.NewGuid().ToString(); question.MaxDuration = rnd.Next(1, 255); question.MinDuration = rnd.Next(1, 255); question.QuestionIndex = rnd.Next(1, 255); question.QuestionType = Guid.NewGuid().ToString(); question.RefId = rnd.Next(1, 255); question.ValidDisplay = randomBool; question.BackButtonEnabled = randomBool; question.ContinuousQuestionId = rnd.Next(1, 255); await question.Update(DbContext).ConfigureAwait(false); List<Question> questions = DbContext.Questions.AsNoTracking().ToList(); List<QuestionVersion> questionVersions = DbContext.QuestionVersions.AsNoTracking().ToList(); Assert.NotNull(questions); Assert.NotNull(questionVersions); Assert.AreEqual(1,questions.Count()); Assert.AreEqual(2,questionVersions.Count()); Assert.AreEqual(question.CreatedAt.ToString(), questions[0].CreatedAt.ToString()); Assert.AreEqual(question.Version, questions[0].Version); // Assert.AreEqual(question.UpdatedAt.ToString(), questions[0].UpdatedAt.ToString()); Assert.AreEqual(questions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(question.Id, questionVersions[0].Id); Assert.AreEqual(question.Image, questions[0].Image); Assert.AreEqual(question.Maximum, questions[0].Maximum); Assert.AreEqual(question.Minimum, questions[0].Minimum); Assert.AreEqual(question.Prioritised, questions[0].Prioritised); Assert.AreEqual(question.Type, questions[0].Type); Assert.AreEqual(question.FontSize, questions[0].FontSize); Assert.AreEqual(question.ImagePosition, questions[0].ImagePosition); Assert.AreEqual(question.MaxDuration, questions[0].MaxDuration); Assert.AreEqual(question.MinDuration, questions[0].MinDuration); Assert.AreEqual(question.QuestionIndex, questions[0].QuestionIndex); Assert.AreEqual(question.QuestionType, questions[0].QuestionType); Assert.AreEqual(question.RefId, questions[0].RefId); Assert.AreEqual(question.ValidDisplay, questions[0].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questions[0].BackButtonEnabled); Assert.AreEqual(question.QuestionSetId, questionSetForQuestion.Id); //Old Version Assert.AreEqual(question.CreatedAt.ToString(), questionVersions[0].CreatedAt.ToString()); Assert.AreEqual(1, questionVersions[0].Version); // Assert.AreEqual(oldUpdatedAt.ToString(), questionVersions[0].UpdatedAt.ToString()); Assert.AreEqual(questionVersions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(question.Id, questionVersions[0].QuestionId); Assert.AreEqual(oldImage, questionVersions[0].Image); Assert.AreEqual(oldMaximum, questionVersions[0].Maximum); Assert.AreEqual(oldMinimum, questionVersions[0].Minimum); Assert.AreEqual(oldPrioritised, questionVersions[0].Prioritised); Assert.AreEqual(oldType, questionVersions[0].Type); Assert.AreEqual(oldFontSize, questionVersions[0].FontSize); Assert.AreEqual(oldImagePosition, questionVersions[0].ImagePosition); Assert.AreEqual(oldMaxDuration, questionVersions[0].MaxDuration); Assert.AreEqual(oldMinDuration, questionVersions[0].MinDuration); Assert.AreEqual(oldQuestionIndex, questionVersions[0].QuestionIndex); Assert.AreEqual(oldQuestionType, questionVersions[0].QuestionType); Assert.AreEqual(oldRefId, questionVersions[0].RefId); Assert.AreEqual(oldValidDisplau, questionVersions[0].ValidDisplay); Assert.AreEqual(oldBackButtonEnabled, questionVersions[0].BackButtonEnabled); Assert.AreEqual(questionSetForQuestion.Id, questionVersions[0].QuestionSetId); //New Version Assert.AreEqual(question.CreatedAt.ToString(), questionVersions[1].CreatedAt.ToString()); Assert.AreEqual(2, questionVersions[1].Version); // Assert.AreEqual(question.UpdatedAt.ToString(), questionVersions[1].UpdatedAt.ToString()); Assert.AreEqual(questionVersions[1].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(question.Id, questionVersions[0].QuestionId); Assert.AreEqual(question.Image, questionVersions[1].Image); Assert.AreEqual(question.Maximum, questionVersions[1].Maximum); Assert.AreEqual(question.Minimum, questionVersions[1].Minimum); Assert.AreEqual(question.Prioritised, questionVersions[1].Prioritised); Assert.AreEqual(question.Type, questionVersions[1].Type); Assert.AreEqual(question.FontSize, questionVersions[1].FontSize); Assert.AreEqual(question.ImagePosition, questionVersions[1].ImagePosition); Assert.AreEqual(question.MaxDuration, questionVersions[1].MaxDuration); Assert.AreEqual(question.MinDuration, questionVersions[1].MinDuration); Assert.AreEqual(question.QuestionIndex, questionVersions[1].QuestionIndex); Assert.AreEqual(question.QuestionType, questionVersions[1].QuestionType); Assert.AreEqual(question.RefId, questionVersions[1].RefId); Assert.AreEqual(question.ValidDisplay, questionVersions[1].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questionVersions[1].BackButtonEnabled); Assert.AreEqual(questionSetForQuestion.Id, questionVersions[1].QuestionSetId); } [Test] public async Task Questions_Delete_DoesSetWorkflowStateToRemoved() { //Arrange Random rnd = new Random(); bool randomBool = rnd.Next(0, 2) > 0; QuestionSet questionSetForQuestion = new QuestionSet { Name = Guid.NewGuid().ToString(), Share = randomBool, HasChild = randomBool, ParentId = rnd.Next(1, 255), PossiblyDeployed = randomBool }; await questionSetForQuestion.Create(DbContext).ConfigureAwait(false); Question question = new Question { Image = randomBool, Maximum = rnd.Next(1, 255), Minimum = rnd.Next(1, 255), Prioritised = randomBool, Type = Guid.NewGuid().ToString(), FontSize = Guid.NewGuid().ToString(), ImagePosition = Guid.NewGuid().ToString(), MaxDuration = rnd.Next(1, 255), MinDuration = rnd.Next(1, 255), QuestionIndex = rnd.Next(1, 255), QuestionType = Guid.NewGuid().ToString(), RefId = rnd.Next(1, 255), ValidDisplay = randomBool, BackButtonEnabled = randomBool, ContinuousQuestionId = rnd.Next(1, 255), QuestionSetId = questionSetForQuestion.Id }; await question.Create(DbContext).ConfigureAwait(false); //Act DateTime? oldUpdatedAt = question.UpdatedAt; await question.Delete(DbContext); List<Question> questions = DbContext.Questions.AsNoTracking().ToList(); List<QuestionVersion> questionVersions = DbContext.QuestionVersions.AsNoTracking().ToList(); Assert.NotNull(questions); Assert.NotNull(questionVersions); Assert.AreEqual(1,questions.Count()); Assert.AreEqual(2,questionVersions.Count()); Assert.AreEqual(question.CreatedAt.ToString(), questions[0].CreatedAt.ToString()); Assert.AreEqual(question.Version, questions[0].Version); // Assert.AreEqual(question.UpdatedAt.ToString(), questions[0].UpdatedAt.ToString()); Assert.AreEqual(questions[0].WorkflowState, Constants.WorkflowStates.Removed); Assert.AreEqual(question.Id, questionVersions[0].Id); Assert.AreEqual(question.Image, questions[0].Image); Assert.AreEqual(question.Maximum, questions[0].Maximum); Assert.AreEqual(question.Minimum, questions[0].Minimum); Assert.AreEqual(question.Prioritised, questions[0].Prioritised); Assert.AreEqual(question.Type, questions[0].Type); Assert.AreEqual(question.FontSize, questions[0].FontSize); Assert.AreEqual(question.ImagePosition, questions[0].ImagePosition); Assert.AreEqual(question.MaxDuration, questions[0].MaxDuration); Assert.AreEqual(question.MinDuration, questions[0].MinDuration); Assert.AreEqual(question.QuestionIndex, questions[0].QuestionIndex); Assert.AreEqual(question.QuestionType, questions[0].QuestionType); Assert.AreEqual(question.RefId, questions[0].RefId); Assert.AreEqual(question.ValidDisplay, questions[0].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questions[0].BackButtonEnabled); Assert.AreEqual(question.QuestionSetId, questionSetForQuestion.Id); //Old Version Assert.AreEqual(question.CreatedAt.ToString(), questionVersions[0].CreatedAt.ToString()); Assert.AreEqual(1, questionVersions[0].Version); // Assert.AreEqual(oldUpdatedAt.ToString(), questionVersions[0].UpdatedAt.ToString()); Assert.AreEqual(questionVersions[0].WorkflowState, Constants.WorkflowStates.Created); Assert.AreEqual(question.Id, questionVersions[0].QuestionId); Assert.AreEqual(question.Image, questionVersions[0].Image); Assert.AreEqual(question.Maximum, questionVersions[0].Maximum); Assert.AreEqual(question.Minimum, questionVersions[0].Minimum); Assert.AreEqual(question.Prioritised, questionVersions[0].Prioritised); Assert.AreEqual(question.Type, questionVersions[0].Type); Assert.AreEqual(question.FontSize, questionVersions[0].FontSize); Assert.AreEqual(question.ImagePosition, questionVersions[0].ImagePosition); Assert.AreEqual(question.MaxDuration, questionVersions[0].MaxDuration); Assert.AreEqual(question.MinDuration, questionVersions[0].MinDuration); Assert.AreEqual(question.QuestionIndex, questionVersions[0].QuestionIndex); Assert.AreEqual(question.QuestionType, questionVersions[0].QuestionType); Assert.AreEqual(question.RefId, questionVersions[0].RefId); Assert.AreEqual(question.ValidDisplay, questionVersions[0].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questionVersions[0].BackButtonEnabled); Assert.AreEqual(questionSetForQuestion.Id, questionVersions[0].QuestionSetId); //New Version Assert.AreEqual(question.CreatedAt.ToString(), questionVersions[1].CreatedAt.ToString()); Assert.AreEqual(2, questionVersions[1].Version); // Assert.AreEqual(question.UpdatedAt.ToString(), questionVersions[1].UpdatedAt.ToString()); Assert.AreEqual(questionVersions[1].WorkflowState, Constants.WorkflowStates.Removed); Assert.AreEqual(question.Id, questionVersions[0].QuestionId); Assert.AreEqual(question.Image, questionVersions[1].Image); Assert.AreEqual(question.Maximum, questionVersions[1].Maximum); Assert.AreEqual(question.Minimum, questionVersions[1].Minimum); Assert.AreEqual(question.Prioritised, questionVersions[1].Prioritised); Assert.AreEqual(question.Type, questionVersions[1].Type); Assert.AreEqual(question.FontSize, questionVersions[1].FontSize); Assert.AreEqual(question.ImagePosition, questionVersions[1].ImagePosition); Assert.AreEqual(question.MaxDuration, questionVersions[1].MaxDuration); Assert.AreEqual(question.MinDuration, questionVersions[1].MinDuration); Assert.AreEqual(question.QuestionIndex, questionVersions[1].QuestionIndex); Assert.AreEqual(question.QuestionType, questionVersions[1].QuestionType); Assert.AreEqual(question.RefId, questionVersions[1].RefId); Assert.AreEqual(question.ValidDisplay, questionVersions[1].ValidDisplay); Assert.AreEqual(question.BackButtonEnabled, questionVersions[1].BackButtonEnabled); Assert.AreEqual(questionSetForQuestion.Id, questionVersions[1].QuestionSetId); } } }
// // https://github.com/mythz/ServiceStack.Redis // ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2013 ServiceStack. // // Licensed under the same terms of Redis and ServiceStack: new BSD license. // using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace ServiceStack.Redis.Generic { internal class RedisClientList<T> : IRedisList<T> { private readonly RedisTypedClient<T> client; private readonly string listId; private const int PageLimit = 1000; public RedisClientList(RedisTypedClient<T> client, string listId) { this.listId = listId; this.client = client; } public string Id { get { return listId; } } public IEnumerator<T> GetEnumerator() { return this.Count <= PageLimit ? client.GetAllItemsFromList(this).GetEnumerator() : GetPagingEnumerator(); } public IEnumerator<T> GetPagingEnumerator() { var skip = 0; List<T> pageResults; do { pageResults = client.GetRangeFromList(this, skip, PageLimit); foreach (var result in pageResults) { yield return result; } skip += PageLimit; } while (pageResults.Count == PageLimit); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(T item) { client.AddItemToList(this, item); } public void Clear() { client.RemoveAllFromList(this); } public bool Contains(T item) { //TODO: replace with native implementation when exists foreach (var existingItem in this) { if (Equals(existingItem, item)) return true; } return false; } public void CopyTo(T[] array, int arrayIndex) { var allItemsInList = client.GetAllItemsFromList(this); allItemsInList.CopyTo(array, arrayIndex); } public bool Remove(T item) { var index = this.IndexOf(item); if (index != -1) { this.RemoveAt(index); return true; } return false; } public int Count { get { return (int)client.GetListCount(this); } } public bool IsReadOnly { get { return false; } } public int IndexOf(T item) { //TODO: replace with native implementation when exists var i = 0; foreach (var existingItem in this) { if (Equals(existingItem, item)) return i; i++; } return -1; } public void Insert(int index, T item) { client.InsertAfterItemInList(this, this[index], item); } public void RemoveAt(int index) { //TODO: replace with native implementation when one exists var markForDelete = Guid.NewGuid().ToString(); client.NativeClient.LSet(listId, index, Encoding.UTF8.GetBytes(markForDelete)); const int removeAll = 0; client.NativeClient.LRem(listId, removeAll, Encoding.UTF8.GetBytes(markForDelete)); } public T this[int index] { get { return client.GetItemFromList(this, index); } set { client.SetItemInList(this, index, value); } } public List<T> GetAll() { return client.GetAllItemsFromList(this); } public List<T> GetRange(int startingFrom, int endingAt) { return client.GetRangeFromList(this, startingFrom, endingAt); } public List<T> GetRangeFromSortedList(int startingFrom, int endingAt) { return client.SortList(this, startingFrom, endingAt); } public void RemoveAll() { client.RemoveAllFromList(this); } public void Trim(int keepStartingFrom, int keepEndingAt) { client.TrimList(this, keepStartingFrom, keepEndingAt); } public long RemoveValue(T value) { return client.RemoveItemFromList(this, value); } public long RemoveValue(T value, int noOfMatches) { return client.RemoveItemFromList(this, value, noOfMatches); } public void AddRange(IEnumerable<T> values) { client.AddRangeToList(this, values); } public void Append(T value) { Add(value); } public void Prepend(T value) { client.PrependItemToList(this, value); } public T RemoveStart() { return client.RemoveStartFromList(this); } public T BlockingRemoveStart(TimeSpan? timeOut) { return client.BlockingRemoveStartFromList(this, timeOut); } public T RemoveEnd() { return client.RemoveEndFromList(this); } public void Enqueue(T value) { client.EnqueueItemOnList(this, value); } public T Dequeue() { return client.DequeueItemFromList(this); } public T BlockingDequeue(TimeSpan? timeOut) { return client.BlockingDequeueItemFromList(this, timeOut); } public void Push(T value) { client.PushItemToList(this, value); } public T Pop() { return client.PopItemFromList(this); } public T BlockingPop(TimeSpan? timeOut) { return client.BlockingPopItemFromList(this, timeOut); } public T PopAndPush(IRedisList<T> toList) { return client.PopAndPushItemBetweenLists(this, toList); } public T BlockingPopAndPush(IRedisList<T> toList, TimeSpan? timeOut) { return client.BlockingPopAndPushItemBetweenLists(this, toList, timeOut); } } }
namespace android.graphics { [global::MonoJavaBridge.JavaClass()] public partial class Region : java.lang.Object, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Region() { InitJNI(); } protected Region(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public sealed partial class Op : java.lang.Enum { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Op() { InitJNI(); } internal Op(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _values3748; public static global::android.graphics.Region.Op[] values() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.Region.Op>(@__env.CallStaticObjectMethod(android.graphics.Region.Op.staticClass, global::android.graphics.Region.Op._values3748)) as android.graphics.Region.Op[]; } internal static global::MonoJavaBridge.MethodId _valueOf3749; public static global::android.graphics.Region.Op valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.Region.Op.staticClass, global::android.graphics.Region.Op._valueOf3749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Region.Op; } internal static global::MonoJavaBridge.FieldId _DIFFERENCE3750; public static global::android.graphics.Region.Op DIFFERENCE { get { return default(global::android.graphics.Region.Op); } } internal static global::MonoJavaBridge.FieldId _INTERSECT3751; public static global::android.graphics.Region.Op INTERSECT { get { return default(global::android.graphics.Region.Op); } } internal static global::MonoJavaBridge.FieldId _REPLACE3752; public static global::android.graphics.Region.Op REPLACE { get { return default(global::android.graphics.Region.Op); } } internal static global::MonoJavaBridge.FieldId _REVERSE_DIFFERENCE3753; public static global::android.graphics.Region.Op REVERSE_DIFFERENCE { get { return default(global::android.graphics.Region.Op); } } internal static global::MonoJavaBridge.FieldId _UNION3754; public static global::android.graphics.Region.Op UNION { get { return default(global::android.graphics.Region.Op); } } internal static global::MonoJavaBridge.FieldId _XOR3755; public static global::android.graphics.Region.Op XOR { get { return default(global::android.graphics.Region.Op); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Region.Op.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Region$Op")); global::android.graphics.Region.Op._values3748 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Region.Op.staticClass, "values", "()[Landroid/graphics/Region/Op;"); global::android.graphics.Region.Op._valueOf3749 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Region.Op.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Region$Op;"); } } internal static global::MonoJavaBridge.MethodId _finalize3756; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Region._finalize3756); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._finalize3756); } internal static global::MonoJavaBridge.MethodId _equals3757; public override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._equals3757, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._equals3757, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isEmpty3758; public virtual bool isEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._isEmpty3758); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._isEmpty3758); } internal static global::MonoJavaBridge.MethodId _contains3759; public virtual bool contains(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._contains3759, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._contains3759, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _set3760; public virtual bool set(android.graphics.Region arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._set3760, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._set3760, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _set3761; public virtual bool set(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._set3761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._set3761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _set3762; public virtual bool set(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._set3762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._set3762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _union3763; public virtual bool union(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._union3763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._union3763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _writeToParcel3764; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Region._writeToParcel3764, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._writeToParcel3764, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents3765; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.Region._describeContents3765); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._describeContents3765); } internal static global::MonoJavaBridge.MethodId _getBounds3766; public virtual global::android.graphics.Rect getBounds() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Region._getBounds3766)) as android.graphics.Rect; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._getBounds3766)) as android.graphics.Rect; } internal static global::MonoJavaBridge.MethodId _getBounds3767; public virtual bool getBounds(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._getBounds3767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._getBounds3767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _translate3768; public virtual void translate(int arg0, int arg1, android.graphics.Region arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Region._translate3768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._translate3768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _translate3769; public virtual void translate(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Region._translate3769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._translate3769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _op3770; public virtual bool op(android.graphics.Rect arg0, android.graphics.Region arg1, android.graphics.Region.Op arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._op3770, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._op3770, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _op3771; public virtual bool op(int arg0, int arg1, int arg2, int arg3, android.graphics.Region.Op arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._op3771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._op3771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _op3772; public virtual bool op(android.graphics.Rect arg0, android.graphics.Region.Op arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._op3772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._op3772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _op3773; public virtual bool op(android.graphics.Region arg0, android.graphics.Region arg1, android.graphics.Region.Op arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._op3773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._op3773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _op3774; public virtual bool op(android.graphics.Region arg0, android.graphics.Region.Op arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._op3774, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._op3774, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _quickReject3775; public virtual bool quickReject(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._quickReject3775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._quickReject3775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _quickReject3776; public virtual bool quickReject(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._quickReject3776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._quickReject3776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _quickReject3777; public virtual bool quickReject(android.graphics.Region arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._quickReject3777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._quickReject3777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setEmpty3778; public virtual void setEmpty() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Region._setEmpty3778); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._setEmpty3778); } internal static global::MonoJavaBridge.MethodId _setPath3779; public virtual bool setPath(android.graphics.Path arg0, android.graphics.Region arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._setPath3779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._setPath3779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isRect3780; public virtual bool isRect() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._isRect3780); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._isRect3780); } internal static global::MonoJavaBridge.MethodId _isComplex3781; public virtual bool isComplex() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._isComplex3781); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._isComplex3781); } internal static global::MonoJavaBridge.MethodId _getBoundaryPath3782; public virtual global::android.graphics.Path getBoundaryPath() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Region._getBoundaryPath3782)) as android.graphics.Path; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._getBoundaryPath3782)) as android.graphics.Path; } internal static global::MonoJavaBridge.MethodId _getBoundaryPath3783; public virtual bool getBoundaryPath(android.graphics.Path arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._getBoundaryPath3783, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._getBoundaryPath3783, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _quickContains3784; public virtual bool quickContains(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._quickContains3784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._quickContains3784, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _quickContains3785; public virtual bool quickContains(android.graphics.Rect arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Region._quickContains3785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Region.staticClass, global::android.graphics.Region._quickContains3785, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _Region3786; public Region() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Region.staticClass, global::android.graphics.Region._Region3786); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Region3787; public Region(android.graphics.Region arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Region.staticClass, global::android.graphics.Region._Region3787, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Region3788; public Region(android.graphics.Rect arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Region.staticClass, global::android.graphics.Region._Region3788, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Region3789; public Region(int arg0, int arg1, int arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Region.staticClass, global::android.graphics.Region._Region3789, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _CREATOR3790; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Region.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Region")); global::android.graphics.Region._finalize3756 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "finalize", "()V"); global::android.graphics.Region._equals3757 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::android.graphics.Region._isEmpty3758 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "isEmpty", "()Z"); global::android.graphics.Region._contains3759 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "contains", "(II)Z"); global::android.graphics.Region._set3760 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "set", "(Landroid/graphics/Region;)Z"); global::android.graphics.Region._set3761 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "set", "(IIII)Z"); global::android.graphics.Region._set3762 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "set", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Region._union3763 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "union", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Region._writeToParcel3764 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.graphics.Region._describeContents3765 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "describeContents", "()I"); global::android.graphics.Region._getBounds3766 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "getBounds", "()Landroid/graphics/Rect;"); global::android.graphics.Region._getBounds3767 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "getBounds", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Region._translate3768 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "translate", "(IILandroid/graphics/Region;)V"); global::android.graphics.Region._translate3769 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "translate", "(II)V"); global::android.graphics.Region._op3770 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "op", "(Landroid/graphics/Rect;Landroid/graphics/Region;Landroid/graphics/Region$Op;)Z"); global::android.graphics.Region._op3771 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "op", "(IIIILandroid/graphics/Region$Op;)Z"); global::android.graphics.Region._op3772 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "op", "(Landroid/graphics/Rect;Landroid/graphics/Region$Op;)Z"); global::android.graphics.Region._op3773 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "op", "(Landroid/graphics/Region;Landroid/graphics/Region;Landroid/graphics/Region$Op;)Z"); global::android.graphics.Region._op3774 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "op", "(Landroid/graphics/Region;Landroid/graphics/Region$Op;)Z"); global::android.graphics.Region._quickReject3775 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "quickReject", "(IIII)Z"); global::android.graphics.Region._quickReject3776 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "quickReject", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Region._quickReject3777 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "quickReject", "(Landroid/graphics/Region;)Z"); global::android.graphics.Region._setEmpty3778 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "setEmpty", "()V"); global::android.graphics.Region._setPath3779 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "setPath", "(Landroid/graphics/Path;Landroid/graphics/Region;)Z"); global::android.graphics.Region._isRect3780 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "isRect", "()Z"); global::android.graphics.Region._isComplex3781 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "isComplex", "()Z"); global::android.graphics.Region._getBoundaryPath3782 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "getBoundaryPath", "()Landroid/graphics/Path;"); global::android.graphics.Region._getBoundaryPath3783 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "getBoundaryPath", "(Landroid/graphics/Path;)Z"); global::android.graphics.Region._quickContains3784 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "quickContains", "(IIII)Z"); global::android.graphics.Region._quickContains3785 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "quickContains", "(Landroid/graphics/Rect;)Z"); global::android.graphics.Region._Region3786 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "<init>", "()V"); global::android.graphics.Region._Region3787 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "<init>", "(Landroid/graphics/Region;)V"); global::android.graphics.Region._Region3788 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "<init>", "(Landroid/graphics/Rect;)V"); global::android.graphics.Region._Region3789 = @__env.GetMethodIDNoThrow(global::android.graphics.Region.staticClass, "<init>", "(IIII)V"); } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.VisualStudio.TestTools.UnitTesting; using NakedFramework; using NakedFramework.Architecture.Component; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.Reflect; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Metamodel.Facet; using NakedObjects.Reflector.FacetFactory; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace NakedObjects.Reflector.Test.FacetFactory; [TestClass] public class DisabledAnnotationFacetFactoryTest : AbstractFacetFactoryTest { private DisabledAnnotationFacetFactory facetFactory; protected override Type[] SupportedTypes => new[] { typeof(IDisabledFacet) }; protected override IFacetFactory FacetFactory => facetFactory; [TestMethod] public void TestDisabledAnnotationPickedUpOnAction() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var actionMethod = FindMethod(typeof(Customer2), "SomeAction"); metamodel = facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is DisabledFacetAbstract); AssertNoMethodsRemoved(); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledAnnotationPickedUpOnCollection() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer1), "Orders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is DisabledFacetAbstract); AssertNoMethodsRemoved(); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledAnnotationPickedUpOnProperty() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var property = FindProperty(typeof(Customer), "NumberOfOrders"); metamodel = facetFactory.Process(Reflector, property, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); Assert.IsNotNull(facet); Assert.IsTrue(facet is DisabledFacetAbstract); AssertNoMethodsRemoved(); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledAnnotationPickedUpOnParameter() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var actionMethod = FindMethod(typeof(Customer7), nameof(Customer7.SomeAction), new[] { typeof(string) }); metamodel = facetFactory.ProcessParams(Reflector, actionMethod, 0, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); var disabledFacetAbstract = (DisabledFacetAbstract)facet; Assert.AreEqual(WhenTo.Always, disabledFacetAbstract.Value); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledWhenAlwaysAnnotationPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var actionMethod = FindMethod(typeof(Customer3), "SomeAction"); metamodel = facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); var disabledFacetAbstract = (DisabledFacetAbstract)facet; Assert.AreEqual(WhenTo.Always, disabledFacetAbstract.Value); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledWhenNeverAnnotationPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var actionMethod = FindMethod(typeof(Customer4), "SomeAction"); metamodel = facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); var disabledFacetAbstract = (DisabledFacetAbstract)facet; Assert.AreEqual(WhenTo.Never, disabledFacetAbstract.Value); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledWhenOncePersistedAnnotationPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var actionMethod = FindMethod(typeof(Customer5), "SomeAction"); metamodel = facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); var disabledFacetAbstract = (DisabledFacetAbstract)facet; Assert.AreEqual(WhenTo.OncePersisted, disabledFacetAbstract.Value); Assert.IsNotNull(metamodel); } [TestMethod] public void TestDisabledWhenUntilPersistedAnnotationPickedUpOn() { IImmutableDictionary<string, ITypeSpecBuilder> metamodel = new Dictionary<string, ITypeSpecBuilder>().ToImmutableDictionary(); var actionMethod = FindMethod(typeof(Customer6), "SomeAction"); metamodel = facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification, metamodel); var facet = Specification.GetFacet(typeof(IDisabledFacet)); var disabledFacetAbstract = (DisabledFacetAbstract)facet; Assert.AreEqual(WhenTo.UntilPersisted, disabledFacetAbstract.Value); Assert.IsNotNull(metamodel); } [TestMethod] public override void TestFeatureTypes() { var featureTypes = facetFactory.FeatureTypes; Assert.IsFalse(featureTypes.HasFlag(FeatureType.Objects)); Assert.IsTrue(featureTypes.HasFlag(FeatureType.Properties)); Assert.IsTrue(featureTypes.HasFlag(FeatureType.Collections)); Assert.IsTrue(featureTypes.HasFlag(FeatureType.Actions)); Assert.IsTrue(featureTypes.HasFlag(FeatureType.ActionParameters)); } #region Nested type: Customer private class Customer { [Disabled] public int NumberOfOrders => 0; } #endregion #region Nested type: Customer1 private class Customer1 { [Disabled] public IList Orders => null; } #endregion #region Nested type: Customer2 private class Customer2 { [Disabled] public void SomeAction() { } } #endregion #region Nested type: Customer3 private class Customer3 { [Disabled(WhenTo.Always)] public void SomeAction() { } } #endregion #region Nested type: Customer4 private class Customer4 { [Disabled(WhenTo.Never)] public void SomeAction() { } } #endregion #region Nested type: Customer5 private class Customer5 { [Disabled(WhenTo.OncePersisted)] public void SomeAction() { } } #endregion #region Nested type: Customer6 private class Customer6 { [Disabled(WhenTo.UntilPersisted)] public void SomeAction() { } } #endregion #region Nested type: Customer7 private class Customer7 { public void SomeAction([Disabled] string disabledParameter) { } } #endregion #region Setup/Teardown [TestInitialize] public override void SetUp() { base.SetUp(); facetFactory = new DisabledAnnotationFacetFactory(GetOrder<DisabledAnnotationFacetFactory>(), LoggerFactory); } [TestCleanup] public override void TearDown() { facetFactory = null; base.TearDown(); } #endregion } // Copyright (c) Naked Objects Group Ltd. // ReSharper restore UnusedMember.Local
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Nohros.Configuration; namespace Nohros.Data.Json { /// <summary> /// A <see cref="JsonStringBuilder"/> is a builder that is used to build /// string-like json elements. /// </summary> /// <remarks> /// This class is a simple builder and should be used only to simplify the /// json serialization process. The Write(..) methods do not perform any /// validation of the correctness of the JSON format, it simple writes the /// data (escaping when nescessary). We do not guarantee that the final /// string is a valid json string, but we can ensure that each Write(..) /// method writes a valid json element. /// </remarks> public class JsonStringBuilder { enum State { None = 0, ReservedBeginToken = 1, ReservedEndToken = 2, ContentToken = 3 } /// <summary> /// Wraps a token and its type into a single object. /// </summary> struct Token { readonly TokenType type_; readonly string value_; #region .ctor /// <summary> /// Initializes a new instance of the <see cref="Token"/> class by using /// the token value and type. /// </summary> /// <param name="value"> /// The token's values. /// </param> /// <param name="type"> /// The type of the token. /// </param> public Token(string value, TokenType type) { value_ = value; type_ = type; } #endregion /// <summary> /// Gets the token's value. /// </summary> public string Value { get { return value_; } } /// <summary> /// Gets the type of the token. /// </summary> public TokenType Type { get { return type_; } } } /// <summary> /// Provides a way to identify if a token is a structural token or a /// token whose value was specified by the user. /// </summary> enum TokenType { Structural = 0, Value = 1 } /// <summary> /// Defines a method that executes an operation using a /// <see cref="JsonStringBuilder"/> object that returns that object after /// the operation is completed. /// </summary> /// <returns> /// A <see cref="JsonStringBuilder"/> object. /// </returns> public delegate void BuilderDelegate(JsonStringBuilder builder); /// <summary> /// Defines the method that is called by the /// <see cref="JsonStringBuilder.ForEach{T}"/> method for each element /// in the collection passed to thar method. /// </summary> /// <typeparam name="T"> /// The type of objects that the collection passed to the /// <see cref="JsonStringBuilder.ForEach{T}"/> method contain. /// </typeparam> /// <param name="obj"></param> /// <param name="builder"></param> public delegate void ForEachDelegate<T>(T obj, JsonStringBuilder builder); const string kBeginObject = "{"; const string kEndObject = "}"; const string kBeginArray = "["; const string kEndArray = "]"; const string kNameValueSeparator = ":"; const string kValueSeparator = ","; const string kDefaultNumberFormat = "G"; const string kDoubleQuote = "\""; const char kLargestEscapableChar = '\\'; static readonly char[] escape_chars_ = new char[] {'"', '\n', '\t', '\\', '\f', '\b'}; readonly List<Token> tokens_; State current_state_; int last_written_token_position_; string memoized_json_string_; // Json numbers uses a format that is culture invariant and is equals to // the numeric format used by US culture. CultureInfo numeric_format_; #region .ctor /// <summary> /// Initializes a new instance of the <see cref="JsonStringBuilder"/> class. /// </summary> public JsonStringBuilder() { tokens_ = new List<Token>(); current_state_ = State.None; last_written_token_position_ = 0; // Json numbers uses a format that is culture invariant and is equals to // the numeric format used by US culture. numeric_format_ = new CultureInfo("en-US"); } #endregion /// <summary> /// Appends the begin array token to the current json string. /// </summary> public JsonStringBuilder WriteBeginArray() { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kBeginArray, TokenType.Structural)); } /// <summary> /// Appends the end array token to the current json string. /// </summary> public JsonStringBuilder WriteEndArray() { ++last_written_token_position_; return WriteReservedEndToken(new Token(kEndArray, TokenType.Structural)); } /// <summary> /// Executes the action <paramref name="action"/> and returns the instance /// of the <see cref="JsonStringBuilder"/> object where the /// <see cref="Run"/> method was called. /// </summary> /// <param name="action"> /// A <see cref="Action{T}"/> to be executed. /// </param> /// <returns> /// The instance of the <see cref="JsonStringBuilder"/> where the /// <see cref="Run"/> method was called. /// </returns> public JsonStringBuilder Run(Action<JsonStringBuilder> action) { action(this); return this; } /// <summary> /// Appends the begin object token to the current json string. /// </summary> public JsonStringBuilder WriteBeginObject() { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kBeginObject, TokenType.Structural)); } /// <summary> /// Appends the begin object token to the current json string, execute /// the <see cref="Action{T}"/> and appends the end object token the the /// current json string. /// </summary> /// <param name="action"> /// A <see cref="Action{T}"/> to be executed after appending the begin /// object token to the current json string. /// </param> /// <returns></returns> public JsonStringBuilder WrapInObject(Action<JsonStringBuilder> action) { WriteBeginObject(); action(this); WriteEndObject(); return this; } /// <summary> /// Appends the begin array token to the current json string, execute /// the <see cref="Action{T}"/> and appends the end array token the the /// current json string. /// </summary> /// <param name="action"> /// A <see cref="Action{T}"/> to be executed after appending the begin /// array token to the current json string. /// </param> /// <returns></returns> public JsonStringBuilder WrapInArray(Action<JsonStringBuilder> action) { WriteBeginArray(); action(this); WriteEndArray(); return this; } /// <summary> /// Appends the end object token to the current json string. /// </summary> public JsonStringBuilder WriteEndObject() { ++last_written_token_position_; return WriteReservedEndToken(new Token(kEndObject, TokenType.Structural)); } /// <summary> /// Appends the string <paramref name="value"/> to the current json string. /// </summary> /// <remarks> /// This method encloses the string in a double quotes. /// <paramref name="value"/>. /// </remarks> public JsonStringBuilder WriteString(string value) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token((value ?? "null"), TokenType.Value)) .WriteContentToken(new Token(kDoubleQuote, TokenType.Structural)); } /// <summary> /// Appends the string <paramref name="value"/> to the current json string. /// </summary> /// <remarks> /// This method write the specified string as is, which means that it do /// not encloses the string in a double quotes. /// </remarks> public JsonStringBuilder WriteUnquotedString(string value) { ++last_written_token_position_; return WriteContentToken(new Token(value ?? "null", TokenType.Value)); } public JsonStringBuilder WriteStringArray(string[] data) { WriteBeginArray(); for (int i = 0, j = data.Length; i < j; i++) { WriteString(data[i]); } // rewind the pointer to the begining of the JSON array last_written_token_position_ -= data.Length; // Write end array advances the pointer, which causes the pointer to // points to the first token after the begin array token. This is ok, // since the begin array token should not be escaped. return WriteEndArray(); } /// <summary> /// Performs the specified action on each element of the /// <see cref="elements"/> collection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="elements"> /// A collection of elements to perform the <see cref="ForEachDelegate{T}"/> /// action over each element. /// </param> /// <param name="action"> /// The <see cref="ForEachDelegate{T}"/> delegate to perform on each /// element of <paramref name="elements"/> collection. /// </param> /// <remarks> /// The <see cref="ForEachDelegate{T}"/> is a delegate to a method that /// performs an action on the object passed to it. The elements of the /// <paramref name="elements"/> are individually passed to the /// <see cref="ForEachDelegate{T}"/> delegate. /// <para> /// This method is a O(n) operation, where n is the number of elements /// of the <paramref name="elements"/> collection. /// </para> /// </remarks> public JsonStringBuilder ForEach<T>(IEnumerable<T> elements, ForEachDelegate<T> action) { foreach (T element in elements) { action(element, this); } return this; } public JsonStringBuilder WriteTokenArray(IJsonToken[] tokens) { WriteBeginArray(); for (int i = 0, j = tokens.Length; i < j; i++) { WriteUnquotedString(tokens[i].AsJson()); } // rewind the pointer to the begining of the JSON array. last_written_token_position_ -= tokens.Length; // Write end array advances the pointer, which causes the pointer to // points to the first token after the begin array token. This is ok, // since the begin array token should not be escaped. return WriteEndArray(); } public JsonStringBuilder WriteTokenArray(IEnumerable<IJsonToken> tokens) { WriteBeginArray(); foreach (IJsonToken token in tokens) { // Since we do not now the size of the tokens collections we need to // rewind the pointer at each iteration. --last_written_token_position_; WriteUnquotedString(token.AsJson()); } // Write end array advances the pointer, which causes the pointer to // points to the first token after the begin array token. This is ok, // since the begin array token should not be escaped. return WriteEndArray(); } /// <summary> /// Appends the string representation of the integer /// <paramref name="value"/> to the current json string. /// </summary> /// <param name="value"> /// The integer value to be appended to the current json string. /// </param> public JsonStringBuilder WriteNumber(int value) { return WriteNumber(value, kDefaultNumberFormat); } /// <summary> /// Writes the string representation of the long /// <paramref name="value"/> to the current json string. /// </summary> /// <param name="value"> /// The long value to be appended to the current json string. /// </param> public JsonStringBuilder WriteNumber(long value) { return WriteNumber(value, kDefaultNumberFormat); } /// <summary> /// Writes the string representation of the double /// <paramref name="value"/> to the current json string. /// </summary> /// <param name="value"> /// The double value to be appended to the current json string. /// </param> public JsonStringBuilder WriteNumber(double value) { return WriteNumber(value, kDefaultNumberFormat); } /// <summary> /// Writes the string representation of the integer /// <paramref name="value"/> to the current json string using the specified /// format. /// </summary> /// <param name="value"> /// The integer value to be appended to the current json string. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <remarks> /// This method does not check if the specified format is a valid json /// format. /// </remarks> public JsonStringBuilder WriteNumber(int value, string format) { ++last_written_token_position_; return WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Writes the string representation of the long /// <paramref name="value"/> to the current json string using the specified /// format. /// </summary> /// <param name="value"> /// The long value to be appended to the current json string. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <exception cref="FormatException"> /// <paramref name="format"/> is invalid or not supported. /// </exception> /// <remarks> /// This method does not check if the specified format is a valid json /// format. /// </remarks> public JsonStringBuilder WriteNumber(long value, string format) { ++last_written_token_position_; return WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Writes the string representation of the double /// <paramref name="value"/> to the current json string using the specified /// format. /// </summary> /// <param name="value"> /// The double value to be appended to the current json string. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <exception cref="FormatException"> /// <paramref name="format"/> is invalid or not supported. /// </exception> /// <remarks> /// This method does not check if the specified format is a valid json /// format. /// </remarks> public JsonStringBuilder WriteNumber(double value, string format) { ++last_written_token_position_; return WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is <paramref name="value"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <remarks> /// This method encloses the name and value in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":"value" /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, string value) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(name, TokenType.Value)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(kNameValueSeparator, TokenType.Structural)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(value, TokenType.Value)) .WriteContentToken(new Token(kDoubleQuote, TokenType.Structural)); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <remarks> /// This method encloses the name and in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name": /// </para> /// </remarks> public JsonStringBuilder WriteMemberName(string name) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(name, TokenType.Value)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(kNameValueSeparator, TokenType.Structural)); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is <paramref name="value"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, int value) { return WriteMember(name, value, kDefaultNumberFormat); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is <paramref name="value"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, long value) { return WriteMember(name, value, kDefaultNumberFormat); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is <paramref name="value"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, double value) { return WriteMember(name, value, kDefaultNumberFormat); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is <paramref name="value"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, decimal value) { return WriteMember(name, value, kDefaultNumberFormat); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is the string representation of /// <paramref name="value"/> formatted using the specified /// <paramref name="format"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// <para> /// This method does not check if the specified format is a valid json /// format. /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, int value, string format) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(name, TokenType.Value)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(kNameValueSeparator, TokenType.Structural)) .WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is the string representation of /// <paramref name="value"/> formatted using the specified /// <paramref name="format"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// <para> /// This method does not check if the specified format is a valid json /// format. /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, long value, string format) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(name, TokenType.Value)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(kNameValueSeparator, TokenType.Structural)) .WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is the string representation of /// <paramref name="value"/> formatted using the specified /// <paramref name="format"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// <para> /// This method does not check if the specified format is a valid json /// format. /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, double value, string format) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(name, TokenType.Value)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(kNameValueSeparator, TokenType.Structural)) .WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Appends the json string that represents a member which name is /// <paramref name="name"/> and value is the string representation of /// <paramref name="value"/> formatted using the specified /// <paramref name="format"/>. /// </summary> /// <param name="name"> /// The name part of the json member. /// </param> /// <param name="value"> /// The value part of the json member. /// </param> /// <param name="format"> /// A standard or custom numeric format string. /// </param> /// <remarks> /// This method encloses the name in a double quotes. /// <para> /// The string that will be append should be something like the string /// above: /// </para> /// <para> /// "name":value /// </para> /// <para> /// This method does not check if the specified format is a valid json /// format. /// </para> /// </remarks> public JsonStringBuilder WriteMember(string name, decimal value, string format) { ++last_written_token_position_; return WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(name, TokenType.Value)) .WriteReservedBeginToken(new Token(kDoubleQuote, TokenType.Structural)) .WriteReservedBeginToken(new Token(kNameValueSeparator, TokenType.Structural)) .WriteContentToken(new Token(value.ToString(format, numeric_format_), TokenType.Value)); } /// <summary> /// Escapes a minimal set of characters (\n,\\,\r,\t,",\f,\b) by replacing /// them with their escapes codes. /// </summary> /// <returns>The escaped version of <see cref="token"/></returns> public static string Escape(string token) { StringBuilder escaped = new StringBuilder(); int last_replace_position = 0; for (int m = 0, n = token.Length; m < n; m++) { char c = token[m]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\' && c != '"') { continue; } string escape_string; switch (c) { case '\n': escape_string = @"\n"; break; case '\r': escape_string = @"\r"; break; case '\t': escape_string = @"\t"; break; case '"': escape_string = "\\\""; break; case '\\': escape_string = @"\\"; break; case '\f': escape_string = @"\f"; break; case '\b': escape_string = @"\b"; break; case '\u0085': // Next Line escape_string = @"\u0085"; break; case '\u2028': // Line Separator escape_string = @"\u2028"; break; case '\u2029': // Paragraph Separator escape_string = @"\u2029"; break; default: if (c <= '\u001f') { escape_string = ToCharAsUnicode(c); break; } continue; } // If we are here, we found some character that needs to be escaped set // the last replace pointer to the location where the replacement was // performed plus the size of the escaped character. escaped.Append(string.Concat( token.Substring(last_replace_position, m - last_replace_position), escape_string)); last_replace_position += (m - last_replace_position + 1); } if (last_replace_position < token.Length) { escaped.Append(token.Substring(last_replace_position)); } return escaped.ToString(); } /// <summary> /// Escapes a minimal set of characters (\n,\\,\r,\t,",\f,\b) by replacing /// them with their escapes codes within the last written token. /// </summary> public JsonStringBuilder Escape() { for (int i = last_written_token_position_ - 1, j = tokens_.Count; i < j; i++) { Token token = tokens_[i]; // Structural tokens does should not be escaped. if (token.Type == TokenType.Structural) { continue; } string new_token = string.Empty; int last_replace_position = 0; for (int m = 0, n = token.Value.Length; m < n; m++) { char c = token.Value[m]; // don't escape standard text/numbers except '\' and the text delimiter if (c >= ' ' && c < 128 && c != '\\') { continue; } string escape_string; switch (c) { case '\n': escape_string = @"\n"; break; case '\r': escape_string = @"\r"; break; case '\t': escape_string = @"\t"; break; case '"': escape_string = "\\\""; break; case '\\': escape_string = @"\\"; break; case '\f': escape_string = @"\f"; break; case '\b': escape_string = @"\b"; break; case '\u0085': // Next Line escape_string = @"\u0085"; break; case '\u2028': // Line Separator escape_string = @"\u2028"; break; case '\u2029': // Paragraph Separator escape_string = @"\u2029"; break; default: if (c <= '\u001f') { escape_string = ToCharAsUnicode(c); break; } continue; } // If we are here, we found some character that needs to be escaped. new_token += string.Concat( token.Value.Substring(last_replace_position, m - last_replace_position), escape_string); // set the last replace pointer to the location where the // replacement was performed plus 1 escaped character. last_replace_position += (m - last_replace_position + 1); } // Replace the old token with the new token if the old one was // modified. if (last_replace_position != 0) { if (last_replace_position < token.Value.Length) { new_token += token.Value.Substring(last_replace_position); } tokens_[i] = new Token(new_token, token.Type); } } return this; } static string ToCharAsUnicode(char c) { char h1 = IntToHex((c >> 12) & '\x000f'); char h2 = IntToHex((c >> 8) & '\x000f'); char h3 = IntToHex((c >> 4) & '\x000f'); char h4 = IntToHex(c & '\x000f'); return new string(new[] {'\\', 'u', h1, h2, h3, h4}); } static char IntToHex(int n) { if (n <= 9) { return (char) (n + 48); } return (char) ((n - 10) + 97); } JsonStringBuilder WriteReservedBeginToken(Token token) { /*switch (current_state_) { case State.None: case State.ReservedBeginToken: tokens_.Add(token); break; case State.ReservedEndToken: case State.ContentToken: tokens_.Add(new Token(kValueSeparator, TokenType.Structural)); tokens_.Add(token); break; }*/ WriteContentToken(token); current_state_ = State.ReservedBeginToken; return this; } JsonStringBuilder WriteReservedEndToken(Token token) { tokens_.Add(token); current_state_ = State.ReservedEndToken; return this; } JsonStringBuilder WriteContentToken(Token token) { switch (current_state_) { case State.None: case State.ReservedBeginToken: tokens_.Add(token); break; case State.ReservedEndToken: case State.ContentToken: tokens_.Add(new Token(kValueSeparator, TokenType.Structural)); tokens_.Add(token); break; } current_state_ = State.ContentToken; return this; } /// <summary> /// Gets the string representing the current json string contained in /// this builder. /// </summary> public override string ToString() { if (memoized_json_string_ == null) { StringBuilder builder = new StringBuilder(); for (int i = 0, j = tokens_.Count; i < j; i++) { builder.Append(tokens_[i].Value); } memoized_json_string_ = builder.ToString(); } return memoized_json_string_; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>BatchPredictionJob</c> resource.</summary> public sealed partial class BatchPredictionJobName : gax::IResourceName, sys::IEquatable<BatchPredictionJobName> { /// <summary>The possible contents of <see cref="BatchPredictionJobName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c>. /// </summary> ProjectLocationBatchPredictionJob = 1, } private static gax::PathTemplate s_projectLocationBatchPredictionJob = new gax::PathTemplate("projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}"); /// <summary>Creates a <see cref="BatchPredictionJobName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="BatchPredictionJobName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static BatchPredictionJobName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new BatchPredictionJobName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="BatchPredictionJobName"/> with the pattern /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchPredictionJobId"> /// The <c>BatchPredictionJob</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns>A new instance of <see cref="BatchPredictionJobName"/> constructed from the provided ids.</returns> public static BatchPredictionJobName FromProjectLocationBatchPredictionJob(string projectId, string locationId, string batchPredictionJobId) => new BatchPredictionJobName(ResourceNameType.ProjectLocationBatchPredictionJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), batchPredictionJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(batchPredictionJobId, nameof(batchPredictionJobId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="BatchPredictionJobName"/> with pattern /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchPredictionJobId"> /// The <c>BatchPredictionJob</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="BatchPredictionJobName"/> with pattern /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c>. /// </returns> public static string Format(string projectId, string locationId, string batchPredictionJobId) => FormatProjectLocationBatchPredictionJob(projectId, locationId, batchPredictionJobId); /// <summary> /// Formats the IDs into the string representation of this <see cref="BatchPredictionJobName"/> with pattern /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchPredictionJobId"> /// The <c>BatchPredictionJob</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="BatchPredictionJobName"/> with pattern /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c>. /// </returns> public static string FormatProjectLocationBatchPredictionJob(string projectId, string locationId, string batchPredictionJobId) => s_projectLocationBatchPredictionJob.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(batchPredictionJobId, nameof(batchPredictionJobId))); /// <summary> /// Parses the given resource name string into a new <see cref="BatchPredictionJobName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="batchPredictionJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="BatchPredictionJobName"/> if successful.</returns> public static BatchPredictionJobName Parse(string batchPredictionJobName) => Parse(batchPredictionJobName, false); /// <summary> /// Parses the given resource name string into a new <see cref="BatchPredictionJobName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="batchPredictionJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="BatchPredictionJobName"/> if successful.</returns> public static BatchPredictionJobName Parse(string batchPredictionJobName, bool allowUnparsed) => TryParse(batchPredictionJobName, allowUnparsed, out BatchPredictionJobName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BatchPredictionJobName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="batchPredictionJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="BatchPredictionJobName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string batchPredictionJobName, out BatchPredictionJobName result) => TryParse(batchPredictionJobName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BatchPredictionJobName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="batchPredictionJobName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="BatchPredictionJobName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string batchPredictionJobName, bool allowUnparsed, out BatchPredictionJobName result) { gax::GaxPreconditions.CheckNotNull(batchPredictionJobName, nameof(batchPredictionJobName)); gax::TemplatedResourceName resourceName; if (s_projectLocationBatchPredictionJob.TryParseName(batchPredictionJobName, out resourceName)) { result = FromProjectLocationBatchPredictionJob(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(batchPredictionJobName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private BatchPredictionJobName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string batchPredictionJobId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; BatchPredictionJobId = batchPredictionJobId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="BatchPredictionJobName"/> class from the component parts of /// pattern <c>projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="batchPredictionJobId"> /// The <c>BatchPredictionJob</c> ID. Must not be <c>null</c> or empty. /// </param> public BatchPredictionJobName(string projectId, string locationId, string batchPredictionJobId) : this(ResourceNameType.ProjectLocationBatchPredictionJob, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), batchPredictionJobId: gax::GaxPreconditions.CheckNotNullOrEmpty(batchPredictionJobId, nameof(batchPredictionJobId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>BatchPredictionJob</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string BatchPredictionJobId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationBatchPredictionJob: return s_projectLocationBatchPredictionJob.Expand(ProjectId, LocationId, BatchPredictionJobId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as BatchPredictionJobName); /// <inheritdoc/> public bool Equals(BatchPredictionJobName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(BatchPredictionJobName a, BatchPredictionJobName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(BatchPredictionJobName a, BatchPredictionJobName b) => !(a == b); } public partial class BatchPredictionJob { /// <summary> /// <see cref="gcav::BatchPredictionJobName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::BatchPredictionJobName BatchPredictionJobName { get => string.IsNullOrEmpty(Name) ? null : gcav::BatchPredictionJobName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary><see cref="ModelName"/>-typed view over the <see cref="Model"/> resource name property.</summary> public ModelName ModelAsModelName { get => string.IsNullOrEmpty(Model) ? null : ModelName.Parse(Model, allowUnparsed: true); set => Model = value?.ToString() ?? ""; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text.RegularExpressions; using DBlog.TransitData; using DBlog.Tools.Web; using System.Text; using DBlog.Data.Hibernate; using DBlog.TransitData.References; using DBlog.Tools.Web.Html; public partial class ShowBlog : BlogPage { private HtmlMeta mHtmlMetaDescription = null; protected void Page_Load(object sender, EventArgs e) { try { if (Header != null) { Header.Controls.Add(HtmlMetaDescription); } DBlogMaster master = (DBlogMaster)this.Master; master.TopicChanged += new ViewTopicsControl.TopicChangedHandler(topics_TopicChanged); master.Search += new SearchControl.SearchHandler(search_Search); master.DateRangeChanged += new DateRangeControl.DateRangeHandler(master_DateRangeChanged); grid.OnGetDataSource += new EventHandler(grid_OnGetDataSource); if (!IsPostBack) { String topicName = Request.Params["t"]; if (! string.IsNullOrEmpty(topicName)) { TransitTopic topic = SessionManager.GetCachedObject<TransitTopic>("GetTopicByName", SessionManager.Ticket, topicName); if (topic == null) { throw new Exception("Invalid topic: " + topicName); } TopicId = topic.Id; } else { TopicId = RequestId; } Query = Request.Params["q"]; GetData(sender, e); } } catch (Exception ex) { ReportException(ex); } } void master_DateRangeChanged(object sender, DateRangeControl.DateRangeEventArgs e) { try { DateStart = e.DateStart; DateEnd = e.DateEnd; GetData(sender, e); panelPosts.Update(); } catch (Exception ex) { ReportException(ex); } } private int mTopicId = 0; private string mQuery = string.Empty; private DateTime mDateStart = DateTime.MinValue; private DateTime mDateEnd = DateTime.MaxValue; public DateTime DateStart { get { return DBlog.Tools.Web.ViewState<DateTime>.GetViewStateValue( EnableViewState, ViewState, "DateStart", mDateStart); } set { DBlog.Tools.Web.ViewState<DateTime>.SetViewStateValue( EnableViewState, ViewState, "DateStart", value, ref mDateStart); } } public DateTime DateEnd { get { return DBlog.Tools.Web.ViewState<DateTime>.GetViewStateValue( EnableViewState, ViewState, "DateEnd", mDateEnd); } set { DBlog.Tools.Web.ViewState<DateTime>.SetViewStateValue( EnableViewState, ViewState, "DateEnd", value, ref mDateEnd); } } public int TopicId { get { return DBlog.Tools.Web.ViewState<int>.GetViewStateValue( EnableViewState, ViewState, "TopicId", mTopicId); } set { DBlog.Tools.Web.ViewState<int>.SetViewStateValue( EnableViewState, ViewState, "TopicId", value, ref mTopicId); } } public string Query { get { return DBlog.Tools.Web.ViewState<string>.GetViewStateValue( EnableViewState, ViewState, "Query", mQuery); } set { DBlog.Tools.Web.ViewState<string>.SetViewStateValue( EnableViewState, ViewState, "Query", value, ref mQuery); } } public void search_Search(object sender, SearchControl.SearchEventArgs e) { try { Query = e.Query; grid.RepeatRows = 20; GetData(sender, e); panelPosts.Update(); } catch (Exception ex) { ReportException(ex); } } public void topics_TopicChanged(object sender, ViewTopicsControl.TopicChangedEventArgs e) { try { TopicId = e.TopicId; GetData(sender, e); panelPosts.Update(); } catch (Exception ex) { ReportException(ex); } } void grid_OnGetDataSource(object sender, EventArgs e) { TransitPostQueryOptions options = GetOptions(); grid.DataSource = SessionManager.GetCachedCollection<TransitPost>( "GetPosts", SessionManager.PostTicket, options); GetCriteria(); } private TransitPostQueryOptions GetOptions() { TransitPostQueryOptions options = new TransitPostQueryOptions(TopicId, Query, grid.PageSize, grid.CurrentPageIndex); options.DateStart = DateStart; options.DateEnd = DateEnd; options.PublishedOnly = ! SessionManager.IsAdministrator; options.DisplayedOnly = ! SessionManager.IsAdministrator; options.SortDirection = WebServiceQuerySortDirection.Descending; options.SortExpression = string.IsNullOrEmpty(options.Query) ? "Created" : "Rank"; return options; } public void GetData(object sender, EventArgs e) { grid.CurrentPageIndex = 0; grid.VirtualItemCount = SessionManager.GetCachedCollectionCount<TransitPost>( "GetPostsCount", SessionManager.PostTicket, GetOptions()); if (grid.VirtualItemCount == 0) { labelPosts.Text = "No Posts"; labelPosts.Visible = true; } else { labelPosts.Visible = false; } grid_OnGetDataSource(sender, e); grid.DataBind(); } private void GetCriteria() { StringBuilder queryText = new StringBuilder(); if (!string.IsNullOrEmpty(Query)) { queryText.AppendFormat("Found {0} post{1} with \"{2}\"", grid.VirtualItemCount, grid.VirtualItemCount == 1 ? "" : "s", Renderer.Render(Query)); if (TopicId != 0) { queryText.AppendFormat(" in \"{0}\"", Renderer.Render( SessionManager.GetCachedObject<TransitTopic>("GetTopicById", SessionManager.Ticket, TopicId).Name)); } queryText.Append("."); } else if (TopicId > 0) { queryText.AppendFormat("{0} post{1} in \"{2}\" ...", grid.VirtualItemCount, grid.VirtualItemCount == 1 ? "" : "s", Renderer.Render( SessionManager.GetCachedObject<TransitTopic>("GetTopicById", SessionManager.Ticket, TopicId).Name)); } if (queryText.Length > 0) { labelCriteria.Text = queryText.ToString(); labelCriteria.Visible = true; } else { labelCriteria.Visible = false; } } public string GetTopics(TransitTopic[] topics) { StringBuilder sb = new StringBuilder(); foreach (TransitTopic topic in topics) { if (sb.Length != 0) sb.Append(", "); sb.Append(Renderer.Render(topic.Name)); } return sb.ToString(); } public void list_ItemCommand(object source, DataListCommandEventArgs e) { try { switch (e.CommandName) { case "Delete": { SessionManager.BlogService.DeletePost(SessionManager.Ticket, int.Parse(e.CommandArgument.ToString())); SessionManager.Invalidate<TransitPost>(); ReportInfo("Item Deleted"); GetData(source, e); } break; case "Display": { TransitPost t_post = SessionManager.BlogService.GetPostById(SessionManager.Ticket, int.Parse(e.CommandArgument.ToString())); t_post.Display = ! t_post.Display; SessionManager.BlogService.CreateOrUpdatePost(SessionManager.Ticket, t_post); ReportInfo(t_post.Display ? "Post Displayed" : "Post Hidden"); GetData(source, e); break; } case "Sticky": { TransitPost t_post = SessionManager.BlogService.GetPostById(SessionManager.Ticket, int.Parse(e.CommandArgument.ToString())); t_post.Sticky = ! t_post.Sticky; SessionManager.BlogService.CreateOrUpdatePost(SessionManager.Ticket, t_post); ReportInfo(t_post.Sticky ? "Post Stuck" : "Post Unstuck"); GetData(source, e); break; } } } catch (Exception ex) { ReportException(ex); } } public string GetCounter(long count) { return string.Format("{0} Click{1}", count, count != 1 ? "s" : string.Empty); } public string GetImagesLink(int images_count) { if (images_count > 1) { return string.Format("&#187; {0} more image{1} after the cut ...", images_count , images_count == 1 ? string.Empty : "s"); } return string.Empty; } public string GetImagesShortLink(int images_count) { StringBuilder result = new StringBuilder(); if (images_count > 1) { result.AppendFormat(" | {0} Image{1}", images_count , images_count == 1 ? string.Empty : "s"); } return result.ToString(); } public string GetPostLink(int images_count, int id, string link, int image_id) { if (images_count == 1 && image_id > 0) { return string.Format("./ShowImage.aspx?id={0}&pid={1}", image_id, id); } else { return link; } } public HtmlMeta HtmlMetaDescription { get { if (mHtmlMetaDescription == null) { mHtmlMetaDescription = new HtmlMeta(); mHtmlMetaDescription.Name = "description"; mHtmlMetaDescription.Content = SessionManager.GetSetting( "description", string.Empty); } return mHtmlMetaDescription; } } public override string RenderEx(string text, int id) { if (string.IsNullOrEmpty(text)) return string.Empty; return base.RenderEx(Cutter.Cut(text, id), id); } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Student Medication Doses Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SMCDDataSet : EduHubDataSet<SMCD> { /// <inheritdoc /> public override string Name { get { return "SMCD"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SMCDDataSet(EduHubContext Context) : base(Context) { Index_SMCDKEY = new Lazy<Dictionary<int, IReadOnlyList<SMCD>>>(() => this.ToGroupedDictionary(i => i.SMCDKEY)); Index_STAFF = new Lazy<NullDictionary<string, IReadOnlyList<SMCD>>>(() => this.ToGroupedNullDictionary(i => i.STAFF)); Index_TID = new Lazy<Dictionary<int, SMCD>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SMCD" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SMCD" /> fields for each CSV column header</returns> internal override Action<SMCD, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SMCD, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "SMCDKEY": mapper[i] = (e, v) => e.SMCDKEY = int.Parse(v); break; case "STAFF": mapper[i] = (e, v) => e.STAFF = v; break; case "ADMIN_DATE": mapper[i] = (e, v) => e.ADMIN_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "ADMIN_TIME": mapper[i] = (e, v) => e.ADMIN_TIME = v == null ? (short?)null : short.Parse(v); break; case "DOSE": mapper[i] = (e, v) => e.DOSE = v; break; case "ADMIN_BY_OTHER": mapper[i] = (e, v) => e.ADMIN_BY_OTHER = v; break; case "ADMIN_NOTES": mapper[i] = (e, v) => e.ADMIN_NOTES = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SMCD" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SMCD" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SMCD" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SMCD}"/> of entities</returns> internal override IEnumerable<SMCD> ApplyDeltaEntities(IEnumerable<SMCD> Entities, List<SMCD> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SMCDKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.SMCDKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, IReadOnlyList<SMCD>>> Index_SMCDKEY; private Lazy<NullDictionary<string, IReadOnlyList<SMCD>>> Index_STAFF; private Lazy<Dictionary<int, SMCD>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SMCD by SMCDKEY field /// </summary> /// <param name="SMCDKEY">SMCDKEY value used to find SMCD</param> /// <returns>List of related SMCD entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SMCD> FindBySMCDKEY(int SMCDKEY) { return Index_SMCDKEY.Value[SMCDKEY]; } /// <summary> /// Attempt to find SMCD by SMCDKEY field /// </summary> /// <param name="SMCDKEY">SMCDKEY value used to find SMCD</param> /// <param name="Value">List of related SMCD entities</param> /// <returns>True if the list of related SMCD entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySMCDKEY(int SMCDKEY, out IReadOnlyList<SMCD> Value) { return Index_SMCDKEY.Value.TryGetValue(SMCDKEY, out Value); } /// <summary> /// Attempt to find SMCD by SMCDKEY field /// </summary> /// <param name="SMCDKEY">SMCDKEY value used to find SMCD</param> /// <returns>List of related SMCD entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SMCD> TryFindBySMCDKEY(int SMCDKEY) { IReadOnlyList<SMCD> value; if (Index_SMCDKEY.Value.TryGetValue(SMCDKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SMCD by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find SMCD</param> /// <returns>List of related SMCD entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SMCD> FindBySTAFF(string STAFF) { return Index_STAFF.Value[STAFF]; } /// <summary> /// Attempt to find SMCD by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find SMCD</param> /// <param name="Value">List of related SMCD entities</param> /// <returns>True if the list of related SMCD entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTAFF(string STAFF, out IReadOnlyList<SMCD> Value) { return Index_STAFF.Value.TryGetValue(STAFF, out Value); } /// <summary> /// Attempt to find SMCD by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find SMCD</param> /// <returns>List of related SMCD entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SMCD> TryFindBySTAFF(string STAFF) { IReadOnlyList<SMCD> value; if (Index_STAFF.Value.TryGetValue(STAFF, out value)) { return value; } else { return null; } } /// <summary> /// Find SMCD by TID field /// </summary> /// <param name="TID">TID value used to find SMCD</param> /// <returns>Related SMCD entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SMCD FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SMCD by TID field /// </summary> /// <param name="TID">TID value used to find SMCD</param> /// <param name="Value">Related SMCD entity</param> /// <returns>True if the related SMCD entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SMCD Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SMCD by TID field /// </summary> /// <param name="TID">TID value used to find SMCD</param> /// <returns>Related SMCD entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SMCD TryFindByTID(int TID) { SMCD value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SMCD table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SMCD]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SMCD]( [TID] int IDENTITY NOT NULL, [SMCDKEY] int NOT NULL, [STAFF] varchar(4) NULL, [ADMIN_DATE] datetime NULL, [ADMIN_TIME] smallint NULL, [DOSE] varchar(30) NULL, [ADMIN_BY_OTHER] varchar(30) NULL, [ADMIN_NOTES] varchar(MAX) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SMCD_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SMCD_Index_SMCDKEY] ON [dbo].[SMCD] ( [SMCDKEY] ASC ); CREATE NONCLUSTERED INDEX [SMCD_Index_STAFF] ON [dbo].[SMCD] ( [STAFF] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SMCD]') AND name = N'SMCD_Index_STAFF') ALTER INDEX [SMCD_Index_STAFF] ON [dbo].[SMCD] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SMCD]') AND name = N'SMCD_Index_TID') ALTER INDEX [SMCD_Index_TID] ON [dbo].[SMCD] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SMCD]') AND name = N'SMCD_Index_STAFF') ALTER INDEX [SMCD_Index_STAFF] ON [dbo].[SMCD] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SMCD]') AND name = N'SMCD_Index_TID') ALTER INDEX [SMCD_Index_TID] ON [dbo].[SMCD] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SMCD"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SMCD"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SMCD> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SMCD] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SMCD data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SMCD data set</returns> public override EduHubDataSetDataReader<SMCD> GetDataSetDataReader() { return new SMCDDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SMCD data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SMCD data set</returns> public override EduHubDataSetDataReader<SMCD> GetDataSetDataReader(List<SMCD> Entities) { return new SMCDDataReader(new EduHubDataSetLoadedReader<SMCD>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SMCDDataReader : EduHubDataSetDataReader<SMCD> { public SMCDDataReader(IEduHubDataSetReader<SMCD> Reader) : base (Reader) { } public override int FieldCount { get { return 11; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // SMCDKEY return Current.SMCDKEY; case 2: // STAFF return Current.STAFF; case 3: // ADMIN_DATE return Current.ADMIN_DATE; case 4: // ADMIN_TIME return Current.ADMIN_TIME; case 5: // DOSE return Current.DOSE; case 6: // ADMIN_BY_OTHER return Current.ADMIN_BY_OTHER; case 7: // ADMIN_NOTES return Current.ADMIN_NOTES; case 8: // LW_DATE return Current.LW_DATE; case 9: // LW_TIME return Current.LW_TIME; case 10: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // STAFF return Current.STAFF == null; case 3: // ADMIN_DATE return Current.ADMIN_DATE == null; case 4: // ADMIN_TIME return Current.ADMIN_TIME == null; case 5: // DOSE return Current.DOSE == null; case 6: // ADMIN_BY_OTHER return Current.ADMIN_BY_OTHER == null; case 7: // ADMIN_NOTES return Current.ADMIN_NOTES == null; case 8: // LW_DATE return Current.LW_DATE == null; case 9: // LW_TIME return Current.LW_TIME == null; case 10: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // SMCDKEY return "SMCDKEY"; case 2: // STAFF return "STAFF"; case 3: // ADMIN_DATE return "ADMIN_DATE"; case 4: // ADMIN_TIME return "ADMIN_TIME"; case 5: // DOSE return "DOSE"; case 6: // ADMIN_BY_OTHER return "ADMIN_BY_OTHER"; case 7: // ADMIN_NOTES return "ADMIN_NOTES"; case 8: // LW_DATE return "LW_DATE"; case 9: // LW_TIME return "LW_TIME"; case 10: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "SMCDKEY": return 1; case "STAFF": return 2; case "ADMIN_DATE": return 3; case "ADMIN_TIME": return 4; case "DOSE": return 5; case "ADMIN_BY_OTHER": return 6; case "ADMIN_NOTES": return 7; case "LW_DATE": return 8; case "LW_TIME": return 9; case "LW_USER": return 10; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="WmlMobileTextWriter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Web.Mobile; using System.Web.UI.MobileControls; using System.Text.RegularExpressions; using System.Diagnostics; using System.Web.Security; using System.Security.Permissions; using SR=System.Web.UI.MobileControls.Adapters.SR; #if COMPILING_FOR_SHIPPED_SOURCE using Adapters=System.Web.UI.MobileControls.ShippedAdapterSource; namespace System.Web.UI.MobileControls.ShippedAdapterSource #else using Adapters=System.Web.UI.MobileControls.Adapters; namespace System.Web.UI.MobileControls.Adapters #endif { /* * WmlMobileTextWriter class. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class WmlMobileTextWriter : MobileTextWriter { private TextWriter _realInnerWriter; private EmptyTextWriter _analyzeWriter; private bool _analyzeMode = false; private MobilePage _page; private Form _currentForm; private bool[] _usingPostBackType = new bool[] { false, false }; private bool[] _writtenPostBackType = new bool[] { false, false }; private int _numberOfPostBacks; private bool _postBackCardsEfficient = false; private IDictionary _formVariables = null; private IDictionary _controlShortNames = null; private Stack _layoutStack = new Stack(); private Stack _formatStack = new Stack(); private WmlLayout _currentWrittenLayout = null; private WmlFormat _currentWrittenFormat = null; private bool _pendingBreak = false; private bool _inAnchor = false; private int _numberOfSoftkeys; private bool _provideBackButton = false; private bool _writtenFormVariables = false; private bool _alwaysScrambleClientIDs = false; private const String _largeTag = "big"; private const String _smallTag = "small"; private const String _boldTag = "b"; private const String _italicTag = "i"; internal const String _postBackCardPrefix = "__pbc"; private const String _postBackWithVarsCardId = "__pbc1"; private const String _postBackWithoutVarsCardId = "__pbc2"; internal const String _postBackEventTargetVarName = "mcsvt"; internal const String _postBackEventArgumentVarName = "mcsva"; private const String _shortNamePrefix = "mcsv"; private const int _maxShortNameLength = 16; private static Random _random = new Random(); /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WmlMobileTextWriter"]/*' /> public WmlMobileTextWriter(TextWriter writer, MobileCapabilities device, MobilePage page) : base(writer, device) { _realInnerWriter = writer; _page = page; _numberOfSoftkeys = Device.NumberOfSoftkeys; if (_numberOfSoftkeys > 2) { _numberOfSoftkeys = 2; } // For phones that don't have a back button, assign a softkey. if (_numberOfSoftkeys == 2 && !Device.HasBackButton) { _numberOfSoftkeys = 1; _provideBackButton = true; _alwaysScrambleClientIDs = _provideBackButton && !device.CanRenderOneventAndPrevElementsTogether; } } // AnalyzeMode is set to true during first analysis pass of rendering. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.AnalyzeMode"]/*' /> public bool AnalyzeMode { get { return _analyzeMode; } set { _analyzeMode = value; if (value) { _analyzeWriter = new EmptyTextWriter(); InnerWriter = _analyzeWriter; } else { InnerWriter = _realInnerWriter; } } } internal bool HasFormVariables { get { return _writtenFormVariables; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.EnterLayout"]/*' /> public override void EnterLayout(Style style) { if (AnalyzeMode) { return; } WmlLayout newLayout = new WmlLayout(style, CurrentLayout); _layoutStack.Push(newLayout); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.ExitLayout"]/*' /> public override void ExitLayout(Style style, bool breakAfter) { if (!AnalyzeMode) { if (breakAfter) { PendingBreak = true; } _layoutStack.Pop(); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.EnterFormat"]/*' /> public override void EnterFormat(Style style) { if (AnalyzeMode) { return; } WmlFormat newFormat = new WmlFormat(style, CurrentFormat); _formatStack.Push(newFormat); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.ExitFormat"]/*' /> public override void ExitFormat(Style style) { if (AnalyzeMode) { return; } _formatStack.Pop(); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.BeginForm"]/*' /> public virtual void BeginForm(Form form) { _cachedFormQueryString = null; _currentForm = form; _writtenFormVariables = false; // To keep track of postbacks which submit form variables, // and postbacks that don't. Used for postback cards // (see UsePostBackCards) _usingPostBackType[0] = _usingPostBackType[1] = false; if (AnalyzeMode) { _numberOfPostBacks = 0; _postBackCardsEfficient = false; _controlShortNames = null; } else { PendingBreak = false; _currentWrittenLayout = null; _currentWrittenFormat = null; RenderBeginForm(form); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.EndForm"]/*' /> public virtual void EndForm() { if (AnalyzeMode) { // Analyze form when done. PostAnalyzeForm(); } else { RenderEndForm(); } } // Single parameter - used for rendering ordinary inline text // (with encoding but without breaks). /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderText"]/*' /> public void RenderText(String text) { RenderText(text, false, true); } // Two parameters - used for rendering encoded text with or without breaks) /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderText1"]/*' /> public void RenderText(String text, bool breakAfter) { RenderText(text, breakAfter, true); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderText2"]/*' /> public virtual void RenderText(String text, bool breakAfter, bool encodeText) { if (!AnalyzeMode) { EnsureLayout(); // Don't use formatting tags inside anchor. if (!_inAnchor) { EnsureFormat(); } WriteText(text, encodeText); if (breakAfter) { PendingBreak = true; } } } // Escape '&' in XML if it hasn't been internal String EscapeAmpersand(String url) { const char ampersand = '&'; const String ampEscaped = "amp;"; if (url == null) { return null; } int ampPos = url.IndexOf(ampersand); while (ampPos != -1) { if (url.Length - ampPos <= ampEscaped.Length || url.Substring(ampPos + 1, ampEscaped.Length) != ampEscaped) { url = url.Insert(ampPos + 1, ampEscaped); } ampPos = url.IndexOf(ampersand, ampPos + ampEscaped.Length + 1); } return url; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderBeginHyperlink"]/*' /> public virtual void RenderBeginHyperlink(String targetUrl, bool encodeUrl, String softkeyLabel, bool implicitSoftkeyLabel, bool mapToSoftkey) { if (!AnalyzeMode) { EnsureLayout(); EnsureFormat(); WriteBeginTag("a"); Write(" href=\""); if (encodeUrl) { WriteEncodedUrl(targetUrl); } else { Write(EscapeAmpersand(targetUrl)); } Write("\""); if (softkeyLabel != null && softkeyLabel.Length > 0 && !RequiresNoSoftkeyLabels()) { WriteTextEncodedAttribute("title", softkeyLabel); } Write(">"); _inAnchor = true; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderEndHyperlink"]/*' /> public virtual void RenderEndHyperlink(bool breakAfter) { if (!AnalyzeMode) { WriteEndTag("a"); if (breakAfter) { PendingBreak = true; } _inAnchor = false; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderTextBox"]/*' /> public virtual void RenderTextBox(String id, String value, String format, String title, bool password, int size, int maxLength, bool generateRandomID, bool breakAfter) { if (!AnalyzeMode) { // Input tags cannot appear inside character formatting tags, // so close any character formatting. CloseCharacterFormat(); // Certain devices always render a break before a <select>. If // we're on such a device, cancel any pending breaks so as not // to get an extra line of whitespace. if (Device.RendersBreakBeforeWmlSelectAndInput) { PendingBreak = false; } EnsureLayout(); WriteBeginTag("input"); // Map the client ID to a short name. See // MapClientIDToShortName for details. WriteAttribute("name", MapClientIDToShortName(id, generateRandomID)); if (password) { WriteAttribute("type", "password"); } if (format != null && format.Length > 0) { WriteAttribute("format", format); } if (title != null && title.Length > 0) { WriteTextEncodedAttribute("title", title); } if (size > 0) { WriteAttribute("size", size.ToString(CultureInfo.InvariantCulture)); } if (maxLength > 0) { WriteAttribute("maxlength", maxLength.ToString(CultureInfo.InvariantCulture)); } if ((!_writtenFormVariables || ((WmlPageAdapter) Page.Adapter).RequiresValueAttributeInInputTag()) && value != null && (value.Length > 0 || password)) { WriteTextEncodedAttribute("value", value); } WriteLine(" />"); if (breakAfter && !Device.RendersBreaksAfterWmlInput) { PendingBreak = true; } } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderImage"]/*' /> public virtual void RenderImage(String source, String localSource, String alternateText, bool breakAfter) { if (!AnalyzeMode) { EnsureLayout(); WriteBeginTag("img"); WriteAttribute("src", source, true /*encode*/); if (localSource != null) { WriteAttribute("localsrc", localSource, true /*encode*/); } WriteTextEncodedAttribute("alt", alternateText != null ? alternateText : String.Empty); Write(" />"); if (breakAfter) { PendingBreak = true; } } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderBeginPostBack"]/*' /> public virtual void RenderBeginPostBack(String softkeyLabel, bool implicitSoftkeyLabel, bool mapToSoftkey) { if (!AnalyzeMode) { EnsureLayout(); EnsureFormat(); WriteBeginTag("anchor"); if (softkeyLabel != null && softkeyLabel.Length > 0 && !RequiresNoSoftkeyLabels()) { WriteTextEncodedAttribute("title", softkeyLabel); } Write(">"); _inAnchor = true; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderEndPostBack"]/*' /> public virtual void RenderEndPostBack(String target, String argument, WmlPostFieldType postBackType, bool includeVariables, bool breakAfter) { if (AnalyzeMode) { // Analyze postbacks to see if postback cards should // be rendered. AnalyzePostBack(includeVariables, postBackType); } else { RenderGoAction(target, argument, postBackType, includeVariables); WriteEndTag("anchor"); if (breakAfter) { PendingBreak = true; } _inAnchor = false; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderBeginSelect"]/*' /> public virtual void RenderBeginSelect(String name, String iname, String ivalue, String title, bool multiSelect) { if (!AnalyzeMode) { // Select tags cannot appear inside character formatting tags, // so close any character formatting. CloseCharacterFormat(); // Certain devices always render a break before a <select>. If // we're on such a device, cancel any pending breaks so as not // to get an extra line of whitespace. if (Device.RendersBreakBeforeWmlSelectAndInput) { PendingBreak = false; } EnsureLayout(); WriteBeginTag("select"); if (name != null && name.Length > 0) { // Map the client ID to a short name. See // MapClientIDToShortName for details. WriteAttribute("name", MapClientIDToShortName(name, false)); } if (iname != null && iname.Length > 0) { // Map the client ID to a short name. See // MapClientIDToShortName for details. WriteAttribute("iname", MapClientIDToShortName(iname, false)); } if (!_writtenFormVariables && ivalue != null && ivalue.Length > 0) { WriteTextEncodedAttribute("ivalue", ivalue); } if (title != null && title.Length >0) { WriteTextEncodedAttribute("title", title); } if (multiSelect) { WriteAttribute("multiple", "true"); } Write(">"); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderEndSelect"]/*' /> public virtual void RenderEndSelect(bool breakAfter) { if (!AnalyzeMode) { WriteEndTag("select"); if (breakAfter && !Device.RendersBreaksAfterWmlInput) { PendingBreak = true; } } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderSelectOption"]/*' /> public virtual void RenderSelectOption(String text) { if (!AnalyzeMode) { WriteFullBeginTag("option"); WriteEncodedText(text); WriteEndTag("option"); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderSelectOption1"]/*' /> public virtual void RenderSelectOption(String text, String value) { if (!AnalyzeMode) { WriteBeginTag("option"); WriteAttribute("value", value, true); Write(">"); WriteEncodedText(text); WriteEndTag("option"); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.BeginCustomMarkup"]/*' /> public virtual void BeginCustomMarkup() { if (!AnalyzeMode) { EnsureLayout(); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.EndCustomMarkup"]/*' /> public virtual void EndCustomMarkup() { } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.AddFormVariable"]/*' /> public void AddFormVariable(String clientID, String value, bool generateRandomID) { // On first (analyze) pass, form variables are added to // an array. On second pass, they are rendered. This ensures // that only visible controls generate variables. if (AnalyzeMode) { if (_formVariables == null) { _formVariables = new ListDictionary(); } // Map the client ID to a short name. See // MapClientIDToShortName for details. _formVariables[MapClientIDToShortName(clientID, generateRandomID)] = value; } } // Call to reset formatting state before outputting custom stuff. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.ResetFormattingState"]/*' /> public virtual void ResetFormattingState() { if (!AnalyzeMode) { CloseCharacterFormat(); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderExtraCards"]/*' /> public virtual void RenderExtraCards() { RenderPostBackCards(); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.IsValidSoftkeyLabel"]/*' /> public virtual bool IsValidSoftkeyLabel(String label) { return label != null && label.Length > 0 && label.Length <= Device.MaximumSoftkeyLabelLength; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderGoAction"]/*' /> public virtual void RenderGoAction(String target, String argument, WmlPostFieldType postBackType, bool includeVariables) { WriteBeginTag("go"); Write(" href=\""); IDictionary postBackVariables = null; if (includeVariables) { postBackVariables = ((WmlFormAdapter)CurrentForm.Adapter).CalculatePostBackVariables(); if (postBackVariables == null || postBackVariables.Count == 0) { includeVariables = false; } } bool externalSubmit; if (postBackType == WmlPostFieldType.Submit) { externalSubmit = CurrentForm.Action.Length > 0; postBackType = WmlPostFieldType.Normal; } else { externalSubmit = false; } if (target != null && !externalSubmit && UsePostBackCard(includeVariables)) { _writtenPostBackType[includeVariables ? 0 : 1] = true; // If using postback cards, render a go action to the given // postback card, along with setvars setting the target and // argument. Write("#"); Write(includeVariables ? _postBackWithVarsCardId : _postBackWithoutVarsCardId); Write("\">"); WriteBeginTag("setvar"); WriteAttribute("name", _postBackEventTargetVarName); WriteAttribute("value", target); Write("/>"); WriteBeginTag("setvar"); WriteAttribute("name", _postBackEventArgumentVarName); Write(" value=\""); if (argument != null) { if (postBackType == WmlPostFieldType.Variable) { Write("$("); Write(argument); Write(")"); } else { WriteEncodedText(argument); } } Write("\"/>"); } else { // This is the real postback. bool encode = false; String url = CalculateFormPostBackUrl(externalSubmit, ref encode); FormMethod method = CurrentForm.Method; String queryString = CalculateFormQueryString(); if (encode) { WriteEncodedUrl(url); } else { Write(url); } if(externalSubmit && queryString != null && queryString.Length > 0) { if(Device.RequiresUniqueFilePathSuffix) { int loc = queryString.IndexOf('&'); if(loc != -1) { queryString = queryString.Substring(0, loc); } } else { queryString = null; } } // Add any query string. if (queryString != null && queryString.Length > 0) { if(externalSubmit && (url.IndexOf('?') != -1)) { Write("&amp;"); } else { Write("?"); } if (queryString.IndexOf('$') != -1) { queryString = queryString.Replace("$", "$$"); } if(Page.Adapter.PersistCookielessData && Device.CanRenderOneventAndPrevElementsTogether) { queryString = ReplaceFormsCookieWithVariable(queryString); } base.WriteEncodedText(queryString); } Write("\""); // Method defaults to get in WML, so write it if it's not. if (method == FormMethod.Post) { WriteAttribute("method", "post"); } Write(">"); // Write the view state as a postfield. if (!externalSubmit) { String pageState = Page.ClientViewState; if (pageState != null) { if (Device.RequiresSpecialViewStateEncoding) { pageState = ((WmlPageAdapter) Page.Adapter).EncodeSpecialViewState(pageState); } WritePostField(MobilePage.ViewStateID, pageState); } // Write the event target. if (target != null) { WritePostField(MobilePage.HiddenPostEventSourceId, target); } else { // Target is null when the action is generated from a postback // card itself. In this case, set the event target to whatever // the original event target was. WritePostFieldVariable(MobilePage.HiddenPostEventSourceId, _postBackEventTargetVarName); } // Write the event argument, if valid. if (argument != null) { WritePostField(MobilePage.HiddenPostEventArgumentId, argument, postBackType); } } // Write postfields for form variables, if desired. Commands, for example, // include form variables. Links do not. if (includeVariables) { if (postBackVariables != null) { foreach (DictionaryEntry entry in postBackVariables) { Control ctl = (Control)entry.Key; Object value = entry.Value; if (value == null) { // Dynamic value. // Map the client ID to a short name. See // MapClientIDToShortName for details. // Note: Because this is called on the second pass, // we can just pass false as the second parameter WritePostFieldVariable(ctl.UniqueID, MapClientIDToShortName(ctl.ClientID, false)); } else { // Static value. WritePostField(ctl.UniqueID, (String)value); } } } } // Always include page hidden variables. if (Page.HasHiddenVariables()) { String hiddenVariablePrefix = MobilePage.HiddenVariablePrefix; foreach (DictionaryEntry entry in Page.HiddenVariables) { if (entry.Value != null) { WritePostField(hiddenVariablePrefix + (String)entry.Key, (String)entry.Value); } } } } WriteEndTag("go"); } // Called after form is completed to analyze. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.PostAnalyzeForm"]/*' /> protected virtual void PostAnalyzeForm() { // Use postback cards if the number of postbacks exceeds the number // of required postback cards. // int numberOfCardsRequired = (_usingPostBackType[0] ? 1 : 0) + (_usingPostBackType[1] ? 1 : 0); if (_numberOfPostBacks > numberOfCardsRequired) { _postBackCardsEfficient = true; } } // Calculates the URL to output for the postback. Other writers may // override. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.CalculateFormPostBackUrl"]/*' /> protected virtual String CalculateFormPostBackUrl(bool externalSubmit, ref bool encode) { String url = CurrentForm.Action; if (externalSubmit && url.Length > 0) { url = CurrentForm.ResolveUrl(url); encode = false; } else { url = Page.RelativeFilePath; encode = true; } return url; } // Calculates the query string to output for the postback. Other // writers may override. internal String ReplaceFormsCookieWithVariable(String queryString) { String formsAuthCookieName = FormsAuthentication.FormsCookieName; if(!String.IsNullOrEmpty(formsAuthCookieName)) { int index = queryString.IndexOf(formsAuthCookieName + "=", StringComparison.Ordinal); if(index != -1) { int valueStart = index + formsAuthCookieName.Length + 1; int valueEnd = queryString.IndexOf('&', valueStart); if(valueStart < queryString.Length) { int length = ((valueEnd != -1) ? valueEnd : queryString.Length) - valueStart; queryString = queryString.Remove(valueStart, length); queryString = queryString.Insert(valueStart, "$(" + MapClientIDToShortName("__facn", false) + ")"); } } } return queryString; } private String _cachedFormQueryString; /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.CalculateFormQueryString"]/*' /> protected virtual String CalculateFormQueryString() { if (_cachedFormQueryString != null) { return _cachedFormQueryString; } String queryString = null; if (CurrentForm.Method != FormMethod.Get) { queryString = Page.QueryStringText; } if (Device.RequiresUniqueFilePathSuffix) { String ufps = Page.UniqueFilePathSuffix; if (queryString != null && queryString.Length > 0) { queryString = String.Concat(ufps, "&", queryString); } else { queryString = ufps; } } _cachedFormQueryString = queryString; return queryString; } internal virtual bool ShouldWriteFormID(Form form) { WmlPageAdapter pageAdapter = (WmlPageAdapter)CurrentForm.MobilePage.Adapter; return (form.ID != null && pageAdapter.RendersMultipleForms()); } // Renders the beginning of a form. // /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderBeginForm"]/*' /> protected virtual void RenderBeginForm(Form form) { WmlFormAdapter formAdapter = (WmlFormAdapter)CurrentForm.Adapter; IDictionary attributes = new ListDictionary(); if (ShouldWriteFormID(form)) { attributes.Add("id", form.ClientID); } String title = form.Title; if (title.Length > 0) { attributes.Add("title", title); } // Let the form adapter render the tag. This bit of indirection is // somewhat horky, but necessary so that people can subclass adapters // without worrying about the fact that much of the real work is done // in the writer. formAdapter.RenderCardTag(this, attributes); // Write form variables. if ((_formVariables != null && _formVariables.Count > 0) && (!_provideBackButton || Device.CanRenderOneventAndPrevElementsTogether)) { _writtenFormVariables = true; Write("<onevent type=\"onenterforward\"><refresh>"); foreach (DictionaryEntry entry in _formVariables) { WriteBeginTag("setvar"); WriteAttribute("name", (String)entry.Key); WriteTextEncodedAttribute("value", (String)entry.Value); Write(" />"); } WriteLine("</refresh></onevent>"); } formAdapter.RenderExtraCardElements(this); if (_provideBackButton) { Write("<do type=\"prev\" label=\""); Write(SR.GetString(SR.WmlMobileTextWriterBackLabel)); WriteLine("\"><prev /></do>"); } } // Renders the ending of a form. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderEndForm"]/*' /> protected virtual void RenderEndForm() { CloseParagraph(); WriteEndTag("card"); WriteLine(); } // Postback cards provide an alternate, space-efficient way of doing // postbacks, on forms that have a lot of postback links. Instead of // posting back directly, postback links switch to a postback card, setting // variables for event target and argument. The postback card has // an onenterforward event that submits the postback. It also has // an onenterbackward, so that it becomes transparent in the card history. // (Clicking Back to enter the postback card immediately takes you // to the previous card) /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.UsePostBackCard"]/*' /> protected virtual bool UsePostBackCard(bool includeVariables) { bool b = _postBackCardsEfficient && Device.CanRenderPostBackCards; if (b && includeVariables) { WmlPageAdapter pageAdapter = (WmlPageAdapter)CurrentForm.MobilePage.Adapter; if (pageAdapter.RendersMultipleForms()) { b = false; } } return b; } // Renders postback cards. private void RenderPostBackCards() { for (int i = 0; i < 2; i++) { if (_writtenPostBackType[i]) { WriteBeginTag("card"); WriteAttribute("id", i == 0 ? _postBackWithVarsCardId : _postBackWithoutVarsCardId); WriteLine(">"); Write("<onevent type=\"onenterforward\">"); RenderGoAction(null, _postBackEventArgumentVarName, WmlPostFieldType.Variable, i == 0); WriteLine("</onevent>"); WriteLine("<onevent type=\"onenterbackward\"><prev /></onevent>"); WriteLine("</card>"); } } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderFormDoEvent"]/*' /> protected void RenderFormDoEvent(String doType, String arg, WmlPostFieldType postBackType, String text) { RenderDoEvent(doType, CurrentForm.UniqueID, arg, postBackType, text, true); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.RenderDoEvent"]/*' /> protected void RenderDoEvent(String doType, String target, String arg, WmlPostFieldType postBackType, String text, bool includeVariables) { //EnsureLayout(); WriteBeginTag("do"); WriteAttribute("type", doType); if (text != null && text.Length > 0) { WriteTextEncodedAttribute("label", text); } Write(">"); RenderGoAction(target, arg, postBackType, includeVariables); WriteEndTag("do"); } // Makes sure the writer has rendered a paragraph tag corresponding to // the current layout. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.EnsureLayout"]/*' /> protected virtual void EnsureLayout() { WmlLayout layout = CurrentLayout; if (_currentWrittenLayout != null && layout.Compare(_currentWrittenLayout)) { // Same layout as before. Only write any pending break. if (PendingBreak) { // Avoid writing tags like </b> AFTER the <br/>, instead // writing them before. if (_currentWrittenFormat != null && !CurrentFormat.Compare(_currentWrittenFormat)) { CloseCharacterFormat(); } WriteBreak(); } } else { // Layout has changed. Close current layout, and open new one. CloseParagraph(); OpenParagraph(layout, layout.Align != Alignment.Left, layout.Wrap != Wrapping.Wrap); } PendingBreak = false; } // Makes sure the writer has rendered character formatting tags // corresponding to the current format. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.EnsureFormat"]/*' /> protected virtual void EnsureFormat() { WmlFormat format = CurrentFormat; if (_currentWrittenFormat == null || !format.Compare(_currentWrittenFormat)) { CloseCharacterFormat(); OpenCharacterFormat(format, format.Bold, format.Italic, format.Size != FontSize.Normal); } } // Opens a paragraph with the given layout. Only the specified // attributes are used. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.OpenParagraph"]/*' /> protected virtual void OpenParagraph(WmlLayout layout, bool writeAlignment, bool writeWrapping) { if (_currentWrittenLayout == null) { WriteBeginTag("p"); if (writeAlignment) { String alignment; switch (layout.Align) { case Alignment.Right: alignment = "right"; break; case Alignment.Center: alignment = "center"; break; default: alignment = "left"; break; } WriteAttribute("align", alignment); } if (writeWrapping) { WriteAttribute("mode", layout.Wrap == Wrapping.NoWrap ? "nowrap" : "wrap"); } Write(">"); _currentWrittenLayout = layout; } } // Close any open paragraph. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.CloseParagraph"]/*' /> protected virtual void CloseParagraph() { if (_currentWrittenLayout != null) { CloseCharacterFormat(); WriteEndTag("p"); _currentWrittenLayout = null; } } // Renders tags to enter the given character format. Only the specified // attributes are used. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.OpenCharacterFormat"]/*' /> protected virtual void OpenCharacterFormat(WmlFormat format, bool writeBold, bool writeItalic, bool writeSize) { if (_currentWrittenFormat == null) { if (writeBold && format.Bold) { WriteFullBeginTag(_boldTag); format.WrittenBold = true; } if (writeItalic && format.Italic) { WriteFullBeginTag(_italicTag); format.WrittenItalic = true; } if (writeSize && format.Size != FontSize.Normal) { WriteFullBeginTag(format.Size == FontSize.Large ? _largeTag : _smallTag); format.WrittenSize = true; } _currentWrittenFormat = format; } } // Close any open character formatting tags. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.CloseCharacterFormat"]/*' /> protected virtual void CloseCharacterFormat() { if (_currentWrittenFormat != null) { if (_currentWrittenFormat.WrittenSize) { WriteEndTag(_currentWrittenFormat.Size == FontSize.Large ? _largeTag : _smallTag); } if (_currentWrittenFormat.WrittenItalic) { WriteEndTag(_italicTag); } if (_currentWrittenFormat.WrittenBold) { WriteEndTag(_boldTag); } _currentWrittenFormat = null; } } private static readonly char[] _attributeCharacters = new char[] {'"', '&', '<', '>', '$'}; /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteAttribute"]/*' /> public override void WriteAttribute(String attribute, String value, bool encode) { // If in analyze mode, we don't actually have to perform the conversion, because // it's not getting written anyway. // If the value is null, we return without writing anything. This is different // from HtmlTextWriter, which writes the name of the attribute, but no value at all. // A name with no value is illegal in Wml. if (value == null) { return; } if (AnalyzeMode) { encode = false; } if (encode) { // Unlike HTML encoding, we need to replace $ with $$, and <> with &lt; and &gt;. // We can't do this by piggybacking HtmlTextWriter.WriteAttribute, because it // would translate the & in &lt; or &gt; to &amp;. So we more or less copy the // ASP.NET code that does similar encoding. Write(' '); Write(attribute); Write("=\""); int cb = value.Length; int pos = value.IndexOfAny(_attributeCharacters); if (pos == -1) { Write(value); } else { char[] s = value.ToCharArray(); int startPos = 0; while (pos < cb) { if (pos > startPos) { Write(s, startPos, pos - startPos); } char ch = s[pos]; switch (ch) { case '\"': Write("&quot;"); break; case '&': Write("&amp;"); break; case '<': Write("&lt;"); break; case '>': Write("&gt;"); break; case '$': Write("$$"); break; } startPos = pos + 1; pos = value.IndexOfAny(_attributeCharacters, startPos); if (pos == -1) { Write(s, startPos, cb - startPos); break; } } } Write('\"'); } else { base.WriteAttribute(attribute, value, encode); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteTextEncodedAttribute"]/*' /> protected void WriteTextEncodedAttribute(String attribute, String value) { WriteAttribute(attribute, value, true); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.CurrentForm"]/*' /> protected Form CurrentForm { get { return _currentForm; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.Page"]/*' /> protected MobilePage Page { get { return _page; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.NumberOfSoftkeys"]/*' /> protected int NumberOfSoftkeys { get { return _numberOfSoftkeys; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.AnalyzePostBack"]/*' /> protected virtual void AnalyzePostBack(bool includeVariables, WmlPostFieldType postBackType) { _usingPostBackType[includeVariables ? 0 : 1] = true; if (postBackType != WmlPostFieldType.Submit || CurrentForm.Action.Length == 0) { _numberOfPostBacks++; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteEncodedUrl"]/*' /> public override void WriteEncodedUrl(String url) { if (url == null) { return; } int i = url.IndexOf('?'); if (i != -1) { WriteUrlEncodedString(url.Substring(0, i), false); String s = url.Substring(i); if (s.IndexOf('$') != -1) { s = s.Replace("$", "%24"); } base.WriteEncodedText(s); //WriteEncodedText(url.Substring(i)); } else { WriteUrlEncodedString(url, false); } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteEncodedText"]/*' /> public override void WriteEncodedText(String text) { if (text == null) { return; } if (text.IndexOf('$') != -1) { text = text.Replace("$", "$$"); } base.WriteEncodedText(text); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteText"]/*' /> public void WriteText(String text, bool encodeText) { if (encodeText) { WriteEncodedText(text); } else { WritePlainText(text); } } private void WritePlainText(String text) { if (text == null) { return; } if (text.IndexOf('$') != -1) { text = text.Replace("$", "$$"); } Write(text); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WriteBreak"]/*' /> protected new void WriteBreak() { Write("<br/>\r\n"); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WritePostField"]/*' /> public void WritePostField(String name, String value) { WritePostField(name, value, WmlPostFieldType.Normal); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WritePostFieldVariable"]/*' /> public void WritePostFieldVariable(String name, String arg) { WritePostField(name, arg, WmlPostFieldType.Variable); } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.WritePostField1"]/*' /> public void WritePostField(String name, String value, WmlPostFieldType type) { Write("<postfield name=\""); Write(name); Write("\" value=\""); if (type == WmlPostFieldType.Variable) { Write("$("); } if (type == WmlPostFieldType.Normal) { if (Device.RequiresUrlEncodedPostfieldValues) { WriteEncodedUrlParameter(value); } else { WriteEncodedText(value); } } else { Write(value); } if (type == WmlPostFieldType.Variable) { Write(")"); } Write("\" />"); } // MapClientIDToShortName provides a unique map of control ClientID properties // to shorter names. In cases where a control has a very long ClientID, a // shorter unique name is used. All references to the client ID on the page // are mapped, resulting in the same postback regardless of mapping. // MapClientIDToShortName also scrambles client IDs that need to be // scrambled for security reasons. /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.MapClientIDToShortName"]/*' /> protected internal String MapClientIDToShortName(String clientID, bool generateRandomID) { if (_alwaysScrambleClientIDs) { generateRandomID = true; } if (_controlShortNames != null) { String lookup = (String)_controlShortNames[clientID]; if (lookup != null) { return lookup; } } if (!generateRandomID) { bool shortID = clientID.Length < _maxShortNameLength; // Map names with underscores and conflicting names regardless of length. bool goodID = !HasUnnamedControlId(clientID) && !NameConflicts(clientID); if (shortID && goodID) { return clientID; } } if (_controlShortNames == null) { _controlShortNames = new ListDictionary(); } String shortName; if (generateRandomID) { shortName = GetRandomID(5); } else { shortName = String.Empty; } shortName = String.Concat(_shortNamePrefix, shortName, _controlShortNames.Count.ToString(CultureInfo.InvariantCulture)); _controlShortNames[clientID] = shortName; return shortName; } // VSWhidbey 280485: We used to check '_' for default control id. But // VSWhidbey 188477 removed the '_', so here it checks "ctl" with id // separator (for naming container case) instead. private bool HasUnnamedControlId(string clientID) { const string unnamedIdPrefix = "ctl"; if (clientID.StartsWith(unnamedIdPrefix, StringComparison.Ordinal)) { return true; } string unnamedIdPrefixWithIdSeparator = Page.IdSeparator + unnamedIdPrefix; int unnamedIdPrefixLength = unnamedIdPrefix.Length; if (clientID.Length > unnamedIdPrefixLength && clientID.IndexOf(unnamedIdPrefixWithIdSeparator, unnamedIdPrefixLength, StringComparison.Ordinal) != -1) { return true; } return false; } private String GetRandomID(int length) { Byte[] randomBytes = new Byte[length]; _random.NextBytes(randomBytes); char[] randomChars = new char[length]; for (int i = 0; i < length; i++) { randomChars[i] = (char)((((int)randomBytes[i]) % 26) + 'a'); } return new String(randomChars); } private bool NameConflicts(String name) { if (name == null) { return false; } Debug.Assert(_postBackEventTargetVarName.ToLower(CultureInfo.InvariantCulture) == _postBackEventTargetVarName && _postBackEventArgumentVarName.ToLower(CultureInfo.InvariantCulture) == _postBackEventArgumentVarName && _shortNamePrefix.ToLower(CultureInfo.InvariantCulture) == _shortNamePrefix); name = name.ToLower(CultureInfo.InvariantCulture); return name == _postBackEventTargetVarName || name == _postBackEventArgumentVarName || name.StartsWith(_shortNamePrefix, StringComparison.Ordinal); } private static readonly WmlLayout _defaultLayout = new WmlLayout(Alignment.Left, Wrapping.Wrap); /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.DefaultLayout"]/*' /> protected virtual WmlLayout DefaultLayout { get { return _defaultLayout; } } private WmlLayout CurrentLayout { get { if (_layoutStack.Count > 0) { return (WmlLayout)_layoutStack.Peek(); } else { return DefaultLayout; } } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.PendingBreak"]/*' /> protected bool PendingBreak { get { return _pendingBreak; } set { _pendingBreak = value; } } private static readonly WmlFormat _defaultFormat = new WmlFormat(false, false, FontSize.Normal); /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlMobileTextWriter.DefaultFormat"]/*' /> protected virtual WmlFormat DefaultFormat { get { return _defaultFormat; } } private WmlFormat CurrentFormat { get { if (_formatStack.Count > 0) { return (WmlFormat)_formatStack.Peek(); } else { return DefaultFormat; } } } private bool _requiresNoSoftkeyLabels = false; private bool _haveRequiresNoSoftkeyLabels = false; private bool RequiresNoSoftkeyLabels() { if (!_haveRequiresNoSoftkeyLabels) { String RequiresNoSoftkeyLabelsString = Device["requiresNoSoftkeyLabels"]; if (RequiresNoSoftkeyLabelsString == null) { _requiresNoSoftkeyLabels = false; } else { _requiresNoSoftkeyLabels = Convert.ToBoolean(RequiresNoSoftkeyLabelsString, CultureInfo.InvariantCulture); } _haveRequiresNoSoftkeyLabels = true; } return _requiresNoSoftkeyLabels; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlLayout"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] protected class WmlLayout { private Wrapping _wrap; private Alignment _align; /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlLayout.WmlLayout"]/*' /> public WmlLayout(Style style, WmlLayout currentLayout) { Alignment align = (Alignment)style[Style.AlignmentKey, true]; Align = (align != Alignment.NotSet) ? align : currentLayout.Align; Wrapping wrap = (Wrapping)style[Style.WrappingKey , true]; Wrap = (wrap != Wrapping.NotSet) ? wrap : currentLayout.Wrap; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlLayout.WmlLayout1"]/*' /> public WmlLayout(Alignment alignment, Wrapping wrapping) { Align = alignment; Wrap = wrapping; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlLayout.Wrap"]/*' /> public Wrapping Wrap { get { return _wrap; } set { _wrap = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlLayout.Align"]/*' /> public Alignment Align { get { return _align; } set { _align = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlLayout.Compare"]/*' /> public virtual bool Compare(WmlLayout layout) { return Wrap == layout.Wrap && Align == layout.Align; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] protected class WmlFormat { private bool _bold; private bool _italic; private FontSize _size; private bool _writtenBold = false; private bool _writtenItalic = false; private bool _writtenSize = false; /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.WmlFormat"]/*' /> public WmlFormat(Style style, WmlFormat currentFormat) { BooleanOption bold = (BooleanOption)style[Style.BoldKey, true]; Bold = (bold != BooleanOption.NotSet) ? bold == BooleanOption.True : currentFormat.Bold; BooleanOption italic = (BooleanOption)style[Style.ItalicKey, true]; Italic = (italic != BooleanOption.NotSet) ? italic == BooleanOption.True : currentFormat.Italic; FontSize fontSize = (FontSize)style[Style.FontSizeKey, true]; Size = (fontSize != FontSize.NotSet) ? fontSize : currentFormat.Size; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.WmlFormat1"]/*' /> public WmlFormat(bool bold, bool italic, FontSize size) { Bold = bold; Italic = italic; Size = size; } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.Bold"]/*' /> public bool Bold { get { return _bold; } set { _bold = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.Italic"]/*' /> public bool Italic { get { return _italic; } set { _italic = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.Size"]/*' /> public FontSize Size { get { return _size; } set { _size = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.WrittenBold"]/*' /> public bool WrittenBold { get { return _writtenBold; } set { _writtenBold = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.WrittenItalic"]/*' /> public bool WrittenItalic { get { return _writtenItalic; } set { _writtenItalic = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.WrittenSize"]/*' /> public bool WrittenSize { get { return _writtenSize; } set { _writtenSize = value; } } /// <include file='doc\WmlMobileTextWriter.uex' path='docs/doc[@for="WmlFormat.Compare"]/*' /> public virtual bool Compare(WmlFormat format) { return Bold == format.Bold && Italic == format.Italic && Size == format.Size; } } } }
// 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.Security; using System.Threading; namespace System.Runtime.Serialization { /// <summary>The structure for holding all of the data needed for object serialization and deserialization.</summary> public sealed class SerializationInfo { private const int DefaultSize = 4; // Even though we have a dictionary, we're still keeping all the arrays around for back-compat. // Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added. private string[] _names; private object?[] _values; private Type[] _types; private int _count; private readonly Dictionary<string, int> _nameToIndex; private readonly IFormatterConverter _converter; private string _rootTypeName; private string _rootTypeAssemblyName; private Type _rootType; internal static AsyncLocal<bool> AsyncDeserializationInProgress { get; } = new AsyncLocal<bool>(); #if !CORECLR // On AoT, assume private members are reflection blocked, so there's no further protection required // for the thread's DeserializationTracker [ThreadStatic] private static DeserializationTracker? t_deserializationTracker; private static DeserializationTracker GetThreadDeserializationTracker() => t_deserializationTracker ??= new DeserializationTracker(); #endif // !CORECLR // Returns true if deserialization is currently in progress public static bool DeserializationInProgress { #if CORECLR [DynamicSecurityMethod] // Methods containing StackCrawlMark local var must be marked DynamicSecurityMethod #endif get { if (AsyncDeserializationInProgress.Value) { return true; } #if CORECLR StackCrawlMark stackMark = StackCrawlMark.LookForMe; DeserializationTracker tracker = Thread.GetThreadDeserializationTracker(ref stackMark); #else DeserializationTracker tracker = GetThreadDeserializationTracker(); #endif bool result = tracker.DeserializationInProgress; return result; } } // Throws a SerializationException if dangerous deserialization is currently // in progress public static void ThrowIfDeserializationInProgress() { if (DeserializationInProgress) { throw new SerializationException(SR.Serialization_DangerousDeserialization); } } // Throws a DeserializationBlockedException if dangerous deserialization is currently // in progress and the AppContext switch Switch.System.Runtime.Serialization.SerializationGuard.{switchSuffix} // is not true. The value of the switch is cached in cachedValue to avoid repeated lookups: // 0: No value cached // 1: The switch is true // -1: The switch is false public static void ThrowIfDeserializationInProgress(string switchSuffix, ref int cachedValue) { const string SwitchPrefix = "Switch.System.Runtime.Serialization.SerializationGuard."; if (switchSuffix == null) { throw new ArgumentNullException(nameof(switchSuffix)); } if (string.IsNullOrWhiteSpace(switchSuffix)) { throw new ArgumentException(SR.Argument_EmptyName, nameof(switchSuffix)); } if (cachedValue == 0) { bool isEnabled = false; if (AppContext.TryGetSwitch(SwitchPrefix + switchSuffix, out isEnabled) && isEnabled) { cachedValue = 1; } else { cachedValue = -1; } } if (cachedValue == 1) { return; } else if (cachedValue == -1) { if (DeserializationInProgress) { throw new SerializationException(SR.Format(SR.Serialization_DangerousDeserialization_Switch, SwitchPrefix + switchSuffix)); } } else { throw new ArgumentOutOfRangeException(nameof(cachedValue)); } } // Declares that the current thread and async context have begun deserialization. // In this state, if the SerializationGuard or other related AppContext switches are set, // actions likely to be dangerous during deserialization, such as starting a process will be blocked. // Returns a DeserializationToken that must be disposed to remove the deserialization state. #if CORECLR [DynamicSecurityMethod] // Methods containing StackCrawlMark local var must be marked DynamicSecurityMethod #endif public static DeserializationToken StartDeserialization() { if (LocalAppContextSwitches.SerializationGuard) { #if CORECLR StackCrawlMark stackMark = StackCrawlMark.LookForMe; DeserializationTracker tracker = Thread.GetThreadDeserializationTracker(ref stackMark); #else DeserializationTracker tracker = GetThreadDeserializationTracker(); #endif if (!tracker.DeserializationInProgress) { lock (tracker) { if (!tracker.DeserializationInProgress) { AsyncDeserializationInProgress.Value = true; tracker.DeserializationInProgress = true; return new DeserializationToken(tracker); } } } } return new DeserializationToken(null); } [CLSCompliant(false)] public SerializationInfo(Type type, IFormatterConverter converter) { if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } if (converter == null) { throw new ArgumentNullException(nameof(converter)); } _rootType = type; _rootTypeName = type.FullName!; _rootTypeAssemblyName = type.Module.Assembly.FullName!; _names = new string[DefaultSize]; _values = new object[DefaultSize]; _types = new Type[DefaultSize]; _nameToIndex = new Dictionary<string, int>(); _converter = converter; } [CLSCompliant(false)] public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust) : this(type, converter) { // requireSameTokenInPartialTrust is a vacuous parameter in a platform that does not support partial trust. } public string FullTypeName { get => _rootTypeName; set { if (null == value) { throw new ArgumentNullException(nameof(value)); } _rootTypeName = value; IsFullTypeNameSetExplicit = true; } } public string AssemblyName { get => _rootTypeAssemblyName; set { if (null == value) { throw new ArgumentNullException(nameof(value)); } _rootTypeAssemblyName = value; IsAssemblyNameSetExplicit = true; } } public bool IsFullTypeNameSetExplicit { get; private set; } public bool IsAssemblyNameSetExplicit { get; private set; } public void SetType(Type type) { if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } if (!ReferenceEquals(_rootType, type)) { _rootType = type; _rootTypeName = type.FullName!; _rootTypeAssemblyName = type.Module.Assembly.FullName!; IsFullTypeNameSetExplicit = false; IsAssemblyNameSetExplicit = false; } } public int MemberCount => _count; public Type ObjectType => _rootType; public SerializationInfoEnumerator GetEnumerator() => new SerializationInfoEnumerator(_names, _values, _types, _count); private void ExpandArrays() { int newSize; Debug.Assert(_names.Length == _count, "[SerializationInfo.ExpandArrays]_names.Length == _count"); newSize = (_count * 2); // In the pathological case, we may wrap if (newSize < _count) { if (int.MaxValue > _count) { newSize = int.MaxValue; } } // Allocate more space and copy the data string[] newMembers = new string[newSize]; object[] newData = new object[newSize]; Type[] newTypes = new Type[newSize]; Array.Copy(_names, newMembers, _count); Array.Copy(_values, newData, _count); Array.Copy(_types, newTypes, _count); // Assign the new arrays back to the member vars. _names = newMembers; _values = newData; _types = newTypes; } public void AddValue(string name, object? value, Type type) { if (null == name) { throw new ArgumentNullException(nameof(name)); } if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } AddValueInternal(name, value, type); } public void AddValue(string name, object? value) { if (null == value) { AddValue(name, value, typeof(object)); } else { AddValue(name, value, value.GetType()); } } public void AddValue(string name, bool value) { AddValue(name, (object)value, typeof(bool)); } public void AddValue(string name, char value) { AddValue(name, (object)value, typeof(char)); } [CLSCompliant(false)] public void AddValue(string name, sbyte value) { AddValue(name, (object)value, typeof(sbyte)); } public void AddValue(string name, byte value) { AddValue(name, (object)value, typeof(byte)); } public void AddValue(string name, short value) { AddValue(name, (object)value, typeof(short)); } [CLSCompliant(false)] public void AddValue(string name, ushort value) { AddValue(name, (object)value, typeof(ushort)); } public void AddValue(string name, int value) { AddValue(name, (object)value, typeof(int)); } [CLSCompliant(false)] public void AddValue(string name, uint value) { AddValue(name, (object)value, typeof(uint)); } public void AddValue(string name, long value) { AddValue(name, (object)value, typeof(long)); } [CLSCompliant(false)] public void AddValue(string name, ulong value) { AddValue(name, (object)value, typeof(ulong)); } public void AddValue(string name, float value) { AddValue(name, (object)value, typeof(float)); } public void AddValue(string name, double value) { AddValue(name, (object)value, typeof(double)); } public void AddValue(string name, decimal value) { AddValue(name, (object)value, typeof(decimal)); } public void AddValue(string name, DateTime value) { AddValue(name, (object)value, typeof(DateTime)); } internal void AddValueInternal(string name, object? value, Type type) { if (_nameToIndex.ContainsKey(name)) { throw new SerializationException(SR.Serialization_SameNameTwice); } _nameToIndex.Add(name, _count); // If we need to expand the arrays, do so. if (_count >= _names.Length) { ExpandArrays(); } // Add the data and then advance the counter. _names[_count] = name; _values[_count] = value; _types[_count] = type; _count++; } /// <summary> /// Finds the value if it exists in the current data. If it does, we replace /// the values, if not, we append it to the end. This is useful to the /// ObjectManager when it's performing fixups. /// /// All error checking is done with asserts. Although public in coreclr, /// it's not exposed in a contract and is only meant to be used by corefx. /// /// This isn't a public API, but it gets invoked dynamically by /// BinaryFormatter /// /// This should not be used by clients: exposing out this functionality would allow children /// to overwrite their parent's values. It is public in order to give corefx access to it for /// its ObjectManager implementation, but it should not be exposed out of a contract. /// </summary> /// <param name="name"> The name of the data to be updated.</param> /// <param name="value"> The new value.</param> /// <param name="type"> The type of the data being added.</param> public void UpdateValue(string name, object value, Type type) { Debug.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null"); Debug.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null"); Debug.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null"); int index = FindElement(name); if (index < 0) { AddValueInternal(name, value, type); } else { _values[index] = value; _types[index] = type; } } private int FindElement(string name) { if (null == name) { throw new ArgumentNullException(nameof(name)); } int index; if (_nameToIndex.TryGetValue(name, out index)) { return index; } return -1; } /// <summary> /// Gets the location of a particular member and then returns /// the value of the element at that location. The type of the member is /// returned in the foundType field. /// </summary> /// <param name="name"> The name of the element to find.</param> /// <param name="foundType"> The type of the element associated with the given name.</param> /// <returns>The value of the element at the position associated with name.</returns> private object? GetElement(string name, out Type foundType) { int index = FindElement(name); if (index == -1) { throw new SerializationException(SR.Format(SR.Serialization_NotFound, name)); } Debug.Assert(index < _values.Length, "[SerializationInfo.GetElement]index<_values.Length"); Debug.Assert(index < _types.Length, "[SerializationInfo.GetElement]index<_types.Length"); foundType = _types[index]; Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return _values[index]; } private object? GetElementNoThrow(string name, out Type? foundType) { int index = FindElement(name); if (index == -1) { foundType = null; return null; } Debug.Assert(index < _values.Length, "[SerializationInfo.GetElement]index<_values.Length"); Debug.Assert(index < _types.Length, "[SerializationInfo.GetElement]index<_types.Length"); foundType = _types[index]; Debug.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null"); return _values[index]; } public object? GetValue(string name, Type type) { if ((object)type == null) { throw new ArgumentNullException(nameof(type)); } if (!type.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeType); Type foundType; object? value = GetElement(name, out foundType); if (ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) { return value; } Debug.Assert(_converter != null, "[SerializationInfo.GetValue]_converter!=null"); return _converter.Convert(value, type); } internal object? GetValueNoThrow(string name, Type type) { Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null"); Debug.Assert(type.IsRuntimeImplemented(), "[SerializationInfo.GetValue]type is not a runtime type"); Type? foundType; object? value = GetElementNoThrow(name, out foundType); if (value == null) return null; if (ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType)) { return value; } Debug.Assert(_converter != null, "[SerializationInfo.GetValue]_converter!=null"); return _converter.Convert(value, type); } public bool GetBoolean(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(bool)) ? (bool)value! : _converter.ToBoolean(value!); // if value is null To* method will either deal with it or throw } public char GetChar(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(char)) ? (char)value! : _converter.ToChar(value!); } [CLSCompliant(false)] public sbyte GetSByte(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(sbyte)) ? (sbyte)value! : _converter.ToSByte(value!); } public byte GetByte(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(byte)) ? (byte)value! : _converter.ToByte(value!); } public short GetInt16(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(short)) ? (short)value! : _converter.ToInt16(value!); } [CLSCompliant(false)] public ushort GetUInt16(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(ushort)) ? (ushort)value! : _converter.ToUInt16(value!); } public int GetInt32(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(int)) ? (int)value! : _converter.ToInt32(value!); } [CLSCompliant(false)] public uint GetUInt32(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(uint)) ? (uint)value! : _converter.ToUInt32(value!); } public long GetInt64(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(long)) ? (long)value! : _converter.ToInt64(value!); } [CLSCompliant(false)] public ulong GetUInt64(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(ulong)) ? (ulong)value! : _converter.ToUInt64(value!); } public float GetSingle(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(float)) ? (float)value! : _converter.ToSingle(value!); } public double GetDouble(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(double)) ? (double)value! : _converter.ToDouble(value!); } public decimal GetDecimal(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(decimal)) ? (decimal)value! : _converter.ToDecimal(value!); } public DateTime GetDateTime(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(DateTime)) ? (DateTime)value! : _converter.ToDateTime(value!); } public string? GetString(string name) { Type foundType; object? value = GetElement(name, out foundType); return ReferenceEquals(foundType, typeof(string)) || value == null ? (string?)value : _converter.ToString(value); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Bond.Internal.Reflection; public static class Reflection { static readonly object Empty = new object(); static readonly Dictionary<BondDataType, string> bondTypeName = new Dictionary<BondDataType, string> { {BondDataType.BT_BOOL, "bool"}, {BondDataType.BT_UINT8, "uint8"}, {BondDataType.BT_UINT16, "uint16"}, {BondDataType.BT_UINT32, "uint32"}, {BondDataType.BT_UINT64, "uint64"}, {BondDataType.BT_FLOAT, "float"}, {BondDataType.BT_DOUBLE, "double"}, {BondDataType.BT_STRING, "string"}, {BondDataType.BT_LIST, "list"}, {BondDataType.BT_SET, "set"}, {BondDataType.BT_MAP, "map"}, {BondDataType.BT_INT8, "int8"}, {BondDataType.BT_INT16, "int16"}, {BondDataType.BT_INT32, "int32"}, {BondDataType.BT_INT64, "int64"}, {BondDataType.BT_WSTRING, "wstring"} }; #region Public APIs /// <summary> /// Get list of fields for a Bond schema /// </summary> public static IEnumerable<ISchemaField> GetSchemaFields(this Type type) { var fields = from fieldInfo in type.GetTypeInfo().DeclaredFields.Where(f => f.IsPublic) let idAttr = fieldInfo.GetAttribute<IdAttribute>() where idAttr != null select new Field(fieldInfo, idAttr.Value) as ISchemaField; var properties = from propertyInfo in type.GetTypeInfo().DeclaredProperties let idAttr = propertyInfo.GetAttribute<IdAttribute>() where idAttr != null select new Property(propertyInfo, idAttr.Value) as ISchemaField; var concatenated = fields.Concat(properties); return concatenated.OrderBy(m => m.Id); } /// <summary> /// Get the inner Type of composite/container types /// </summary> public static Type GetValueType(this Type type) { if (type.IsBondNullable() || type.IsBonded()) return type.GetTypeInfo().GenericTypeArguments[0]; if (type.IsArray) return type.GetElementType(); if (type.IsBondBlob()) return typeof(sbyte); return type.GetMethod(typeof(IEnumerable<>), "GetEnumerator") .ReturnType .GetTypeInfo() .GetDeclaredProperty("Current") .PropertyType; } /// <summary> /// Get the key and value Type for a map /// </summary> public static KeyValuePair<Type, Type> GetKeyValueType(this Type type) { var types = GetValueType(type).GetTypeInfo().GenericTypeArguments; if (types.Length != 2) { throw new InvalidOperationException("Expected generic type with 2 type arguments."); } return new KeyValuePair<Type, Type>(types[0], types[1]); } /// <summary> /// Get a value indicating whether the Type is a Bond schema /// </summary> public static bool IsBondStruct(this Type type) { return null != type.GetAttribute<SchemaAttribute>(); } /// <summary> /// Get a value indicating whether the Type is a bonded&lt;T> /// </summary> public static bool IsBonded(this Type type) { if (type.IsGenericType()) { var definition = type.GetGenericTypeDefinition(); return definition == typeof(IBonded<>) || definition == typeof(Tag.bonded<>) || definition.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IBonded)); } return false; } /// <summary> /// Get a value indicating whether the Type is a Bond nullable type /// </summary> public static bool IsBondNullable(this Type type) { return type.IsGenericType() && (type.GetGenericTypeDefinition() == typeof(Tag.nullable<>)); } /// <summary> /// Get a value indicating whether the Type is a Bond string /// </summary> public static bool IsBondString(this Type type) { return type == typeof(Tag.wstring) || type == typeof(string); } /// <summary> /// Get a value indicating whether the Type is a Bond blob /// </summary> public static bool IsBondBlob(this Type type) { return type == typeof(Tag.blob) || type == typeof(ArraySegment<byte>); } /// <summary> /// Get a value indicating whether the Type is a Bond list /// or a Bond vector /// </summary> public static bool IsBondList(this Type type) { if (type.IsGenericType()) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IList<>) || genericType == typeof(ICollection<>)) return true; } return typeof(IList).IsAssignableFrom(type) || typeof(ICollection).IsAssignableFrom(type); } /// <summary> /// Get a value indicating whether the Type is a Bond map /// </summary> public static bool IsBondMap(this Type type) { if (type.IsGenericType()) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IDictionary<,>)) return true; } return typeof(IDictionary).IsAssignableFrom(type); } /// <summary> /// Get a value indicating whether the Type is a Bond set /// </summary> public static bool IsBondSet(this Type type) { if (!type.IsGenericType()) return false; return typeof(ISet<>).MakeGenericType(type.GetTypeInfo().GenericTypeArguments[0]).IsAssignableFrom(type); } /// <summary> /// Get a value indicating whether the Type is a Bond container /// </summary> public static bool IsBondContainer(this Type type) { return type.IsBondList() || type.IsBondSet() || type.IsBondMap() || type.IsBondBlob(); } /// <summary> /// Get the BondDataType value for the Type /// </summary> public static BondDataType GetBondDataType(this Type type) { while (true) { if (type.IsBondStruct() || type.IsBonded()) return BondDataType.BT_STRUCT; if (type.IsBondNullable()) return BondDataType.BT_LIST; if (type.IsBondMap()) return BondDataType.BT_MAP; if (type.IsBondSet()) return BondDataType.BT_SET; if (type.IsBondList() || type.IsBondBlob()) return BondDataType.BT_LIST; if (type.IsEnum()) return BondDataType.BT_INT32; if (type == typeof(string)) return BondDataType.BT_STRING; if (type == typeof(Tag.wstring)) return BondDataType.BT_WSTRING; if (type == typeof(bool)) return BondDataType.BT_BOOL; if (type == typeof(byte)) return BondDataType.BT_UINT8; if (type == typeof(UInt16)) return BondDataType.BT_UINT16; if (type == typeof(UInt32)) return BondDataType.BT_UINT32; if (type == typeof(UInt64)) return BondDataType.BT_UINT64; if (type == typeof(float)) return BondDataType.BT_FLOAT; if (type == typeof(double)) return BondDataType.BT_DOUBLE; if (type == typeof(sbyte)) return BondDataType.BT_INT8; if (type == typeof(Int16)) return BondDataType.BT_INT16; if (type == typeof(Int32)) return BondDataType.BT_INT32; if (type == typeof(Int64)) return BondDataType.BT_INT64; if (type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetValueType(); continue; } return BondDataType.BT_UNAVAILABLE; } } /// <summary> /// Get the ListSubType value for the Type /// </summary> public static ListSubType GetBondListDataType(this Type type) { while (true) { if (type.IsBondNullable()) return ListSubType.NULLABLE_SUBTYPE; if (type.IsBondBlob()) return ListSubType.BLOB_SUBTYPE; if (type.IsBondList()) return ListSubType.NO_SUBTYPE; if (type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetValueType(); continue; } return ListSubType.NO_SUBTYPE; } } /// <summary> /// Get the Type representing the base schema or null if the schema has no base /// </summary> public static Type GetBaseSchemaType(this Type type) { if (type.IsClass()) { var baseType = type.GetBaseType(); return baseType != null && baseType.GetAttribute<SchemaAttribute>() != null ? baseType : null; } if (type.IsInterface()) { // Get all base interfaces. In case if an inheritance chain longer than 2, this returns all // the base interfaces flattened in no particular order, so we have to find the direct parent. var baseInterfaces = type.GetTypeInfo().ImplementedInterfaces .Where(t => t.GetAttribute<SchemaAttribute>() != null).ToArray(); for (var i = 0; i < baseInterfaces.Length; i++) { var baseInterface = baseInterfaces[i]; var indirectBaseInterfacesCount = baseInterface.GetTypeInfo().ImplementedInterfaces .Count(t => t.GetAttribute<SchemaAttribute>() != null); if (indirectBaseInterfacesCount == baseInterfaces.Length - 1) { return baseInterface; } } } return null; } /// <summary> /// Get the Type of the schema field, including any type annotations from TypeAttribute /// </summary> /// <remarks> /// In some cases this may not be the actual type of the property or field. /// If the property or field has a TypeAttribute, this will be the attribute's value /// and can provide schema information that is not available on the actual /// property/field type. /// </remarks> public static Type GetSchemaType(this ISchemaField schemaField) { var type = schemaField.MemberType; var typeAttr = schemaField.GetAttribute<TypeAttribute>(); if (typeAttr != null) { type = ResolveTypeArgumentTags(type, typeAttr.Value); } return type; } #endregion #region Internal /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "int Math::Abs(int)" overload, you can write: /// <code>(MethodInfo)BondReflection.InfoOf((int x) => Math.Abs(x))</code> /// </example> static MemberInfo InfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { if (expression == null) throw new ArgumentNullException("expression"); return InfoOf(expression.Body); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if that member is not a method. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "int Math::Abs(int)" overload, you can write: /// <code>BondReflection.MethodInfoOf((int x) => Math.Abs(x))</code> /// </example> internal static MethodInfo MethodInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { return InfoOf(expression) as MethodInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a generic method definition. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the generic method definition for some "int Foo::Bar&lt;T>(T)" overload, you can write: /// <code>BondReflection.GenericMethodInfoOf((int x) => Foo.Bar(x))</code>, which returns the definition Foo.Bar&lt;> /// </example> internal static MethodInfo GenericMethodInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { var methodInfo = MethodInfoOf(expression); return methodInfo == null ? null : methodInfo.GetGenericMethodDefinition(); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a PropertyInfo. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the PropertyInfo for the "int Foo::SomeProperty", you can write: /// <code>BondReflection.PropertyInfoOf((Foo f) => f.SomeProperty)</code> /// </example> internal static PropertyInfo PropertyInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { return InfoOf(expression) as PropertyInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a FieldInfo. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the FieldInfo for the "int Foo::someField" field, you can write: /// <code>BondReflection.FieldInfoOf((Foo f) => f.someField)</code> /// </example> internal static FieldInfo FieldInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { return InfoOf(expression) as FieldInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the PropertyInfo of "DateTime DateTime::Now { get; }", you can write: /// <code>(PropertyInfo)BondReflection.InfoOf(() => DateTime.Now)</code> /// </example> static MemberInfo InfoOf<TResult>(Expression<Func<TResult>> expression) { if (expression == null) throw new ArgumentNullException("expression"); return InfoOf(expression.Body); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if that member is not a method. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "int Math::Abs(int)" overload, you can write: /// <code>BondReflection.MethodInfoOf(() => Math.Abs(default(int)))</code> /// </example> internal static MethodInfo MethodInfoOf<TResult>(Expression<Func<TResult>> expression) { return InfoOf(expression) as MethodInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a generic method definition. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the generic method definition for some "int Foo::Bar&lt;T>(T)" overload, you can write: /// <code>BondReflection.GenericMethodInfoOf(() => Foo.Bar(default(int)))</code>, which returns the definition Foo.Bar&lt;> /// </example> internal static MethodInfo GenericMethodInfoOf<TResult>(Expression<Func<TResult>> expression) { var methodInfo = MethodInfoOf(expression); return methodInfo == null ? null : methodInfo.GetGenericMethodDefinition(); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "void Console::WriteLine(string)" overload, you can write: /// <code>(MethodInfo)BondReflection.InfoOf((string s) => Console.WriteLine(s))</code> /// </example> static MemberInfo InfoOf<T>(Expression<Action<T>> expression) { if (expression == null) throw new ArgumentNullException("expression"); return InfoOf(expression.Body); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if that member is not a method. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "void Foo::DoThing(int)" overload, you can write: /// <code>BondReflection.MethodInfoOf(() => Foo.DoThing(default(int)))</code> /// </example> internal static MethodInfo MethodInfoOf<T>(Expression<Action<T>> expression) { return InfoOf(expression) as MethodInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a generic method definition. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the generic method definition for some "void Foo::Bar&lt;T>(T)" overload, you can write: /// <code>BondReflection.GenericMethodInfoOf(() => Foo.Bar(default(int)))</code>, which returns the definition Foo.Bar&lt;> /// </example> internal static MethodInfo GenericMethodInfoOf<T>(Expression<Action<T>> expression) { var methodInfo = MethodInfoOf(expression); return methodInfo == null ? null : methodInfo.GetGenericMethodDefinition(); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> static MemberInfo InfoOf(Expression expression) { if (expression == null) throw new ArgumentNullException("expression"); MethodCallExpression mce; MemberExpression me; NewExpression ne; UnaryExpression ue; BinaryExpression be; if ((mce = expression as MethodCallExpression) != null) { return mce.Method; } else if ((me = expression as MemberExpression) != null) { return me.Member; } else if ((ne = expression as NewExpression) != null) { return ne.Constructor; } else if ((ue = expression as UnaryExpression) != null) { if (ue.Method != null) { return ue.Method; } } else if ((be = expression as BinaryExpression) != null) { if (be.Method != null) { return be.Method; } } throw new NotSupportedException("Expression tree type doesn't have an extractable MemberInfo object."); } internal static Modifier GetModifier(this ISchemaField schemaField) { return schemaField.GetAttribute<RequiredAttribute>() != null ? Modifier.Required : schemaField.GetAttribute<RequiredOptionalAttribute>() != null ? Modifier.RequiredOptional : Modifier.Optional; } internal static int GetHierarchyDepth(this RuntimeSchema schema) { if (!schema.IsStruct) return 0; var depth = 0; for (var type = schema.TypeDef; type != null; type = schema.SchemaDef.structs[type.struct_def].base_def) depth++; return depth; } internal static int GetHierarchyDepth(this Type type) { var depth = 0; for (; type != null; type = type.GetBaseSchemaType()) depth++; return depth; } internal static string GetSchemaName(this Type type) { string name; if (type.IsBondStruct() || type.IsEnum()) { name = type.Name; var n = name.IndexOf('`'); if (n >= 0) name = name.Remove(n); } else if (type.IsBondBlob()) { return "blob"; } else if (type.IsBonded()) { name = "bonded"; } else if (type.IsBondNullable()) { name = "nullable"; } else { name = bondTypeName[type.GetBondDataType()]; } if (!type.IsGenericType()) return name; var args = type.GetTypeInfo().GenericTypeArguments; var builder = new StringBuilder(name, args.Length * 64); builder.Append("<"); for (var i = 0; i < args.Length; ++i) { if (i != 0) builder.Append(", "); builder.Append(args[i].GetSchemaFullName()); } builder.Append(">"); return builder.ToString(); } internal static string GetSchemaFullName(this Type type) { if (type.IsBondStruct() || type.IsEnum()) return type.GetSchemaNamespace() + "." + type.GetSchemaName(); return type.GetSchemaName(); } static string GetSchemaNamespace(this Type type) { var attr = type.GetAttribute<NamespaceAttribute>(); if (attr != null) return attr.Value; return type.Namespace; } static T GetAttribute<T>(this MemberInfo type) where T : class { return type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; } internal static T GetAttribute<T>(this Type type) where T : class { // ReSharper disable once RedundantCast // This explicit cast is needed because when targeting non-portable runtime, // type.GetTypeInfo returns an object which is also a Type, causing wrong call. return GetAttribute<T>(type.GetTypeInfo() as MemberInfo); } static T GetAttribute<T>(this ISchemaField schemaField) where T : class { return schemaField.MemberInfo.GetAttribute<T>(); } static Type ResolveTypeArgumentTags(Type memberType, Type schemaType) { if (schemaType.IsGenericType()) { Type[] memberTypeArguments; var schemaGenericType = schemaType.GetGenericTypeDefinition(); var memberGenericType = memberType.IsGenericType() ? memberType.GetGenericTypeDefinition() : null; if ((schemaGenericType == typeof(Tag.nullable<>) && memberGenericType != typeof(Nullable<>)) || (schemaGenericType == typeof(Tag.bonded<>) && memberGenericType != typeof(IBonded<>))) { memberTypeArguments = new[] { memberType }; } else { memberTypeArguments = memberType.GetTypeInfo().GenericTypeArguments; } return schemaGenericType.MakeGenericType(Enumerable.Zip( memberTypeArguments, schemaType.GetTypeInfo().GenericTypeArguments, ResolveTypeArgumentTags).ToArray()); } return (schemaType == typeof(Tag.structT) || schemaType == typeof(Tag.classT)) ? memberType : schemaType; } internal static Type GetObjectType(this Type schemaType) { if (schemaType == typeof(Tag.wstring)) { return typeof(string); } if (schemaType == typeof(Tag.blob)) { return typeof(ArraySegment<byte>); } if (schemaType.IsGenericType()) { return schemaType.GetGenericTypeDefinition().MakeGenericType( schemaType.GetTypeInfo().GenericTypeArguments.Select(type => { if (type.IsGenericType()) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(Tag.nullable<>)) { var nullableValue = type.GetTypeInfo().GenericTypeArguments[0]; return nullableValue.IsClass() || nullableValue.IsBondBlob() ? nullableValue.GetObjectType() : typeof(Nullable<>).MakeGenericType(nullableValue.GetObjectType()); } if (genericType == typeof(Tag.bonded<>)) { return typeof(IBonded<>).MakeGenericType(type.GetTypeInfo().GenericTypeArguments[0].GetObjectType()); } } return type.GetObjectType(); }).ToArray()); } return schemaType; } internal static object GetDefaultValue(this ISchemaField schemaField) { var declaringType = schemaField.DeclaringType; var declaringTypeInfo = declaringType.GetTypeInfo(); var defaultAttribute = schemaField.GetAttribute<DefaultAttribute>(); // For interfaces determine member default value from the type and/or DefaultAttribute if (declaringTypeInfo.IsInterface) { var schemaType = schemaField.GetSchemaType(); if (defaultAttribute != null) { if (defaultAttribute.Value == null) { return null; } if (schemaType.IsBondNullable() || schemaType.IsBondStruct() || schemaType.IsBondContainer()) { InvalidDefaultAttribute(schemaField, defaultAttribute.Value); } return defaultAttribute.Value; } else { if (schemaType.IsBondNullable()) { return null; } if (schemaType.IsBondStruct() || schemaType.IsBonded() || schemaType.IsBondContainer() || schemaType.IsBondBlob()) { return Empty; } if (schemaType.IsBondString()) { return string.Empty; } return Activator.CreateInstance(schemaField.MemberType); } } if (defaultAttribute != null) { InvalidDefaultAttribute(schemaField, defaultAttribute.Value); } // For classes create a default instance and get the actual default value of the member var objectType = declaringType.GetObjectType(); var objectMemeber = objectType.GetSchemaFields().Single(m => m.Id == schemaField.Id); var obj = Activator.CreateInstance(objectType); var defaultValue = objectMemeber.GetValue(obj); return defaultValue; } static void InvalidDefaultAttribute(ISchemaField schemaField, object value) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Invalid default value '{2}' specified by DefaultAttribute for {0}.{1}", schemaField.DeclaringType, schemaField.Name, value == null ? "null" : value.ToString())); } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.ImageBuilders { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract partial class CompilationState : IDisposable { protected class StateForLocalStackAssignment { // // State // internal StackLocationExpression m_var; internal BitVector m_liveness = new BitVector(); internal BitVector m_interferesWith = new BitVector(); internal BitVector m_sharesSourceVariableWith = new BitVector(); internal BitVector m_sharesOffsetOfSourceVariableWith = new BitVector(); internal uint m_offset; // // Constructor Methods // internal StateForLocalStackAssignment( StackLocationExpression var ) { m_var = var; m_offset = uint.MaxValue; } // // Helper Methods // internal void SetLiveness( BitVector[] livenessMap , BitVector[] defVectors , VariableExpression.Property[] properties , Operator[] operators ) { int varIdx = m_var.SpanningTreeIndex; // // TODO: Once we have proper pointer analysis, we could weaken the check. // For now, we just don't want to have this variable aliased. // if((properties[varIdx] & VariableExpression.Property.AddressTaken) != 0) { m_liveness.SetRange( 0, operators.Length ); } else { m_liveness.OrInPlace( livenessMap[varIdx] ); // // We also include all the operators that follow a definition of the stack location, // because a dead assignment won't appear in the liveness map but it does change the state of the stack. // foreach(int defIdx in defVectors[varIdx]) { m_liveness.Set( defIdx + 1 ); } } } //--// internal static void Correlate( List< StateForLocalStackAssignment > states ) { for(int stateIdx = 0; stateIdx < states.Count; stateIdx++) { StateForLocalStackAssignment state = states[stateIdx]; VariableExpression srcVar = state.m_var.SourceVariable; uint srcOffset = state.m_var.SourceOffset; state.m_sharesSourceVariableWith .Set( stateIdx ); state.m_sharesOffsetOfSourceVariableWith.Set( stateIdx ); for(int stateIdx2 = stateIdx + 1; stateIdx2 < states.Count; stateIdx2++) { StateForLocalStackAssignment state2 = states[stateIdx2]; VariableExpression srcVar2 = state2.m_var.SourceVariable; uint srcOffset2 = state2.m_var.SourceOffset; if(state.m_liveness.IsIntersectionEmpty( state2.m_liveness ) == false) { state .m_interferesWith.Set( stateIdx2 ); state2.m_interferesWith.Set( stateIdx ); } if(srcVar == srcVar2) { state .m_sharesSourceVariableWith.Set( stateIdx2 ); state2.m_sharesSourceVariableWith.Set( stateIdx ); if(srcOffset == srcOffset2) { state .m_sharesOffsetOfSourceVariableWith.Set( stateIdx2 ); state2.m_sharesOffsetOfSourceVariableWith.Set( stateIdx ); } } } } } public static uint ComputeLayout( List< StateForLocalStackAssignment > states ) { BitVector[] offsetsUsage = BitVector.SharedEmptyArray; for(int stateIdx = 0; stateIdx < states.Count; stateIdx++) { StateForLocalStackAssignment state = states[stateIdx]; if(state.m_offset == uint.MaxValue) { VariableExpression srcVar = state.m_var.AggregateVariable; uint size = srcVar.Type.SizeOfHoldingVariableInWords; BitVector liveness; if(size == 1) { CHECKS.ASSERT( state.m_var.SourceOffset == 0, "Mismatch between SourceOffset and Size of object" ); // // Simple case, we don't have to worry about keeping the various fields in the same order. // liveness = state.m_liveness; if(liveness.Cardinality > 0) { uint offset = 0; while(IsOffsetAvailable( ref offsetsUsage, liveness, offset, 1 ) == false) { offset++; } MarkOffsetAsUsed( offsetsUsage, liveness, offset, 1 ); state.m_var.AllocationOffset = offset * sizeof(uint); state.m_offset = offset; } else { state.m_var.Number = int.MaxValue; state.m_offset = uint.MaxValue - 1; } } else { // // Complex case, we have to ensure that the various fields are kept in the same order. // // // Compute the liveness for the whole object. // liveness = new BitVector(); foreach(int stateIdx2 in state.m_sharesSourceVariableWith) { StateForLocalStackAssignment state2 = states[stateIdx2]; liveness.OrInPlace( state2.m_liveness ); } if(liveness.Cardinality > 0) { uint offset = 0; while(IsOffsetAvailable( ref offsetsUsage, liveness, offset, size ) == false) { offset++; } MarkOffsetAsUsed( offsetsUsage, liveness, offset, size ); foreach(int stateIdx2 in state.m_sharesSourceVariableWith) { StateForLocalStackAssignment state2 = states[stateIdx2]; // // If there are multiple variables mapping to the same field, their liveness should be disjoined. // foreach(int stateIdx3 in state2.m_interferesWith) { if(state2.m_sharesOffsetOfSourceVariableWith[ stateIdx3 ]) { throw TypeConsistencyErrorException.Create( "Unsupported scenario: multiple variables mapping to the same field of the same stack variable are alive at the same time: {0} {1}", state2.m_var, states[stateIdx3].m_var ); } } state2.m_var.AllocationOffset = offset * sizeof(uint) + state2.m_var.SourceOffset; state2.m_offset = offset; } } else { foreach(int stateIdx2 in state.m_sharesSourceVariableWith) { StateForLocalStackAssignment state2 = states[stateIdx2]; state2.m_var.Number = int.MaxValue; state2.m_offset = uint.MaxValue - 1; } } } } } return (uint)offsetsUsage.Length; } //--// private static bool IsOffsetAvailable( ref BitVector[] offsetsUsage , BitVector liveness , uint offset , uint size ) { while(size > 0) { offsetsUsage = ArrayUtility.EnsureSizeOfNotNullArray( offsetsUsage, (int)(offset + 1) ); BitVector vec = offsetsUsage[offset]; if(vec != null && vec.IsIntersectionEmpty( liveness ) == false) { return false; } offset++; size--; } return true; } private static void MarkOffsetAsUsed( BitVector[] offsetsUsage , BitVector liveness , uint offset , uint size ) { while(size > 0) { BitVector vec = offsetsUsage[offset]; if(vec == null) { offsetsUsage[offset] = liveness.Clone(); } else { vec.OrInPlace( liveness ); } offset++; size--; } } } // // State // protected Core m_owner; protected ControlFlowGraphStateForCodeTransformation m_cfg; protected List< SequentialRegion > m_associatedRegions; protected SequentialRegion[] m_basicBlockToRegions; // // Cached values, not persisted. // private IDisposable m_cfgLock; protected BasicBlock[] m_basicBlocks; protected BasicBlock[] m_immediateDominators; protected Operator[] m_operators; protected VariableExpression[] m_variables; protected BitVector[] m_livenessAtBasicBlockEntry; // It's indexed as [<basic block index>][<variable index>] protected BitVector[] m_livenessAtBasicBlockExit; // It's indexed as [<basic block index>][<variable index>] protected BitVector[] m_livenessAtOperator; // It's indexed as [<operator index>][<variable index>] protected DataFlow.ControlTree.NaturalLoops m_naturalLoops; private List< Slot > m_topLevelSlots; private AtomicSlot[] m_schedulingLookup; private AtomicSlot[] m_schedulingLoopExits; private BitVector m_vecColdCode; private BitVector m_vecZeroLengthCandidates; private BitVector m_vecReachableFromColdCode; private BitVector m_vecReachableFromEntry; // // Constructor Methods // protected CompilationState() // Default constructor required by TypeSystemSerializer. { m_associatedRegions = new List< SequentialRegion >(); } protected CompilationState( Core owner , ControlFlowGraphStateForCodeTransformation cfg ) : this() { m_owner = owner; m_cfg = cfg; } // // Helper Methods // public virtual void ApplyTransformation( TransformationContextForCodeTransformation context ) { context.Push( this ); context.TransformGeneric( ref m_owner ); context.TransformGeneric( ref m_cfg ); context.Transform ( ref m_associatedRegions ); context.Transform ( ref m_basicBlockToRegions ); context.Pop(); } //--// internal protected int CompareSchedulingWeights( BasicBlock left , BasicBlock right ) { var slotLeft = GetSchedulingSlot( left ); var slotRight = GetSchedulingSlot( right ); return slotLeft.Weight.CompareTo( slotRight.Weight ); } internal protected bool AreBasicBlocksAdjacent( BasicBlock pre , BasicBlock post ) { var slotPre = GetSchedulingSlot( pre ); var slotPost = GetSchedulingSlot( post ); if(IsZeroLengthCandidate( pre )) { return slotPre.SchedulingIndex == slotPost.SchedulingIndex; } return slotPre.SchedulingIndex + 1 == slotPost.SchedulingIndex; } //--// internal void CompileMethod() { PrepareDataStructures(); AssignStackLocations( ); AllocateBasicBlockRegions( ); CollectSchedulingPreferences( ); PropagateColdCodeHints( ); AllocateSchedulingSlots( ); OrderBasicBlocks( ); AssignSchedulingIndex( ); EmitCodeForBasicBlocks(); } //--// protected virtual void PrepareDataStructures() { m_cfgLock = m_cfg.GroupLock( m_cfg.LockSpanningTree() , m_cfg.LockDominance () , m_cfg.LockLiveness () ); m_basicBlocks = m_cfg.DataFlow_SpanningTree_BasicBlocks; m_immediateDominators = m_cfg.DataFlow_ImmediateDominators; m_operators = m_cfg.DataFlow_SpanningTree_Operators; m_variables = m_cfg.DataFlow_SpanningTree_Variables; // // We need to build a slightly different liveness information: Stack Locations should be tracked as aggregates and not invalidated by method calls. // var liveness = DataFlow.LivenessAnalysis.Compute( m_cfg, true ); m_livenessAtBasicBlockEntry = liveness.LivenessAtBasicBlockEntry; m_livenessAtBasicBlockExit = liveness.LivenessAtBasicBlockExit; m_livenessAtOperator = liveness.LivenessAtOperator; //// if(m_cfg.ToString() == sDebugTarget) //// { //// } m_naturalLoops = DataFlow.ControlTree.NaturalLoops.Execute( m_cfg ); //--// int bbNum = m_basicBlocks.Length; m_basicBlockToRegions = new SequentialRegion[bbNum]; m_topLevelSlots = new List< Slot >(); m_schedulingLookup = new AtomicSlot[bbNum]; m_vecColdCode = new BitVector( bbNum ); m_vecZeroLengthCandidates = new BitVector( bbNum ); m_vecReachableFromColdCode = new BitVector( bbNum ); m_vecReachableFromEntry = new BitVector( bbNum ); //--// // // Sort loops from the deep to the shallow. // m_naturalLoops.Loops.Sort( (x, y) => y.Depth.CompareTo( x.Depth ) ); } private void AllocateBasicBlockRegions() { foreach(BasicBlock bb in m_basicBlocks) { SequentialRegion reg = new SequentialRegion( m_owner, bb, m_owner.TypeSystem.PlatformAbstraction.GetMemoryRequirements( bb ) ); m_basicBlockToRegions[bb.SpanningTreeIndex] = reg; TrackRegion( reg ); } } //--// private void PropagateColdCodeHints() { // // Try to maximize the number of basic blocks that are cold, making sure that a block becomes cold if it's dominated by a cold block. // foreach(BasicBlock bb in m_basicBlocks) { if(bb is EntryBasicBlock) { PropagateReachableFromEntry( bb.SpanningTreeIndex ); } if(IsColdCode( bb )) { PropagateReachableFromColdCode( bb.SpanningTreeIndex ); } } } private void PropagateReachableFromEntry( int bbIdx ) { if(m_vecReachableFromEntry.Set( bbIdx )) { foreach(BasicBlockEdge edge in m_basicBlocks[bbIdx].Successors) { BasicBlock bbNext = edge.Successor; if(IsColdCode( bbNext )) { continue; } PropagateReachableFromEntry( bbNext.SpanningTreeIndex ); } } } private void PropagateReachableFromColdCode( int bbIdx ) { if(m_vecReachableFromColdCode.Set( bbIdx )) { foreach(BasicBlockEdge edge in m_basicBlocks[bbIdx].Successors) { BasicBlock bbNext = edge.Successor; int bbNextIdx = bbNext.SpanningTreeIndex; PropagateReachableFromColdCode( bbNextIdx ); } } } //--// public void Dispose() { if(m_cfgLock != null) { if(m_naturalLoops != null) { m_naturalLoops.Dispose(); m_naturalLoops = null; } m_cfgLock.Dispose(); m_cfgLock = null; } } public void ReleaseAllLocks() { if(m_cfgLock != null) { m_cfgLock.Dispose(); m_cfgLock = null; } } //--// private void AssignStackLocations() { if(m_cfg.Method.HasBuildTimeFlag( MethodRepresentation.BuildTimeAttributes.StackNotAvailable ) == false) { VariableExpression.Property[] properties = m_cfg.DataFlow_PropertiesOfVariables; BitVector[] livenessMap = m_cfg.DataFlow_VariableLivenessMap; // It's indexed as [<variable index>][<operator index>] BitVector[] defVectors = m_cfg.DataFlow_BitVectorsForDefinitionChains; int varsNum = m_variables.Length; List< StateForLocalStackAssignment > states = new List< StateForLocalStackAssignment >(); for(int varIdx = 0; varIdx < varsNum; varIdx++) { VariableExpression var = m_variables[varIdx]; PhysicalRegisterExpression regVar = var as PhysicalRegisterExpression; if(regVar != null) { AssignStackLocations_RecordRegister( regVar ); } StackLocationExpression stackVar = var as StackLocationExpression; if(stackVar != null) { if(stackVar.StackPlacement == StackLocationExpression.Placement.Local) { StateForLocalStackAssignment state = new StateForLocalStackAssignment( stackVar ); // // Try to minimize the amount of stack required, using the lifetime information // to carve a slice of the stack just for the amount of time we need to keep the object around. // state.SetLiveness( livenessMap, defVectors, properties, m_operators ); states.Add( state ); } else if(stackVar.StackPlacement == StackLocationExpression.Placement.Out) { AssignStackLocations_RecordStackOut( stackVar ); } } } StateForLocalStackAssignment.Correlate( states ); AssignStackLocations_RecordStackLocal( states ); //--// AssignStackLocations_Finalize(); } } protected abstract void AssignStackLocations_RecordRegister( PhysicalRegisterExpression regVar ); protected abstract void AssignStackLocations_RecordStackOut( StackLocationExpression stackVar ); protected abstract void AssignStackLocations_RecordStackLocal( List< StateForLocalStackAssignment > states ); protected abstract void AssignStackLocations_Finalize(); //--// protected abstract void FixupEmptyRegion( SequentialRegion reg ); //--// public abstract bool CreateCodeMaps(); //--// internal void TrackRegion( SequentialRegion reg ) { m_associatedRegions.Add( reg ); } //--// protected SequentialRegion[] GetSortedCodeRegions() { SequentialRegion[] regArray = ArrayUtility.CopyNotNullArray( m_basicBlockToRegions ); Core.SortRegions( regArray ); return regArray; } // // Access Methods // public Core Owner { get { return m_owner; } } public SequentialRegion[] BasicBlockRegions { get { return m_basicBlockToRegions; } } internal List< SequentialRegion > AssociatedRegions { get { return m_associatedRegions; } } } }
using UnityEngine; using System.Collections; using Zenject; using ModestTree; #pragma warning disable 649 namespace Zenject.Asteroids { public class GuiHandler : MonoBehaviour { Signals.ShipCrashed _shipCrashed; GameController _gameController; [SerializeField] GUIStyle _titleStyle; [SerializeField] GUIStyle _instructionsStyle; [SerializeField] GUIStyle _gameOverStyle; [SerializeField] GUIStyle _timeStyle; [SerializeField] float _gameOverFadeInTime; [SerializeField] float _gameOverStartFadeTime; [SerializeField] float _restartTextStartFadeTime; [SerializeField] float _restartTextFadeInTime; float _gameOverElapsed; [PostInject] public void Construct( GameController gameController, Signals.ShipCrashed shipCrashed) { _gameController = gameController; _shipCrashed = shipCrashed; } void OnGUI() { GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height)); { switch (_gameController.State) { case GameStates.WaitingToStart: { StartGui(); break; } case GameStates.Playing: { PlayingGui(); break; } case GameStates.GameOver: { PlayingGui(); GameOverGui(); break; } default: { Assert.That(false); break; } } } GUILayout.EndArea(); } void GameOverGui() { _gameOverElapsed += Time.deltaTime; if (_gameOverElapsed > _gameOverStartFadeTime) { var px = Mathf.Min(1.0f, (_gameOverElapsed - _gameOverStartFadeTime) / _gameOverFadeInTime); _titleStyle.normal.textColor = new Color(1, 1, 1, px); } else { _titleStyle.normal.textColor = new Color(1, 1, 1, 0); } if (_gameOverElapsed > _restartTextStartFadeTime) { var px = Mathf.Min(1.0f, (_gameOverElapsed - _restartTextStartFadeTime) / _restartTextFadeInTime); _instructionsStyle.normal.textColor = new Color(1, 1, 1, px); } else { _instructionsStyle.normal.textColor = new Color(1, 1, 1, 0); } GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); { GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); { GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Label("GAME OVER", _titleStyle); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.Space(60); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Label("Click to restart", _instructionsStyle); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } void PlayingGui() { GUILayout.BeginVertical(); { GUILayout.Space(30); GUILayout.BeginHorizontal(); { GUILayout.Space(30); GUILayout.Label("Time: " + _gameController.ElapsedTime.ToString("0.##"), _timeStyle); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); } void StartGui() { GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); { GUILayout.Space(100); GUILayout.FlexibleSpace(); GUILayout.BeginVertical(); { GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Label("ASTEROIDS", _titleStyle); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.Space(60); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Label("Click to start", _instructionsStyle); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } void Start() { _shipCrashed.Event += OnShipCrashed; } void OnDestroy() { _shipCrashed.Event -= OnShipCrashed; } void OnShipCrashed() { _gameOverElapsed = 0; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace DisasterRecoveryAPI.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Controls.LdapPersistSearchControl.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap; using Novell.Directory.Ldap.Asn1; namespace Novell.Directory.Ldap.Controls { /// <summary> LdapPersistSearchControl is a Server Control that allows a client /// to receive notifications from the server of changes to entries within /// the searches result set. The client can be notified when an entry is /// added to the result set, when an entry is deleted from the result set, /// when a DN has been changed or when and attribute value has been changed. /// </summary> public class LdapPersistSearchControl:LdapControl { /// <summary> Returns the change types to be monitored as a logical OR of any or /// all of these values: ADD, DELETE, MODIFY, and/or MODDN. /// /// </summary> /// <returns> the change types to be monitored. The logical or of any of /// the following values: ADD, DELETE, MODIFY, and/or MODDN. /// </returns> /// <summary> Sets the change types to be monitored. /// /// types The change types to be monitored as a logical OR of any or all /// of these types: ADD, DELETE, MODIFY, and/or MODDN. Can also be set /// to the value ANY which is defined as the logical OR of all of the /// preceding values. /// </summary> virtual public int ChangeTypes { get { return m_changeTypes; } set { m_changeTypes = value; m_sequence.set_Renamed(CHANGETYPES_INDEX, new Asn1Integer(m_changeTypes)); setValue(); return ; } } /// <summary> Returns true if entry change controls are to be returned with the /// search results. /// /// </summary> /// <returns> true if entry change controls are to be returned with the /// search results. Otherwise, false is returned /// </returns> /// <summary> When set to true, requests that entry change controls be returned with /// the search results. /// /// </summary> /// <param name="returnControls"> true to return entry change controls. /// </param> virtual public bool ReturnControls { get { return m_returnControls; } set { m_returnControls = value; m_sequence.set_Renamed(RETURNCONTROLS_INDEX, new Asn1Boolean(m_returnControls)); setValue(); return ; } } /// <summary> getChangesOnly returns true if only changes are to be returned. /// Results from the initial search are not returned. /// /// </summary> /// <returns> true of only changes are to be returned /// </returns> /// <summary> When set to true, requests that only changes be returned, results from /// the initial search are not returned. /// </summary> /// <param name="changesOnly"> true to skip results for the initial search /// </param> virtual public bool ChangesOnly { get { return m_changesOnly; } set { m_changesOnly = value; m_sequence.set_Renamed(CHANGESONLY_INDEX, new Asn1Boolean(m_changesOnly)); setValue(); return ; } } /* private data members */ private static int SEQUENCE_SIZE = 3; private static int CHANGETYPES_INDEX = 0; private static int CHANGESONLY_INDEX = 1; private static int RETURNCONTROLS_INDEX = 2; private static LBEREncoder s_encoder; private int m_changeTypes; private bool m_changesOnly; private bool m_returnControls; private Asn1Sequence m_sequence; /// <summary> The requestOID of the persistent search control</summary> private static String requestOID = "2.16.840.1.113730.3.4.3"; /// <summary> The responseOID of the psersistent search - entry change control</summary> private static String responseOID = "2.16.840.1.113730.3.4.7"; /// <summary> Change type specifying that you want to track additions of new entries /// to the directory. /// </summary> public const int ADD = 1; /// <summary> Change type specifying that you want to track removals of entries from /// the directory. /// </summary> public const int DELETE = 2; /// <summary> Change type specifying that you want to track modifications of entries /// in the directory. /// </summary> public const int MODIFY = 4; /// <summary> Change type specifying that you want to track modifications of the DNs /// of entries in the directory. /// </summary> public const int MODDN = 8; /// <summary> Change type specifying that you want to track any of the above /// modifications. /// </summary> public static readonly int ANY = ADD | DELETE | MODIFY | MODDN; /* public constructors */ /// <summary> The default constructor. A control with changes equal to ANY, /// isCritical equal to true, changesOnly equal to true, and /// returnControls equal to true /// </summary> public LdapPersistSearchControl():this(ANY, true, true, true) { return ; } /// <summary> Constructs an LdapPersistSearchControl object according to the /// supplied parameters. The resulting control is used to specify a /// persistent search. /// /// </summary> /// <param name="changeTypes"> the change types to monitor. The bitwise OR of any /// of the following values: /// <li> LdapPersistSearchControl.ADD</li> /// <li> LdapPersistSearchControl.DELETE</li> /// <li> LdapPersistSearchControl.MODIFY</li> /// <li> LdapPersistSearchControl.MODDN</li> /// To track all changes the value can be set to: /// <li> LdapPersistSearchControl.ANY</li> /// /// </param> /// <param name="changesOnly"> true if you do not want the server to return /// all existing entries in the directory that match the search /// criteria. (Use this if you just want the changed entries to be /// returned.) /// /// </param> /// <param name="returnControls"> true if you want the server to return entry /// change controls with each entry in the search results. You need to /// return entry change controls to discover what type of change /// and other additional information about the change. /// /// </param> /// <param name="isCritical"> true if this control is critical to the search /// operation. If true and the server does not support this control, /// the server will not perform the search at all. /// </param> public LdapPersistSearchControl(int changeTypes, bool changesOnly, bool returnControls, bool isCritical):base(requestOID, isCritical, null) { m_changeTypes = changeTypes; m_changesOnly = changesOnly; m_returnControls = returnControls; m_sequence = new Asn1Sequence(SEQUENCE_SIZE); m_sequence.add(new Asn1Integer(m_changeTypes)); m_sequence.add(new Asn1Boolean(m_changesOnly)); m_sequence.add(new Asn1Boolean(m_returnControls)); setValue(); return ; } public override String ToString() { sbyte[] data = m_sequence.getEncoding(s_encoder); System.Text.StringBuilder buf = new System.Text.StringBuilder(data.Length); for (int i = 0; i < data.Length; i++) { buf.Append(data[i].ToString()); if (i < data.Length - 1) buf.Append(","); } return buf.ToString(); } /// <summary> Sets the encoded value of the LdapControlClass</summary> private void setValue() { base.setValue(m_sequence.getEncoding(s_encoder)); return ; } static LdapPersistSearchControl() { s_encoder = new LBEREncoder(); /* * This is where we register the control response */ { /* Register the Entry Change control class which is returned by the * server in response to a persistent search request */ try { // Register LdapEntryChangeControl register(responseOID, Type.GetType("Novell.Directory.Ldap.Controls.LdapEntryChangeControl")); } catch (Exception e) { } } } } // end class LdapPersistentSearchControl }
/* * 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.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Piranha.Models; using Piranha.Repositories; namespace Piranha.Services { public class PostService : IPostService { private readonly IPostRepository _repo; private readonly IContentFactory _factory; private readonly ISiteService _siteService; private readonly IPageService _pageService; private readonly IParamService _paramService; private readonly IMediaService _mediaService; private readonly ICache _cache; private readonly ISearch _search; /// <summary> /// Default constructor. /// </summary> /// <param name="repo">The main repository</param> /// <param name="factory">The content factory</param> /// <param name="siteService">The site service</param> /// <param name="pageService">The page service</param> /// <param name="paramService">The param service</param> /// <param name="mediaService">The media service</param> /// <param name="cache">The optional model cache</param> /// <param name="search">The optional search service</param> public PostService(IPostRepository repo, IContentFactory factory, ISiteService siteService, IPageService pageService, IParamService paramService, IMediaService mediaService, ICache cache = null, ISearch search = null) { _repo = repo; _factory = factory; _siteService = siteService; _pageService = pageService; _paramService = paramService; _mediaService = mediaService; _search = search; if ((int)App.CacheLevel > 2) { _cache = cache; } } /// <summary> /// Creates and initializes a new post of the specified type. /// </summary> /// <returns>The created post</returns> public async Task<T> CreateAsync<T>(string typeId = null) where T : PostBase { if (string.IsNullOrEmpty(typeId)) { typeId = typeof(T).Name; } var type = App.PostTypes.GetById(typeId); if (type != null) { var model = await _factory.CreateAsync<T>(type).ConfigureAwait(false); using (var config = new Config(_paramService)) { model.EnableComments = config.CommentsEnabledForPosts; model.CloseCommentsAfterDays = config.CommentsCloseAfterDays; } return model; } return null; } /// <summary> /// Gets the available posts for the specified blog. /// </summary> /// <param name="blogId">The unique blog id</param> /// <param name="index">The optional page to fetch</param> /// <param name="pageSize">The optional page size</param> /// <returns>The posts</returns> public Task<IEnumerable<DynamicPost>> GetAllAsync(Guid blogId, int? index = null, int? pageSize = null) { return GetAllAsync<DynamicPost>(blogId, index, pageSize); } /// <summary> /// Gets the available post items. /// </summary> /// <param name="blogId">The unique id</param> /// <param name="index">The optional page to fetch</param> /// <param name="pageSize">The optional page size</param> /// <returns>The posts</returns> public async Task<IEnumerable<T>> GetAllAsync<T>(Guid blogId, int? index = null, int? pageSize = null) where T : PostBase { if (index.HasValue && !pageSize.HasValue) { // No page size provided, use default archive size using (var config = new Config(_paramService)) { pageSize = config.ArchivePageSize; } } var models = new List<T>(); var posts = await _repo.GetAll(blogId, index, pageSize).ConfigureAwait(false); var pages = new List<PageInfo>(); foreach (var postId in posts) { var post = await GetByIdAsync<T>(postId, pages).ConfigureAwait(false); if (post != null) { models.Add(post); } } return models; } /// <summary> /// Gets the available posts for the specified blog. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The posts</returns> public Task<IEnumerable<DynamicPost>> GetAllBySiteIdAsync(Guid? siteId = null) { return GetAllBySiteIdAsync<DynamicPost>(siteId); } /// <summary> /// Gets the available post items. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The posts</returns> public async Task<IEnumerable<T>> GetAllBySiteIdAsync<T>(Guid? siteId = null) where T : PostBase { var models = new List<T>(); var posts = await _repo.GetAllBySiteId((await EnsureSiteIdAsync(siteId).ConfigureAwait(false)).Value) .ConfigureAwait(false); var pages = new List<PageInfo>(); foreach (var postId in posts) { var post = await GetByIdAsync<T>(postId, pages).ConfigureAwait(false); if (post != null) { models.Add(post); } } return models; } /// <summary> /// Gets the available posts for the specified blog. /// </summary> /// <param name="slug">The blog slug</param> /// <param name="siteId">The optional site id</param> /// <returns>The posts</returns> public Task<IEnumerable<DynamicPost>> GetAllAsync(string slug, Guid? siteId = null) { return GetAllAsync<DynamicPost>(slug, siteId); } /// <summary> /// Gets the available posts for the specified blog. /// </summary> /// <param name="slug">The blog slug</param> /// <param name="siteId">The optional site id</param> /// <returns>The posts</returns> public async Task<IEnumerable<T>> GetAllAsync<T>(string slug, Guid? siteId = null) where T : PostBase { siteId = await EnsureSiteIdAsync(siteId).ConfigureAwait(false); var blogId = await _pageService.GetIdBySlugAsync(slug, siteId).ConfigureAwait(false); if (blogId.HasValue) { return await GetAllAsync<T>(blogId.Value).ConfigureAwait(false); } return new List<T>(); } /// <summary> /// Gets all available categories for the specified blog. /// </summary> /// <param name="blogId">The blog id</param> /// <returns>The available categories</returns> public Task<IEnumerable<Taxonomy>> GetAllCategoriesAsync(Guid blogId) { return _repo.GetAllCategories(blogId); } /// <summary> /// Gets all available tags for the specified blog. /// </summary> /// <param name="blogId">The blog id</param> /// <returns>The available tags</returns> public Task<IEnumerable<Taxonomy>> GetAllTagsAsync(Guid blogId) { return _repo.GetAllTags(blogId); } /// <summary> /// Gets the id of all posts that have a draft for /// the specified blog. /// </summary> /// <param name="blogId">The unique blog id</param> /// <returns>The posts that have a draft</returns> public Task<IEnumerable<Guid>> GetAllDraftsAsync(Guid blogId) { return _repo.GetAllDrafts(blogId); } /// <summary> /// Gets the comments available for the post with the specified id. /// </summary> /// <param name="postId">The unique post id</param> /// <param name="onlyApproved">If only approved comments should be fetched</param> /// <param name="page">The optional page number</param> /// <param name="pageSize">The optional page size</param> /// <returns>The available comments</returns> public Task<IEnumerable<Comment>> GetAllCommentsAsync(Guid? postId = null, bool onlyApproved = true, int? page = null, int? pageSize = null) { return GetAllCommentsAsync(postId, onlyApproved, false, page, pageSize); } /// <summary> /// Gets the pending comments available for the post with the specified id. If no post id /// is provided all comments are fetched. /// </summary> /// <param name="postId">The unique post id</param> /// <param name="page">The optional page number</param> /// <param name="pageSize">The optional page size</param> /// <returns>The available comments</returns> public Task<IEnumerable<Comment>> GetAllPendingCommentsAsync(Guid? postId = null, int? page = null, int? pageSize = null) { return GetAllCommentsAsync(postId, false, true, page, pageSize); } /// <summary> /// Gets the number of available posts in the specified archive. /// </summary> /// <param name="archiveId">The archive id</param> /// <returns>The number of posts</returns> public Task<int> GetCountAsync(Guid archiveId) { return _repo.GetCount(archiveId); } /// <summary> /// Gets the post model with the specified id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The post model</returns> public Task<DynamicPost> GetByIdAsync(Guid id) { return GetByIdAsync<DynamicPost>(id); } /// <summary> /// Gets the post model with the specified id. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="id">The unique id</param> /// <returns>The post model</returns> public Task<T> GetByIdAsync<T>(Guid id) where T : PostBase { return GetByIdAsync<T>(id, new List<PageInfo>()); } /// <summary> /// Gets the post model with the specified slug. /// </summary> /// <param name="blog">The unique blog slug</param> /// <param name="slug">The unique slug</param> /// <param name="siteId">The optional site id</param> /// <returns>The post model</returns> public Task<DynamicPost> GetBySlugAsync(string blog, string slug, Guid? siteId = null) { return GetBySlugAsync<DynamicPost>(blog, slug, siteId); } /// <summary> /// Gets the post model with the specified slug. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="blog">The unique blog slug</param> /// <param name="slug">The unique slug</param> /// <param name="siteId">The optional site id</param> /// <returns>The post model</returns> public async Task<T> GetBySlugAsync<T>(string blog, string slug, Guid? siteId = null) where T : PostBase { siteId = await EnsureSiteIdAsync(siteId).ConfigureAwait(false); var blogId = await _pageService.GetIdBySlugAsync(blog, siteId).ConfigureAwait(false); if (blogId.HasValue) { return await GetBySlugAsync<T>(blogId.Value, slug).ConfigureAwait(false); } return null; } /// <summary> /// Gets the post model with the specified slug. /// </summary> /// <param name="blogId">The unique blog slug</param> /// <param name="slug">The unique slug</param> /// <returns>The post model</returns> public Task<DynamicPost> GetBySlugAsync(Guid blogId, string slug) { return GetBySlugAsync<DynamicPost>(blogId, slug); } /// <summary> /// Gets the post model with the specified slug. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="blogId">The unique blog slug</param> /// <param name="slug">The unique slug</param> /// <returns>The post model</returns> public async Task<T> GetBySlugAsync<T>(Guid blogId, string slug) where T : PostBase { PostBase model = null; // Lets see if we can resolve the slug from cache var postId = _cache?.Get<Guid?>($"PostId_{blogId}_{slug}"); if (postId.HasValue) { if (typeof(T) == typeof(PostInfo)) { model = _cache?.Get<PostInfo>($"PostInfo_{postId.ToString()}"); } else if (!typeof(DynamicPost).IsAssignableFrom(typeof(T))) { model = _cache?.Get<PostBase>(postId.ToString()); } } if (model == null) { model = await _repo.GetBySlug<T>(blogId, slug).ConfigureAwait(false); if (model != null) { var blog = await _pageService.GetByIdAsync<PageInfo>(model.BlogId).ConfigureAwait(false); await OnLoadAsync(model, blog).ConfigureAwait(false); } } if (model != null && model is T) { return (T)model; } return null; } /// <summary> /// Gets the draft for the post model with the specified id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The draft, or null if no draft exists</returns> public Task<DynamicPost> GetDraftByIdAsync(Guid id) { return GetDraftByIdAsync<DynamicPost>(id); } /// <summary> /// Gets the draft for the post model with the specified id. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="id">The unique id</param> /// <returns>The draft, or null if no draft exists</returns> public async Task<T> GetDraftByIdAsync<T>(Guid id) where T : PostBase { var draft = await _repo.GetDraftById<T>(id).ConfigureAwait(false); if (draft != null) { var blog = await _pageService.GetByIdAsync<PageInfo>(draft.BlogId).ConfigureAwait(false); await OnLoadAsync(draft, blog, true).ConfigureAwait(false); } return draft; } /// <summary> /// Gets the category with the given slug. /// </summary> /// <param name="blogId">The blog id</param> /// <param name="slug">The unique slug</param> /// <returns>The model</returns> public async Task<Taxonomy> GetCategoryBySlugAsync(Guid blogId, string slug) { var id = _cache?.Get<Guid?>($"Category_{blogId}_{slug}"); Taxonomy model = null; if (id.HasValue) { model = _cache.Get<Taxonomy>(id.Value.ToString()); } if (model == null) { model = await _repo.GetCategoryBySlug(blogId, slug).ConfigureAwait(false); if (model != null && _cache != null) { _cache.Set(model.Id.ToString(), model); _cache.Set($"Category_{blogId}_{slug}", model.Id); } } return model; } /// <summary> /// Gets the category with the id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The model</returns> public async Task<Taxonomy> GetCategoryByIdAsync(Guid id) { Taxonomy model = _cache?.Get<Taxonomy>(id.ToString()); if (model == null) { model = await _repo.GetCategoryById(id).ConfigureAwait(false); if (model != null && _cache != null) { _cache.Set(model.Id.ToString(), model); } } return model; } /// <summary> /// Gets the tag with the given slug. /// </summary> /// <param name="blogId">The blog id</param> /// <param name="slug">The unique slug</param> /// <returns>The model</returns> public async Task<Taxonomy> GetTagBySlugAsync(Guid blogId, string slug) { var id = _cache?.Get<Guid?>($"Tag_{blogId}_{slug}"); Taxonomy model = null; if (id.HasValue) { model = _cache.Get<Taxonomy>(id.Value.ToString()); } if (model == null) { model = await _repo.GetTagBySlug(blogId, slug).ConfigureAwait(false); if (model != null && _cache != null) { _cache.Set(model.Id.ToString(), model); _cache.Set($"Tag_{blogId}_{slug}", model.Id); } } return model; } /// <summary> /// Gets the category with the id. /// </summary> /// <param name="id">The unique id</param> /// <returns>The model</returns> public async Task<Taxonomy> GetTagByIdAsync(Guid id) { Taxonomy model = _cache?.Get<Taxonomy>(id.ToString()); if (model == null) { model = await _repo.GetTagById(id).ConfigureAwait(false); if (model != null && _cache != null) { _cache.Set(model.Id.ToString(), model); } } return model; } /// <summary> /// Gets the comment with the given id. /// </summary> /// <param name="id">The comment id</param> /// <returns>The model</returns> public Task<Comment> GetCommentByIdAsync(Guid id) { return _repo.GetCommentById(id); } /// <summary> /// Saves the given post model /// </summary> /// <param name="model">The post model</param> public Task SaveAsync<T>(T model) where T : PostBase { return SaveAsync(model, false); } /// <summary> /// Saves the given post model as a draft /// </summary> /// <param name="model">The post model</param> public Task SaveDraftAsync<T>(T model) where T : PostBase { return SaveAsync(model, true); } /// <summary> /// Saves the comment. /// </summary> /// <param name="model">The comment model</param> /// <param name="postId">The unique post id</param> public Task SaveCommentAsync(Guid postId, Comment model) { return SaveCommentAsync(postId, model, false); } /// <summary> /// Saves the comment and verifies if should be approved or not. /// </summary> /// <param name="model">The comment model</param> /// <param name="postId">The unique post id</param> public Task SaveCommentAndVerifyAsync(Guid postId, Comment model) { return SaveCommentAsync(postId, model, true); } /// <summary> /// Gets the comments available for the post with the specified id. /// </summary> /// <param name="postId">The unique post id</param> /// <param name="onlyApproved">If only approved comments should be fetched</param> /// <param name="onlyPending">If only pending comments should be fetched</param> /// <param name="page">The optional page number</param> /// <param name="pageSize">The optional page size</param> /// <returns>The available comments</returns> private async Task<IEnumerable<Comment>> GetAllCommentsAsync(Guid? postId = null, bool onlyApproved = true, bool onlyPending = false, int? page = null, int? pageSize = null) { // Ensure page number if (!page.HasValue) { page = 0; } // Ensure page size if (!pageSize.HasValue) { using (var config = new Config(_paramService)) { pageSize = config.CommentsPageSize; } } // Get the comments IEnumerable<Comment> comments = null; if (onlyPending) { comments = await _repo.GetAllPendingComments(postId, page.Value, pageSize.Value).ConfigureAwait(false); } else { comments = await _repo.GetAllComments(postId, onlyApproved, page.Value, pageSize.Value).ConfigureAwait(false); } // Execute hook foreach (var comment in comments) { App.Hooks.OnLoad<Comment>(comment); } return comments; } /// <summary> /// Saves the comment. /// </summary> /// <param name="model">The comment model</param> /// <param name="postId">The unique post id</param> /// <param name="verify">If default moderation settings should be applied</param> private async Task SaveCommentAsync(Guid postId, Comment model, bool verify) { // Make sure we have a post var post = await GetByIdAsync<PostInfo>(postId).ConfigureAwait(false); if (post != null) { // Ensure id if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } // Ensure created date if (model.Created == DateTime.MinValue) { model.Created = DateTime.Now; } // Ensure content id if (model.ContentId == Guid.Empty) { model.ContentId = postId; } // Validate model var context = new ValidationContext(model); Validator.ValidateObject(model, context, true); // Set approved according to config if we should verify if (verify) { using (var config = new Config(_paramService)) { model.IsApproved = config.CommentsApprove; } App.Hooks.OnValidate<Comment>(model); } // Call hooks & save App.Hooks.OnBeforeSave<Comment>(model); await _repo.SaveComment(postId, model).ConfigureAwait(false); App.Hooks.OnAfterSave<Comment>(model); // Invalidate parent post from cache RemoveFromCache(post); } else { throw new ArgumentException($"Could not find post with id { postId.ToString() }"); } } /// <summary> /// Saves the given post model /// </summary> /// <param name="model">The post model</param> /// <param name="isDraft">If the model should be saved as a draft</param> private async Task SaveAsync<T>(T model, bool isDraft) where T : PostBase { // Ensure id if (model.Id == Guid.Empty) { model.Id = Guid.NewGuid(); } // Validate model var context = new ValidationContext(model); Validator.ValidateObject(model, context, true); // Ensure title since this field isn't required in // the Content base class if (string.IsNullOrWhiteSpace(model.Title)) { throw new ValidationException("The Title field is required"); } // Ensure type id since this field isn't required in // the Content base class if (string.IsNullOrWhiteSpace(model.TypeId)) { throw new ValidationException("The TypeId field is required"); } // Ensure slug if (string.IsNullOrWhiteSpace(model.Slug)) { model.Slug = Utils.GenerateSlug(model.Title, false); } else { model.Slug = Utils.GenerateSlug(model.Slug, false); } // Ensure slug is not null or empty // after removing unwanted characters if (string.IsNullOrWhiteSpace(model.Slug)) { throw new ValidationException("The generated slug is empty as the title only contains special characters, please specify a slug to save the post."); } // Ensure that the slug is unique var duplicate = await GetBySlugAsync(model.BlogId, model.Slug); if (duplicate != null && duplicate.Id != model.Id) { throw new ValidationException("The specified slug already exists, please create a unique slug"); } // Ensure category if (model.Category == null || (string.IsNullOrWhiteSpace(model.Category.Title) && string.IsNullOrWhiteSpace(model.Category.Slug))) { throw new ValidationException("The Category field is required"); } // Call hooks & save App.Hooks.OnBeforeSave<PostBase>(model); // Handle revisions and save var current = await _repo.GetById<PostInfo>(model.Id).ConfigureAwait(false); if ((IsPublished(current) || IsScheduled(current)) && isDraft) { // We're saving a draft since we have a previously // published version of the post await _repo.SaveDraft(model).ConfigureAwait(false); } else { if (current == null && isDraft) { // If we're saving a draft as a normal post instance, make // sure we remove the published date as this sould effectively // publish the post. model.Published = null; } else if (current != null && !isDraft) { using (var config = new Config(_paramService)) { // Save current as a revision before saving the model // and if a draft revision exists, remove it. await _repo.DeleteDraft(model.Id).ConfigureAwait(false); await _repo.CreateRevision(model.Id, config.PostRevisions).ConfigureAwait(false); } } // Save the main post await _repo.Save(model).ConfigureAwait(false); } App.Hooks.OnAfterSave<PostBase>(model); // Update search document if (!isDraft && _search != null) { await _search.SavePostAsync(model); } // Remove the post from cache RemoveFromCache(model); if (!isDraft && _cache != null) { // Clear all categories from cache in case some // unused where deleted. var categories = await _repo.GetAllCategories(model.BlogId).ConfigureAwait(false); foreach (var category in categories) { _cache.Remove(category.Id.ToString()); _cache.Remove($"Category_{model.BlogId}_{category.Slug}"); } // Clear all tags from cache in case some // unused where deleted. var tags = await _repo.GetAllTags(model.BlogId).ConfigureAwait(false); foreach (var tag in tags) { _cache.Remove(tag.Id.ToString()); _cache.Remove($"Tag_{model.BlogId}_{tag.Slug}"); } } } /// <summary> /// Deletes the model with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task DeleteAsync(Guid id) { var model = await GetByIdAsync<PostInfo>(id).ConfigureAwait(false); if (model != null) { await DeleteAsync(model).ConfigureAwait(false); } } /// <summary> /// Deletes the given model. /// </summary> /// <param name="model">The model</param> public async Task DeleteAsync<T>(T model) where T : PostBase { // Call hooks & save App.Hooks.OnBeforeDelete<PostBase>(model); await _repo.Delete(model.Id).ConfigureAwait(false); App.Hooks.OnAfterDelete<PostBase>(model); // Delete search document if (_search != null) { await _search.DeletePostAsync(model); } // Remove from cache & invalidate sitemap RemoveFromCache(model); } /// <summary> /// Deletes the comment with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task DeleteCommentAsync(Guid id) { var model = await GetCommentByIdAsync(id).ConfigureAwait(false); if (model != null) { await DeleteCommentAsync(model).ConfigureAwait(false); } } /// <summary> /// Deletes the given comment. /// </summary> /// <param name="model">The comment</param> public async Task DeleteCommentAsync(Comment model) { var post = await GetByIdAsync<PostInfo>(model.ContentId).ConfigureAwait(false); if (post != null) { // Call hooks & delete App.Hooks.OnBeforeDelete<Comment>(model); await _repo.DeleteComment(model.Id); App.Hooks.OnAfterDelete<Comment>(model); // Remove parent post from cache RemoveFromCache(post); } else { throw new ArgumentException($"Could not find post with id { model.ContentId.ToString() }"); } } /// <summary> /// Gets the post model with the specified id. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="id">The unique id</param> /// <param name="blogPages">The blog pages</param> /// <returns>The post model</returns> private async Task<T> GetByIdAsync<T>(Guid id, IList<PageInfo> blogPages) where T : PostBase { PostBase model = null; if (typeof(T) == typeof(PostInfo)) { model = _cache?.Get<PostInfo>($"PostInfo_{id.ToString()}"); } else if (!typeof(DynamicPost).IsAssignableFrom(typeof(T))) { model = _cache?.Get<PostBase>(id.ToString()); if (model != null) { await _factory.InitAsync(model, App.PostTypes.GetById(model.TypeId)); } } if (model == null) { model = await _repo.GetById<T>(id).ConfigureAwait(false); if (model != null) { var blog = blogPages.FirstOrDefault(p => p.Id == model.BlogId); if (blog == null) { blog = await _pageService.GetByIdAsync<PageInfo>(model.BlogId).ConfigureAwait(false); blogPages.Add(blog); } await OnLoadAsync(model, blog).ConfigureAwait(false); } } if (model != null && model is T) { return (T)model; } return null; } /// <summary> /// Checks if the given site id is empty, and if so /// gets the site id of the default site. /// </summary> /// <param name="siteId">The optional site id</param> /// <returns>The site id</returns> private async Task<Guid?> EnsureSiteIdAsync(Guid? siteId) { if (!siteId.HasValue) { var site = await _siteService.GetDefaultAsync().ConfigureAwait(false); if (site != null) { return site.Id; } } return siteId; } /// <summary> /// Processes the model on load. /// </summary> /// <param name="model">The model</param> /// <param name="blog">The blog page the post belongs to</param> /// <param name="isDraft">If this is a draft</param> private async Task OnLoadAsync(PostBase model, PageInfo blog, bool isDraft = false) { if (model != null) { // Format permalink model.Permalink = $"/{blog.Slug}/{model.Slug}"; // Initialize model if (model is IDynamicContent dynamicModel) { await _factory.InitDynamicAsync(dynamicModel, App.PostTypes.GetById(model.TypeId)); } else { await _factory.InitAsync(model, App.PostTypes.GetById(model.TypeId)); } // Initialize primary image if (model.PrimaryImage == null) { model.PrimaryImage = new Extend.Fields.ImageField(); } if (model.PrimaryImage.Id.HasValue) { await _factory.InitFieldAsync(model.PrimaryImage).ConfigureAwait(false); } // Initialize og image if (model.OgImage == null) { model.OgImage = new Extend.Fields.ImageField(); } if (model.OgImage.Id.HasValue) { await _factory.InitFieldAsync(model.OgImage).ConfigureAwait(false); } App.Hooks.OnLoad(model); // Never cache drafts, dynamic or simple instances if (!isDraft && _cache != null && !(model is DynamicPost)) { if (model is PostInfo) { _cache.Set($"PostInfo_{model.Id.ToString()}", model); } else { _cache.Set(model.Id.ToString(), model); } _cache.Set($"PostId_{model.BlogId}_{model.Slug}", model.Id); } } } /// <summary> /// Removes the given model from cache. /// </summary> /// <param name="post">The post</param> private void RemoveFromCache(PostBase post) { if (_cache != null) { _cache.Remove(post.Id.ToString()); _cache.Remove($"PostId_{post.BlogId}_{post.Slug}"); _cache.Remove($"PostInfo_{post.Id.ToString()}"); } } /// <summary> /// Checks if the given post is published /// </summary> /// <param name="model">The posts model</param> /// <returns>If the post is published</returns> private bool IsPublished (PostBase model) { return model != null && model.Published.HasValue && model.Published.Value <= DateTime.Now; } /// <summary> /// Checks if the given post is scheduled /// </summary> /// <param name="model">The post model</param> /// <returns>If the post is scheduled</returns> private bool IsScheduled(PostBase model) { return model != null && model.Published.HasValue && model.Published.Value > DateTime.Now; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using Apache.NMS.Util; using Apache.NMS.Commands; namespace Apache.NMS.Test { [TestFixture] public class ForeignMessageTransformationTest : NMSTestSupport { private string propertyName = "Test-Property"; private string propertyValue = "Test-Property-Value"; private string mapElementName = "Test-Map-Property"; private string mapElementValue = "Test-Map-Property-Value"; private string textBody = "This is a TextMessage from a Foreign Provider"; private byte[] bytesContent = {1, 2, 3, 4, 5, 6, 7, 8}; private bool a = true; private byte b = 123; private char c = 'c'; private short d = 0x1234; private int e = 0x12345678; private long f = 0x1234567812345678; private string g = "Hello World!"; private bool h = false; private byte i = 0xFF; private short j = -0x1234; private int k = -0x12345678; private long l = -0x1234567812345678; private float m = 2.1F; private double n = 2.3; [Test] public void SendReceiveForeignMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = CreateDestination(session, DestinationType.Topic); using(IMessageConsumer consumer = session.CreateConsumer(destination)) using(IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; Message request = new Message(); request.Properties[propertyName] = propertyValue; producer.Send(request); IMessage message = consumer.Receive(receiveTimeout); Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch(NotSupportedException) { } } } } } [Test] public void SendReceiveForeignTextMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = CreateDestination(session, DestinationType.Topic); using(IMessageConsumer consumer = session.CreateConsumer(destination)) using(IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; TextMessage request = new TextMessage(); request.Properties[propertyName] = propertyValue; request.Text = textBody; producer.Send(request); ITextMessage message = consumer.Receive(receiveTimeout) as ITextMessage; Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // Check the body Assert.AreEqual(textBody, message.Text, "TextMessage body was wrong."); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch(NotSupportedException) { } } } } } [Test] public void SendReceiveForeignBytesMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = CreateDestination(session, DestinationType.Topic); using(IMessageConsumer consumer = session.CreateConsumer(destination)) using(IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; BytesMessage request = new BytesMessage(); request.Properties[propertyName] = propertyValue; request.WriteBytes(bytesContent); producer.Send(request); IBytesMessage message = consumer.Receive(receiveTimeout) as IBytesMessage; Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // Check the body byte[] content = new byte[bytesContent.Length]; Assert.AreEqual(bytesContent.Length, message.ReadBytes(content)); Assert.AreEqual(bytesContent, content, "BytesMessage body was wrong."); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch(NotSupportedException) { } } } } } [Test] public void SendReceiveForeignMapMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = CreateDestination(session, DestinationType.Topic); using(IMessageConsumer consumer = session.CreateConsumer(destination)) using(IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; MapMessage request = new MapMessage(); request.Properties[propertyName] = propertyValue; request.Body[mapElementName] = mapElementValue; producer.Send(request); IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage; Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // Check the body Assert.AreEqual(request.Body.Count, message.Body.Count); Assert.AreEqual(mapElementValue, message.Body[mapElementName], "MapMessage body was wrong."); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch(NotSupportedException) { } } } } } [Test] public void SendReceiveForeignStreamMessageTest( [Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode) { using(IConnection connection = CreateConnection()) { connection.Start(); using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge)) { IDestination destination = CreateDestination(session, DestinationType.Topic); using(IMessageConsumer consumer = session.CreateConsumer(destination)) using(IMessageProducer producer = session.CreateProducer(destination)) { try { producer.DeliveryMode = deliveryMode; StreamMessage request = new StreamMessage(); request.Properties[propertyName] = propertyValue; request.WriteBoolean(a); request.WriteByte(b); request.WriteChar(c); request.WriteInt16(d); request.WriteInt32(e); request.WriteInt64(f); request.WriteString(g); request.WriteBoolean(h); request.WriteByte(i); request.WriteInt16(j); request.WriteInt32(k); request.WriteInt64(l); request.WriteSingle(m); request.WriteDouble(n); producer.Send(request); IStreamMessage message = consumer.Receive(receiveTimeout) as IStreamMessage; Assert.IsNotNull(message, "No message returned!"); Assert.AreEqual(request.Properties.Count, message.Properties.Count, "Invalid number of properties."); Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match"); // Check the body Assert.AreEqual(a, message.ReadBoolean(), "Stream Boolean Value: a"); Assert.AreEqual(b, message.ReadByte(), "Stream Byte Value: b"); Assert.AreEqual(c, message.ReadChar(), "Stream Char Value: c"); Assert.AreEqual(d, message.ReadInt16(), "Stream Int16 Value: d"); Assert.AreEqual(e, message.ReadInt32(), "Stream Int32 Value: e"); Assert.AreEqual(f, message.ReadInt64(), "Stream Int64 Value: f"); Assert.AreEqual(g, message.ReadString(), "Stream String Value: g"); Assert.AreEqual(h, message.ReadBoolean(), "Stream Boolean Value: h"); Assert.AreEqual(i, message.ReadByte(), "Stream Byte Value: i"); Assert.AreEqual(j, message.ReadInt16(), "Stream Int16 Value: j"); Assert.AreEqual(k, message.ReadInt32(), "Stream Int32 Value: k"); Assert.AreEqual(l, message.ReadInt64(), "Stream Int64 Value: l"); Assert.AreEqual(m, message.ReadSingle(), "Stream Single Value: m"); Assert.AreEqual(n, message.ReadDouble(), "Stream Double Value: n"); // use generic API to access entries Assert.AreEqual(propertyValue, message.Properties[propertyName], "generic map entry: " + propertyName); // use type safe APIs Assert.AreEqual(propertyValue, message.Properties.GetString(propertyName), "map entry: " + propertyName); } catch(NotSupportedException) { } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Internal; using System.Text.Unicode; namespace System.Text.Encodings.Web { /// <summary> /// Represents a type used to do JavaScript encoding/escaping. /// </summary> public abstract class JavaScriptEncoder : TextEncoder { /// <summary> /// Returns a default built-in instance of <see cref="JavaScriptEncoder"/>. /// </summary> public static JavaScriptEncoder Default { get { return DefaultJavaScriptEncoder.Singleton; } } /// <summary> /// Creates a new instance of JavaScriptEncoder with provided settings. /// </summary> /// <param name="settings">Settings used to control how the created <see cref="JavaScriptEncoder"/> encodes, primarily which characters to encode.</param> /// <returns>A new instance of the <see cref="JavaScriptEncoder"/>.</returns> public static JavaScriptEncoder Create(TextEncoderSettings settings) { return new DefaultJavaScriptEncoder(settings); } /// <summary> /// Creates a new instance of JavaScriptEncoder specifying character to be encoded. /// </summary> /// <param name="allowedRanges">Set of characters that the encoder is allowed to not encode.</param> /// <returns>A new instance of the <see cref="JavaScriptEncoder"/>.</returns> /// <remarks>Some characters in <paramref name="allowedRanges"/> might still get encoded, i.e. this parameter is just telling the encoder what ranges it is allowed to not encode, not what characters it must not encode.</remarks> public static JavaScriptEncoder Create(params UnicodeRange[] allowedRanges) { return new DefaultJavaScriptEncoder(allowedRanges); } } internal sealed class DefaultJavaScriptEncoder : JavaScriptEncoder { private AllowedCharactersBitmap _allowedCharacters; internal readonly static DefaultJavaScriptEncoder Singleton = new DefaultJavaScriptEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); public DefaultJavaScriptEncoder(TextEncoderSettings filter) { if (filter == null) { throw new ArgumentNullException(nameof(filter)); } _allowedCharacters = filter.GetAllowedCharacters(); // Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed // (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp) _allowedCharacters.ForbidUndefinedCharacters(); // Forbid characters that are special in HTML. // Even though this is a not HTML encoder, // it's unfortunately common for developers to // forget to HTML-encode a string once it has been JS-encoded, // so this offers extra protection. DefaultHtmlEncoder.ForbidHtmlCharacters(_allowedCharacters); _allowedCharacters.ForbidCharacter('\\'); _allowedCharacters.ForbidCharacter('/'); // Forbid GRAVE ACCENT \u0060 character. _allowedCharacters.ForbidCharacter('`'); } public DefaultJavaScriptEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) return true; return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException(nameof(text)); } return _allowedCharacters.FindFirstCharacterToEncode(text, textLength); } // The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF" // We don't need to worry about astral code points since they're represented as encoded // surrogate pairs in the output. public override int MaxOutputCharactersPerInputCharacter { get { return 12; } // "\uFFFF\uFFFF" is the longest encoded form } static readonly char[] s_b = new char[] { '\\', 'b' }; static readonly char[] s_t = new char[] { '\\', 't' }; static readonly char[] s_n = new char[] { '\\', 'n' }; static readonly char[] s_f = new char[] { '\\', 'f' }; static readonly char[] s_r = new char[] { '\\', 'r' }; static readonly char[] s_forward = new char[] { '\\', '/' }; static readonly char[] s_back = new char[] { '\\', '\\' }; // Writes a scalar value as a JavaScript-escaped character (or sequence of characters). // See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9 // http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4 // http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } // ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not. // Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/". // (In ECMA-262 this character is a NonEscape character.) // HTML-specific characters (including apostrophe and quotes) will // be written out as numeric entities for defense-in-depth. // See UnicodeEncoderBase ctor comments for more info. if (!WillEncode(unicodeScalar)) { return TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] toCopy = null; switch (unicodeScalar) { case '\b': toCopy = s_b; break; case '\t': toCopy = s_t; break; case '\n': toCopy = s_n; break; case '\f': toCopy = s_f; break; case '\r': toCopy = s_r; break; case '/': toCopy = s_forward; break; case '\\': toCopy = s_back; break; default: return TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TryCopyCharacters(toCopy, buffer, bufferLength, out numberOfCharactersWritten); } private unsafe static bool TryWriteEncodedScalarAsNumericEntity(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { Debug.Assert(buffer != null && length >= 0); if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { // Convert this back to UTF-16 and write out both characters. char leadingSurrogate, trailingSurrogate; UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue(unicodeScalar, out leadingSurrogate, out trailingSurrogate); int leadingSurrogateCharactersWritten; if (TryWriteEncodedSingleCharacter(leadingSurrogate, buffer, length, out leadingSurrogateCharactersWritten) && TryWriteEncodedSingleCharacter(trailingSurrogate, buffer + leadingSurrogateCharactersWritten, length - leadingSurrogateCharactersWritten, out numberOfCharactersWritten) ) { numberOfCharactersWritten += leadingSurrogateCharactersWritten; return true; } else { numberOfCharactersWritten = 0; return false; } } else { // This is only a single character. return TryWriteEncodedSingleCharacter(unicodeScalar, buffer, length, out numberOfCharactersWritten); } } // Writes an encoded scalar value (in the BMP) as a JavaScript-escaped character. private unsafe static bool TryWriteEncodedSingleCharacter(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { Debug.Assert(buffer != null && length >= 0); Debug.Assert(!UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar), "The incoming value should've been in the BMP."); if (length < 6) { numberOfCharactersWritten = 0; return false; } // Encode this as 6 chars "\uFFFF". *buffer = '\\'; buffer++; *buffer = 'u'; buffer++; *buffer = HexUtil.Int32LsbToHexDigit(unicodeScalar >> 12); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)((unicodeScalar >> 8) & 0xFU)); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)((unicodeScalar >> 4) & 0xFU)); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)(unicodeScalar & 0xFU)); buffer++; numberOfCharactersWritten = 6; 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.Specialized; using System.Configuration.Internal; namespace System.Configuration { public static class ConfigurationManager { // The Configuration System private static volatile IInternalConfigSystem s_configSystem; // Initialization state private static volatile InitState s_initState = InitState.NotStarted; private static readonly object s_initLock = new object(); private static volatile Exception s_initError; // to be used by System.Diagnostics to avoid false config results during config init internal static bool SetConfigurationSystemInProgress => (InitState.NotStarted < s_initState) && (s_initState < InitState.Completed); internal static bool SupportsUserConfig { get { PrepareConfigSystem(); return s_configSystem.SupportsUserConfig; } } public static NameValueCollection AppSettings { get { object section = GetSection("appSettings"); if (!(section is NameValueCollection)) { // If config is null or not the type we expect, the declaration was changed. // Treat it as a configuration error. throw new ConfigurationErrorsException(SR.Config_appsettings_declaration_invalid); } return (NameValueCollection)section; } } public static ConnectionStringSettingsCollection ConnectionStrings { get { object section = GetSection("connectionStrings"); // Verify type, and return the collection if ((section == null) || (section.GetType() != typeof(ConnectionStringsSection))) { // If config is null or not the type we expect, the declaration was changed. // Treat it as a configuration error. throw new ConfigurationErrorsException(SR.Config_connectionstrings_declaration_invalid); } ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)section; return connectionStringsSection.ConnectionStrings; } } // Called by ASP.NET to allow hierarchical configuration settings and ASP.NET specific extenstions. internal static void SetConfigurationSystem(IInternalConfigSystem configSystem, bool initComplete) { lock (s_initLock) { // It is an error if the configuration system has already been set. if (s_initState != InitState.NotStarted) throw new InvalidOperationException(SR.Config_system_already_set); s_configSystem = configSystem; s_initState = initComplete ? InitState.Completed : InitState.Usable; } } private static void EnsureConfigurationSystem() { // If a configuration system has not yet been set, // create the DefaultConfigurationSystem for exe's. lock (s_initLock) { if (s_initState >= InitState.Usable) return; s_initState = InitState.Started; try { try { // Create the system, but let it initialize itself when GetConfig is called, // so that it can handle its own re-entrancy issues during initialization. // // When initialization is complete, the DefaultConfigurationSystem will call // CompleteConfigInit to mark initialization as having completed. // // Note: the ClientConfigurationSystem has a 2-stage initialization, // and that's why s_initState isn't set to InitState.Completed yet. s_configSystem = new ClientConfigurationSystem(); s_initState = InitState.Usable; } catch (Exception e) { s_initError = new ConfigurationErrorsException(SR.Config_client_config_init_error, e); throw s_initError; } } catch { s_initState = InitState.Completed; throw; } } } // Set the initialization error. internal static void SetInitError(Exception initError) { s_initError = initError; } // Mark intiailization as having completed. internal static void CompleteConfigInit() { lock (s_initLock) { s_initState = InitState.Completed; } } private static void PrepareConfigSystem() { // Ensure the configuration system is usable. if (s_initState < InitState.Usable) EnsureConfigurationSystem(); // If there was an initialization error, throw it. if (s_initError != null) throw s_initError; } public static object GetSection(string sectionName) { // Avoid unintended AV's by ensuring sectionName is not empty. // For compatibility, we cannot throw an InvalidArgumentException. if (string.IsNullOrEmpty(sectionName)) return null; PrepareConfigSystem(); object section = s_configSystem.GetSection(sectionName); return section; } public static void RefreshSection(string sectionName) { // Avoid unintended AV's by ensuring sectionName is not empty. // For consistency with GetSection, we should not throw an InvalidArgumentException. if (string.IsNullOrEmpty(sectionName)) return; PrepareConfigSystem(); s_configSystem.RefreshConfig(sectionName); } public static Configuration OpenMachineConfiguration() { return OpenExeConfigurationImpl(null, true, ConfigurationUserLevel.None, null); } public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap) { return OpenExeConfigurationImpl(fileMap, true, ConfigurationUserLevel.None, null); } public static Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel) { return OpenExeConfigurationImpl(null, false, userLevel, null); } public static Configuration OpenExeConfiguration(string exePath) { return OpenExeConfigurationImpl(null, false, ConfigurationUserLevel.None, exePath); } public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel) { return OpenExeConfigurationImpl(fileMap, false, userLevel, null); } public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel, bool preLoad) { return OpenExeConfigurationImpl(fileMap, false, userLevel, null, preLoad); } private static Configuration OpenExeConfigurationImpl(ConfigurationFileMap fileMap, bool isMachine, ConfigurationUserLevel userLevel, string exePath, bool preLoad = false) { // exePath must be specified if not running inside ClientConfigurationSystem if (!isMachine && (((fileMap == null) && (exePath == null)) || ((fileMap != null) && (((ExeConfigurationFileMap)fileMap).ExeConfigFilename == null)))) { if ((s_configSystem != null) && (s_configSystem.GetType() != typeof(ClientConfigurationSystem))) throw new ArgumentException(SR.Config_configmanager_open_noexe); } Configuration config = ClientConfigurationHost.OpenExeConfiguration(fileMap, isMachine, userLevel, exePath); if (preLoad) PreloadConfiguration(config); return config; } /// <summary> /// Recursively loads configuration section groups and sections belonging to a configuration object. /// </summary> private static void PreloadConfiguration(Configuration configuration) { if (null == configuration) return; // Preload root-level sections. foreach (ConfigurationSection section in configuration.Sections) { } // Recursively preload all section groups and sections. foreach (ConfigurationSectionGroup sectionGroup in configuration.SectionGroups) PreloadConfigurationSectionGroup(sectionGroup); } private static void PreloadConfigurationSectionGroup(ConfigurationSectionGroup sectionGroup) { if (null == sectionGroup) return; // Preload sections just by iterating. foreach (ConfigurationSection section in sectionGroup.Sections) { } // Load child section groups. foreach (ConfigurationSectionGroup childSectionGroup in sectionGroup.SectionGroups) PreloadConfigurationSectionGroup(childSectionGroup); } private enum InitState { // Initialization has not yet started. NotStarted = 0, // Initialization has started. Started, // The config system can be used, but initialization is not yet complete. Usable, // The config system has been completely initialized. Completed }; } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.IronPythonTools.Interpreter; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestUtilities { public class PythonPaths { private static readonly List<PythonInterpreterInformation> _foundInRegistry = PythonRegistrySearch .PerformDefaultSearch() .Where(pii => pii.Configuration.Id.Contains("PythonCore|") || pii.Configuration.Id.Contains("ContinuumAnalytics|")) .ToList(); public static readonly PythonVersion Python26 = GetCPythonVersion(PythonLanguageVersion.V26, InterpreterArchitecture.x86); public static readonly PythonVersion Python27 = GetCPythonVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x86); public static readonly PythonVersion Python31 = GetCPythonVersion(PythonLanguageVersion.V31, InterpreterArchitecture.x86); public static readonly PythonVersion Python32 = GetCPythonVersion(PythonLanguageVersion.V32, InterpreterArchitecture.x86); public static readonly PythonVersion Python33 = GetCPythonVersion(PythonLanguageVersion.V33, InterpreterArchitecture.x86); public static readonly PythonVersion Python34 = GetCPythonVersion(PythonLanguageVersion.V34, InterpreterArchitecture.x86); public static readonly PythonVersion Python35 = GetCPythonVersion(PythonLanguageVersion.V35, InterpreterArchitecture.x86); public static readonly PythonVersion Python36 = GetCPythonVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x86); public static readonly PythonVersion Python37 = GetCPythonVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x86); public static readonly PythonVersion IronPython27 = GetIronPythonVersion(false); public static readonly PythonVersion Python26_x64 = GetCPythonVersion(PythonLanguageVersion.V26, InterpreterArchitecture.x64); public static readonly PythonVersion Python27_x64 = GetCPythonVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x64); public static readonly PythonVersion Python31_x64 = GetCPythonVersion(PythonLanguageVersion.V31, InterpreterArchitecture.x64); public static readonly PythonVersion Python32_x64 = GetCPythonVersion(PythonLanguageVersion.V32, InterpreterArchitecture.x64); public static readonly PythonVersion Python33_x64 = GetCPythonVersion(PythonLanguageVersion.V33, InterpreterArchitecture.x64); public static readonly PythonVersion Python34_x64 = GetCPythonVersion(PythonLanguageVersion.V34, InterpreterArchitecture.x64); public static readonly PythonVersion Python35_x64 = GetCPythonVersion(PythonLanguageVersion.V35, InterpreterArchitecture.x64); public static readonly PythonVersion Python36_x64 = GetCPythonVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x64); public static readonly PythonVersion Python37_x64 = GetCPythonVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x64); public static readonly PythonVersion Anaconda27 = GetAnacondaVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x86); public static readonly PythonVersion Anaconda27_x64 = GetAnacondaVersion(PythonLanguageVersion.V27, InterpreterArchitecture.x64); public static readonly PythonVersion Anaconda36 = GetAnacondaVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x86); public static readonly PythonVersion Anaconda36_x64 = GetAnacondaVersion(PythonLanguageVersion.V36, InterpreterArchitecture.x64); public static readonly PythonVersion Anaconda37 = GetAnacondaVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x86); public static readonly PythonVersion Anaconda37_x64 = GetAnacondaVersion(PythonLanguageVersion.V37, InterpreterArchitecture.x64); public static readonly PythonVersion IronPython27_x64 = GetIronPythonVersion(true); public static readonly PythonVersion Jython27 = GetJythonVersion(PythonLanguageVersion.V27); private static PythonVersion GetIronPythonVersion(bool x64) { var exeName = x64 ? "ipy64.exe" : "ipy.exe"; var installPath = IronPythonResolver.GetPythonInstallDir(); if (Directory.Exists(installPath)) { // IronPython changed to Any CPU for ipy.exe and ipy32.exe for 32-bit in 2.7.8 if (File.Exists(Path.Combine(installPath, "ipy32.exe"))) { exeName = x64 ? "ipy.exe" : "ipy32.exe"; } return new PythonVersion( new VisualStudioInterpreterConfiguration( x64 ? "IronPython|2.7-64" : "IronPython|2.7-32", string.Format("IronPython {0} 2.7", x64 ? "64-bit" : "32-bit"), installPath, Path.Combine(installPath, exeName), architecture: x64 ? InterpreterArchitecture.x64 : InterpreterArchitecture.x86, version: new Version(2, 7), pathVar: "IRONPYTHONPATH" ), ironPython: true ); } return null; } private static PythonVersion GetAnacondaVersion(PythonLanguageVersion version, InterpreterArchitecture arch) { var res = _foundInRegistry.FirstOrDefault(ii => ii.Configuration.Id.StartsWith("Global|ContinuumAnalytics|") && ii.Configuration.Architecture == arch && ii.Configuration.Version == version.ToVersion() ); if (res != null) { return new PythonVersion(res.Configuration, cPython: true); } return null; } private static PythonVersion GetCPythonVersion(PythonLanguageVersion version, InterpreterArchitecture arch) { var res = _foundInRegistry.FirstOrDefault(ii => ii.Configuration.Id.StartsWith("Global|PythonCore|") && ii.Configuration.Architecture == arch && ii.Configuration.Version == version.ToVersion() ); if (res != null) { return new PythonVersion(res.Configuration, cPython: true); } var ver = version.ToVersion(); var tag = ver + (arch == InterpreterArchitecture.x86 ? "-32" : ""); foreach (var path in new[] { string.Format("Python{0}{1}", ver.Major, ver.Minor), string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("x")), string.Format("Python{0}{1}-{2}", ver.Major, ver.Minor, arch.ToString("#")), string.Format("Python{0}{1}_{2}", ver.Major, ver.Minor, arch.ToString("#")), }) { var prefixPath = Path.Combine(Environment.GetEnvironmentVariable("SystemDrive"), "\\", path); var exePath = Path.Combine(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable); var procArch = (arch == InterpreterArchitecture.x86) ? ProcessorArchitecture.X86 : (arch == InterpreterArchitecture.x64) ? ProcessorArchitecture.Amd64 : ProcessorArchitecture.None; if (procArch == Microsoft.PythonTools.Infrastructure.NativeMethods.GetBinaryType(path)) { return new PythonVersion(new VisualStudioInterpreterConfiguration( CPythonInterpreterFactoryConstants.GetInterpreterId("PythonCore", tag), "Python {0} {1}".FormatInvariant(arch, ver), prefixPath, exePath, pathVar: CPythonInterpreterFactoryConstants.PathEnvironmentVariableName, architecture: arch, version: ver )); } } return null; } private static PythonVersion GetJythonVersion(PythonLanguageVersion version) { var candidates = new List<DirectoryInfo>(); var ver = version.ToVersion(); var path1 = string.Format("jython{0}{1}*", ver.Major, ver.Minor); var path2 = string.Format("jython{0}.{1}*", ver.Major, ver.Minor); foreach (var drive in DriveInfo.GetDrives()) { if (drive.DriveType != DriveType.Fixed) { continue; } try { candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path1)); candidates.AddRange(drive.RootDirectory.EnumerateDirectories(path2)); } catch { } } foreach (var dir in candidates) { var interpreter = dir.EnumerateFiles("jython.bat").FirstOrDefault(); if (interpreter == null) { continue; } var libPath = dir.EnumerateDirectories("Lib").FirstOrDefault(); if (libPath == null || !libPath.EnumerateFiles("site.py").Any()) { continue; } return new PythonVersion(new VisualStudioInterpreterConfiguration( CPythonInterpreterFactoryConstants.GetInterpreterId( "Jython", version.ToVersion().ToString() ), string.Format("Jython {0}", version.ToVersion()), dir.FullName, interpreter.FullName, version: version.ToVersion() )); } return null; } public static IEnumerable<PythonVersion> AnacondaVersions { get { if (Anaconda37 != null) yield return Anaconda37; if (Anaconda37_x64 != null) yield return Anaconda37_x64; if (Anaconda36 != null) yield return Anaconda36; if (Anaconda36_x64 != null) yield return Anaconda36_x64; if (Anaconda27 != null) yield return Anaconda27; if (Anaconda27_x64 != null) yield return Anaconda27_x64; } } public static IEnumerable<PythonVersion> Versions { get { if (Python26 != null) yield return Python26; if (Python27 != null) yield return Python27; if (Python31 != null) yield return Python31; if (Python32 != null) yield return Python32; if (Python33 != null) yield return Python33; if (Python34 != null) yield return Python34; if (Python35 != null) yield return Python35; if (Python36 != null) yield return Python36; if (Python37 != null) yield return Python37; if (IronPython27 != null) yield return IronPython27; if (Python26_x64 != null) yield return Python26_x64; if (Python27_x64 != null) yield return Python27_x64; if (Python31_x64 != null) yield return Python31_x64; if (Python32_x64 != null) yield return Python32_x64; if (Python33_x64 != null) yield return Python33_x64; if (Python34_x64 != null) yield return Python34_x64; if (Python35_x64 != null) yield return Python35_x64; if (Python36_x64 != null) yield return Python36_x64; if (Python37_x64 != null) yield return Python37_x64; if (IronPython27_x64 != null) yield return IronPython27_x64; if (Jython27 != null) yield return Jython27; } } /// <summary> /// Get the installed Python versions that match the specified name expression and filter. /// </summary> /// <param name="nameExpr">Name or '|' separated list of names that match the fields on <c>PythonPaths</c>. Ex: "Python36", "Python36|Python36_x64"</param> /// <param name="filter">Additional filter.</param> /// <returns>Installed Python versions that match the names and filter.</returns> public static PythonVersion[] GetVersionsByName(string nameExpr, Predicate<PythonVersion> filter = null) { return nameExpr .Split('|') .Select(v => typeof(PythonPaths).GetField(v, BindingFlags.Static | BindingFlags.Public)?.GetValue(null) as PythonVersion) .Where(v => v != null && (filter != null ? filter(v) : true)) .ToArray(); } } public class PythonVersion { public readonly InterpreterConfiguration Configuration; public readonly bool IsCPython; public readonly bool IsIronPython; public PythonVersion(InterpreterConfiguration config, bool ironPython = false, bool cPython = false) { Configuration = config; IsCPython = cPython; IsIronPython = ironPython; } public PythonVersion(string version) { PythonVersion selected; if (version == "Anaconda27") { selected = PythonPaths.Anaconda27 ?? PythonPaths.Anaconda27_x64; } else if (version == "Anaconda36") { selected = PythonPaths.Anaconda36 ?? PythonPaths.Anaconda36_x64; } else { var v = System.Version.Parse(version).ToLanguageVersion(); var candididates = PythonPaths.Versions.Where(pv => pv.IsCPython && pv.Version == v).ToArray(); if (candididates.Length > 1) { selected = candididates.FirstOrDefault(c => c.Isx64) ?? candididates.First(); } else { selected = candididates.FirstOrDefault(); } } selected.AssertInstalled(); Configuration = selected.Configuration; IsCPython = selected.IsCPython; IsIronPython = selected.IsIronPython; } public override string ToString() => Configuration.Description; public string PrefixPath => Configuration.GetPrefixPath(); public string InterpreterPath => Configuration.InterpreterPath; public PythonLanguageVersion Version => Configuration.Version.ToLanguageVersion(); public string Id => Configuration.Id; public bool Isx64 => Configuration.Architecture == InterpreterArchitecture.x64; public InterpreterArchitecture Architecture => Configuration.Architecture; } public static class PythonVersionExtensions { public static void AssertInstalled(this PythonVersion pyVersion, string customMessage = "Python interpreter not installed") { if (pyVersion == null || !File.Exists(pyVersion.InterpreterPath)) { Assert.Inconclusive(customMessage); } } /// <summary> /// Creates a Python virtual environment in vEnvPath directory and installs the specified packages /// </summary> /// <param name="pyVersion"></param> /// <param name="virtualEnvPath"></param> /// <param name="packages"></param> public static void CreatePythonVirtualEnvWithPkgs(this PythonVersion pyVersion, string virtualEnvPath, string[] packages) { pyVersion.CreatePythonVirtualEnv(virtualEnvPath); var envPythonExePath = Path.Combine(virtualEnvPath, "scripts", "python.exe"); foreach (var package in packages.MaybeEnumerate()) { using (var output = ProcessOutput.RunHiddenAndCapture(envPythonExePath, "-m", "pip", "install", package)) { Assert.IsTrue(output.Wait(TimeSpan.FromSeconds(30))); Assert.AreEqual(0, output.ExitCode); } } } /// <summary> /// Creates a Python virtual environment in vEnvPath directory /// </summary> /// <param name="pyVersion"></param> /// <param name="vEnvPath"></param> public static void CreatePythonVirtualEnv(this PythonVersion pyVersion, string vEnvPath) { var virtualEnvModule = (pyVersion.Version < PythonLanguageVersion.V30) ? "virtualenv" : "venv"; using (var p = ProcessOutput.RunHiddenAndCapture(pyVersion.InterpreterPath, "-m", virtualEnvModule, vEnvPath)) { Console.WriteLine(p.Arguments); Assert.IsTrue(p.Wait(TimeSpan.FromMinutes(3))); Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines))); Assert.AreEqual(0, p.ExitCode); } Assert.IsTrue(File.Exists(Path.Combine(vEnvPath, "scripts", "python.exe"))); } } }
// 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.IO; using System.Linq; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class PublicKeyTests { private static PublicKey GetTestRsaKey() { using (var cert = new X509Certificate2(TestData.MsCertificate)) { return cert.PublicKey; } } private static PublicKey GetTestDsaKey() { using (var cert = new X509Certificate2(TestData.DssCer)) { return cert.PublicKey; } } private static PublicKey GetTestECDsaKey() { using (var cert = new X509Certificate2(TestData.ECDsa256Certificate)) { return cert.PublicKey; } } /// <summary> /// First parameter is the cert, the second is a hash of "Hello" /// </summary> public static IEnumerable<object[]> BrainpoolCurves { get { #if uap yield break; #else yield return new object[] { TestData.ECDsabrainpoolP160r1_CertificatePemBytes, "9145C79DD4DF758EB377D13B0DB81F83CE1A63A4099DDC32FE228B06EB1F306423ED61B6B4AF4691".HexToByteArray() }; yield return new object[] { TestData.ECDsabrainpoolP160r1_ExplicitCertificatePemBytes, "6D74F1C9BCBBA5A25F67E670B3DABDB36C24E8FAC3266847EB2EE7E3239208ADC696BB421AB380B4".HexToByteArray() }; #endif } } [Fact] public static void TestOid_RSA() { PublicKey pk = GetTestRsaKey(); Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value); } [Fact] public static void TestOid_DSA() { PublicKey pk = GetTestDsaKey(); Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value); } [Fact] public static void TestOid_ECDSA() { PublicKey pk = GetTestECDsaKey(); Assert.Equal("1.2.840.10045.2.1", pk.Oid.Value); } [Fact] public static void TestPublicKey_Key_RSA() { PublicKey pk = GetTestRsaKey(); using (AsymmetricAlgorithm alg = pk.Key) { Assert.NotNull(alg); Assert.Same(alg, pk.Key); Assert.Equal(2048, alg.KeySize); Assert.IsAssignableFrom(typeof(RSA), alg); VerifyKey_RSA( /* cert */ null, (RSA)alg); } } [Fact] public static void TestPublicKey_Key_DSA() { PublicKey pk = GetTestDsaKey(); using (AsymmetricAlgorithm alg = pk.Key) { Assert.NotNull(alg); Assert.Same(alg, pk.Key); Assert.Equal(1024, alg.KeySize); Assert.IsAssignableFrom(typeof(DSA), alg); VerifyKey_DSA((DSA)alg); } } [Fact] public static void TestPublicKey_Key_ECDSA() { PublicKey pk = GetTestECDsaKey(); Assert.Throws<NotSupportedException>(() => pk.Key); } private static void VerifyKey_DSA(DSA dsa) { DSAParameters dsaParameters = dsa.ExportParameters(false); byte[] expected_g = ( "859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481584413" + "E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310FEFD518" + "AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0DAFDA0" + "79BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D05431D").HexToByteArray(); byte[] expected_p = ( "871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180511D0DCEB8B97928" + "5708C800FC10CB15337A4AC1A48ED31394072015A7A6B525986B49E5E1139737" + "A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA41E8F0763AA613E29" + "C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DFB33C44D2F2DBE819").HexToByteArray(); byte[] expected_q = "E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D".HexToByteArray(); byte[] expected_y = ( "089A43F439B924BEF3529D8D6206D1FCA56A55CAF52B41D6CE371EBF07BDA132" + "C8EADC040007FCF4DA06C1F30504EBD8A77D301F5A4702F01F0D2A0707AC1DA3" + "8DD3251883286E12456234DA62EDA0DF5FE2FA07CD5B16F3638BECCA7786312D" + "A7D3594A4BB14E353884DA0E9AECB86E3C9BDB66FCA78EA85E1CC3F2F8BF0963").HexToByteArray(); Assert.Equal(expected_g, dsaParameters.G); Assert.Equal(expected_p, dsaParameters.P); Assert.Equal(expected_q, dsaParameters.Q); Assert.Equal(expected_y, dsaParameters.Y); } [Fact] public static void TestEncodedKeyValue_RSA() { byte[] expectedPublicKey = ( "3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" + "407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" + "137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" + "b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" + "109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" + "2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" + "2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" + "84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" + "0b950005b14f6571c50203010001").HexToByteArray(); PublicKey pk = GetTestRsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedKeyValue_DSA() { byte[] expectedPublicKey = ( "028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371ebf07" + "bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a0707" + "ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638becca77" + "86312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3f2f8" + "bf0963").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedKeyValue_ECDSA() { // Uncompressed key (04), then the X coord, then the Y coord. string expectedPublicKeyHex = "04" + "448D98EE08AEBA0D8B40F3C6DBD500E8B69F07C70C661771655228EA5A178A91" + "0EF5CB1759F6F2E062021D4F973F5BB62031BE87AE915CFF121586809E3219AF"; PublicKey pk = GetTestECDsaKey(); Assert.Equal(expectedPublicKeyHex, pk.EncodedKeyValue.RawData.ByteArrayToHex()); } [Fact] public static void TestEncodedParameters_RSA() { PublicKey pk = GetTestRsaKey(); // RSA has no key parameters, so the answer is always // DER:NULL (type 0x05, length 0x00) Assert.Equal(new byte[] { 0x05, 0x00 }, pk.EncodedParameters.RawData); } [Fact] public static void TestEncodedParameters_DSA() { byte[] expectedParameters = ( "3082011F02818100871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180" + "511D0DCEB8B979285708C800FC10CB15337A4AC1A48ED31394072015A7A6B525" + "986B49E5E1139737A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA4" + "1E8F0763AA613E29C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DF" + "B33C44D2F2DBE819021500E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D02" + "818100859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481" + "584413E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310F" + "EFD518AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0" + "DAFDA079BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D" + "05431D").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedParameters, pk.EncodedParameters.RawData); } [Fact] public static void TestEncodedParameters_ECDSA() { // OID: 1.2.840.10045.3.1.7 string expectedParametersHex = "06082A8648CE3D030107"; PublicKey pk = GetTestECDsaKey(); Assert.Equal(expectedParametersHex, pk.EncodedParameters.RawData.ByteArrayToHex()); } [Fact] public static void TestKey_RSA() { using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { RSA rsa = cert.GetRSAPublicKey(); VerifyKey_RSA(cert, rsa); } } private static void VerifyKey_RSA(X509Certificate2 cert, RSA rsa) { RSAParameters rsaParameters = rsa.ExportParameters(false); byte[] expectedModulus = ( "E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" + "51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" + "EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" + "C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" + "1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" + "94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" + "C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" + "E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray(); byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 }; byte[] originalModulus = rsaParameters.Modulus; byte[] originalExponent = rsaParameters.Exponent; if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) || !expectedExponent.SequenceEqual(rsaParameters.Exponent)) { Console.WriteLine("Modulus or Exponent not equal"); rsaParameters = rsa.ExportParameters(false); if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) || !expectedExponent.SequenceEqual(rsaParameters.Exponent)) { Console.WriteLine("Second call to ExportParameters did not produce valid data either"); } if (cert != null) { rsa = cert.GetRSAPublicKey(); rsaParameters = rsa.ExportParameters(false); if (!expectedModulus.SequenceEqual(rsaParameters.Modulus) || !expectedExponent.SequenceEqual(rsaParameters.Exponent)) { Console.WriteLine("New key handle ExportParameters was not successful either"); } } } Assert.Equal(expectedModulus, originalModulus); Assert.Equal(expectedExponent, originalExponent); } [Fact] public static void TestKey_RSA384_ValidatesSignature() { byte[] signature = { 0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C, 0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44, 0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68, 0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06, 0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4, 0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (RSA rsa = cert.GetRSAPublicKey()) { Assert.True(rsa.VerifyData(helloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)); } } [Theory, MemberData(nameof(BrainpoolCurves))] public static void TestKey_ECDsabrainpool_PublicKey(byte[] curveData, byte[] notUsed) { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); try { using (var cert = new X509Certificate2(curveData)) { using (ECDsa ec = cert.GetECDsaPublicKey()) { Assert.Equal(160, ec.KeySize); // The public key should be unable to sign. Assert.ThrowsAny<CryptographicException>(() => ec.SignData(helloBytes, HashAlgorithmName.SHA256)); } } } catch (CryptographicException) { // Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail. Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10); Assert.False(PlatformDetection.IsUbuntu && !PlatformDetection.IsUbuntu1404); } } [Fact] public static void TestECDsaPublicKey() { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); // The public key should be unable to sign. Assert.ThrowsAny<CryptographicException>(() => publicKey.SignData(helloBytes, HashAlgorithmName.SHA256)); } } [Fact] public static void TestECDsaPublicKey_ValidatesSignature() { // This signature was produced as the output of ECDsaCng.SignData with the same key // on .NET 4.6. Ensure it is verified here as a data compatibility test. // // Note that since ECDSA signatures contain randomness as an input, this value is unlikely // to be reproduced by another equivalent program. byte[] existingSignature = { // r: 0x7E, 0xD7, 0xEF, 0x46, 0x04, 0x92, 0x61, 0x27, 0x9F, 0xC9, 0x1B, 0x7B, 0x8A, 0x41, 0x6A, 0xC6, 0xCF, 0xD4, 0xD4, 0xD1, 0x73, 0x05, 0x1F, 0xF3, 0x75, 0xB2, 0x13, 0xFA, 0x82, 0x2B, 0x55, 0x11, 0xBE, 0x57, 0x4F, 0x20, 0x07, 0x24, 0xB7, 0xE5, 0x24, 0x44, 0x33, 0xC3, 0xB6, 0x8F, 0xBC, 0x1F, // s: 0x48, 0x57, 0x25, 0x39, 0xC0, 0x84, 0xB9, 0x0E, 0xDA, 0x32, 0x35, 0x16, 0xEF, 0xA0, 0xE2, 0x34, 0x35, 0x7E, 0x10, 0x38, 0xA5, 0xE4, 0x8B, 0xD3, 0xFC, 0xE7, 0x60, 0x25, 0x4E, 0x63, 0xF7, 0xDB, 0x7C, 0xBF, 0x18, 0xD6, 0xD3, 0x49, 0xD0, 0x93, 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.True(isSignatureValid, "isSignatureValid"); } } [Theory, MemberData(nameof(BrainpoolCurves))] public static void TestECDsaPublicKey_BrainpoolP160r1_ValidatesSignature(byte[] curveData, byte[] existingSignature) { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); try { using (var cert = new X509Certificate2(curveData)) { using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(160, publicKey.KeySize); // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.True(isSignatureValid, "isSignatureValid"); unchecked { --existingSignature[existingSignature.Length - 1]; } isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.False(isSignatureValid, "isSignatureValidNeg"); } } } catch (CryptographicException) { // Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail. Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10); Assert.False(PlatformDetection.IsUbuntu && !PlatformDetection.IsUbuntu1404); } } [Fact] public static void TestECDsaPublicKey_NonSignatureCert() { using (var cert = new X509Certificate2(TestData.EccCert_KeyAgreement)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); // But, due to KeyUsage, it shouldn't be used for ECDSA. Assert.Null(publicKey); } } [Fact] public static void TestECDsa224PublicKey() { using (var cert = new X509Certificate2(TestData.ECDsa224Certificate)) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); ECDsa ecdsa; try { ecdsa = cert.GetECDsaPublicKey(); } catch (CryptographicException) { // Windows 7, Windows 8, CentOS. return; } // Other Unix using (ecdsa) { byte[] data = ByteUtils.AsciiBytes("Hello"); byte[] signature = ( // r "8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" + // s "5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray(); Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1)); } } } #if netcoreapp [Fact] public static void TestDSAPublicKey() { using (var cert = new X509Certificate2(TestData.DssCer)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.NotNull(pubKey); VerifyKey_DSA(pubKey); } } [Fact] public static void TestDSAPublicKey_VerifiesSignature() { byte[] data = { 1, 2, 3, 4, 5 }; byte[] wrongData = { 0xFE, 2, 3, 4, 5 }; byte[] signature = "B06E26CFC939F25B864F52ABD3288222363A164259B0027FFC95DBC88F9204F7A51A901F3005C9F7".HexToByteArray(); using (var cert = new X509Certificate2(TestData.Dsa1024Cert)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.True(pubKey.VerifyData(data, signature, HashAlgorithmName.SHA1), "pubKey verifies signature"); Assert.False(pubKey.VerifyData(wrongData, signature, HashAlgorithmName.SHA1), "pubKey verifies tampered data"); signature[0] ^= 0xFF; Assert.False(pubKey.VerifyData(data, signature, HashAlgorithmName.SHA1), "pubKey verifies tampered signature"); } } [Fact] public static void TestDSAPublicKey_RSACert() { using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.Null(pubKey); } } [Fact] public static void TestDSAPublicKey_ECDSACert() { using (var cert = new X509Certificate2(TestData.ECDsa256Certificate)) using (DSA pubKey = cert.GetDSAPublicKey()) { Assert.Null(pubKey); } } #endif [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_ECDsaCng256() { TestKey_ECDsaCng(TestData.ECDsa256Certificate, TestData.ECDsaCng256PublicKey); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_ECDsaCng384() { TestKey_ECDsaCng(TestData.ECDsa384Certificate, TestData.ECDsaCng384PublicKey); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_ECDsaCng521() { TestKey_ECDsaCng(TestData.ECDsa521Certificate, TestData.ECDsaCng521PublicKey); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void TestKey_BrainpoolP160r1() { if (PlatformDetection.WindowsVersion >= 10) { TestKey_ECDsaCng(TestData.ECDsabrainpoolP160r1_CertificatePemBytes, TestData.ECDsabrainpoolP160r1_PublicKey); } } private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected) { #if !uap using (X509Certificate2 cert = new X509Certificate2(certBytes)) { ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey()); CngKey k = e.Key; byte[] blob = k.Export(CngKeyBlobFormat.EccPublicBlob); using (BinaryReader br = new BinaryReader(new MemoryStream(blob))) { int magic = br.ReadInt32(); int cbKey = br.ReadInt32(); Assert.Equal(expected.QX.Length, cbKey); byte[] qx = br.ReadBytes(cbKey); byte[] qy = br.ReadBytes(cbKey); Assert.Equal<byte>(expected.QX, qx); Assert.Equal<byte>(expected.QY, qy); } } #endif // !uap } } }
using System; using System.Xml; using System.Collections; using Stetic.Wrapper; using Mono.Unix; namespace Stetic.Editor { class ActionMenuBar: Gtk.MenuBar, IMenuItemContainer { ActionMenu openSubmenu; ActionTree actionTree; int dropPosition = -1; int dropIndex; ArrayList menuItems = new ArrayList (); bool showPlaceholder; Gtk.Widget addLabel; Gtk.Widget spacerItem; public ActionMenuBar () { DND.DestSet (this, true); } public void FillMenu (ActionTree actionTree) { addLabel = null; if (this.actionTree != null) { this.actionTree.ChildNodeAdded -= OnChildAdded; this.actionTree.ChildNodeRemoved -= OnChildRemoved; } this.actionTree = actionTree; if (actionTree == null) { AddSpacerItem (); return; } actionTree.ChildNodeAdded += OnChildAdded; actionTree.ChildNodeRemoved += OnChildRemoved; HideSpacerItem (); menuItems.Clear (); Widget wrapper = Widget.Lookup (this); foreach (Gtk.Widget w in Children) { Remove (w); w.Destroy (); w.Dispose (); } foreach (ActionTreeNode node in actionTree.Children) { ActionMenuItem aitem = new ActionMenuItem (wrapper, this, node); AddItem (aitem, -1); menuItems.Add (aitem); } if (showPlaceholder) { AddCreateItemLabel (); } else if (actionTree.Children.Count == 0) { // Give some height to the toolbar AddSpacerItem (); } } public object SaveStatus () { ArrayList status = new ArrayList (); for (int n=0; n<menuItems.Count; n++) { ActionMenuItem item = (ActionMenuItem) menuItems [n]; if (item.IsSubmenuVisible) { status.Add (n); OpenSubmenu.SaveStatus (status); break; } } return status; } public void RestoreStatus (object data) { ArrayList status = (ArrayList) data; if (status.Count == 0) return; int pos = (int) status [0]; if (pos >= menuItems.Count) return; ActionMenuItem item = (ActionMenuItem) menuItems [pos]; if (status.Count == 1) { // The last position in the status is the selected item item.Select (); if (item.Node.Action != null && item.Node.Action.Name.Length == 0) { // Then only case when there can have an action when an empty name // is when the user clicked on the "add action" link. In this case, // start editing the item again item.EditingDone += OnEditingDone; item.StartEditing (); } } else { item.ShowSubmenu (); if (OpenSubmenu != null) OpenSubmenu.RestoreStatus (status, 1); } } void AddCreateItemLabel () { HideSpacerItem (); Gtk.Label emptyLabel = new Gtk.Label (); emptyLabel.Xalign = 0; emptyLabel.Markup = "<i><span foreground='darkgrey'>" + Catalog.GetString ("Click to create menu") + "</span></i>"; Gtk.MenuItem mit = new Gtk.MenuItem (); mit.Child = emptyLabel; mit.ButtonPressEvent += OnNewItemPress; Insert (mit, -1); mit.ShowAll (); addLabel = mit; } void AddSpacerItem () { if (spacerItem == null) { Gtk.Label emptyLabel = new Gtk.Label (); emptyLabel.Xalign = 0; emptyLabel.Markup = "<i><span foreground='darkgrey'>" + Catalog.GetString ("Empty menu bar") + "</span></i>"; Gtk.MenuItem mit = new Gtk.MenuItem (); mit.Child = emptyLabel; Insert (mit, -1); spacerItem = mit; ShowAll (); } } void HideSpacerItem () { if (spacerItem != null) { Remove (spacerItem); spacerItem = null; } } void AddItem (ActionMenuItem aitem, int pos) { Gtk.Table t = new Gtk.Table (1, 3, false); aitem.Attach (t, 0, 0); aitem.KeyPressEvent += OnItemKeyPress; t.ShowAll (); CustomMenuBarItem it = new CustomMenuBarItem (); it.ActionMenuItem = aitem; aitem.Bind (it); it.Child = t; it.ShowAll (); Insert (it, pos); } public bool ShowInsertPlaceholder { get { return showPlaceholder; } set { showPlaceholder = value; if (value && addLabel == null) { AddCreateItemLabel (); } else if (!value && addLabel != null) { Remove (addLabel); addLabel = null; if (menuItems.Count == 0) AddSpacerItem (); } } } public void Unselect () { // Unselects any selected item and hides any open submenu menu Widget wrapper = Widget.Lookup (this); if (OpenSubmenu != null) OpenSubmenu.ResetSelection (); IDesignArea area = wrapper.GetDesignArea (); if (area != null) { foreach (Gtk.Widget w in Children) { CustomMenuBarItem it = w as CustomMenuBarItem; if (it != null) area.ResetSelection (it.ActionMenuItem); } } OpenSubmenu = null; } void OnChildAdded (object ob, ActionTreeNodeArgs args) { Refresh (); } void OnChildRemoved (object ob, ActionTreeNodeArgs args) { OpenSubmenu = null; Widget wrapper = Widget.Lookup (this); IDesignArea area = wrapper.GetDesignArea (); IObjectSelection asel = area.GetSelection (); ActionMenuItem curSel = asel != null ? asel.DataObject as ActionMenuItem : null; int pos = menuItems.IndexOf (curSel); foreach (Gtk.Widget w in Children) { if (w is CustomMenuBarItem && ((CustomMenuBarItem)w).ActionMenuItem.Node == args.Node) { Remove (w); menuItems.Remove (((CustomMenuBarItem)w).ActionMenuItem); if (menuItems.Count == 0 && !showPlaceholder) AddSpacerItem (); break; } } if (pos != -1 && pos < menuItems.Count) ((ActionMenuItem)menuItems[pos]).Select (); else if (menuItems.Count > 0) ((ActionMenuItem)menuItems[menuItems.Count-1]).Select (); } void Refresh () { Widget wrapper = Widget.Lookup (this); IDesignArea area = wrapper.GetDesignArea (); if (area == null) return; ActionTreeNode selNode = null; foreach (Gtk.Widget w in Children) { CustomMenuBarItem it = w as CustomMenuBarItem; if (it != null && area.IsSelected (it.ActionMenuItem)) { selNode = it.ActionMenuItem.Node; area.ResetSelection (it.ActionMenuItem); } Remove (w); } FillMenu (actionTree); if (selNode != null) { ActionMenuItem mi = FindMenuItem (selNode); if (mi != null) mi.Select (); } } [GLib.ConnectBeforeAttribute] void OnNewItemPress (object ob, Gtk.ButtonPressEventArgs args) { InsertAction (menuItems.Count); args.RetVal = true; } void InsertAction (int pos) { Widget wrapper = Widget.Lookup (this); using (wrapper.UndoManager.AtomicChange) { Wrapper.Action ac = (Wrapper.Action) ObjectWrapper.Create (wrapper.Project, new Gtk.Action ("", "", null, null)); ActionTreeNode node = new ActionTreeNode (Gtk.UIManagerItemType.Menu, "", ac); actionTree.Children.Insert (pos, node); ActionMenuItem aitem = FindMenuItem (node); aitem.EditingDone += OnEditingDone; aitem.Select (); aitem.StartEditing (); if (wrapper.LocalActionGroups.Count == 0) wrapper.LocalActionGroups.Add (new ActionGroup ("Default")); wrapper.LocalActionGroups[0].Actions.Add (ac); } } void OnEditingDone (object ob, EventArgs args) { ActionMenuItem item = (ActionMenuItem) ob; item.EditingDone -= OnEditingDone; Widget wrapper = Widget.Lookup (this); if (item.Node.Action.GtkAction.Label.Length == 0 && item.Node.Action.GtkAction.StockId == null) { IDesignArea area = wrapper.GetDesignArea (); area.ResetSelection (item); using (wrapper.UndoManager.AtomicChange) { actionTree.Children.Remove (item.Node); wrapper.LocalActionGroups [0].Actions.Remove (item.Node.Action); } } } public void Select (ActionTreeNode node) { ActionMenuItem item = FindMenuItem (node); if (item != null) item.Select (); } public void DropMenu (ActionTreeNode node) { ActionMenuItem item = FindMenuItem (node); if (item != null) { if (item.HasSubmenu) { item.ShowSubmenu (); if (openSubmenu != null) openSubmenu.Select (null); } else item.Select (); } } public ActionMenu OpenSubmenu { get { return openSubmenu; } set { if (openSubmenu != null) { openSubmenu.OpenSubmenu = null; Widget wrapper = Widget.Lookup (this); IDesignArea area = wrapper.GetDesignArea (); if (area != null) area.RemoveWidget (openSubmenu); openSubmenu.Dispose (); } openSubmenu = value; } } bool IMenuItemContainer.IsTopMenu { get { return true; } } Gtk.Widget IMenuItemContainer.Widget { get { return this; } } protected override bool OnDragMotion (Gdk.DragContext context, int x, int y, uint time) { ActionPaletteItem dragItem = DND.DragWidget as ActionPaletteItem; if (dragItem == null) return false; if (actionTree.Children.Count > 0) { ActionMenuItem item = LocateWidget (x, y); if (item != null) { Widget wrapper = Widget.Lookup (this); // Show the submenu to allow droping to it, but avoid // droping a submenu inside itself if (item.HasSubmenu && item.Node != dragItem.Node) item.ShowSubmenu (wrapper.GetDesignArea(), item); // Look for the index where to insert the new item dropIndex = actionTree.Children.IndexOf (item.Node); int mpos = item.Allocation.X + item.Allocation.Width / 2; if (x > mpos) dropIndex++; // Calculate the drop position, used to show the drop bar if (dropIndex == 0) dropPosition = item.Allocation.X; else if (dropIndex == menuItems.Count) dropPosition = item.Allocation.Right; else { item = (ActionMenuItem) menuItems [dropIndex]; ActionMenuItem prevItem = (ActionMenuItem) menuItems [dropIndex - 1]; dropPosition = prevItem.Allocation.Right + (item.Allocation.X - prevItem.Allocation.Right)/2; } } } else dropIndex = 0; QueueDraw (); return base.OnDragMotion (context, x, y, time); } protected override void OnDragLeave (Gdk.DragContext context, uint time) { dropPosition = -1; QueueDraw (); base.OnDragLeave (context, time); } protected override bool OnDragDrop (Gdk.DragContext context, int x, int y, uint time) { ActionPaletteItem dropped = DND.Drop (context, null, time) as ActionPaletteItem; if (dropped == null) return false; if (dropped.Node.Type != Gtk.UIManagerItemType.Menuitem && dropped.Node.Type != Gtk.UIManagerItemType.Menu && dropped.Node.Type != Gtk.UIManagerItemType.Toolitem && dropped.Node.Type != Gtk.UIManagerItemType.Separator) return false; ActionTreeNode newNode = dropped.Node; if (dropped.Node.Type == Gtk.UIManagerItemType.Toolitem) { newNode = newNode.Clone (); newNode.Type = Gtk.UIManagerItemType.Menuitem; } Widget wrapper = Widget.Lookup (this); using (wrapper.UndoManager.AtomicChange) { if (dropIndex < actionTree.Children.Count) { // Do nothing if trying to drop the node over the same node ActionTreeNode dropNode = actionTree.Children [dropIndex]; if (dropNode == dropped.Node) return false; if (newNode.ParentNode != null) newNode.ParentNode.Children.Remove (newNode); // The drop position may have changed after removing the dropped node, // so get it again. dropIndex = actionTree.Children.IndexOf (dropNode); actionTree.Children.Insert (dropIndex, newNode); } else { if (newNode.ParentNode != null) newNode.ParentNode.Children.Remove (newNode); actionTree.Children.Add (newNode); dropIndex = actionTree.Children.Count - 1; } // Select the dropped node ActionMenuItem mi = (ActionMenuItem) menuItems [dropIndex]; mi.Select (); } return base.OnDragDrop (context, x, y, time); } protected override bool OnExposeEvent (Gdk.EventExpose ev) { bool r = base.OnExposeEvent (ev); int w, h; this.GdkWindow.GetSize (out w, out h); if (dropPosition != -1) GdkWindow.DrawRectangle (this.Style.BlackGC, true, dropPosition, 0, 3, h); return r; } void OnItemKeyPress (object s, Gtk.KeyPressEventArgs args) { int pos = menuItems.IndexOf (s); ActionMenuItem item = (ActionMenuItem) s; switch (args.Event.Key) { case Gdk.Key.Left: if (pos > 0) ((ActionMenuItem)menuItems[pos - 1]).Select (); break; case Gdk.Key.Right: if (pos < menuItems.Count - 1) ((ActionMenuItem)menuItems[pos + 1]).Select (); else if (pos == menuItems.Count - 1) InsertAction (menuItems.Count); break; case Gdk.Key.Down: if (item.HasSubmenu) { item.ShowSubmenu (); if (openSubmenu != null) openSubmenu.Select (null); } break; case Gdk.Key.Up: OpenSubmenu = null; break; } args.RetVal = true; } void InsertActionAt (ActionMenuItem item, bool after, bool separator) { int pos = menuItems.IndexOf (item); if (pos == -1) return; if (after) pos++; if (separator) { ActionTreeNode newNode = new ActionTreeNode (Gtk.UIManagerItemType.Separator, null, null); actionTree.Children.Insert (pos, newNode); } else InsertAction (pos); } void Paste (ActionMenuItem item) { } public void ShowContextMenu (ActionItem aitem) { ActionMenuItem menuItem = (ActionMenuItem) aitem; Gtk.Menu m = new Gtk.Menu (); Gtk.MenuItem item = new Gtk.MenuItem (Catalog.GetString ("Insert Before")); m.Add (item); item.Activated += delegate (object s, EventArgs a) { InsertActionAt (menuItem, false, false); }; item = new Gtk.MenuItem (Catalog.GetString ("Insert After")); m.Add (item); item.Activated += delegate (object s, EventArgs a) { InsertActionAt (menuItem, true, false); }; m.Add (new Gtk.SeparatorMenuItem ()); item = new Gtk.ImageMenuItem (Gtk.Stock.Cut, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { menuItem.Cut (); }; item.Visible = false; // No copy & paste for now item = new Gtk.ImageMenuItem (Gtk.Stock.Copy, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { menuItem.Copy (); }; item.Visible = false; // No copy & paste for now item = new Gtk.ImageMenuItem (Gtk.Stock.Paste, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { Paste (menuItem); }; item.Visible = false; // No copy & paste for now item = new Gtk.ImageMenuItem (Gtk.Stock.Delete, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { menuItem.Delete (); }; m.ShowAll (); m.Popup (); } ActionMenuItem LocateWidget (int x, int y) { foreach (ActionMenuItem mi in menuItems) { if (mi.Allocation.Contains (x, y)) return mi; } return null; } ActionMenuItem FindMenuItem (ActionTreeNode node) { foreach (ActionMenuItem mi in menuItems) { if (mi.Node == node) return mi; } return null; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Searchservice { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Indexes. /// </summary> public static partial class IndexesExtensions { /// <summary> /// Creates a new Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index Create(this IIndexes operations, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateAsync(index, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> CreateAsync(this IIndexes operations, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(index, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified as /// a comma-separated list of JSON property names, or '*' for all properties. /// The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexListResult List(this IIndexes operations, string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.ListAsync(select, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified as /// a comma-separated list of JSON property names, or '*' for all properties. /// The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexListResult> ListAsync(this IIndexes operations, string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(select, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index CreateOrUpdate(this IIndexes operations, string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateOrUpdateAsync(indexName, index, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> CreateOrUpdateAsync(this IIndexes operations, string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(indexName, index, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Delete(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.DeleteAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index Get(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> GetAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexGetStatisticsResult GetStatistics(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetStatisticsAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexGetStatisticsResult> GetStatisticsAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatisticsWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext { internal ParameterDefinitionCollection parameters; MethodReturnType return_type; bool has_this; bool explicit_this; MethodCallingConvention calling_convention; internal Collection<GenericParameter> generic_parameters; public virtual bool HasThis { get { return has_this; } set { has_this = value; } } public virtual bool ExplicitThis { get { return explicit_this; } set { explicit_this = value; } } public virtual MethodCallingConvention CallingConvention { get { return calling_convention; } set { calling_convention = value; } } public virtual bool HasParameters { get { return !parameters.IsNullOrEmpty (); } } public virtual Collection<ParameterDefinition> Parameters { get { if (parameters == null) parameters = new ParameterDefinitionCollection (this); return parameters; } } IGenericParameterProvider IGenericContext.Type { get { var declaring_type = this.DeclaringType; var instance = declaring_type as GenericInstanceType; if (instance != null) return instance.ElementType; return declaring_type; } } IGenericParameterProvider IGenericContext.Method { get { return this; } } GenericParameterType IGenericParameterProvider.GenericParameterType { get { return GenericParameterType.Method; } } public virtual bool HasGenericParameters { get { return !generic_parameters.IsNullOrEmpty (); } } public virtual Collection<GenericParameter> GenericParameters { get { if (generic_parameters != null) return generic_parameters; return generic_parameters = new GenericParameterCollection (this); } } public TypeReference ReturnType { get { var return_type = MethodReturnType; return return_type != null ? return_type.ReturnType : null; } set { var return_type = MethodReturnType; if (return_type != null) return_type.ReturnType = value; } } public virtual MethodReturnType MethodReturnType { get { return return_type; } set { return_type = value; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (ReturnType.FullName) .Append (" ") .Append (MemberFullName ()); this.MethodSignatureFullName (builder); return builder.ToString (); } } public virtual bool IsGenericInstance { get { return false; } } public override bool ContainsGenericParameter { get { if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter) return true; if (!HasParameters) return false; var parameters = this.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters [i].ParameterType.ContainsGenericParameter) return true; return false; } } internal MethodReference () { this.return_type = new MethodReturnType (this); this.token = new MetadataToken (TokenType.MemberRef); } public MethodReference (string name, TypeReference returnType) : base (name) { Mixin.CheckType (returnType, Mixin.Argument.returnType); this.return_type = new MethodReturnType (this); this.return_type.ReturnType = returnType; this.token = new MetadataToken (TokenType.MemberRef); } public MethodReference (string name, TypeReference returnType, TypeReference declaringType) : this (name, returnType) { Mixin.CheckType (declaringType, Mixin.Argument.declaringType); this.DeclaringType = declaringType; } public virtual MethodReference GetElementMethod () { return this; } protected override IMemberDefinition ResolveDefinition () { return this.Resolve (); } public new virtual MethodDefinition Resolve () { var module = this.Module; if (module == null) throw new NotSupportedException (); return module.Resolve (this); } } static partial class Mixin { public static bool IsVarArg (this IMethodSignature self) { return (self.CallingConvention & MethodCallingConvention.VarArg) != 0; } public static int GetSentinelPosition (this IMethodSignature self) { if (!self.HasParameters) return -1; var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters [i].ParameterType.IsSentinel) return i; return -1; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // MACTripleDES.cs -- Implementation of the MAC-CBC keyed hash w/ 3DES // // See: http://www.itl.nist.gov/fipspubs/fip81.htm for a spec namespace System.Security.Cryptography { using System.IO; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public class MACTripleDES : KeyedHashAlgorithm { // Output goes to HashMemorySink since we don't care about the actual data private ICryptoTransform m_encryptor; private CryptoStream _cs; private TailStream _ts; private const int m_bitsPerByte = 8; private int m_bytesPerBlock; private TripleDES des; // // public constructors // public MACTripleDES() { KeyValue = new byte[24]; Utils.StaticRandomNumberGenerator.GetBytes(KeyValue); // Create a TripleDES encryptor des = TripleDES.Create(); HashSizeValue = des.BlockSize; m_bytesPerBlock = des.BlockSize/m_bitsPerByte; // By definition, MAC-CBC-3DES takes an IV=0. C# zero-inits arrays, // so all we have to do here is define it. des.IV = new byte[m_bytesPerBlock]; des.Padding = PaddingMode.Zeros; m_encryptor = null; } public MACTripleDES(byte[] rgbKey) : this("System.Security.Cryptography.TripleDES",rgbKey) {} public MACTripleDES(String strTripleDES, byte[] rgbKey) { // Make sure we know which algorithm to use if (rgbKey == null) throw new ArgumentNullException("rgbKey"); Contract.EndContractBlock(); // Create a TripleDES encryptor if (strTripleDES == null) { des = TripleDES.Create(); } else { des = TripleDES.Create(strTripleDES); } HashSizeValue = des.BlockSize; // Stash the key away KeyValue = (byte[]) rgbKey.Clone(); m_bytesPerBlock = des.BlockSize/m_bitsPerByte; // By definition, MAC-CBC-3DES takes an IV=0. C# zero-inits arrays, // so all we have to do here is define it. des.IV = new byte[m_bytesPerBlock]; des.Padding = PaddingMode.Zeros; m_encryptor = null; } public override void Initialize() { m_encryptor = null; } [System.Runtime.InteropServices.ComVisible(false)] public PaddingMode Padding { get { return des.Padding; } set { if ((value < PaddingMode.None) || (PaddingMode.ISO10126 < value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode")); des.Padding = value; } } // // protected methods // protected override void HashCore(byte[] rgbData, int ibStart, int cbSize) { // regenerate the TripleDES object before each call to ComputeHash if (m_encryptor == null) { des.Key = this.Key; m_encryptor = des.CreateEncryptor(); _ts = new TailStream(des.BlockSize / 8); // 8 bytes _cs = new CryptoStream(_ts, m_encryptor, CryptoStreamMode.Write); } // Encrypt using 3DES _cs.Write(rgbData, ibStart, cbSize); } protected override byte[] HashFinal() { // If Hash has been called on a zero buffer if (m_encryptor == null) { des.Key = this.Key; m_encryptor = des.CreateEncryptor(); _ts = new TailStream(des.BlockSize / 8); // 8 bytes _cs = new CryptoStream(_ts, m_encryptor, CryptoStreamMode.Write); } // Finalize the hashing and return the result _cs.FlushFinalBlock(); return _ts.Buffer; } // IDisposable methods protected override void Dispose(bool disposing) { if (disposing) { // dispose of our internal state if (des != null) des.Clear(); if (m_encryptor != null) m_encryptor.Dispose(); if (_cs != null) _cs.Clear(); if (_ts != null) _ts.Clear(); } base.Dispose(disposing); } } // // TailStream is another utility class -- it remembers the last n bytes written to it // This is useful for MAC-3DES since we need to capture only the result of the last block internal sealed class TailStream : Stream { private byte[] _Buffer; private int _BufferSize; private int _BufferIndex = 0; private bool _BufferFull = false; public TailStream(int bufferSize) { _Buffer = new byte[bufferSize]; _BufferSize = bufferSize; } public void Clear() { Close(); } protected override void Dispose(bool disposing) { try { if (disposing) { if (_Buffer != null) { Array.Clear(_Buffer, 0, _Buffer.Length); } _Buffer = null; } } finally { base.Dispose(disposing); } } public byte[] Buffer { get { return (byte[]) _Buffer.Clone(); } } public override bool CanRead { [Pure] get { return false; } } public override bool CanSeek { [Pure] get { return false; } } public override bool CanWrite { [Pure] get { return _Buffer != null; } } public override long Length { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } } public override long Position { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } set { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } } public override void Flush() { return; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } public override void SetLength(long value) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); } public override void Write(byte[] buffer, int offset, int count) { if (_Buffer == null) throw new ObjectDisposedException("TailStream"); // If no bytes to write, then return if (count == 0) return; // The most common case will be when we have a full buffer if (_BufferFull) { // if more bytes are written in this call than the size of the buffer, // just remember the last _BufferSize bytes if (count > _BufferSize) { System.Buffer.InternalBlockCopy(buffer, offset+count-_BufferSize, _Buffer, 0, _BufferSize); return; } else { // move _BufferSize - count bytes left, then copy the new bytes System.Buffer.InternalBlockCopy(_Buffer, _BufferSize - count, _Buffer, 0, _BufferSize - count); System.Buffer.InternalBlockCopy(buffer, offset, _Buffer, _BufferSize - count, count); return; } } else { // buffer isn't full yet, so more cases if (count > _BufferSize) { System.Buffer.InternalBlockCopy(buffer, offset+count-_BufferSize, _Buffer, 0, _BufferSize); _BufferFull = true; return; } else if (count + _BufferIndex >= _BufferSize) { System.Buffer.InternalBlockCopy(_Buffer, _BufferIndex+count-_BufferSize, _Buffer, 0, _BufferSize - count); System.Buffer.InternalBlockCopy(buffer, offset, _Buffer, _BufferIndex, count); _BufferFull = true; return; } else { System.Buffer.InternalBlockCopy(buffer, offset, _Buffer, _BufferIndex, count); _BufferIndex += count; return; } } } } }
namespace Microsoft.Protocols.TestSuites.MS_COPYS { using System; using System.IO; using System.Net; using System.Text; using System.Web.Services.Protocols; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; /// <summary> /// The implementation of the SUT control managed code adapter interface. /// </summary> public class MS_COPYSSUTControlAdapter : ManagedAdapterBase, IMS_COPYSSUTControlAdapter { /// <summary> /// Represents the error messages generated in delete files' process. /// </summary> private StringBuilder errorMessageInDeleteProcess = new StringBuilder(); /// <summary> /// Represents the MS-LISTSWS proxy instance which is used to invoke functions of Lists web service. /// </summary> private ListsSoap listswsProxy = null; /// <summary> /// Initialize the adapter instance. /// </summary> /// <param name="testSite">A return value represents the ITestSite instance which contains the test context.</param> public override void Initialize(ITestSite testSite) { base.Initialize(testSite); TestSuiteManageHelper.Initialize(this.Site); TestSuiteManageHelper.AcceptServerCertificate(); // Initial the listsws proxy without schema validation. if (null == this.listswsProxy) { this.listswsProxy = Proxy.CreateProxy<ListsSoap>(testSite, true, false, false); } FileUrlHelper.ValidateFileUrl(TestSuiteManageHelper.TargetServiceUrlOfMSCOPYS); // Point to listsws service according to the MS-COPYS service URL. string targetServiceUrl = Path.GetDirectoryName(TestSuiteManageHelper.TargetServiceUrlOfMSCOPYS); targetServiceUrl = Path.Combine(targetServiceUrl, @"lists.asmx"); // Work around for local path format mapping to URL path format. targetServiceUrl = targetServiceUrl.Replace(@"\", @"/"); targetServiceUrl = targetServiceUrl.Replace(@":/", @"://"); // Setting the properties of listsws service proxy. this.listswsProxy.Url = targetServiceUrl; this.listswsProxy.Credentials = TestSuiteManageHelper.DefaultUserCredential; this.listswsProxy.SoapVersion = TestSuiteManageHelper.GetSoapProtoclVersionByCurrentSetting(); // 60000 means the configure SOAP Timeout is in minute. this.listswsProxy.Timeout = TestSuiteManageHelper.CurrentSoapTimeOutValue; } /// <summary> /// This method is used to remove the files. /// </summary> /// <param name="fileUrls">Specify the file URLs that will be removed. Each file URL is split by ";" symbol</param> /// <returns>Return true if the operation succeeds, otherwise return false.</returns> public bool DeleteFiles(string fileUrls) { if (string.IsNullOrEmpty(fileUrls)) { throw new ArgumentNullException("fileUrls"); } string[] fileUrlCollection = fileUrls.Split(new string[] { @";" }, StringSplitOptions.RemoveEmptyEntries); foreach (string fileUrlItem in fileUrlCollection) { Uri filePath; if (!Uri.TryCreate(fileUrlItem, UriKind.Absolute, out filePath)) { string errorMsg = string.Format(@"The file URL item[{0}] is not a valid URL. Ignore this."); this.errorMessageInDeleteProcess.AppendLine(errorMsg); continue; } this.DeleteSingleFile(fileUrlItem); } if (this.errorMessageInDeleteProcess.Length > 0) { this.Site.Log.Add( LogEntryKind.Debug, "There are some errors generated in the delete file process:\r\n[{0}]", this.errorMessageInDeleteProcess.ToString()); return false; } else { return true; } } /// <summary> /// This method is used to upload a file to the specified full file URL. The file's content will be random generated, and encoded with UTF8. /// </summary> /// <param name="fileUrl">A parameter represents the absolute URL of a file, where the file will be uploaded.</param> /// <returns>Return true if the operation succeeds, otherwise returns false.</returns> public bool UploadTextFile(string fileUrl) { WebClient client = new WebClient(); try { byte[] contents = System.Text.Encoding.UTF8.GetBytes(Common.GenerateResourceName(Site, "FileContent")); client.Credentials = TestSuiteManageHelper.DefaultUserCredential; client.UploadData(fileUrl, "PUT", contents); } catch (System.Net.WebException ex) { Site.Log.Add( LogEntryKind.TestError, string.Format("Cannot upload the file to the full URL {0}, the exception message is {1}", fileUrl, ex.Message)); return false; } finally { if (client != null) { client.Dispose(); } } return true; } /// <summary> /// A method used to check out a file by specified user credential. /// </summary> /// <param name="fileUrl">A parameter represents the absolute URL of a file which will be check out by specified user.</param> /// <param name="userName">A parameter represents the user name which will undo checkout the file. The file must be stored in the destination SUT which is indicated by "SutComputerName" property in "SharePointCommonConfiguration.deployment.ptfconfig" file.</param> /// <param name="password">A parameter represents the password of the user.</param> /// <param name="domain">A parameter represents the domain of the user.</param> /// <returns>Return true if the operation succeeds, otherwise returns false.</returns> public bool CheckOutFileByUser(string fileUrl, string userName, string password, string domain) { #region parameter validation FileUrlHelper.ValidateFileUrl(fileUrl); if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } #endregion parameter validation if (null == this.listswsProxy) { throw new InvalidOperationException("The LISTSWS proxy is not initialized, should call the [Initialize] method before calling this method."); } this.listswsProxy.Credentials = new NetworkCredential(userName, password, domain); bool checkOutResult; try { checkOutResult = this.listswsProxy.CheckOutFile(fileUrl, bool.TrueString, string.Empty); } catch (SoapException soapEx) { this.Site.Log.Add( LogEntryKind.Debug, @"There is an exception generated when the SUT control adapter try to check out a file[{0}]:\r\nExcetption Message:\r\n[{1}]\r\\nStackTrace:\r\n[{2}]", fileUrl, string.IsNullOrEmpty(soapEx.Message) ? "None" : soapEx.Message, string.IsNullOrEmpty(soapEx.StackTrace) ? "None" : soapEx.StackTrace); return false; } finally { this.listswsProxy.Credentials = TestSuiteManageHelper.DefaultUserCredential; } return checkOutResult; } /// <summary> /// A method used to undo checkout for a file by specified user credential. /// </summary> /// <param name="fileUrl">A parameter represents the absolute URL of a file which will be undo checkout by specified user.</param> /// <param name="userName">A parameter represents the user name which will check out the file. The file must be stored in the destination SUT which is indicated by "SutComputerName" property in "SharePointCommonConfiguration.deployment.ptfconfig" file.</param> /// <param name="password">A parameter represents the password of the user.</param> /// <param name="domain">A parameter represents the domain of the user.</param> /// <returns>Return true if the operation succeeds, otherwise returns false.</returns> public bool UndoCheckOutFileByUser(string fileUrl, string userName, string password, string domain) { #region parameter validation FileUrlHelper.ValidateFileUrl(fileUrl); if (string.IsNullOrEmpty(userName)) { throw new ArgumentNullException("userName"); } #endregion parameter validation if (null == this.listswsProxy) { throw new InvalidOperationException("The LISTSWS proxy is not initialized, should call the [Initialize] method before calling this method."); } this.listswsProxy.Credentials = new NetworkCredential(userName, password, domain); bool undoCheckOutResult; try { undoCheckOutResult = this.listswsProxy.UndoCheckOut(fileUrl); } catch (SoapException soapEx) { this.Site.Log.Add( LogEntryKind.Debug, @"There is an exception generated when the SUT control adapter try to undo check out for a file[{0}]:\r\nExcetption Message:\r\n[{1}]\r\\nStackTrace:\r\n[{2}]", fileUrl, string.IsNullOrEmpty(soapEx.Message) ? "None" : soapEx.Message, string.IsNullOrEmpty(soapEx.StackTrace) ? "None" : soapEx.StackTrace); return false; } finally { this.listswsProxy.Credentials = TestSuiteManageHelper.DefaultUserCredential; } return undoCheckOutResult; } /// <summary> /// This method is used to remove the file. /// </summary> /// <param name="singleFileUrl">Specify the file URL that will be removed.</param> private void DeleteSingleFile(string singleFileUrl) { HttpWebRequest deleteRequest = HttpWebRequest.Create(singleFileUrl) as HttpWebRequest; HttpWebResponse response = null; deleteRequest.Credentials = TestSuiteManageHelper.DefaultUserCredential; deleteRequest.Method = "DELETE"; try { response = deleteRequest.GetResponse() as HttpWebResponse; } catch (System.Net.WebException ex) { string errorMsg = string.Format( @"Cannot delete the file[{0}], the exception message is {1}", singleFileUrl, ex.Message); this.errorMessageInDeleteProcess.AppendLine(errorMsg); } finally { if (response != null) { response.Close(); } } // For the loop, sleep zero to ensure other control thread can visit the CPU resource. This is for optimizing performance. System.Threading.Thread.Sleep(0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TWCore.Collections; using TWCore.Messaging.Configuration; using TWCore.Messaging.NSQ; using TWCore.Serialization; using TWCore.Services; // ReSharper disable ConvertToConstant.Local // ReSharper disable UnusedMember.Global // ReSharper disable InconsistentNaming // ReSharper disable UnusedVariable // ReSharper disable AccessToDisposedClosure namespace TWCore.Tests { /// <inheritdoc /> public class NSQTest : ContainerParameterService { public NSQTest() : base("nsqtest", "NSQ Test") { } protected override void OnHandler(ParameterHandlerInfo info) { Core.Log.Warning("Starting NSQ Test"); #region Set Config var mqConfig = new MQPairConfig { Name = "QueueTest", Types = new MQObjectTypes { ClientType = typeof(NSQueueClient), ServerType = typeof(NSQueueServer), AdminType = typeof(NSQueueAdmin) }, RawTypes = new MQObjectTypes { ClientType = typeof(NSQueueRawClient), ServerType = typeof(NSQueueRawServer), AdminType = typeof(NSQueueAdmin) }, ClientQueues = new List<MQClientQueues> { new MQClientQueues { EnvironmentName = "", MachineName = "", SendQueues = new List<MQConnection> { new MQConnection("localhost:4150", "TEST_RQ", null) }, RecvQueue = new MQConnection("localhost:4150", "TEST_RS", null) } }, ServerQueues = new List<MQServerQueues> { new MQServerQueues { EnvironmentName = "", MachineName = "", RecvQueues = new List<MQConnection> { new MQConnection("localhost:4150", "TEST_RQ", null) } } }, RequestOptions = new MQRequestOptions { SerializerMimeType = SerializerManager.DefaultBinarySerializer.MimeTypes[0], //CompressorEncodingType = "gzip", ClientSenderOptions = new MQClientSenderOptions { Label = "TEST REQUEST", MessageExpirationInSec = 30, MessagePriority = MQMessagePriority.Normal, Recoverable = false }, ServerReceiverOptions = new MQServerReceiverOptions { MaxSimultaneousMessagesPerQueue = 20000, ProcessingWaitOnFinalizeInSec = 10, SleepOnExceptionInSec = 1000 } }, ResponseOptions = new MQResponseOptions { SerializerMimeType = SerializerManager.DefaultBinarySerializer.MimeTypes[0], //CompressorEncodingType = "gzip", ClientReceiverOptions = new MQClientReceiverOptions(60, new KeyValue<string, string>("SingleResponseQueue", "true") ), ServerSenderOptions = new MQServerSenderOptions { Label = "TEST RESPONSE", MessageExpirationInSec = 30, MessagePriority = MQMessagePriority.Normal, Recoverable = false } } }; #endregion JsonTextSerializerExtensions.Serializer.Indent = true; mqConfig.SerializeToXmlFile("nsqConfig.xml"); mqConfig.SerializeToJsonFile("nsqConfig.json"); var manager = mqConfig.GetQueueManager(); manager.CreateClientQueues(); //Core.DebugMode = true; Core.Log.MaxLogLevel = Diagnostics.Log.LogLevel.InfoDetail; Core.Log.Warning("Starting with Normal Listener and Client"); NormalTest(mqConfig); mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "true"; Core.Log.Warning("Starting with RAW Listener and Client"); RawTest(mqConfig); } private static void NormalTest(MQPairConfig mqConfig) { using (var mqServer = mqConfig.GetServer()) { mqServer.RequestReceived += (s, e) => { e.Response.Body = new SerializedObject("Bienvenido!!!"); return Task.CompletedTask; }; mqServer.StartListeners(); using (var mqClient = mqConfig.GetClient()) { var totalQ = 20000; #region Sync Mode Core.Log.Warning("Sync Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults(); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("Parallel Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { Task.WaitAll( Enumerable.Range(0, totalQ).Select((i, mc) => (Task)mc.SendAndReceiveAsync<string>("Hola mundo"), mqClient).ToArray() ); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults(); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "false"; using (var mqClient = mqConfig.GetClient()) { var totalQ = 50; #region Sync Mode Core.Log.Warning("Sync Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults(); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("Parallel Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { Task.WaitAll( Enumerable.Range(0, totalQ).Select((i, mc) => (Task)mc.SendAndReceiveAsync<string>("Hola mundo"), mqClient).ToArray() ); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults(); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } } } private static void RawTest(MQPairConfig mqConfig) { using (var mqServer = mqConfig.GetRawServer()) { var byteRequest = new byte[] { 0x21, 0x22, 0x23, 0x24, 0x25, 0x30, 0x31, 0x32, 0x33, 0x34 }; var byteResponse = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x11, 0x12, 0x13, 0x14 }; mqServer.RequestReceived += (s, e) => { e.Response = byteResponse; return Task.CompletedTask; }; mqServer.StartListeners(); using (var mqClient = mqConfig.GetRawClient()) { var totalQ = 20000; #region Sync Mode Core.Log.Warning("RAW Sync Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults(); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("RAW Parallel Mode Test, using Unique Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { Task.WaitAll( Enumerable.Range(0, totalQ).Select((i, vTuple) => (Task)vTuple.mqClient.SendAndReceiveAsync(vTuple.byteRequest), (mqClient, byteRequest)).ToArray() ); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults(); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "false"; using (var mqClient = mqConfig.GetRawClient()) { var totalQ = 50; #region Sync Mode Core.Log.Warning("RAW Sync Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times")) { for (var i = 0; i < totalQ; i++) { var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults(); } Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion #region Parallel Mode Core.Log.Warning("RAW Parallel Mode Test, using Multiple Response Queue"); using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times")) { Task.WaitAll( Enumerable.Range(0, totalQ).Select((i, vTuple) => (Task)vTuple.mqClient.SendAndReceiveAsync(vTuple.byteRequest), (mqClient, byteRequest)).ToArray() ); //Parallel.For(0, totalQ, i => //{ // var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults(); //}); Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds)); Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ)); } Console.ReadLine(); #endregion } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace BatchClientIntegrationTests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using BatchTestCommon; using Fixtures; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Common; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using IntegrationTestUtilities; using Microsoft.Azure.Batch.Protocol.BatchRequests; using Microsoft.Rest.Azure; using Xunit; using Xunit.Abstractions; using Protocol = Microsoft.Azure.Batch.Protocol; /// <summary> /// Tests focused primarily on the <see cref="ComputeNode"/>. /// </summary> [Collection("SharedPoolCollection")] public class ComputeNodeIntegrationTests { private readonly ITestOutputHelper testOutputHelper; private readonly PoolFixture poolFixture; private static readonly TimeSpan TestTimeout = TimeSpan.FromMinutes(1); public ComputeNodeIntegrationTests(ITestOutputHelper testOutputHelper, PaasWindowsPoolFixture poolFixture) { this.testOutputHelper = testOutputHelper; this.poolFixture = poolFixture; } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void BugComputeNodeMissingStartTaskInfo_RunAfterPoolIsUsed() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { CloudPool pool = batchCli.PoolOperations.GetPool(this.poolFixture.PoolId); // confirm start task info exists and has rational values foreach (ComputeNode curComputeNode in pool.ListComputeNodes()) { StartTaskInformation sti = curComputeNode.StartTaskInformation; // set when pool was created Assert.NotNull(sti); Assert.True(StartTaskState.Running == sti.State || StartTaskState.Completed == sti.State); } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void Bug1771163TestGetComputeNode_RefreshComputeNode() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { PoolOperations poolOperations = batchCli.PoolOperations; List<ComputeNode> computeNodeList = poolOperations.ListComputeNodes(this.poolFixture.PoolId).ToList(); ComputeNode computeNodeToGet = computeNodeList.First(); string computeNodeId = computeNodeToGet.Id; // // Get compute node via the manager // ComputeNode computeNodeFromManager = poolOperations.GetComputeNode(this.poolFixture.PoolId, computeNodeId); CompareComputeNodeObjects(computeNodeToGet, computeNodeFromManager); // // Get compute node via the pool // CloudPool pool = poolOperations.GetPool(this.poolFixture.PoolId); ComputeNode computeNodeFromPool = pool.GetComputeNode(computeNodeId); CompareComputeNodeObjects(computeNodeToGet, computeNodeFromPool); // // Refresh compute node // //Refresh with a detail level computeNodeToGet.Refresh(new ODATADetailLevel() { SelectClause = "affinityId,id" }); //Confirm we have the reduced detail level Assert.Equal(computeNodeToGet.AffinityId, computeNodeFromManager.AffinityId); Assert.Null(computeNodeToGet.IPAddress); Assert.Null(computeNodeToGet.LastBootTime); Assert.Null(computeNodeToGet.State); Assert.Null(computeNodeToGet.StartTaskInformation); //Refresh again with increased detail level computeNodeToGet.Refresh(); CompareComputeNodeObjects(computeNodeToGet, computeNodeFromManager); } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void Bug2302907_TestComputeNodeDoesInheritBehaviors() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment(), addDefaultRetryPolicy: false).Result) { Microsoft.Azure.Batch.Protocol.RequestInterceptor interceptor = new Microsoft.Azure.Batch.Protocol.RequestInterceptor(); batchCli.PoolOperations.CustomBehaviors.Add(interceptor); List<ComputeNode> computeNodeList = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId).ToList(); ComputeNode computeNode = computeNodeList.First(); Assert.Equal(2, computeNode.CustomBehaviors.Count); Assert.Contains(interceptor, computeNode.CustomBehaviors); } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)] public void Bug2329884_ComputeNodeRecentTasksAndComputeNodeError() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { string jobId = "Bug2329884Job-" + TestUtilities.GetMyName(); Protocol.RequestInterceptor interceptor = null; try { const string taskId = "hiWorld"; // // Create the job // CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation()); unboundJob.PoolInformation.PoolId = this.poolFixture.PoolId; unboundJob.Commit(); CloudJob boundJob = batchCli.JobOperations.GetJob(jobId); CloudTask myTask = new CloudTask(taskId, "cmd /c echo hello world"); boundJob.AddTask(myTask); this.testOutputHelper.WriteLine("Initial job commit()"); // // Wait for task to go to completion // Utilities utilities = batchCli.Utilities; TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor(); taskStateMonitor.WaitAll( boundJob.ListTasks(), Microsoft.Azure.Batch.Common.TaskState.Completed, new TimeSpan(0, 3 /*min*/, 0)); CloudTask boundTask = boundJob.GetTask(taskId); //Since the compute node name comes back as "Node:<computeNodeId>" we need to split on : to get the actual compute node name string computeNodeId = boundTask.ComputeNodeInformation.AffinityId.Split(':')[1]; // // Check recent tasks // ComputeNode computeNode = batchCli.PoolOperations.GetComputeNode(this.poolFixture.PoolId, computeNodeId); this.testOutputHelper.WriteLine("Recent tasks:"); foreach (TaskInformation recentTask in computeNode.RecentTasks) { this.testOutputHelper.WriteLine("Compute node has recent task Job: {0}, Task: {1}, State: {2}, Subtask: {3}", recentTask.JobId, recentTask.TaskId, recentTask.TaskState, recentTask.SubtaskId); } TaskInformation myTaskInfo = computeNode.RecentTasks.First(taskInfo => taskInfo.JobId.Equals( jobId, StringComparison.InvariantCultureIgnoreCase) && taskInfo.TaskId.Equals(taskId, StringComparison.InvariantCultureIgnoreCase)); Assert.Equal(TaskState.Completed, myTaskInfo.TaskState); Assert.NotNull(myTaskInfo.ExecutionInformation); Assert.Equal(0, myTaskInfo.ExecutionInformation.ExitCode); // // Check compute node Error // const string expectedErrorCode = "TestErrorCode"; const string expectedErrorMessage = "Test error message"; const string nvpValue = "Test"; //We use mocking to return a fake compute node object here to test Compute Node Error because we cannot force one easily interceptor = new Protocol.RequestInterceptor((req => { if (req is ComputeNodeGetBatchRequest) { var typedRequest = req as ComputeNodeGetBatchRequest; typedRequest.ServiceRequestFunc = (token) => { var response = new AzureOperationResponse<Protocol.Models.ComputeNode, Protocol.Models.ComputeNodeGetHeaders>(); List<Protocol.Models.ComputeNodeError> errors = new List<Protocol.Models.ComputeNodeError>(); //Generate first Compute Node Error List<Protocol.Models.NameValuePair> nvps = new List<Protocol.Models.NameValuePair>(); nvps.Add(new Protocol.Models.NameValuePair() { Name = nvpValue, Value = nvpValue }); Protocol.Models.ComputeNodeError error1 = new Protocol.Models.ComputeNodeError(); error1.Code = expectedErrorCode; error1.Message = expectedErrorMessage; error1.ErrorDetails = nvps; errors.Add(error1); //Generate second Compute Node Error nvps = new List<Protocol.Models.NameValuePair>(); nvps.Add(new Protocol.Models.NameValuePair() { Name = nvpValue, Value = nvpValue }); Protocol.Models.ComputeNodeError error2 = new Protocol.Models.ComputeNodeError(); error2.Code = expectedErrorCode; error2.Message = expectedErrorMessage; error2.ErrorDetails = nvps; errors.Add(error2); Protocol.Models.ComputeNode protoComputeNode = new Protocol.Models.ComputeNode(); protoComputeNode.Id = computeNodeId; protoComputeNode.State = Protocol.Models.ComputeNodeState.Idle; protoComputeNode.Errors = errors; response.Body = protoComputeNode; return Task.FromResult(response); }; } })); batchCli.PoolOperations.CustomBehaviors.Add(interceptor); computeNode = batchCli.PoolOperations.GetComputeNode(this.poolFixture.PoolId, computeNodeId); Assert.Equal(computeNodeId, computeNode.Id); Assert.NotNull(computeNode.Errors); Assert.Equal(2, computeNode.Errors.Count()); foreach (ComputeNodeError computeNodeError in computeNode.Errors) { Assert.Equal(expectedErrorCode, computeNodeError.Code); Assert.Equal(expectedErrorMessage, computeNodeError.Message); Assert.NotNull(computeNodeError.ErrorDetails); Assert.Equal(1, computeNodeError.ErrorDetails.Count()); Assert.Contains(nvpValue, computeNodeError.ErrorDetails.First().Name); } } finally { batchCli.JobOperations.DeleteJob(jobId); } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)] public void Bug1770933_1770935_1771164_AddUserCRUDAndGetRDP() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { // names to create/delete List<string> names = new List<string>() { TestUtilities.GetMyName(), TestUtilities.GetMyName() + "1", TestUtilities.GetMyName() + "2", TestUtilities.GetMyName() + "3", TestUtilities.GetMyName() + "4" }; // pick a compute node to victimize with user accounts IEnumerable<ComputeNode> ienmComputeNodes = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId); List<ComputeNode> computeNodeList = new List<ComputeNode>(ienmComputeNodes); ComputeNode computeNode = computeNodeList[0]; try { string rdpFileName = "Bug1770933.rdp"; // test user public constructor and IPoolMgr verbs { ComputeNodeUser newUser = batchCli.PoolOperations.CreateComputeNodeUser(this.poolFixture.PoolId, computeNode.Id); newUser.Name = names[0]; newUser.IsAdmin = true; newUser.ExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1.0); newUser.Password = @"!!Admin!!"; // commit that creates/adds the user newUser.Commit(ComputeNodeUserCommitSemantics.AddUser); // now update the user's password newUser.Password = @"!!!Admin!!!"; // commit that updates newUser.Commit(ComputeNodeUserCommitSemantics.UpdateUser); // clean up from prev run if (File.Exists(rdpFileName)) { File.Delete(rdpFileName); } // pull the rdp file batchCli.PoolOperations.GetRDPFile(this.poolFixture.PoolId, computeNode.Id, rdpFileName); // simple validation tests on the rdp file TestFileExistsAndHasLength(rdpFileName); // cleanup the rdp file File.Delete(rdpFileName); // "test" delete user from IPoolMgr // TODO: when GET/LIST User is available we should close the loop and confirm the user is gone. batchCli.PoolOperations.DeleteComputeNodeUser(this.poolFixture.PoolId, computeNode.Id, newUser.Name); } // test IPoolMgr CreateUser { ComputeNodeUser pmcUser = batchCli.PoolOperations.CreateComputeNodeUser(this.poolFixture.PoolId, computeNode.Id); pmcUser.Name = names[1]; pmcUser.IsAdmin = true; pmcUser.ExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1.0); pmcUser.Password = @"!!!Admin!!!"; // add the user pmcUser.Commit(ComputeNodeUserCommitSemantics.AddUser); // pull rdp file batchCli.PoolOperations.GetRDPFile(this.poolFixture.PoolId, computeNode.Id, rdpFileName); // simple validation on rdp file TestFileExistsAndHasLength(rdpFileName); // cleanup File.Delete(rdpFileName); // delete user batchCli.PoolOperations.DeleteComputeNodeUser(this.poolFixture.PoolId, computeNode.Id, pmcUser.Name); } // test IComputeNode verbs { ComputeNodeUser poolMgrUser = batchCli.PoolOperations.CreateComputeNodeUser(this.poolFixture.PoolId, computeNode.Id); poolMgrUser.Name = names[2]; poolMgrUser.IsAdmin = true; poolMgrUser.ExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1.0); poolMgrUser.Password = @"!!!Admin!!!"; poolMgrUser.Commit(ComputeNodeUserCommitSemantics.AddUser); // pull rdp file computeNode.GetRDPFile(rdpFileName); // simple validation on rdp file TestFileExistsAndHasLength(rdpFileName); // cleanup File.Delete(rdpFileName); // delete user computeNode.DeleteComputeNodeUser(poolMgrUser.Name); } // test ComputeNodeUser.Delete { ComputeNodeUser usrDelete = batchCli.PoolOperations.CreateComputeNodeUser(this.poolFixture.PoolId, computeNode.Id); usrDelete.Name = names[3]; usrDelete.ExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1.0); usrDelete.Password = @"!!!Admin!!!"; usrDelete.Commit(ComputeNodeUserCommitSemantics.AddUser); usrDelete.Delete(); } // test rdp-by-stream IPoolMgr and IComputeNode // the by-stream paths do not converge with the by-filename paths until IProtocol so we test them seperately { ComputeNodeUser byStreamUser = batchCli.PoolOperations.CreateComputeNodeUser(this.poolFixture.PoolId, computeNode.Id); byStreamUser.Name = names[4]; byStreamUser.IsAdmin = true; byStreamUser.ExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1.0); byStreamUser.Password = @"!!!Admin!!!"; byStreamUser.Commit(ComputeNodeUserCommitSemantics.AddUser); // IPoolMgr using (Stream rdpStreamPoolMgr = File.Create(rdpFileName)) { batchCli.PoolOperations.GetRDPFile(this.poolFixture.PoolId, computeNode.Id, rdpStreamPoolMgr); rdpStreamPoolMgr.Flush(); rdpStreamPoolMgr.Close(); TestFileExistsAndHasLength(rdpFileName); File.Delete(rdpFileName); } // IComputeNode using (Stream rdpViaIComputeNode = File.Create(rdpFileName)) { computeNode.GetRDPFile(rdpViaIComputeNode); rdpViaIComputeNode.Flush(); rdpViaIComputeNode.Close(); TestFileExistsAndHasLength(rdpFileName); File.Delete(rdpFileName); } // delete the user account byStreamUser.Delete(); } } finally { // clear any old accounts foreach (string curName in names) { bool hitException = false; try { ComputeNodeUser deleteThis = batchCli.PoolOperations.CreateComputeNodeUser(this.poolFixture.PoolId, computeNode.Id); deleteThis.Name = curName; deleteThis.Delete(); } catch (BatchException ex) { Assert.Equal(BatchErrorCodeStrings.NodeUserNotFound, ex.RequestInformation.BatchError.Code); hitException = true; } Assert.True(hitException, "Should have hit exception on user: " + curName + ", compute node: " + computeNode.Id + "."); } } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void Bug2342986_StartTaskMissingOnComputeNode() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { CloudPool pool = batchCli.PoolOperations.GetPool(this.poolFixture.PoolId); this.testOutputHelper.WriteLine("Getting pool"); StartTask poolStartTask = pool.StartTask; Assert.NotNull(poolStartTask); Assert.NotNull(poolStartTask.EnvironmentSettings); IEnumerable<ComputeNode> computeNodes = pool.ListComputeNodes(); Assert.True(computeNodes.Any()); this.testOutputHelper.WriteLine("Checking every compute nodes start task in the pool matches the pools start task"); foreach (ComputeNode computeNode in computeNodes) { this.testOutputHelper.WriteLine("Checking start task of compute node: {0}", computeNode.Id); //Check that the property is correctly set on each compute node Assert.NotNull(computeNode.StartTask); Assert.Equal(poolStartTask.CommandLine, computeNode.StartTask.CommandLine); Assert.Equal(poolStartTask.MaxTaskRetryCount, computeNode.StartTask.MaxTaskRetryCount); Assert.Equal(AutoUserScope.Task, poolStartTask.UserIdentity.AutoUser.Scope); Assert.Equal(AutoUserScope.Task, computeNode.StartTask.UserIdentity.AutoUser.Scope); Assert.Equal(poolStartTask.WaitForSuccess, computeNode.StartTask.WaitForSuccess); if (poolStartTask.EnvironmentSettings != null) { Assert.Equal(poolStartTask.EnvironmentSettings.Count, computeNode.StartTask.EnvironmentSettings.Count); foreach (EnvironmentSetting environmentSetting in poolStartTask.EnvironmentSettings) { EnvironmentSetting matchingEnvSetting = computeNode.StartTask.EnvironmentSettings.FirstOrDefault(envSetting => envSetting.Name == environmentSetting.Name); Assert.NotNull(matchingEnvSetting); Assert.Equal(environmentSetting.Name, matchingEnvSetting.Name); Assert.Equal(environmentSetting.Value, matchingEnvSetting.Value); } } if (poolStartTask.ResourceFiles != null) { Assert.Equal(poolStartTask.ResourceFiles.Count, computeNode.StartTask.ResourceFiles.Count); foreach (ResourceFile resourceFile in poolStartTask.ResourceFiles) { ResourceFile matchingResourceFile = computeNode.StartTask.ResourceFiles.FirstOrDefault(item => item.HttpUrl == resourceFile.HttpUrl); Assert.NotNull(matchingResourceFile); Assert.Equal(resourceFile.HttpUrl, matchingResourceFile.HttpUrl); Assert.Equal(resourceFile.FilePath, matchingResourceFile.FilePath); } } //Try to set some properties of the compute node's start task and ensure it fails TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.CommandLine = "Test"; }); TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.MaxTaskRetryCount = 5; }); TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.UserIdentity = new UserIdentity("foo"); }); TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.WaitForSuccess = true; }); TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.EnvironmentSettings = new List<EnvironmentSetting>(); }); if (computeNode.StartTask.EnvironmentSettings != null) { TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.EnvironmentSettings.Add(new EnvironmentSetting("test", "test")); }); } TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.ResourceFiles = new List<ResourceFile>(); }); if (computeNode.StartTask.ResourceFiles != null) { TestUtilities.AssertThrows<InvalidOperationException>(() => { computeNode.StartTask.ResourceFiles.Add(ResourceFile.FromUrl("test", "test")); }); } } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)] public async Task OnlineOfflineTest() { await SynchronizationContextHelper.RunTestAsync(async () => { using (BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync()) { TimeSpan refreshPollingTimeout = TimeSpan.FromMinutes(3); CloudPool pool = this.poolFixture.Pool; List<ComputeNode> nodes = pool.ListComputeNodes().ToList(); Assert.True(nodes.Count > 0); // pick a victim compute node. cleanup code needs this set ComputeNode victim = nodes[0]; try { Assert.True(victim.SchedulingState.HasValue && (SchedulingState.Enabled == victim.SchedulingState)); Assert.True(victim.State.HasValue && (ComputeNodeState.Idle == victim.State)); // PoolOperations methods { // disable task scheduling batchCli.PoolOperations.DisableComputeNodeScheduling(pool.Id, victim.Id, DisableComputeNodeSchedulingOption.Terminate); // Li says state change is not atomic so we will sleep // asserted above this node is idle so no need to wait for task fussery await TestUtilities.RefreshBasedPollingWithTimeoutAsync( refreshing: victim, condition: () => Task.FromResult(victim.SchedulingState.HasValue && (SchedulingState.Disabled == victim.SchedulingState)), timeout: refreshPollingTimeout).ConfigureAwait(false); Assert.Equal<SchedulingState?>(SchedulingState.Disabled, victim.SchedulingState); // enable task scheduling batchCli.PoolOperations.EnableComputeNodeScheduling(pool.Id, victim.Id); await TestUtilities.RefreshBasedPollingWithTimeoutAsync( refreshing: victim, condition: () => Task.FromResult(victim.SchedulingState.HasValue && (SchedulingState.Enabled == victim.SchedulingState)), timeout: refreshPollingTimeout); Assert.Equal<SchedulingState?>(SchedulingState.Enabled, victim.SchedulingState); } // ComputeNode methods { // disable task scheduling victim.DisableScheduling(DisableComputeNodeSchedulingOption.TaskCompletion); await TestUtilities.RefreshBasedPollingWithTimeoutAsync( refreshing: victim, condition: () => Task.FromResult(victim.SchedulingState.HasValue && (SchedulingState.Disabled == victim.SchedulingState)), timeout: refreshPollingTimeout).ConfigureAwait(false); Assert.Equal<SchedulingState?>(SchedulingState.Disabled, victim.SchedulingState); // enable task scheduling victim.EnableScheduling(); await TestUtilities.RefreshBasedPollingWithTimeoutAsync( refreshing: victim, condition: () => Task.FromResult(victim.SchedulingState.HasValue && (SchedulingState.Enabled == victim.SchedulingState)), timeout: refreshPollingTimeout).ConfigureAwait(false); Assert.Equal<SchedulingState?>(SchedulingState.Enabled, victim.SchedulingState); // now test azureerror code for: NodeAlreadyInTargetSchedulingState bool gotCorrectException = false; try { victim.EnableScheduling(); // it is already enabled so this should trigger exception } catch (Exception ex) { TestUtilities.AssertIsBatchExceptionAndHasCorrectAzureErrorCode(ex, Microsoft.Azure.Batch.Common.BatchErrorCodeStrings.NodeAlreadyInTargetSchedulingState, this.testOutputHelper); gotCorrectException = true; } if (!gotCorrectException) { throw new Exception("OnlineOfflineTest: failed to see an exception for NodeAlreadyInTargetSchedulingState test"); } } } finally // restore state of victim compute node { try { // do not pollute the shared pool with disabled scheduling if (null != victim) { victim.EnableScheduling(); } } catch (Exception ex) { this.testOutputHelper.WriteLine(string.Format("OnlineOfflineTest: exception during exit trying to restore scheduling state: {0}", ex.ToString())); } } } }, TestTimeout); } #region Test helpers private static void CompareComputeNodeObjects(ComputeNode first, ComputeNode second) { Assert.Equal(first.AffinityId, second.AffinityId); Assert.Equal(first.IPAddress, second.IPAddress); Assert.Equal(first.LastBootTime, second.LastBootTime); Assert.Equal(first.Id, second.Id); Assert.Equal(first.StateTransitionTime, second.StateTransitionTime); Assert.Equal(first.Url, second.Url); Assert.Equal(first.AllocationTime, second.AllocationTime); Assert.Equal(first.VirtualMachineSize, second.VirtualMachineSize); } private static void TestFileExistsAndHasLength(string filename) { // make some easy tests on the rdp file FileInfo rdpInfo = new FileInfo(filename); Assert.True(rdpInfo.Length > 0); // gets existance and content } #endregion } [Collection("SharedLinuxPoolCollection")] public class IntegrationComputeNodeLinuxTests { private readonly ITestOutputHelper testOutputHelper; private readonly PoolFixture poolFixture; private static readonly TimeSpan TestTimeout = TimeSpan.FromMinutes(3); public IntegrationComputeNodeLinuxTests(ITestOutputHelper testOutputHelper, IaasLinuxPoolFixture poolFixture) { this.testOutputHelper = testOutputHelper; this.poolFixture = poolFixture; } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestComputeNodeUserIaas() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { CloudPool sharedPool = this.poolFixture.Pool; List<string> cnuNamesToDelete = new List<string>(); // pick a compute node to victimize with user accounts var nodes = sharedPool.ListComputeNodes().ToList(); ComputeNode cn = nodes[0]; try { ComputeNodeUser bob = batchCli.PoolOperations.CreateComputeNodeUser(sharedPool.Id, cn.Id); bob.Name = "bob"; bob.ExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(25); bob.Password = "password"; bob.SshPublicKey = "base64=="; cnuNamesToDelete.Add(bob.Name); // remember to clean this up bob.Commit(ComputeNodeUserCommitSemantics.AddUser); bob.SshPublicKey = "base65=="; bob.Commit(ComputeNodeUserCommitSemantics.UpdateUser); // TODO: need to close the loop on this somehow... move to unit/interceptor-based? // currently the server is timing out. } finally { // clear any old accounts try { foreach (string curCNUName in cnuNamesToDelete) { this.testOutputHelper.WriteLine("TestComputeNodeUserIAAS attempting to delete the following <nodeid,user>: <{0},{1}>", cn.Id, curCNUName); cn.DeleteComputeNodeUser(curCNUName); } } catch (Exception ex) { this.testOutputHelper.WriteLine("TestComputeNodeUserIAAS: exception deleting user account. ex: " + ex.ToString()); } } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void ComputeNodeUploadLogs() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result) { var node = batchCli.PoolOperations.ListComputeNodes(this.poolFixture.PoolId).First(); // Generate a storage container URL StagingStorageAccount storageAccount = TestUtilities.GetStorageCredentialsFromEnvironment(); CloudStorageAccount cloudStorageAccount = new CloudStorageAccount( new StorageCredentials(storageAccount.StorageAccount, storageAccount.StorageAccountKey), blobEndpoint: storageAccount.BlobUri, queueEndpoint: null, tableEndpoint: null, fileEndpoint: null); CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient(); const string containerName = "computenodelogscontainer"; var container = blobClient.GetContainerReference(containerName); try { container.CreateIfNotExists(); // Ensure that there are no items in the container to begin with var blobs = container.ListBlobs(); Assert.Empty(blobs); var sas = container.GetSharedAccessSignature(new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Write, SharedAccessExpiryTime = DateTime.UtcNow.AddDays(1) }); var fullSas = container.Uri + sas; var startTime = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(5)); var result = batchCli.PoolOperations.UploadComputeNodeBatchServiceLogs( this.poolFixture.PoolId, node.Id, fullSas, startTime); Assert.NotEqual(0, result.NumberOfFilesUploaded); Assert.NotEmpty(result.VirtualDirectoryName); // Allow up to 2m for files to get uploaded DateTime timeoutAt = DateTime.UtcNow.AddMinutes(2); while (DateTime.UtcNow < timeoutAt) { blobs = container.ListBlobs(); if (blobs.Any()) { break; } } Assert.NotEmpty(blobs); } finally { container.DeleteIfExists(); } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestGetRemoteLoginSettings() { Action test = () => { using (BatchClient batchCli = TestUtilities.OpenBatchClientAsync(TestUtilities.GetCredentialsFromEnvironment()).Result) { CloudPool sharedPool = this.poolFixture.Pool; try { // get a compute node. // get its RLS via PoolOps and via CN // Assert there are values and that the values are equal var nodes = sharedPool.ListComputeNodes().ToList(); Assert.Equal<int>(expected: 1, actual: nodes.Count); ComputeNode cn = nodes[0]; // get the RLS via each object RemoteLoginSettings rlsViaPoolOps = batchCli.PoolOperations.GetRemoteLoginSettings(sharedPool.Id, cn.Id); RemoteLoginSettings rlsViaNode = cn.GetRemoteLoginSettings(); // they must have RLS Assert.NotNull(rlsViaNode); Assert.NotNull(rlsViaPoolOps); // there must be an IP in each RLS Assert.False(string.IsNullOrWhiteSpace(rlsViaPoolOps.IPAddress)); Assert.False(string.IsNullOrWhiteSpace(rlsViaNode.IPAddress)); // the ports must match Assert.Equal(expected: rlsViaNode.Port, actual: rlsViaPoolOps.Port); } finally { // cleanup goes here } } }; SynchronizationContextHelper.RunTest(test, TestTimeout); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// The common Data Lake Analytics job information properties. /// </summary> public partial class JobInformation { /// <summary> /// Initializes a new instance of the JobInformation class. /// </summary> public JobInformation() { } /// <summary> /// Initializes a new instance of the JobInformation class. /// </summary> /// <param name="name">the friendly name of the job.</param> /// <param name="type">the job type of the current job (Hive or USql). /// Possible values include: 'USql', 'Hive'</param> /// <param name="properties">the job specific properties.</param> /// <param name="jobId">the job's unique identifier (a GUID).</param> /// <param name="submitter">the user or account that submitted the /// job.</param> /// <param name="errorMessage">the error message details for the job, /// if the job failed.</param> /// <param name="degreeOfParallelism">the degree of parallelism used /// for this job. This must be greater than 0.</param> /// <param name="priority">the priority value for the current job. /// Lower numbers have a higher priority. By default, a job has a /// priority of 1000. This must be greater than 0.</param> /// <param name="submitTime">the time the job was submitted to the /// service.</param> /// <param name="startTime">the start time of the job.</param> /// <param name="endTime">the completion time of the job.</param> /// <param name="state">the job state. When the job is in the Ended /// state, refer to Result and ErrorMessage for details. Possible /// values include: 'Accepted', 'Compiling', 'Ended', 'New', /// 'Queued', 'Running', 'Scheduling', 'Starting', 'Paused', /// 'WaitingForCapacity'</param> /// <param name="result">the result of job execution or the current /// result of the running job. Possible values include: 'None', /// 'Succeeded', 'Cancelled', 'Failed'</param> /// <param name="logFolder">the log folder path to use in the /// following format: /// adl://<accountName>.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/.</param> /// <param name="logFilePatterns">the list of log file name patterns /// to find in the logFolder. '*' is the only matching character /// allowed. Example format: jobExecution*.log or *mylog*.txt</param> /// <param name="stateAuditRecords">the job state audit records, /// indicating when various operations have been performed on this /// job.</param> public JobInformation(string name, JobType type, JobProperties properties, Guid? jobId = default(Guid?), string submitter = default(string), IList<JobErrorDetails> errorMessage = default(IList<JobErrorDetails>), int? degreeOfParallelism = default(int?), int? priority = default(int?), DateTimeOffset? submitTime = default(DateTimeOffset?), DateTimeOffset? startTime = default(DateTimeOffset?), DateTimeOffset? endTime = default(DateTimeOffset?), JobState? state = default(JobState?), JobResult? result = default(JobResult?), string logFolder = default(string), IList<string> logFilePatterns = default(IList<string>), IList<JobStateAuditRecord> stateAuditRecords = default(IList<JobStateAuditRecord>)) { JobId = jobId; Name = name; Type = type; Submitter = submitter; ErrorMessage = errorMessage; DegreeOfParallelism = degreeOfParallelism; Priority = priority; SubmitTime = submitTime; StartTime = startTime; EndTime = endTime; State = state; Result = result; LogFolder = logFolder; LogFilePatterns = logFilePatterns; StateAuditRecords = stateAuditRecords; Properties = properties; } /// <summary> /// Gets or sets the job's unique identifier (a GUID). /// </summary> [JsonProperty(PropertyName = "jobId")] public Guid? JobId { get; set; } /// <summary> /// Gets or sets the friendly name of the job. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets or sets the job type of the current job (Hive or USql). /// Possible values include: 'USql', 'Hive' /// </summary> [JsonProperty(PropertyName = "type")] public JobType Type { get; set; } /// <summary> /// Gets or sets the user or account that submitted the job. /// </summary> [JsonProperty(PropertyName = "submitter")] public string Submitter { get; set; } /// <summary> /// Gets the error message details for the job, if the job failed. /// </summary> [JsonProperty(PropertyName = "errorMessage")] public IList<JobErrorDetails> ErrorMessage { get; private set; } /// <summary> /// Gets or sets the degree of parallelism used for this job. This /// must be greater than 0. /// </summary> [JsonProperty(PropertyName = "degreeOfParallelism")] public int? DegreeOfParallelism { get; set; } /// <summary> /// Gets or sets the priority value for the current job. Lower numbers /// have a higher priority. By default, a job has a priority of 1000. /// This must be greater than 0. /// </summary> [JsonProperty(PropertyName = "priority")] public int? Priority { get; set; } /// <summary> /// Gets the time the job was submitted to the service. /// </summary> [JsonProperty(PropertyName = "submitTime")] public DateTimeOffset? SubmitTime { get; private set; } /// <summary> /// Gets the start time of the job. /// </summary> [JsonProperty(PropertyName = "startTime")] public DateTimeOffset? StartTime { get; private set; } /// <summary> /// Gets the completion time of the job. /// </summary> [JsonProperty(PropertyName = "endTime")] public DateTimeOffset? EndTime { get; private set; } /// <summary> /// Gets the job state. When the job is in the Ended state, refer to /// Result and ErrorMessage for details. Possible values include: /// 'Accepted', 'Compiling', 'Ended', 'New', 'Queued', 'Running', /// 'Scheduling', 'Starting', 'Paused', 'WaitingForCapacity' /// </summary> [JsonProperty(PropertyName = "state")] public JobState? State { get; private set; } /// <summary> /// Gets the result of job execution or the current result of the /// running job. Possible values include: 'None', 'Succeeded', /// 'Cancelled', 'Failed' /// </summary> [JsonProperty(PropertyName = "result")] public JobResult? Result { get; private set; } /// <summary> /// Gets the log folder path to use in the following format: /// adl://&lt;accountName&gt;.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/. /// </summary> [JsonProperty(PropertyName = "logFolder")] public string LogFolder { get; private set; } /// <summary> /// Gets or sets the list of log file name patterns to find in the /// logFolder. '*' is the only matching character allowed. Example /// format: jobExecution*.log or *mylog*.txt /// </summary> [JsonProperty(PropertyName = "logFilePatterns")] public IList<string> LogFilePatterns { get; set; } /// <summary> /// Gets the job state audit records, indicating when various /// operations have been performed on this job. /// </summary> [JsonProperty(PropertyName = "stateAuditRecords")] public IList<JobStateAuditRecord> StateAuditRecords { get; private set; } /// <summary> /// Gets or sets the job specific properties. /// </summary> [JsonProperty(PropertyName = "properties")] public JobProperties Properties { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } if (Properties == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Properties"); } if (this.Properties != null) { this.Properties.Validate(); } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using FluentAssertions; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using NuGet.ProjectModel; using NuGet.Versioning; using Xunit; using Microsoft.DotNet.Tools.Tests.Utilities; using Microsoft.DotNet.CommandFactory; using LocalizableStrings = Microsoft.DotNet.CommandFactory.LocalizableStrings; namespace Microsoft.DotNet.Tests { public class GivenAProjectToolsCommandResolver : TestBase { private static readonly NuGetFramework s_toolPackageFramework = NuGetFrameworks.NetCoreApp22; private const string TestProjectName = "AppWithToolDependency"; [Fact] public void ItReturnsNullWhenCommandNameIsNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] { "" }, ProjectDirectory = "/some/directory" }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenProjectDirectoryIsNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = null }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenProjectDirectoryDoesNotContainAProjectFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var projectDirectory = TestAssets.CreateTestDirectory(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = projectDirectory.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsNullWhenCommandNameDoesNotExistInProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void ItReturnsACommandSpecWithDOTNETAsFileNameAndCommandNameInArgsWhenCommandNameExistsInProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void ItEscapesCommandArgumentsWhenReturningACommandSpec() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = new[] { "arg with space" }, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull("Because the command is a project tool dependency"); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void ItReturnsACommandSpecWithArgsContainingCommandPathWhenReturningACommandSpecAndCommandArgumentsAreNull() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-portable.dll"); } [Fact] public void ItReturnsACommandSpecWithArgsContainingCommandPathWhenInvokingAToolReferencedWithADifferentCasing() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-prefercliruntime", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-prefercliruntime.dll"); } [Fact] public void ItWritesADepsJsonFileNextToTheLockfile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var repoDirectoriesProvider = new RepoDirectoriesProvider(); var nugetPackagesRoot = repoDirectoriesProvider.NugetPackages; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var directory = Path.GetDirectoryName(lockFilePath); var depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); if (depsJsonFile != null) { File.Delete(depsJsonFile); } var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); new DirectoryInfo(directory) .Should().HaveFilesMatching("*.deps.json", SearchOption.TopDirectoryOnly); } [Fact] public void GenerateDepsJsonMethodDoesntOverwriteWhenDepsFileAlreadyExists() { var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var repoDirectoriesProvider = new RepoDirectoriesProvider(); var nugetPackagesRoot = repoDirectoriesProvider.NugetPackages; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var lockFile = new LockFileFormat().Read(lockFilePath); // NOTE: We must not use the real deps.json path here as it will interfere with tests running in parallel. var depsJsonFile = Path.GetTempFileName(); File.WriteAllText(depsJsonFile, "temp"); var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); projectToolsCommandResolver.GenerateDepsJsonFile( lockFile, s_toolPackageFramework, depsJsonFile, new SingleProjectInfo("dotnet-portable", "1.0.0", Enumerable.Empty<ResourceAssemblyInfo>()), GetToolDepsJsonGeneratorProject()); File.ReadAllText(depsJsonFile).Should().Be("temp"); File.Delete(depsJsonFile); } [Fact] public void ItDoesNotAddFxVersionAsAParamWhenTheToolDoesNotHaveThePrefercliruntimeFile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var testInstance = TestAssets.Get(TestProjectName) .CreateInstance() .WithSourceFiles() .WithRestoreFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = testInstance.Root.FullName }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().NotContain("--fx-version"); } [Fact] public void ItFindsToolsLocatedInTheNuGetFallbackFolder() { var testInstance = TestAssets.Get("AppWithFallbackFolderToolDependency") .CreateInstance("NF") // use shorter name since path could be too long .WithSourceFiles() .WithNuGetConfigAndExternalRestoreSources(new RepoDirectoriesProvider().TestPackages); var testProjectDirectory = testInstance.Root.FullName; var fallbackFolder = Path.Combine(testProjectDirectory, "fallbackFolder"); PopulateFallbackFolder(testProjectDirectory, fallbackFolder); var nugetConfig = UseNuGetConfigWithFallbackFolder(testInstance, fallbackFolder); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfig}") .Should() .Pass(); new DotnetCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"fallbackfoldertool").Should().Pass(); } [Fact] public void ItShowsAnErrorWhenTheToolDllIsNotFound() { var testInstance = TestAssets.Get("AppWithFallbackFolderToolDependency") .CreateInstance("DN") // use shorter name since path could be too long .WithSourceFiles() .WithNuGetConfigAndExternalRestoreSources(new RepoDirectoriesProvider().TestPackages); var testProjectDirectory = testInstance.Root.FullName; var fallbackFolder = Path.Combine(testProjectDirectory, "fallbackFolder"); var nugetPackages = Path.Combine(testProjectDirectory, "nugetPackages"); PopulateFallbackFolder(testProjectDirectory, fallbackFolder); var nugetConfig = UseNuGetConfigWithFallbackFolder(testInstance, fallbackFolder); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfig} /p:RestorePackagesPath={nugetPackages}") .Should() .Pass(); // We need to run the tool once to generate the deps.json // otherwise we end up with a different error message. new DotnetCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"fallbackfoldertool /p:RestorePackagesPath={nugetPackages}").Should().Pass(); Directory.Delete(Path.Combine(fallbackFolder, "dotnet-fallbackfoldertool"), true); new DotnetCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"fallbackfoldertool /p:RestorePackagesPath={nugetPackages}") .Should().Fail().And.NotHaveStdOutContaining(string.Format(LocalizableStrings.CommandAssembliesNotFound, "dotnet-fallbackfoldertool")); } private void PopulateFallbackFolder(string testProjectDirectory, string fallbackFolder) { var nugetConfigPath = Path.Combine(testProjectDirectory, "NuGet.Config"); new RestoreCommand() .WithWorkingDirectory(testProjectDirectory) .Execute($"--configfile {nugetConfigPath} --packages {fallbackFolder}") .Should() .Pass(); Directory.Delete(Path.Combine(fallbackFolder, ".tools"), true); } private string UseNuGetConfigWithFallbackFolder(TestAssetInstance testInstance, string fallbackFolder) { var nugetConfig = testInstance.Root.GetFile("NuGet.Config").FullName; File.WriteAllText( nugetConfig, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <fallbackPackageFolders> <add key=""MachineWide"" value=""{fallbackFolder}""/> </fallbackPackageFolders> </configuration> "); return nugetConfig; } private ProjectToolsCommandResolver SetupProjectToolsCommandResolver() { Environment.SetEnvironmentVariable( Constants.MSBUILD_EXE_PATH, Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll")); var packagedCommandSpecFactory = new PackagedCommandSpecFactoryWithCliRuntime(); var projectToolsCommandResolver = new ProjectToolsCommandResolver(packagedCommandSpecFactory, new EnvironmentProvider()); return projectToolsCommandResolver; } private string GetToolDepsJsonGeneratorProject() { // When using the product, the ToolDepsJsonGeneratorProject property is used to get this path, but for testing // we'll hard code the path inside the SDK since we don't have a project to evaluate here return Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "Sdks", "Microsoft.NET.Sdk", "targets", "GenerateDeps", "GenerateDeps.proj"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using PushNotification.Plugin.Abstractions; using Android.Gms.Gcm; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Support.V4.App; using Android.Media; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PushNotification.Plugin { /// <summary> /// Push Notification Message Handler /// </summary> [Service(Exported = false, Name = "pushnotification.plugin.PushNotificationGcmListener")] [IntentFilter(new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "@PACKAGE_NAME@" })] public class PushNotificationGcmListener : GcmListenerService { /// <summary> /// Called when message is received. /// </summary> /// <param name="from"></param> /// <param name="extras"></param> public override void OnMessageReceived(string from, Bundle extras) { if (extras != null && !extras.IsEmpty) { System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - GCM Listener - Push Received"); var parameters = new Dictionary<string, object>(); JObject values = new JObject(); foreach (var key in extras.KeySet()) { var value = extras.Get(key).ToString(); if (CrossPushNotification.ValidateJSON(value)) { values.Add(key, JObject.Parse(value)); } else { values.Add(key, value); } parameters.Add(key, extras.Get(key)); System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - GCM Listener - Push Params {key} : {extras.Get(key)}"); } Context context = Android.App.Application.Context; CrossPushNotification.PushNotificationListener.OnMessage(values, DeviceType.Android); try { int notifyId = 0; string title = context.ApplicationInfo.LoadLabel(context.PackageManager); string message = ""; string tag = ""; if (!string.IsNullOrEmpty(CrossPushNotification.NotificationContentTextKey) && parameters.ContainsKey(CrossPushNotification.NotificationContentTextKey)) { message = parameters[CrossPushNotification.NotificationContentTextKey].ToString(); } else if (parameters.ContainsKey(PushNotificationKey.Alert)) { message = parameters[PushNotificationKey.Alert].ToString(); } else if (parameters.ContainsKey(PushNotificationKey.Message)) { message = parameters[PushNotificationKey.Message].ToString(); } else if (parameters.ContainsKey(PushNotificationKey.Subtitle)) { message = parameters[PushNotificationKey.Subtitle].ToString(); } else if (parameters.ContainsKey(PushNotificationKey.Text)) { message = parameters[PushNotificationKey.Text].ToString(); } if (!string.IsNullOrEmpty(CrossPushNotification.NotificationContentTitleKey) && parameters.ContainsKey(CrossPushNotification.NotificationContentTitleKey)) { title = parameters[CrossPushNotification.NotificationContentTitleKey].ToString(); } else if (parameters.ContainsKey(PushNotificationKey.Title)) { if (!string.IsNullOrEmpty(message)) { title = parameters[PushNotificationKey.Title].ToString(); } else { message = parameters[PushNotificationKey.Title].ToString(); } } if (string.IsNullOrEmpty(message)) { var data = (!string.IsNullOrEmpty(CrossPushNotification.NotificationContentDataKey) && values[CrossPushNotification.NotificationContentDataKey] != null) ? values[CrossPushNotification.NotificationContentDataKey] : values[PushNotificationKey.Data]; if (data != null) { if (!string.IsNullOrEmpty(CrossPushNotification.NotificationContentTextKey) && data[CrossPushNotification.NotificationContentTextKey] != null) { message = data[CrossPushNotification.NotificationContentTextKey].ToString(); } else if (data[PushNotificationKey.Alert] != null) { message = data[PushNotificationKey.Alert].ToString(); } else if (data[PushNotificationKey.Message] != null) { message = data[PushNotificationKey.Message].ToString(); } else if (data[PushNotificationKey.Subtitle] != null) { message = data[PushNotificationKey.Subtitle].ToString(); } else if (data[PushNotificationKey.Text] != null) { message = data[PushNotificationKey.Text].ToString(); } if (!string.IsNullOrEmpty(CrossPushNotification.NotificationContentTitleKey) && data[CrossPushNotification.NotificationContentTitleKey] != null) { title = data[CrossPushNotification.NotificationContentTitleKey].ToString(); } else if (data[PushNotificationKey.Title] != null) { if (!string.IsNullOrEmpty(message)) { title = data[PushNotificationKey.Title].ToString(); } else { message = data[PushNotificationKey.Title].ToString(); } } } } if (parameters.ContainsKey(PushNotificationKey.Id)) { var str = parameters[PushNotificationKey.Id].ToString(); try { notifyId = Convert.ToInt32(str); } catch (System.Exception ex) { // Keep the default value of zero for the notify_id, but log the conversion problem. System.Diagnostics.Debug.WriteLine("Failed to convert {0} to an integer", str); } } if (parameters.ContainsKey(PushNotificationKey.Tag)) { tag = parameters[PushNotificationKey.Tag].ToString(); } if (!parameters.ContainsKey(PushNotificationKey.Silent) || !System.Boolean.Parse(parameters[PushNotificationKey.Silent].ToString())) { if (CrossPushNotification.PushNotificationListener.ShouldShowNotification()) { CreateNotification(title, message, notifyId, tag, extras); } } } catch (Java.Lang.Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } catch (System.Exception ex1) { System.Diagnostics.Debug.WriteLine(ex1.ToString()); } } } void CreateNotification(string title, string message, int notifyId, string tag, Bundle extras) { System.Diagnostics.Debug.WriteLine($"{PushNotificationKey.DomainName} - PushNotification - Message {title} : {message}"); NotificationCompat.Builder builder = null; Context context = Android.App.Application.Context; if (CrossPushNotification.SoundUri == null) { CrossPushNotification.SoundUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); } try { if (CrossPushNotification.IconResource == 0) { CrossPushNotification.IconResource = context.ApplicationInfo.Icon; } else { string name = context.Resources.GetResourceName(CrossPushNotification.IconResource); if (name == null) { CrossPushNotification.IconResource = context.ApplicationInfo.Icon; } } } catch (Android.Content.Res.Resources.NotFoundException ex) { CrossPushNotification.IconResource = context.ApplicationInfo.Icon; System.Diagnostics.Debug.WriteLine(ex.ToString()); } Intent resultIntent = context.PackageManager.GetLaunchIntentForPackage(context.PackageName); //Intent resultIntent = new Intent(context, typeof(T)); if (extras != null) { resultIntent.PutExtras(extras); } // Create a PendingIntent; we're only using one PendingIntent (ID = 0): const int pendingIntentId = 0; PendingIntent resultPendingIntent = PendingIntent.GetActivity(context, pendingIntentId, resultIntent, PendingIntentFlags.OneShot | PendingIntentFlags.UpdateCurrent); // Build the notification builder = new NotificationCompat.Builder(context) .SetAutoCancel(true) // dismiss the notification from the notification area when the user clicks on it .SetContentIntent(resultPendingIntent) // start up this activity when the user clicks the intent. .SetContentTitle(title) // Set the title .SetSound(CrossPushNotification.SoundUri) .SetSmallIcon(CrossPushNotification.IconResource) // This is the icon to display .SetContentText(message); // the message to display. if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBean) { // Using BigText notification style to support long message var style = new NotificationCompat.BigTextStyle(); style.BigText(message); builder.SetStyle(style); } NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService); notificationManager.Notify(tag, notifyId, builder.Build()); } } }
using System; using System.IO; using bv.common.Core; using bv.common.Diagnostics; using System.Drawing; namespace bv.common.Configuration { public class BaseSettings { private const int DefaultSqlTimeout = 200; public const string Asterisk = "*"; public static bool DebugOutput { get { return Config.GetBoolSetting("DebugOutput", true); } } public static string DebugLogFile { get { return Config.GetSetting("DebugLogFile", null); } } public static bool TranslationMode { get { return Config.GetBoolSetting("TranslationMode"); } } public static int DebugDetailLevel { get { int level; if (Int32.TryParse(Config.GetSetting("DebugDetailLevel", "0"), out level)) { return level; } return 0; } } public static string ObjectsSchemaPath { get { string path = Config.GetSetting("SchemaPath", "..\\..\\Schema") + "\\Objects\\"; Dbg.Assert(Directory.Exists(path), "objects schema path <{0}> doesn\'t exists", path); return path; } } public static string ConnectionString { get { return Config.GetSetting("SQLConnectionString", "Persist Security Info=False;User ID={0};Password={1};Initial Catalog={2};Data Source={3};Asynchronous Processing=True;"); } } public static int SqlCommandTimeout { get { return Config.GetIntSetting("SqlCommandTimeout", 200); } } public static bool UseDefaultLogin { get { return Config.GetBoolSetting("UseDefaultLogin"); } } public static string DefaultOrganization { get { return Config.GetSetting("DefaultOrganization", null); } } public static string DefaultUser { get { return Config.GetSetting("DefaultUser", null); } } public static string DefaultPassword { get { return Config.GetSetting("DefaultPassword", null); } } public static string SqlServer { get { return Config.GetSetting("SQLServer", "(local)"); } } public static string SqlDatabase { get { return Config.GetSetting("SQLDatabase", "eidss"); } } public static string SqlUser { get { return Config.GetSetting("SQLUser", null); } } public static string SqlPassword { get { return Config.GetSetting("SQLPassword", null); } } public static string InplaceShowDropDown { get { return Config.GetSetting("InplaceShowDropDown", null); } } public static string ShowDropDown { get { return Config.GetSetting("ShowDropDown", null); } } public static int LookupCacheRefreshInterval { get { return Config.GetIntSetting("LookupCacheRefreshInterval", 500); } } public static int LookupCacheIdleRefreshInterval { get { return Config.GetIntSetting("LookupCacheIdleRefreshInterval", 500); } } public static bool ForceMemoryFlush { get { return Config.GetBoolSetting("ForceMemoryFlush", true); } } public static bool ForceFormsDisposing { get { return Config.GetBoolSetting("ForceFormsDisposing", true); } } public static int PagerPageSize { get { return Config.GetIntSetting("PagerPageSize", 50); } } public static int WebBarcodePageWidth { get { return Config.GetIntSetting("WebBarcodePageWidth", 150); } } public static int WebBarcodePageHeight { get { return Config.GetIntSetting("WebBarcodePageHeight", 50); } } public static int PagerPageCount { get { return Config.GetIntSetting("PagerPageCount", 10); } } public static bool DontStartClient { get { return Config.GetBoolSetting("DontStartClient"); } } public static int ConnectionSource { get { return Config.GetIntSetting("ConnectionSource", 0); } } public static int TcpPort { get { return Config.GetIntSetting("TcpPort", 4005); } } //Possible values: Default, ClientID, User private static string s_SystemFontName; public static string SystemFontName { get { if (Utils.Str(s_SystemFontName) == "") { s_SystemFontName = Config.GetSetting("SystemFontName", FontFamily.GenericSansSerif.Name); } return s_SystemFontName; } } private static string s_GGSystemFontName = ""; public static string GGSystemFontName { get { if (Utils.Str(s_GGSystemFontName) == "") { s_GGSystemFontName = Config.GetSetting("GeorgianSystemFontName", "Sylfaen"); } return s_GGSystemFontName; } } private static float s_SystemFontSize; public static float SystemFontSize { get { if (s_SystemFontSize == 0) { string fontSizeStr = Config.GetSetting("SystemFontSize", null); if (fontSizeStr != null) { Single.TryParse(fontSizeStr, out s_SystemFontSize); } } if (s_SystemFontSize == 0) { s_SystemFontSize = (float) (8.25); } return s_SystemFontSize; } } private static float s_GGSystemFontSize; public static float GGSystemFontSize { get { if (s_GGSystemFontSize == 0) { string fontSizeStr = Config.GetSetting("GeorgianSystemFontSize", null); if (fontSizeStr != null) { Single.TryParse(fontSizeStr, out s_GGSystemFontSize); } } if (s_GGSystemFontSize == 0) { s_GGSystemFontSize = (float) (8.25); } return s_GGSystemFontSize; } } public static string DefaultLanguage { get { return Config.GetSetting("DefaultLanguage", "en"); } } public static string BarcodePrinter { get { return Config.GetSetting("BarcodePrinter", null); } } public static string DocumentPrinter { get { return Config.GetSetting("DocumentPrinter", null); } } public static int LookupCacheTimeout { get { return Config.GetIntSetting("LookupTimeout", 300); } } public static bool IgnoreAbsentResources { get { return Config.GetBoolSetting("IgnoreAbsentResources"); } } public static bool ShowClearLookupButton { get { return Config.GetBoolSetting("ShowClearLookupButton", true); } } public static bool ShowClearRepositoryLookupButton { get { return Config.GetBoolSetting("ShowClearRepositoryLookupButton"); } } public static string DetailFormType { get { return Config.GetSetting("DetailFormType", "Normal"); } } public static bool ShowDeleteButtonOnDetailForm { get { return Config.GetBoolSetting("ShowDeleteButtonOnDetailForm"); } } public static bool ShowSaveButtonOnDetailForm { get { return Config.GetBoolSetting("ShowSaveButtonOnDetailForm"); } } public static bool ShowNewButtonOnDetailForm { get { return Config.GetBoolSetting("ShowNewButtonOnDetailForm"); } } public static bool DirectDataAccess { get { return Config.GetBoolSetting("DirectDataAccess", true); } } public static string OneInstanceMethod { get { return Config.GetSetting("OneInstanceMethod"); } } public static bool ShowCaptionOnToolbar { get { return Config.GetBoolSetting("ShowCaptionOnToolbar"); } } public static bool ShowEmptyListOnSearch { get { return Config.GetBoolSetting("ShowEmptyListOnSearch", true); } } public static bool ShowAvrAsterisk { get { return Config.GetBoolSetting("ShowAvrAsterisk", true); } } public static bool UseAvrCache { get { return Config.GetBoolSetting("UseAvrCache", true); } } public static bool PrintMapInVetReports { get { return Config.GetBoolSetting("PrintMapInVetReports", true); } } public static bool ShowDateTimeFormatAsNullText { get { return Config.GetBoolSetting("ShowDateTimeFormatAsNullText", true); } } public static bool ShowSaveDataPrompt { get { return Config.GetBoolSetting("ShowSaveDataPrompt", true); } } public static bool ShowNavigatorInH02Form { get { return Config.GetBoolSetting("ShowNavigatorInH02Form"); } } public static bool ShowBigLayoutWarning { get { return Config.GetBoolSetting("ShowBigLayoutWarning"); } } public static bool AvrMemoryEconomyMode { get { return Config.GetBoolSetting("AvrMemoryEconomyMode"); } } public static bool ThrowExceptionOnError { get { bool fromUnitTest = Utils.IsCalledFromUnitTest(); return Config.GetBoolSetting("ThrowExceptionOnError", fromUnitTest); } } public static bool SaveOnCancel { get { return Config.GetBoolSetting("SaveOnCancel", true); } } public static bool ShowDeletePrompt { get { return Config.GetBoolSetting("ShowDeletePrompt", true); } } public static bool ShowRecordsFromCurrentSiteForNewCase { get { return Config.GetBoolSetting("ShowRecordsFromCurrentSiteForNewCase", true); } } public static bool AutoClickDuplicateSearchButton { get { return Config.GetBoolSetting("AutoClickDuplicateSearchButton", true); } } public static string SkinName { get { return Config.GetSetting("SkinName", "eidss money twins"); } } public static string ServerPath { get { return Config.GetSetting("ServerPath"); } } public static string SkinAssembly { get { return Config.GetSetting("SkinAssembly"); } } public static bool IgnoreTopMaxCount { get { return Config.GetBoolSetting("IgnoreTopMaxCount"); } } public static bool AsSessionTableView { get { return Config.GetBoolSetting("AsSessionTableView"); } } public static string ArchiveConnectionString { get { return Config.GetSetting("ArchiveConnectionString"); } } public static bool WarnIfResourceEmpty { get { return Config.GetBoolSetting("WarnIfResourceEmpty"); } } public static bool LabSimplifiedMode { get { return Config.GetBoolSetting("LabSimplifiedMode"); } } public static string EpiInfoPath { get { return Config.GetSetting("EpiInfoPath"); } } public static int CheckNotificationSeconds { get { return Config.GetIntSetting("CheckNotificationSeconds", 10); } } public static int AutoHideNotificationSeconds { get { return Config.GetIntSetting("AutoHideNotificationSeconds", 1200); } } public static int SelectTopMaxCount { get { return Config.GetIntSetting("SelectTopMaxCount", 10000); } } public static int DefaultDateFilter { get { return Config.GetIntSetting("DefaultDateFilter", 14); } } public static bool ScanFormsMode { get { return Config.GetBoolSetting("ScanFormsMode"); } } public static bool UpdateConnectionInfo { get { return Config.GetBoolSetting("UpdateConnectionInfo", true); } } public static bool PlaySoundForAlerts { get { return Config.GetBoolSetting("PlaySoundForAlerts"); } } public static bool DefaultRegionInSearch { get { return Config.GetBoolSetting("DefaultRegionInSearch", true); } } public static bool RecalcFiltration { get { return Config.GetBoolSetting("RecalcFiltration"); } } public static string AVRServiceHostURL { get { return Config.GetSetting("AVRServiceHostURL","http://localhost:8071/"); } } public static string DefaultMapProject { get { return Config.GetSetting("DefaultMapProject"); } } public static int TicketExpiration { get { return Config.GetIntSetting("TicketExpiration", 30); } } public static int EventLogListenInterval { get { return Config.GetIntSetting("EventLogListenInterval", 500); } } public static int DelayedReplicationPeriod { get { return Config.GetIntSetting("DelayedReplicationPeriod", 60000); } } public static int AvrRowsPerPage { get { return Config.GetIntSetting("AvrRowsPerPage", 20); } } public static bool UseOrganizationInLogin { get { return Config.GetBoolSetting("UseOrganizationInLogin"); } } public static int ListGridPageSize { get { return Config.GetIntSetting("ListGridPageSize", 50); } } public static int PopupGridPageSize { get { return Config.GetIntSetting("PopupGridPageSize", 50); } } public static int DetailGridPageSize { get { return Config.GetIntSetting("DetailGridPageSize", 10); } } public static string AvrExportUtilX86 { get { return Config.GetSetting("AvrExportUtilX86", "eidss.avr.export.x86.exe"); } } public static string AvrExportUtilX64 { get { return Config.GetSetting("AvrExportUtilX64", "eidss.avr.export.x64.exe"); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using System.Threading.Tasks.Dataflow.Internal; using Xunit; namespace System.Threading.Tasks.Dataflow.Tests { public class TransformBlockTests { [Fact] public async Task TestCtor() { var blocks = new[] { new TransformBlock<int, string>(i => i.ToString()), new TransformBlock<int, string>(i => i.ToString(), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }), new TransformBlock<int, string>(i => TaskShim.Run(() => i.ToString()), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }) }; foreach (var block in blocks) { Assert.Equal(expected: 0, actual: block.InputCount); Assert.Equal(expected: 0, actual: block.OutputCount); Assert.False(block.Completion.IsCompleted); } blocks = new[] { new TransformBlock<int, string>(i => i.ToString(), new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) }), new TransformBlock<int, string>(i => TaskShim.Run(() => i.ToString()), new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) }) }; foreach (var block in blocks) { Assert.Equal(expected: 0, actual: block.InputCount); Assert.Equal(expected: 0, actual: block.OutputCount); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => block.Completion); } } [Fact] public void TestArgumentExceptions() { Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>((Func<int, Task<int>>)null)); Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>(i => i, null)); Assert.Throws<ArgumentNullException>(() => new TransformBlock<int, int>(i => TaskShim.Run(() => i), null)); DataflowTestHelpers.TestArgumentsExceptions(new TransformBlock<int, int>(i => i)); } [Fact] public void TestToString() { DataflowTestHelpers.TestToString(nameFormat => nameFormat != null ? new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) : new TransformBlock<int, int>(i => i)); } [Fact] public async Task TestOfferMessage() { var generators = new Func<TransformBlock<int, int>>[] { () => new TransformBlock<int, int>(i => i), () => new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 }), () => new TransformBlock<int, int>(i => TaskShim.Run(() => i), new ExecutionDataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1 }) }; foreach (var generator in generators) { DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator()); var target = generator(); DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target); DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target); target = generator(); await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target); DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target); } } [Fact] public void TestPost() { foreach (bool bounded in DataflowTestHelpers.BooleanValues) foreach (var tb in new[] { new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 }), new TransformBlock<int, int>(i => TaskShim.Run(() => i), new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 })}) { Assert.True(tb.Post(0), "Expected non-completed TransformBlock to accept Post'd message"); tb.Complete(); Assert.False(tb.Post(0), "Expected Complete'd TransformBlock to decline messages"); } } [Fact] public Task TestCompletionTask() { return DataflowTestHelpers.TestCompletionTask(() => new TransformBlock<int, int>(i => i)); } [Fact] public async Task TestLinkToOptions() { const int Messages = 1; foreach (bool append in DataflowTestHelpers.BooleanValues) foreach (var tb in new[] { new TransformBlock<int, int>(i => i), new TransformBlock<int, int>(i => TaskShim.Run(() => i)) }) { var values = new int[Messages]; var targets = new ActionBlock<int>[Messages]; for (int i = 0; i < Messages; i++) { int slot = i; targets[i] = new ActionBlock<int>(item => values[slot] = item); tb.LinkTo(targets[i], new DataflowLinkOptions { MaxMessages = 1, Append = append }); } tb.PostRange(0, Messages); tb.Complete(); await tb.Completion; for (int i = 0; i < Messages; i++) { Assert.Equal( expected: append ? i : Messages - i - 1, actual: values[i]); } } } [Fact] public async Task TestReceives() { for (int test = 0; test < 2; test++) { foreach (var tb in new[] { new TransformBlock<int, int>(i => i * 2), new TransformBlock<int, int>(i => TaskShim.Run(() => i * 2)) }) { tb.PostRange(0, 5); for (int i = 0; i < 5; i++) { Assert.Equal(expected: i * 2, actual: await tb.ReceiveAsync()); } int item; IList<int> items; Assert.False(tb.TryReceive(out item)); Assert.False(tb.TryReceiveAll(out items)); } } } [Fact] public async Task TestCircularLinking() { const int Iters = 200; foreach (bool sync in DataflowTestHelpers.BooleanValues) { var tcs = new TaskCompletionSource<bool>(); Func<int, int> body = i => { if (i >= Iters) tcs.SetResult(true); return i + 1; }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(body) : new TransformBlock<int, int>(i => TaskShim.Run(() => body(i))); using (tb.LinkTo(tb)) { tb.Post(0); await tcs.Task; tb.Complete(); } } } [Fact] public async Task TestProducerConsumer() { foreach (TaskScheduler scheduler in new[] { TaskScheduler.Default, new ConcurrentExclusiveSchedulerPair().ConcurrentScheduler }) foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1, 2 }) foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 }) foreach (int dop in new[] { 1, 2 }) foreach (bool sync in DataflowTestHelpers.BooleanValues) { const int Messages = 100; var options = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity, MaxDegreeOfParallelism = dop, MaxMessagesPerTask = maxMessagesPerTask, TaskScheduler = scheduler }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(i => i, options) : new TransformBlock<int, int>(i => TaskShim.Run(() => i), options); await TaskShim.WhenAll( TaskShim.Run(async delegate { // consumer int i = 0; while (await tb.OutputAvailableAsync()) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); i++; } }), TaskShim.Run(async delegate { // producer for (int i = 0; i < Messages; i++) { await tb.SendAsync(i); } tb.Complete(); })); } } [Fact] public async Task TestMessagePostponement() { const int Excess = 10; foreach (int boundedCapacity in new[] { 1, 3 }) { var options = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity }; foreach (var tb in new[] { new TransformBlock<int, int>(i => i, options), new TransformBlock<int, int>(i => TaskShim.Run(() => i), options) }) { var sendAsync = new Task<bool>[boundedCapacity + Excess]; for (int i = 0; i < boundedCapacity + Excess; i++) { sendAsync[i] = tb.SendAsync(i); } tb.Complete(); for (int i = 0; i < boundedCapacity; i++) { Assert.True(sendAsync[i].IsCompleted); Assert.True(sendAsync[i].Result); } for (int i = 0; i < Excess; i++) { Assert.False(await sendAsync[boundedCapacity + i]); } } } } [Fact] public async Task TestReserveReleaseConsume() { var tb = new TransformBlock<int, int>(i => i * 2); tb.Post(1); await DataflowTestHelpers.TestReserveAndRelease(tb); tb = new TransformBlock<int, int>(i => i * 2); tb.Post(2); await DataflowTestHelpers.TestReserveAndConsume(tb); } [Fact] public async Task TestCountZeroAtCompletion() { var cts = new CancellationTokenSource(); var tb = new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions() { CancellationToken = cts.Token }); tb.Post(1); cts.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion); Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); cts = new CancellationTokenSource(); tb = new TransformBlock<int, int>(i => i); tb.Post(1); ((IDataflowBlock)tb).Fault(new InvalidOperationException()); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => tb.Completion); Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); } [Fact] public void TestInputCount() { foreach (bool sync in DataflowTestHelpers.BooleanValues) { Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2); Func<int, int> body = item => { barrier1.SignalAndWait(); // will test InputCount here barrier2.SignalAndWait(); return item; }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(body) : new TransformBlock<int, int>(i => TaskShim.Run(() => body(i))); for (int iter = 0; iter < 2; iter++) { tb.PostItems(1, 2); for (int i = 1; i >= 0; i--) { barrier1.SignalAndWait(); Assert.Equal(expected: i, actual: tb.InputCount); barrier2.SignalAndWait(); } } } } [Fact] //[OuterLoop] // spins waiting for a condition to be true, though it should happen very quickly public async Task TestCount() { var tb = new TransformBlock<int, int>(i => i); Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); tb.PostRange(1, 11); await TaskShim.Run(() => SpinWait.SpinUntil(() => tb.OutputCount == 10)); for (int i = 10; i > 0; i--) { int item; Assert.True(tb.TryReceive(out item)); Assert.Equal(expected: 11 - i, actual: item); Assert.Equal(expected: i - 1, actual: tb.OutputCount); } } [Fact] public async Task TestChainedSendReceive() { foreach (bool post in DataflowTestHelpers.BooleanValues) foreach (bool sync in DataflowTestHelpers.BooleanValues) { const int Iters = 10; Func<TransformBlock<int, int>> func = sync ? (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => i * 2)) : (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => TaskShim.Run(() => i * 2))); var network = DataflowTestHelpers.Chain<TransformBlock<int, int>, int>(4, func); for (int i = 0; i < Iters; i++) { if (post) { network.Post(i); } else { await network.SendAsync(i); } Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync()); } } } [Fact] public async Task TestSendAllThenReceive() { foreach (bool post in DataflowTestHelpers.BooleanValues) foreach (bool sync in DataflowTestHelpers.BooleanValues) { const int Iters = 10; Func<TransformBlock<int, int>> func = sync ? (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => i * 2)) : (Func<TransformBlock<int, int>>)(() => new TransformBlock<int, int>(i => TaskShim.Run(() => i * 2))); var network = DataflowTestHelpers.Chain<TransformBlock<int, int>, int>(4, func); if (post) { network.PostRange(0, Iters); } else { await TaskShim.WhenAll(from i in Enumerable.Range(0, Iters) select network.SendAsync(i)); } for (int i = 0; i < Iters; i++) { Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync()); } } } [Fact] public async Task TestPrecanceled() { var bb = new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) }); int ignoredValue; IList<int> ignoredValues; IDisposable link = bb.LinkTo(DataflowBlock.NullTarget<int>()); Assert.NotNull(link); link.Dispose(); Assert.False(bb.Post(42)); var t = bb.SendAsync(42); Assert.True(t.IsCompleted); Assert.False(t.Result); Assert.False(bb.TryReceiveAll(out ignoredValues)); Assert.False(bb.TryReceive(out ignoredValue)); Assert.NotNull(bb.Completion); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion); bb.Complete(); // just make sure it doesn't throw } [Fact] public async Task TestExceptions() { var tb1 = new TransformBlock<int, int>((Func<int, int>)(i => { throw new InvalidCastException(); })); var tb2 = new TransformBlock<int, int>((Func<int, Task<int>>)(i => { throw new InvalidProgramException(); })); var tb3 = new TransformBlock<int, int>((Func<int, Task<int>>)(i => TaskShim.Run((Func<int>)(() => { throw new InvalidTimeZoneException(); })))); for (int i = 0; i < 3; i++) { tb1.Post(i); tb2.Post(i); tb3.Post(i); } await Assert.ThrowsAsync<InvalidCastException>(() => tb1.Completion); await Assert.ThrowsAsync<InvalidProgramException>(() => tb2.Completion); await Assert.ThrowsAsync<InvalidTimeZoneException>(() => tb3.Completion); Assert.All(new[] { tb1, tb2, tb3 }, tb => Assert.True(tb.InputCount == 0 && tb.OutputCount == 0)); } [Fact] public async Task TestFaultingAndCancellation() { foreach (bool fault in DataflowTestHelpers.BooleanValues) { var cts = new CancellationTokenSource(); var tb = new TransformBlock<int, int>(i => i, new ExecutionDataflowBlockOptions { CancellationToken = cts.Token }); tb.PostRange(0, 4); Assert.Equal(expected: 0, actual: await tb.ReceiveAsync()); Assert.Equal(expected: 1, actual: await tb.ReceiveAsync()); if (fault) { Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)tb).Fault(null)); ((IDataflowBlock)tb).Fault(new InvalidCastException()); await Assert.ThrowsAsync<InvalidCastException>(() => tb.Completion); } else { cts.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion); } Assert.Equal(expected: 0, actual: tb.InputCount); Assert.Equal(expected: 0, actual: tb.OutputCount); } } [Fact] public async Task TestCancellationExceptionsIgnored() { var t = new TransformBlock<int, int>(i => { if ((i % 2) == 0) throw new OperationCanceledException(); return i; }); t.PostRange(0, 2); t.Complete(); for (int i = 0; i < 2; i++) { if ((i % 2) != 0) { Assert.Equal(expected: i, actual: await t.ReceiveAsync()); } } await t.Completion; } [Fact] public async Task TestNullTasksIgnored() { foreach (int dop in new[] { DataflowBlockOptions.Unbounded, 1, 2 }) { var tb = new TransformBlock<int, int>(i => { if ((i % 2) == 0) return null; return TaskShim.Run(() => i); }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop }); const int Iters = 100; tb.PostRange(0, Iters); tb.Complete(); for (int i = 0; i < Iters; i++) { if ((i % 2) != 0) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); } } await tb.Completion; } } // Verifies that internally, TransformBlock does not get confused // between Func<T, Task<object>> and Func<T, object>. [Fact] public async Task TestCtorOverloading() { Func<object, Task<object>> f = x => TaskShim.FromResult<object>(x); for (int test = 0; test < 2; test++) { TransformBlock<object, object> tf = test == 0 ? new TransformBlock<object, object>(f) : new TransformBlock<object, object>((Func<object, object>)f); var tcs = new TaskCompletionSource<bool>(); ActionBlock<object> a = new ActionBlock<object>(x => { Assert.Equal(expected: test == 1, actual: x is Task<object>); tcs.SetResult(true); }); tf.LinkTo(a); tf.Post(new object()); await tcs.Task; } } [Fact] public async Task TestFaultyLinkedTarget() { var tb = new TransformBlock<int, int>(i => i); tb.LinkTo(new DelegatePropagator<int, int> { OfferMessageDelegate = delegate { throw new InvalidCastException(); } }); tb.Post(42); await Assert.ThrowsAsync<InvalidCastException>(() => tb.Completion); } [Fact] public async Task TestOrdering() { const int iters = 1000; foreach (int mmpt in new[] { DataflowBlockOptions.Unbounded, 1 }) foreach (int dop in new[] { 1, 2, DataflowBlockOptions.Unbounded }) { var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, MaxMessagesPerTask = mmpt }; var tb = new TransformBlock<int, int>(i => i, options); tb.PostRange(0, iters); for (int i = 0; i < iters; i++) { Assert.Equal(expected: i, actual: await tb.ReceiveAsync()); } tb.Complete(); await tb.Completion; } } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyAvOpenhomeOrgTime1 : ICpProxy, IDisposable { void SyncTime(out uint aTrackCount, out uint aDuration, out uint aSeconds); void BeginTime(CpProxy.CallbackAsyncComplete aCallback); void EndTime(IntPtr aAsyncHandle, out uint aTrackCount, out uint aDuration, out uint aSeconds); void SetPropertyTrackCountChanged(System.Action aTrackCountChanged); uint PropertyTrackCount(); void SetPropertyDurationChanged(System.Action aDurationChanged); uint PropertyDuration(); void SetPropertySecondsChanged(System.Action aSecondsChanged); uint PropertySeconds(); } internal class SyncTimeAvOpenhomeOrgTime1 : SyncProxyAction { private CpProxyAvOpenhomeOrgTime1 iService; private uint iTrackCount; private uint iDuration; private uint iSeconds; public SyncTimeAvOpenhomeOrgTime1(CpProxyAvOpenhomeOrgTime1 aProxy) { iService = aProxy; } public uint TrackCount() { return iTrackCount; } public uint Duration() { return iDuration; } public uint Seconds() { return iSeconds; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndTime(aAsyncHandle, out iTrackCount, out iDuration, out iSeconds); } }; /// <summary> /// Proxy for the av.openhome.org:Time:1 UPnP service /// </summary> public class CpProxyAvOpenhomeOrgTime1 : CpProxy, IDisposable, ICpProxyAvOpenhomeOrgTime1 { private OpenHome.Net.Core.Action iActionTime; private PropertyUint iTrackCount; private PropertyUint iDuration; private PropertyUint iSeconds; private System.Action iTrackCountChanged; private System.Action iDurationChanged; private System.Action iSecondsChanged; private Mutex iPropertyLock; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyAvOpenhomeOrgTime1(CpDevice aDevice) : base("av-openhome-org", "Time", 1, aDevice) { OpenHome.Net.Core.Parameter param; iActionTime = new OpenHome.Net.Core.Action("Time"); param = new ParameterUint("TrackCount"); iActionTime.AddOutputParameter(param); param = new ParameterUint("Duration"); iActionTime.AddOutputParameter(param); param = new ParameterUint("Seconds"); iActionTime.AddOutputParameter(param); iTrackCount = new PropertyUint("TrackCount", TrackCountPropertyChanged); AddProperty(iTrackCount); iDuration = new PropertyUint("Duration", DurationPropertyChanged); AddProperty(iDuration); iSeconds = new PropertyUint("Seconds", SecondsPropertyChanged); AddProperty(iSeconds); iPropertyLock = new Mutex(); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aTrackCount"></param> /// <param name="aDuration"></param> /// <param name="aSeconds"></param> public void SyncTime(out uint aTrackCount, out uint aDuration, out uint aSeconds) { SyncTimeAvOpenhomeOrgTime1 sync = new SyncTimeAvOpenhomeOrgTime1(this); BeginTime(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aTrackCount = sync.TrackCount(); aDuration = sync.Duration(); aSeconds = sync.Seconds(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndTime().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginTime(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionTime, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentUint((ParameterUint)iActionTime.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentUint((ParameterUint)iActionTime.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentUint((ParameterUint)iActionTime.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aTrackCount"></param> /// <param name="aDuration"></param> /// <param name="aSeconds"></param> public void EndTime(IntPtr aAsyncHandle, out uint aTrackCount, out uint aDuration, out uint aSeconds) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aTrackCount = Invocation.OutputUint(aAsyncHandle, index++); aDuration = Invocation.OutputUint(aAsyncHandle, index++); aSeconds = Invocation.OutputUint(aAsyncHandle, index++); } /// <summary> /// Set a delegate to be run when the TrackCount state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgTime1 instance will not overlap.</remarks> /// <param name="aTrackCountChanged">The delegate to run when the state variable changes</param> public void SetPropertyTrackCountChanged(System.Action aTrackCountChanged) { lock (iPropertyLock) { iTrackCountChanged = aTrackCountChanged; } } private void TrackCountPropertyChanged() { lock (iPropertyLock) { ReportEvent(iTrackCountChanged); } } /// <summary> /// Set a delegate to be run when the Duration state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgTime1 instance will not overlap.</remarks> /// <param name="aDurationChanged">The delegate to run when the state variable changes</param> public void SetPropertyDurationChanged(System.Action aDurationChanged) { lock (iPropertyLock) { iDurationChanged = aDurationChanged; } } private void DurationPropertyChanged() { lock (iPropertyLock) { ReportEvent(iDurationChanged); } } /// <summary> /// Set a delegate to be run when the Seconds state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgTime1 instance will not overlap.</remarks> /// <param name="aSecondsChanged">The delegate to run when the state variable changes</param> public void SetPropertySecondsChanged(System.Action aSecondsChanged) { lock (iPropertyLock) { iSecondsChanged = aSecondsChanged; } } private void SecondsPropertyChanged() { lock (iPropertyLock) { ReportEvent(iSecondsChanged); } } /// <summary> /// Query the value of the TrackCount property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the TrackCount property</returns> public uint PropertyTrackCount() { PropertyReadLock(); uint val; try { val = iTrackCount.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the Duration property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the Duration property</returns> public uint PropertyDuration() { PropertyReadLock(); uint val; try { val = iDuration.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the Seconds property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the Seconds property</returns> public uint PropertySeconds() { PropertyReadLock(); uint val; try { val = iSeconds.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionTime.Dispose(); iTrackCount.Dispose(); iDuration.Dispose(); iSeconds.Dispose(); } } }
using System; using System.Windows.Forms; using System.Collections; using System.Drawing; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// /// </summary> public class GeneralWLSearch : Search { //Search parameters private string m_PoS; //Part of Speech private bool m_IsRootOnly; private bool m_IsIdenticalVowelsInWord; private bool m_IsIdenticalVowelsInRoot; private bool m_BrowseView; private string m_WordCVShape; private string m_RootCVShape; private int m_MinSyllables; private int m_MaxSyllables; private SearchOptions.Position m_WordPosition; private SearchOptions.Position m_RootPosition; private string m_Title; //Search title private Settings m_Settings; //Application Settings private PSTable m_PSTable; //Parts of Speech entry private Font m_DefaultFont; //Default Font private Color m_HighlightColor; //Highlight Color //private const string kTitle = "General Search"; //private const string kBrowseTitle = kTitle + " Browse View"; public GeneralWLSearch(int number, Settings s) : base(number, SearchDefinition.kGeneralWL) { m_IsRootOnly = false; m_IsIdenticalVowelsInWord = false; m_IsIdenticalVowelsInRoot = false; m_BrowseView = false; m_WordCVShape = ""; m_RootCVShape = ""; m_MinSyllables = 0; m_MaxSyllables = 0; m_WordPosition = SearchOptions.Position.Any; m_RootPosition = SearchOptions.Position.Any; m_Settings = s; //m_Title = "General Search"; m_Title = m_Settings.LocalizationTable.GetMessage("GeneralSearchT"); if (m_Title == "") m_Title = "General Search"; m_PSTable = m_Settings.PSTable; m_DefaultFont = m_Settings.OptionSettings.GetDefaultFont(); m_HighlightColor = m_Settings.OptionSettings.HighlightColor; } public string PoS { get { return m_PoS; } set { m_PoS = value; } } public bool IsRootOnly { get {return m_IsRootOnly;} set { m_IsRootOnly = value; } } public bool IsIdenticalVowelsInWord { get {return m_IsIdenticalVowelsInWord;} set { m_IsIdenticalVowelsInWord = value; } } public bool IsIdenticalVowelsInRoot { get {return m_IsIdenticalVowelsInRoot;} set { m_IsIdenticalVowelsInRoot = value; } } public bool BrowseView { get { return m_BrowseView; } set { m_BrowseView = value; } } public string WordCVShape { get {return m_WordCVShape;} set { m_WordCVShape = value; } } public string RootCVShape { get {return m_RootCVShape;} set { m_RootCVShape = value; } } public int MinSyllables { get { return m_MinSyllables; } set { m_MinSyllables = value; } } public int MaxSyllables { get { return m_MaxSyllables; } set { m_MaxSyllables = value; } } public SearchOptions.Position WordPosition { get {return m_WordPosition;} set { m_WordPosition = value; } } public SearchOptions.Position RootPosition { get {return m_RootPosition;} set { m_RootPosition = value; } } public string Title { get {return m_Title;} } public PSTable PSTable { get {return m_PSTable;} } public Color HighlightColor { get { return m_HighlightColor; } } public Font DefaultFont { get { return m_DefaultFont; } } public bool SetupSearch() { bool flag = false; FormSearchOptions form = new FormSearchOptions(this.PSTable, true, true, m_Settings.LocalizationTable); form.Text = m_Settings.LocalizationTable.GetMessage("GeneralSearchT"); if (form.Text == "") form.Text = "General Search"; DialogResult dr = form.ShowDialog(); if ( dr == DialogResult.OK ) { if (form.PSTE != null) this.PoS = form.PSTE.Code; this.IsRootOnly = form.IsRootOnly; this.IsIdenticalVowelsInWord = form.IsIdenticalVowelsInWord; this.IsIdenticalVowelsInRoot = form.IsIdenticalVowelsInRoot; this.WordCVShape = form.WordCVShape; this.RootCVShape = form.RootCVShape; this.MinSyllables = form.MinSyllables; this.MaxSyllables = form.MaxSyllables; this.WordPosition = form.WordPosition; this.BrowseView = form.IsBrowseView; SearchDefinition sd = new SearchDefinition(SearchDefinition.kGeneralWL); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; if (this.PoS != "") { sdp = new SearchDefinitionParm(SearchOptions.kPS, this.PoS); sd.AddSearchParm(sdp); } if (this.IsRootOnly) { sdp = new SearchDefinitionParm(SearchOptions.kRootsOnly); sd.AddSearchParm(sdp); } if (this.IsIdenticalVowelsInWord) { sdp = new SearchDefinitionParm(SearchOptions.kSameVowelsInWord); sd.AddSearchParm(sdp); } if (this.IsIdenticalVowelsInRoot) { sdp = new SearchDefinitionParm(SearchOptions.kSameVowelsInRoot); } if (this.WordCVShape != "") { sdp = new SearchDefinitionParm(SearchOptions.kWordCVShape,this.WordCVShape); sd.AddSearchParm(sdp); } if (this.RootCVShape != "") { sdp = new SearchDefinitionParm(SearchOptions.kRootCVShape,this.RootCVShape); sd.AddSearchParm(sdp); } if (this.MinSyllables > 0) { sdp = new SearchDefinitionParm(SearchOptions.kMinSyllables, this.MinSyllables.ToString().Trim()); sd.AddSearchParm(sdp); } if (this.m_MaxSyllables > 0) { sdp = new SearchDefinitionParm(SearchOptions.kMaxSyllales, this.m_MaxSyllables.ToString().Trim()); sd.AddSearchParm(sdp); } if (this.WordPosition != SearchOptions.Position.Any) { sdp = new SearchDefinitionParm(SearchOptions.kWordPosition, this.WordPosition.ToString()); sd.AddSearchParm(sdp); } if (this.RootPosition != SearchOptions.Position.Any) { sdp = new SearchDefinitionParm(SearchOptions.kRootPosition, this.RootPosition.ToString()); sd.AddSearchParm(sdp); } if (this.BrowseView) { sdp = new SearchDefinitionParm(SearchOptions.kBrowseView); sd.AddSearchParm(sdp); } this.SearchDefinition = sd; flag = true; } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = true; this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); string str = ""; strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; //strText += this.SearchCount.ToString() + " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += this.SearchCount.ToString() + Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public GeneralWLSearch ExecuteGeneralSearch(WordList wl) { int nCount = 0; string strResult = wl.GetDisplayHeadings() + Environment.NewLine; SearchOptions so = new SearchOptions(this.PSTable); so = this.SearchDefinition.MakeSearchOptions(so); Word wrd = null; int nWord = wl.WordCount(); for (int i = 0; i < nWord; i++) { wrd = wl.GetWord(i); if (so != null) { if (so.MatchesWord(wrd)) { nCount++; strResult += wl.GetDisplayLineForWord(i) + Environment.NewLine; } } } if (nCount > 0) { this.SearchResults = strResult; this.SearchCount = nCount; } else { //this.SearchResults = "***No Results***"; this.SearchResults = m_Settings.LocalizationTable.GetMessage("Search1"); if (this.SearchResults == "") this.SearchResults = "***No Results***"; this.SearchCount = 0; } return this; } public GeneralWLSearch BrowseGeneralSearch(WordList wl) { int nCount = 0; string str = ""; ArrayList al = null; Color clr = this.HighlightColor; Font fnt = this.DefaultFont; Word wrd = null; ; FormBrowse form = new FormBrowse(); str = m_Settings.LocalizationTable.GetMessage("SearchB"); if (str == "") str = "Browse View"; form.Text = this.Title + " - " + str; al = wl.GetDisplayHeadingsAsArray(); form.AddColHeaders(al, clr, fnt); SearchOptions so = new SearchOptions(m_Settings.PSTable); so = this.SearchDefinition.MakeSearchOptions(so); for (int i = 0; i < wl.WordCount(); i++) { wrd = wl.GetWord(i); if (so != null) { if (so.MatchesWord(wrd)) { nCount++; al = wrd.GetWordInfoAsArray(); form.AddRow(al); } } } //form.Text += " - " + nCount.ToString() + " entries"; str = m_Settings.LocalizationTable.GetMessage("Search3"); if (str == "") str = "entries"; form.Text += " - " + nCount.ToString() + Constants.Space + str; form.Show(); return this; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: SccStamp.cs 618 2009-05-30 00:18:30Z azizatif $")] namespace Elmah { #region Imports using System; using System.Globalization; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Collections.Generic; using Mannex; #endregion /// <summary> /// Represents a source code control (SCC) stamp and its components. /// </summary> [ Serializable ] public sealed class SccStamp { private readonly string _id; private readonly string _author; private readonly string _fileName; private readonly int _revision; private readonly DateTime _lastChanged; private static readonly Regex _regex; static SccStamp() { // // Expression to help parse: // // STAMP := "$Id:" FILENAME REVISION DATE TIME "Z" USERNAME "$" // DATE := 4-DIGIT-YEAR "-" 2-DIGIT-MONTH "-" 2-DIGIT-DAY // TIME := HH ":" MM ":" SS // var escapedNonFileNameChars = Regex.Escape(new string(Path.GetInvalidFileNameChars())); _regex = new Regex( @"\$ id: \s* (?<f>[^" + escapedNonFileNameChars + @"]+) \s+ # FILENAME (?<r>[0-9]+) \s+ # REVISION ((?<y>[0-9]{4})-(?<mo>[0-9]{2})-(?<d>[0-9]{2})) \s+ # DATE ((?<h>[0-9]{2})\:(?<mi>[0-9]{2})\:(?<s>[0-9]{2})Z) \s+ # TIME (UTC) (?<a>\w+) # AUTHOR", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled); } /// <summary> /// Initializes an <see cref="SccStamp"/> instance given a SCC stamp /// ID. The ID is expected to be in the format popularized by CVS /// and SVN. /// </summary> public SccStamp(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); var match = _regex.Match(id); if (!match.Success) throw new ArgumentException(null, "id"); _id = id; var groups = match.Groups; _fileName = groups["f"].Value; _revision = int.Parse(groups["r"].Value); _author = groups["a"].Value; var year = int.Parse(groups["y"].Value); var month = int.Parse(groups["mo"].Value); var day = int.Parse(groups["d"].Value); var hour = int.Parse(groups["h"].Value); var minute = int.Parse(groups["mi"].Value); var second = int.Parse(groups["s"].Value); _lastChanged = new DateTime(year, month, day, hour, minute, second).ToLocalTime(); } /// <summary> /// Gets the original SCC stamp ID. /// </summary> public string Id { get { return _id; } } /// <summary> /// Gets the author component of the SCC stamp ID. /// </summary> public string Author { get { return _author; } } /// <summary> /// Gets the file name component of the SCC stamp ID. /// </summary> public string FileName { get { return _fileName; } } /// <summary> /// Gets the revision number component of the SCC stamp ID. /// </summary> public int Revision { get { return _revision; } } /// <summary> /// Gets the last modification time component of the SCC stamp ID. /// </summary> public DateTime LastChanged { get { return _lastChanged; } } /// <summary> /// Gets the last modification time, in coordinated universal time /// (UTC), component of the SCC stamp ID in local time. /// </summary> public DateTime LastChangedUtc { get { return _lastChanged.ToUniversalTime(); } } public override string ToString() { return Id; } /// <summary> /// Finds and builds an array of <see cref="SccStamp"/> instances /// from all the <see cref="SccAttribute"/> attributes applied to /// the given assembly. /// </summary> public static SccStamp[] FindAll(Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); var attributes = (SccAttribute[]) Attribute.GetCustomAttributes(assembly, typeof(SccAttribute), false); if (attributes.Length == 0) return new SccStamp[0]; var list = new List<SccStamp>(attributes.Length); foreach (var attribute in attributes) { var id = attribute.Id.Trim(); if (id.Length > 0 && string.Compare("$Id" + /* IMPORTANT! */ "$", id, true, CultureInfo.InvariantCulture) != 0) list.Add(new SccStamp(id)); } return list.ToArray(); } /// <summary> /// Finds the latest SCC stamp for an assembly. The latest stamp is /// the one with the highest revision number. /// </summary> public static SccStamp FindLatest(Assembly assembly) { return FindLatest(FindAll(assembly)); } /// <summary> /// Finds the latest stamp among an array of <see cref="SccStamp"/> /// objects. The latest stamp is the one with the highest revision /// number. /// </summary> public static SccStamp FindLatest(SccStamp[] stamps) { if (stamps == null) throw new ArgumentNullException("stamps"); if (stamps.Length == 0) return null; stamps = stamps.CloneObject(); SortByRevision(stamps, /* descending */ true); return stamps[0]; } /// <summary> /// Sorts an array of <see cref="SccStamp"/> objects by their /// revision numbers in ascending order. /// </summary> public static void SortByRevision(SccStamp[] stamps) { SortByRevision(stamps, false); } /// <summary> /// Sorts an array of <see cref="SccStamp"/> objects by their /// revision numbers in ascending or descending order. /// </summary> public static void SortByRevision(SccStamp[] stamps, bool descending) { Comparison<SccStamp> comparer = (lhs, rhs) => lhs.Revision.CompareTo(rhs.Revision); Array.Sort(stamps, descending ? ((lhs, rhs) => -comparer(lhs, rhs)) : comparer); } } }
/* * Copyright (C) 2007-2014 ARGUS TV * http://www.argus-tv.com * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using ArgusTV.DataContracts; namespace ArgusTV.ServiceProxy { /// <summary> /// Core service proxy. /// </summary> public partial class CoreServiceProxy : RestProxyBase { /// <summary> /// Constructs a channel to the service. /// </summary> internal CoreServiceProxy() : base("Core") { _listenerClient = CreateHttpClient(); _listenerClient.Timeout = TimeSpan.FromDays(1); } #region Initialization /// <summary> /// Ping ARGUS TV server and test the API version. /// </summary> /// <param name="requestedApiVersion">The API version the client needs, pass in Constants.CurrentApiVersion.</param> /// <returns>0 if client and server are compatible, -1 if the client is too old and +1 if the client is newer than the server.</returns> public async Task<int> Ping(int requestedApiVersion) { var request = NewRequest(HttpMethod.Get, "Ping/{0}", requestedApiVersion); var result = await ExecuteAsync<PingResult>(request, logError: false).ConfigureAwait(false); return result.Result; } private class PingResult { public int Result { get; set; } } /// <summary> /// Get the server's MAC address(es). These can be stored on the client after a successful /// connect and later used to re-connect with wake-on-lan. /// </summary> /// <returns>An array containing one or more MAC addresses in HEX string format (e.g. "A1B2C3D4E5F6").</returns> public async Task<IEnumerable<string>> GetMacAddresses() { var request = NewRequest(HttpMethod.Get, "GetMacAddresses"); return await ExecuteAsync<List<string>>(request).ConfigureAwait(false); } /// <summary> /// Check to see if there is a newer version of ARGUS TV available online. /// </summary> /// <returns>A NewVersionInfo object if there is a newer version available, null if the current installation is up-to-date.</returns> public async Task<NewVersionInfo> IsNewerVersionAvailable() { var request = NewRequest(HttpMethod.Get, "IsNewerVersionAvailable"); return await ExecuteAsync<NewVersionInfo>(request).ConfigureAwait(false); } /// <summary> /// Get the server's version as a string. /// </summary> /// <returns>Returns the ARGUS TV product version, for display purposes. Don't use this to do version checking!</returns> public async Task<string> GetServerVersion() { var request = NewRequest(HttpMethod.Get, "Version"); var result = await ExecuteAsync<GetVersionResult>(request).ConfigureAwait(false); return result.Version; } private class GetVersionResult { public string Version { get; set; } } #endregion #region Event Listeners private HttpClient _listenerClient; /// <summary> /// Subscribe your client to a group of ARGUS TV events using a polling mechanism. /// </summary> /// <param name="uniqueClientId">The unique ID (e.g. your DNS hostname combined with a constant GUID) to identify your client.</param> /// <param name="eventGroups">The event group(s) to subscribe to (flags can be OR'd).</param> public async Task SubscribeServiceEvents(string uniqueClientId, EventGroup eventGroups) { var request = NewRequest(HttpMethod.Post, "ServiceEvents/{0}/Subscribe/{1}", uniqueClientId, eventGroups); await ExecuteAsync(request).ConfigureAwait(false); } /// <summary> /// Unsubscribe your client from all ARGUS TV events. /// </summary> /// <param name="uniqueClientId">The unique ID (e.g. your DNS hostname combined with a constant GUID) to identify your client.</param> public async Task UnsubscribeServiceEvents(string uniqueClientId) { var request = NewRequest(HttpMethod.Post, "ServiceEvents/{0}/Unsubscribe", uniqueClientId); await ExecuteAsync(request).ConfigureAwait(false); } /// <summary> /// Get all queued ARGUS TV events for your client. Call this every X seconds to get informed at a regular interval about what happened. /// </summary> /// <param name="uniqueClientId">The unique ID (e.g. your DNS hostname combined with a constant GUID) to identify your client.</param> /// <param name="cancellationToken">The cancellation token to potentially abort the request (or CancellationToken.None).</param> /// <param name="timeoutSeconds">The maximum timeout of the request (default is 5 minutes).</param> /// <returns>Zero or more service events, or null in case your subscription has expired.</returns> public async Task<List<ServiceEvent>> GetServiceEvents(string uniqueClientId, CancellationToken cancellationToken, int timeoutSeconds = 300) { var request = NewRequest(HttpMethod.Get, "ServiceEvents/{0}/{1}", uniqueClientId, timeoutSeconds); // By default return an empty list (e.g. in case of a timeout or abort), the client will simply need to call this again. GetServiceEventsResult result = new GetServiceEventsResult() { Events = new List<ServiceEvent>() }; #if DOTNET4 using (var timeoutCancellationSource = new CancellationTokenSource()) #else using (var timeoutCancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(Math.Max(timeoutSeconds, 30)))) #endif using (var linkedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationSource.Token)) { #if DOTNET4 Task.Factory.StartNew(() => { cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(Math.Max(timeoutSeconds, 30))); timeoutCancellationSource.Cancel(); }).ConfigureAwait(false); #endif try { using (var response = await _listenerClient.SendAsync(request, linkedCancellationSource.Token)) { result = await DeserializeResponseContentAsync<GetServiceEventsResult>(response); } } catch (AggregateException ex) { if (IsConnectionError(ex.InnerException)) { throw new ArgusTVNotFoundException(ex.InnerException.InnerException.Message); } // Check if we're dealing with either a timeout or an explicit cancellation (same exception in both cases). if (!(ex.InnerException is TaskCanceledException)) { throw; } } } if (result == null || result.Expired) { return null; } return result.Events; } private class GetServiceEventsResult { public bool Expired { get; set; } public List<ServiceEvent> Events { get; set; } } #endregion #region Power Management /// <summary> /// Tell the server we'd like to keep it alive for a little longer. A client /// should call this method every two minutes or so to keep the server from /// entering standby (if it is configured to do so). /// </summary> public void KeepServerAlive() { var request = NewRequest(HttpMethod.Post, "KeepServerAlive"); ExecuteAsync(request).ConfigureAwait(false); // no need to await this, we send the keep-alive fully async } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.GrainDirectory; using Orleans.Providers; using Orleans.Runtime.Configuration; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.Placement; using Orleans.Runtime.Scheduler; using Orleans.Storage; namespace Orleans.Runtime { internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener { /// <summary> /// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected. /// </summary> [Serializable] internal class DuplicateActivationException : Exception { public ActivationAddress ActivationToUse { get; private set; } public SiloAddress PrimaryDirectoryForGrain { get; private set; } // for diagnostics only! public DuplicateActivationException() : base("DuplicateActivationException") { } public DuplicateActivationException(string msg) : base(msg) { } public DuplicateActivationException(string message, Exception innerException) : base(message, innerException) { } public DuplicateActivationException(ActivationAddress activationToUse) : base("DuplicateActivationException") { ActivationToUse = activationToUse; } public DuplicateActivationException(ActivationAddress activationToUse, SiloAddress primaryDirectoryForGrain) : base("DuplicateActivationException") { ActivationToUse = activationToUse; PrimaryDirectoryForGrain = primaryDirectoryForGrain; } #if !NETSTANDARD // Implementation of exception serialization with custom properties according to: // http://stackoverflow.com/questions/94488/what-is-the-correct-way-to-make-a-custom-net-exception-serializable protected DuplicateActivationException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info != null) { ActivationToUse = (ActivationAddress) info.GetValue("ActivationToUse", typeof (ActivationAddress)); PrimaryDirectoryForGrain = (SiloAddress) info.GetValue("PrimaryDirectoryForGrain", typeof (SiloAddress)); } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info != null) { info.AddValue("ActivationToUse", ActivationToUse, typeof (ActivationAddress)); info.AddValue("PrimaryDirectoryForGrain", PrimaryDirectoryForGrain, typeof (SiloAddress)); } // MUST call through to the base class to let it save its own state base.GetObjectData(info, context); } #endif } [Serializable] internal class NonExistentActivationException : Exception { public ActivationAddress NonExistentActivation { get; private set; } public bool IsStatelessWorker { get; private set; } public NonExistentActivationException() : base("NonExistentActivationException") { } public NonExistentActivationException(string msg) : base(msg) { } public NonExistentActivationException(string message, Exception innerException) : base(message, innerException) { } public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker) : base(msg) { NonExistentActivation = nonExistentActivation; IsStatelessWorker = isStatelessWorker; } #if !NETSTANDARD protected NonExistentActivationException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info != null) { NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress)); IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool)); } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info != null) { info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress)); info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool)); } // MUST call through to the base class to let it save its own state base.GetObjectData(info, context); } #endif } public GrainTypeManager GrainTypeManager { get; private set; } public SiloAddress LocalSilo { get; private set; } internal ISiloStatusOracle SiloStatusOracle { get; set; } internal readonly ActivationCollector ActivationCollector; private readonly ILocalGrainDirectory directory; private readonly OrleansTaskScheduler scheduler; private readonly ActivationDirectory activations; private IStorageProviderManager storageProviderManager; private Dispatcher dispatcher; private readonly Logger logger; private int collectionNumber; private int destroyActivationsNumber; private IDisposable gcTimer; private readonly GlobalConfiguration config; private readonly string localSiloName; private readonly CounterStatistic activationsCreated; private readonly CounterStatistic activationsDestroyed; private readonly CounterStatistic activationsFailedToActivate; private readonly IntValueStatistic inProcessRequests; private readonly CounterStatistic collectionCounter; private readonly GrainCreator grainCreator; internal Catalog( GrainId grainId, SiloAddress silo, string siloName, ILocalGrainDirectory grainDirectory, GrainTypeManager typeManager, OrleansTaskScheduler scheduler, ActivationDirectory activationDirectory, ClusterConfiguration config, GrainCreator grainCreator, out Action<Dispatcher> setDispatcher) : base(grainId, silo) { LocalSilo = silo; localSiloName = siloName; directory = grainDirectory; activations = activationDirectory; this.scheduler = scheduler; GrainTypeManager = typeManager; collectionNumber = 0; destroyActivationsNumber = 0; this.grainCreator = grainCreator; logger = LogManager.GetLogger("Catalog", Runtime.LoggerType.Runtime); this.config = config.Globals; setDispatcher = d => dispatcher = d; ActivationCollector = new ActivationCollector(config); GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false); IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count); activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED); activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED); activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE); collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS); inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () => { long counter = 0; lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; counter += data.GetRequestCount(); } } return counter; }); } internal void SetStorageManager(IStorageProviderManager storageManager) { storageProviderManager = storageManager; } internal void Start() { if (gcTimer != null) gcTimer.Dispose(); var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum, "Catalog.GCTimer"); t.Start(); gcTimer = t; } private Task OnTimer(object _) { return CollectActivationsImpl(true); } public Task CollectActivations(TimeSpan ageLimit) { return CollectActivationsImpl(false, ageLimit); } private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan)) { var watch = new Stopwatch(); watch.Start(); var number = Interlocked.Increment(ref collectionNumber); long memBefore = GC.GetTotalMemory(false) / (1024 * 1024); logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.", number, memBefore, activations.Count, ActivationCollector.ToString()); List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit); collectionCounter.Increment(); var count = 0; if (list != null && list.Count > 0) { count = list.Count; if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId)); await DeactivateActivationsFromCollector(list); } long memAfter = GC.GetTotalMemory(false) / (1024 * 1024); watch.Stop(); logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.", number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed); } public List<Tuple<GrainId, string, int>> GetGrainStatistics() { var counts = new Dictionary<string, Dictionary<GrainId, int>>(); lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; if (data == null || data.GrainInstance == null) continue; // TODO: generic type expansion var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType); Dictionary<GrainId, int> grains; int n; if (!counts.TryGetValue(grainTypeName, out grains)) { counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } }); } else if (!grains.TryGetValue(data.Grain, out n)) grains[data.Grain] = 1; else grains[data.Grain] = n + 1; } } return counts .SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value))) .ToList(); } public List<DetailedGrainStatistic> GetDetailedGrainStatistics(string[] types=null) { var stats = new List<DetailedGrainStatistic>(); lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; if (data == null || data.GrainInstance == null) continue; if (types==null || types.Contains(TypeUtils.GetFullName(data.GrainInstanceType))) { stats.Add(new DetailedGrainStatistic() { GrainType = TypeUtils.GetFullName(data.GrainInstanceType), GrainIdentity = data.Grain, SiloAddress = data.Silo, Category = data.Grain.Category.ToString() }); } } } return stats; } public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics() { return activations.GetSimpleGrainStatistics(); } public DetailedGrainReport GetDetailedGrainReport(GrainId grain) { var report = new DetailedGrainReport { Grain = grain, SiloAddress = LocalSilo, SiloName = localSiloName, LocalCacheActivationAddresses = directory.GetLocalCacheData(grain), LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses, PrimaryForGrain = directory.GetPrimaryForGrain(grain) }; try { PlacementStrategy unused; MultiClusterRegistrationStrategy unusedActivationStrategy; string grainClassName; GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused, out unusedActivationStrategy); report.GrainClassTypeName = grainClassName; } catch (Exception exc) { report.GrainClassTypeName = exc.ToString(); } List<ActivationData> acts = activations.FindTargets(grain); report.LocalActivations = acts != null ? acts.Select(activationData => activationData.ToDetailedString()).ToList() : new List<string>(); return report; } #region MessageTargets /// <summary> /// Register a new object to which messages can be delivered with the local lookup table and scheduler. /// </summary> /// <param name="activation"></param> public void RegisterMessageTarget(ActivationData activation) { var context = new SchedulingContext(activation); scheduler.RegisterWorkContext(context); activations.RecordNewTarget(activation); activationsCreated.Increment(); } /// <summary> /// Unregister message target and stop delivering messages to it /// </summary> /// <param name="activation"></param> public void UnregisterMessageTarget(ActivationData activation) { activations.RemoveTarget(activation); // this should be removed once we've refactored the deactivation code path. For now safe to keep. ActivationCollector.TryCancelCollection(activation); activationsDestroyed.Increment(); scheduler.UnregisterWorkContext(new SchedulingContext(activation)); if (activation.GrainInstance == null) return; var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType); activations.DecrementGrainCounter(grainTypeName); activation.SetGrainInstance(null); } /// <summary> /// FOR TESTING PURPOSES ONLY!! /// </summary> /// <param name="grain"></param> internal int UnregisterGrainForTesting(GrainId grain) { var acts = activations.FindTargets(grain); if (acts == null) return 0; int numActsBefore = acts.Count; foreach (var act in acts) UnregisterMessageTarget(act); return numActsBefore; } #endregion #region Grains internal bool CanInterleave(ActivationId running, Message message) { ActivationData target; GrainTypeData data; return TryGetActivationData(running, out target) && target.GrainInstance != null && GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) && (data.IsReentrant || data.MayInterleave((InvokeMethodRequest)message.BodyObject)); } public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null) { GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments); } #endregion #region Activations public int ActivationCount { get { return activations.Count; } } /// <summary> /// If activation already exists, use it /// Otherwise, create an activation of an existing grain by reading its state. /// Return immediately using a dummy that will queue messages. /// Concurrently start creating and initializing the real activation and replace it when it is ready. /// </summary> /// <param name="address">Grain's activation address</param> /// <param name="newPlacement">Creation of new activation was requested by the placement director.</param> /// <param name="grainType">The type of grain to be activated or created</param> /// <param name="genericArguments">Specific generic type of grain to be activated or created</param> /// <param name="requestContextData">Request context data.</param> /// <param name="activatedPromise"></param> /// <returns></returns> public ActivationData GetOrCreateActivation( ActivationAddress address, bool newPlacement, string grainType, string genericArguments, Dictionary<string, object> requestContextData, out Task activatedPromise) { ActivationData result; activatedPromise = TaskDone.Done; PlacementStrategy placement; lock (activations) { if (TryGetActivationData(address.Activation, out result)) { return result; } int typeCode = address.Grain.GetTypeCode(); string actualGrainType = null; MultiClusterRegistrationStrategy activationStrategy; if (typeCode != 0) { GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy, genericArguments); } else { // special case for Membership grain. placement = SystemPlacement.Singleton; activationStrategy = ClusterLocalRegistration.Singleton; } if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating()) { // create a dummy activation that will queue up messages until the real data arrives if (string.IsNullOrEmpty(grainType)) { grainType = actualGrainType; } // We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory. result = new ActivationData( address, genericArguments, placement, activationStrategy, ActivationCollector, config.Application.GetCollectionAgeLimit(grainType)); RegisterMessageTarget(result); } } // End lock // Did not find and did not start placing new if (result == null) { var msg = String.Format("Non-existent activation: {0}, grain type: {1}.", address.ToFullString(), grainType); if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment(); throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement); } SetupActivationInstance(result, grainType, genericArguments); activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData); return result; } private void SetupActivationInstance(ActivationData result, string grainType, string genericArguments) { lock (result) { if (result.GrainInstance == null) { CreateGrainInstance(grainType, result, genericArguments); } } } private async Task InitActivation(ActivationData activation, string grainType, string genericArguments, Dictionary<string, object> requestContextData) { // We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly) // the operations required to turn the "dummy" activation into a real activation ActivationAddress address = activation.Address; int initStage = 0; // A chain of promises that will have to complete in order to complete the activation // Register with the grain directory, register with the store if necessary and call the Activate method on the new activation. try { initStage = 1; await RegisterActivationInGrainDirectoryAndValidate(activation); initStage = 2; await SetupActivationState(activation, String.IsNullOrEmpty(genericArguments) ? grainType : $"{grainType}[{genericArguments}]"); initStage = 3; await InvokeActivate(activation, requestContextData); ActivationCollector.ScheduleCollection(activation); // Success!! Log the result, and start processing messages if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address); } catch (Exception ex) { lock (activation) { activation.SetState(ActivationState.Invalid); try { UnregisterMessageTarget(activation); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc); } switch (initStage) { case 1: // failed to RegisterActivationInGrainDirectory ActivationAddress target = null; Exception dupExc; // Failure!! Could it be that this grain uses single activation placement, and there already was an activation? if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc)) { target = ((DuplicateActivationException) dupExc).ActivationToUse; CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS) .Increment(); } activation.ForwardingAddress = target; if (target != null) { var primary = ((DuplicateActivationException)dupExc).PrimaryDirectoryForGrain; // If this was a duplicate, it's not an error, just a race. // Forward on all of the pending messages, and then forget about this activation. string logMsg = String.Format("Tried to create a duplicate activation {0}, but we'll use {1} instead. " + "GrainInstanceType is {2}. " + "{3}" + "Full activation address is {4}. We have {5} messages to forward.", address, target, activation.GrainInstanceType, primary != null ? "Primary Directory partition for this grain is " + primary + ". " : String.Empty, address.ToFullString(), activation.WaitingCount); if (activation.IsUsingGrainDirectory) { logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg); } else { if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_DuplicateActivation, logMsg); } RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex); } else { logger.Warn(ErrorCode.Runtime_Error_100064, String.Format("Failed to RegisterActivationInGrainDirectory for {0}.", activation), ex); // Need to undo the registration we just did earlier if (activation.IsUsingGrainDirectory) { scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force), SchedulingContext).Ignore(); } RerouteAllQueuedMessages(activation, null, "Failed RegisterActivationInGrainDirectory", ex); } break; case 2: // failed to setup persistent state logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState, String.Format("Failed to SetupActivationState for {0}.", activation), ex); // Need to undo the registration we just did earlier if (activation.IsUsingGrainDirectory) { scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force), SchedulingContext).Ignore(); } RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex); break; case 3: // failed to InvokeActivate logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate, String.Format("Failed to InvokeActivate for {0}.", activation), ex); // Need to undo the registration we just did earlier if (activation.IsUsingGrainDirectory) { scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force), SchedulingContext).Ignore(); } RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex); break; } } throw; } } /// <summary> /// Perform just the prompt, local part of creating an activation object /// Caller is responsible for registering locally, registering with store and calling its activate routine /// </summary> /// <param name="grainTypeName"></param> /// <param name="data"></param> /// <param name="genericArguments"></param> /// <returns></returns> private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments) { string grainClassName; if (!GrainTypeManager.TryGetPrimaryImplementation(grainTypeName, out grainClassName)) { // Lookup from grain type code var typeCode = data.Grain.GetTypeCode(); if (typeCode != 0) { PlacementStrategy unused; MultiClusterRegistrationStrategy unusedActivationStrategy; GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments); } else { grainClassName = grainTypeName; } } GrainTypeData grainTypeData = GrainTypeManager[grainClassName]; //Get the grain's type Type grainType = grainTypeData.Type; //Gets the type for the grain's state Type stateObjectType = grainTypeData.StateObjectType; lock (data) { Grain grain; //Create a new instance of a stateless grain if (stateObjectType == null) { //Create a new instance of the given grain type grain = grainCreator.CreateGrainInstance(grainType, data.Identity); } //Create a new instance of a stateful grain else { SetupStorageProvider(grainType, data); grain = grainCreator.CreateGrainInstance(grainType, data.Identity, stateObjectType, data.StorageProvider); } grain.Data = data; data.SetGrainInstance(grain); } activations.IncrementGrainCounter(grainClassName); if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId); } private void SetupStorageProvider(Type grainType, ActivationData data) { var grainTypeName = grainType.FullName; // Get the storage provider name, using the default if not specified. var attr = grainType.GetTypeInfo().GetCustomAttributes<StorageProviderAttribute>(true).FirstOrDefault(); var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME; IStorageProvider provider; if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0) { var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName); logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg); throw new BadProviderConfigException(errMsg); } if (string.IsNullOrWhiteSpace(storageProviderName)) { // Use default storage provider provider = storageProviderManager.GetDefaultProvider(); } else { // Look for MemoryStore provider as special case name bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase); storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive); if (provider == null) { var errMsg = string.Format( "Cannot find storage provider with Name={0} for grain type {1}", storageProviderName, grainTypeName); logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg); throw new BadProviderConfigException(errMsg); } } data.StorageProvider = provider; if (logger.IsVerbose2) { string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}", storageProviderName, grainTypeName); logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg); } } private async Task SetupActivationState(ActivationData result, string grainType) { var statefulGrain = result.GrainInstance as IStatefulGrain; if (statefulGrain == null) { return; } var state = statefulGrain.GrainState; if (result.StorageProvider != null && state != null) { var sw = Stopwatch.StartNew(); var innerState = statefulGrain.GrainState.State; // Populate state data try { var grainRef = result.GrainReference; await scheduler.RunOrQueueTask(() => result.StorageProvider.ReadStateAsync(grainType, grainRef, state), new SchedulingContext(result)); sw.Stop(); StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed); } catch (Exception ex) { StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference); sw.Stop(); if (!(ex.GetBaseException() is KeyNotFoundException)) throw; statefulGrain.GrainState.State = innerState; // Just keep original empty state object } } } /// <summary> /// Try to get runtime data for an activation /// </summary> /// <param name="activationId"></param> /// <param name="data"></param> /// <returns></returns> public bool TryGetActivationData(ActivationId activationId, out ActivationData data) { data = null; if (activationId.IsSystem) return false; data = activations.FindTarget(activationId); return data != null; } private Task DeactivateActivationsFromCollector(List<ActivationData> list) { logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count); foreach (var activation in list) { lock (activation) { activation.PrepareForDeactivation(); // Don't accept any new messages } } return DestroyActivations(list); } // To be called fro within Activation context. // Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task. internal void DeactivateActivationOnIdle(ActivationData data) { bool promptly = false; bool alreadBeingDestroyed = false; lock (data) { if (data.State == ActivationState.Valid) { // Change the ActivationData state here, since we're about to give up the lock. data.PrepareForDeactivation(); // Don't accept any new messages ActivationCollector.TryCancelCollection(data); if (!data.IsCurrentlyExecuting) { promptly = true; } else // busy, so destroy later. { data.AddOnInactive(() => DestroyActivationVoid(data)); } } else if (data.State == ActivationState.Create) { throw new InvalidOperationException(String.Format( "Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.", data.ToString())); } else if (data.State == ActivationState.Activating) { throw new InvalidOperationException(String.Format( "Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.", data.ToString())); } else { alreadBeingDestroyed = true; } } logger.Info(ErrorCode.Catalog_ShutdownActivations_2, "DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle")); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE).Increment(); if (promptly) { DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed! } } /// <summary> /// Gracefully deletes activations, putting it into a shutdown state to /// complete and commit outstanding transactions before deleting it. /// To be called not from within Activation context, so can be awaited. /// </summary> /// <param name="list"></param> /// <returns></returns> internal async Task DeactivateActivations(List<ActivationData> list) { if (list == null || list.Count == 0) return; if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count); List<ActivationData> destroyNow = null; List<MultiTaskCompletionSource> destroyLater = null; int alreadyBeingDestroyed = 0; foreach (var d in list) { var activationData = d; // capture lock (activationData) { if (activationData.State == ActivationState.Valid) { // Change the ActivationData state here, since we're about to give up the lock. activationData.PrepareForDeactivation(); // Don't accept any new messages ActivationCollector.TryCancelCollection(activationData); if (!activationData.IsCurrentlyExecuting) { if (destroyNow == null) { destroyNow = new List<ActivationData>(); } destroyNow.Add(activationData); } else // busy, so destroy later. { if (destroyLater == null) { destroyLater = new List<MultiTaskCompletionSource>(); } var tcs = new MultiTaskCompletionSource(1); destroyLater.Add(tcs); activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs)); } } else { alreadyBeingDestroyed++; } } } int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count; int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count; logger.Info(ErrorCode.Catalog_ShutdownActivations_3, "DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.", list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count); if (destroyNow != null && destroyNow.Count > 0) { await DestroyActivations(destroyNow); } if (destroyLater != null && destroyLater.Count > 0) { await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray()); } } public Task DeactivateAllActivations() { logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations."); var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList(); return DeactivateActivations(activationsToShutdown); } /// <summary> /// Deletes activation immediately regardless of active transactions etc. /// For use by grain delete, transaction abort, etc. /// </summary> /// <param name="activation"></param> private void DestroyActivationVoid(ActivationData activation) { StartDestroyActivations(new List<ActivationData> { activation }); } private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs) { StartDestroyActivations(new List<ActivationData> { activation }, tcs); } /// <summary> /// Forcibly deletes activations now, without waiting for any outstanding transactions to complete. /// Deletes activation immediately regardless of active transactions etc. /// For use by grain delete, transaction abort, etc. /// </summary> /// <param name="list"></param> /// <returns></returns> // Overall code flow: // Deactivating state was already set before, in the correct context under lock. // that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued) // Wait for all already scheduled ticks to finish // CallGrainDeactivate // when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks): // Unregister in the directory // when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest): // Set Invalid state // UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor). // InvalidateCacheEntry // Reroute pending private Task DestroyActivations(List<ActivationData> list) { var tcs = new MultiTaskCompletionSource(list.Count); StartDestroyActivations(list, tcs); return tcs.Task; } private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null) { int number = destroyActivationsNumber; destroyActivationsNumber++; try { logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count); // step 1 - WaitForAllTimersToFinish var tasks1 = new List<Task>(); foreach (var activation in list) { tasks1.Add(activation.WaitForAllTimersToFinish()); } try { await Task.WhenAll(tasks1); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc); } // step 2 - CallGrainDeactivate var tasks2 = new List<Tuple<Task, ActivationData>>(); foreach (var activation in list) { var activationData = activation; // Capture loop variable var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData)); tasks2.Add(new Tuple<Task, ActivationData>(task, activationData)); } var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>(); asyncQueue.Queue(tasks2, tupleList => { FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs); GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe. }); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc); } } private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs) { try { //logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count); // step 3 - UnregisterManyAsync try { List<ActivationAddress> activationsToDeactivate = list. Where((ActivationData d) => d.IsUsingGrainDirectory). Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList(); if (activationsToDeactivate.Count > 0) { await scheduler.RunOrQueueTask(() => directory.UnregisterManyAsync(activationsToDeactivate, UnregistrationCause.Force), SchedulingContext); } } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc); } // step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate foreach (var activationData in list) { try { lock (activationData) { activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished } UnregisterMessageTarget(activationData); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc); } try { // IMPORTANT: no more awaits and .Ignore after that point. // Just use this opportunity to invalidate local Cache Entry as well. // If this silo is not the grain directory partition for this grain, it may have it in its cache. directory.InvalidateCacheEntry(activationData.Address); RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation"); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc); } } // step 5 - Resolve any waiting TaskCompletionSource if (tcs != null) { tcs.SetMultipleResults(list.Count); } logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count); }catch (Exception exc) { logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc); } } private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { lock (activation) { List<Message> msgs = activation.DequeueAllWaitingMessages(); if (msgs == null || msgs.Count <= 0) return; if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation)); dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc); } } private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData) { var grainTypeName = activation.GrainInstanceType.FullName; // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName); // Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function try { RequestContext.Import(requestContextData); await activation.GrainInstance.OnActivateAsync(); if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName); lock (activation) { if (activation.State == ActivationState.Activating) { activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished } if (!activation.IsCurrentlyExecuting) { activation.RunOnInactive(); } // Run message pump to see if there is a new request is queued to be processed dispatcher.RunMessagePump(activation); } } catch (Exception exc) { logger.Error(ErrorCode.Catalog_ErrorCallingActivate, string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc); activation.SetState(ActivationState.Invalid); // Mark this activation as unusable activationsFailedToActivate.Increment(); throw; } } private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation) { try { var grainTypeName = activation.GrainInstanceType.FullName; // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName); // Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function try { // just check in case this activation data is already Invalid or not here at all. ActivationData ignore; if (TryGetActivationData(activation.ActivationId, out ignore) && activation.State == ActivationState.Deactivating) { RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake. await activation.GrainInstance.OnDeactivateAsync(); } if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName); } catch (Exception exc) { logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate, string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc); } if (activation.IsUsingStreams) { try { await activation.DeactivateStreamResources(); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc); } } } catch(Exception exc) { logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc); } return activation; } private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation) { ActivationAddress address = activation.Address; // Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker. // Among those that are registered in the directory, we currently do not have any multi activations. if (activation.IsUsingGrainDirectory) { var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext); if (address.Equals(result.Address)) return; SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain); throw new DuplicateActivationException(result.Address, primaryDirectoryForGrain); } else { StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement; int maxNumLocalActivations = stPlacement.MaxLocal; lock (activations) { List<ActivationData> local; if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations) return; var id = StatelessWorkerDirector.PickRandom(local).Address; throw new DuplicateActivationException(id); } } // We currently don't have any other case for multiple activations except for StatelessWorker. } #endregion #region Activations - private /// <summary> /// Invoke the activate method on a newly created activation /// </summary> /// <param name="activation"></param> /// <param name="requestContextData"></param> /// <returns></returns> private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData) { // NOTE: This should only be called with the correct schedulering context for the activation to be invoked. lock (activation) { activation.SetState(ActivationState.Activating); } return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), new SchedulingContext(activation)); // Target grain's scheduler context); // ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest } #endregion #region IPlacementContext public Logger Logger => logger; public bool FastLookup(GrainId grain, out AddressesAndTag addresses) { return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0; // NOTE: only check with the local directory cache. // DO NOT check in the local activations TargetDirectory!!! // The only source of truth about which activation should be legit to is the state of the ditributed directory. // Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth"). // If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it, // thus volaiting the single-activation semantics and not converging even eventualy! } public Task<AddressesAndTag> FullLookup(GrainId grain) { return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext); } public Task<AddressesAndTag> LookupInCluster(GrainId grain, string clusterId) { return scheduler.RunOrQueueTask(() => directory.LookupInCluster(grain, clusterId), this.SchedulingContext); } public bool LocalLookup(GrainId grain, out List<ActivationData> addresses) { addresses = activations.FindTargets(grain); return addresses != null; } public List<SiloAddress> AllActiveSilos { get { var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList(); if (result.Count > 0) return result; logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty"); return new List<SiloAddress> { LocalSilo }; } } public SiloStatus LocalSiloStatus { get { return SiloStatusOracle.CurrentStatus; } } #endregion #region Implementation of ICatalog public Task CreateSystemGrain(GrainId grainId, string grainType) { ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId); Task activatedPromise; GetOrCreateActivation(target, true, grainType, null, null, out activatedPromise); return activatedPromise ?? TaskDone.Done; } public Task DeleteActivations(List<ActivationAddress> addresses) { return DestroyActivations(TryGetActivationDatas(addresses)); } private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses) { var datas = new List<ActivationData>(addresses.Count); foreach (var activationAddress in addresses) { ActivationData data; if (TryGetActivationData(activationAddress.Activation, out data)) datas.Add(data); } return datas; } #endregion #region Implementation of ISiloStatusListener public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // ignore joining events and also events on myself. if (updatedSilo.Equals(LocalSilo)) return; // We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states, // since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses, // thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified. // We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well. if (!status.IsTerminating()) return; if (status == SiloStatus.Dead) { RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(updatedSilo); } var activationsToShutdown = new List<ActivationData>(); try { // scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner. lock (activations) { foreach (var activation in activations) { try { var activationData = activation.Value; if (!activationData.IsUsingGrainDirectory) continue; if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue; lock (activationData) { // adapted from InsideGarinClient.DeactivateOnIdle(). activationData.ResetKeepAliveRequest(); activationsToShutdown.Add(activationData); } } catch (Exception exc) { logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception, String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc); } } } logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification, String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.", activationsToShutdown.Count, updatedSilo.ToStringWithHashCode())); } finally { // outside the lock. if (activationsToShutdown.Count > 0) { DeactivateActivations(activationsToShutdown).Ignore(); } } } #endregion } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey 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 License using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; using JsonFx.CodeGen; using JsonFx.Serialization.Resolvers; #if !NET20 && !NET30 && !WINDOWS_PHONE using System.Linq; #endif #if NET40 && !WINDOWS_PHONE using JsonObject=System.Dynamic.ExpandoObject; #else using JsonObject=System.Collections.Generic.Dictionary<string, object>; #endif namespace JsonFx.Serialization { /// <summary> /// Type Coercion Utility /// </summary> public sealed class TypeCoercionUtility : IResolverCacheContainer { #region Constants internal const string AnonymousTypePrefix = "<>f__AnonymousType"; internal static readonly string TypeGenericIEnumerable = typeof(IEnumerable<>).FullName; internal static readonly string TypeGenericICollection = typeof(ICollection<>).FullName; internal static readonly string TypeGenericIDictionary = typeof(IDictionary<,>).FullName; private const string ErrorNullValueType = "{0} does not accept null as a value"; private const string ErrorCtor = "Unable to find a suitable constructor for instantiating the target Type. ({0})"; private const string ErrorCannotInstantiateAsT = "Type {0} is not of Type {1}"; private const string ErrorGenericIDictionary = "Types which implement Generic IDictionary<TKey, TValue> also need to implement IDictionary to be deserialized. ({0})"; private const string ErrorGenericIDictionaryKeys = "Types which implement Generic IDictionary<TKey, TValue> need to have string keys to be deserialized. ({0})"; #endregion Constants #region Fields private readonly bool AllowNullValueTypes; private readonly ResolverCache ResolverCache; #endregion Fields #region Init /// <summary> /// Ctor /// </summary> /// <param name="cacheContainer"></param> /// <param name="allowNullValueTypes"></param> public TypeCoercionUtility(IResolverCacheContainer cacheContainer, bool allowNullValueTypes) : this(cacheContainer.ResolverCache, allowNullValueTypes) { } /// <summary> /// Ctor /// </summary> /// <param name="resolverCache"></param> /// <param name="allowNullValueTypes"></param> public TypeCoercionUtility(ResolverCache resolverCache, bool allowNullValueTypes) { if (resolverCache == null) { throw new ArgumentNullException("resolverCache"); } this.ResolverCache = resolverCache; this.AllowNullValueTypes = allowNullValueTypes; } #endregion Init #region Object Manipulation Methods /// <summary> /// Instantiates a new instance of objectType. /// </summary> /// <param name="objectType"></param> /// <returns>objectType instance</returns> internal object InstantiateObjectDefaultCtor(Type targetType) { if (targetType == null || targetType.IsValueType || targetType.IsAbstract || targetType == typeof(object) || targetType == typeof(string)) { return new JsonObject(); } targetType = TypeCoercionUtility.ResolveInterfaceType(targetType); if (targetType.IsInterface) { return new JsonObject(); } FactoryMap factory = this.ResolverCache.LoadFactory(targetType); if ((factory == null) || (factory.Ctor == null) || ((factory.CtorArgs != null) && (factory.CtorArgs.Length > 0))) { return new JsonObject(); } // default constructor return factory.Ctor(); } /// <summary> /// Instantiates a new instance of objectType. /// </summary> /// <param name="objectType"></param> /// <returns>objectType instance</returns> internal object InstantiateObject(Type targetType, object args) { targetType = TypeCoercionUtility.ResolveInterfaceType(targetType); FactoryMap factory = this.ResolverCache.LoadFactory(targetType); if ((factory == null) || (factory.Ctor == null)) { throw new TypeCoercionException(String.Format( TypeCoercionUtility.ErrorCtor, targetType.FullName)); } if ((factory.CtorArgs == null) || (factory.CtorArgs.Length < 1)) { // default constructor return factory.Ctor(); } object[] ctorArgs = new object[factory.CtorArgs.Length]; IDictionary<string, object> genericArgs = args as IDictionary<string, object>; if (genericArgs != null) { for (int i=0, length=ctorArgs.Length; i<length; i++) { string name = factory.CtorArgs[i].Name; Type type = factory.CtorArgs[i].ParameterType; foreach (string key in genericArgs.Keys) { try { if (StringComparer.OrdinalIgnoreCase.Equals(key, name)) { ctorArgs[i] = this.CoerceType(type, genericArgs[key]); break; } } catch { } } } } else { IDictionary otherArgs = args as IDictionary; if (otherArgs != null) { for (int i=0, length=ctorArgs.Length; i<length; i++) { string name = factory.CtorArgs[i].Name; Type type = factory.CtorArgs[i].ParameterType; foreach (string key in otherArgs.Keys) { try { if (StringComparer.OrdinalIgnoreCase.Equals(key, name)) { ctorArgs[i] = this.CoerceType(type, otherArgs[key]); break; } } catch { } } } } } // use a custom constructor return factory.Ctor(ctorArgs); } /// <summary> /// Helper method to set value of a member. /// </summary> /// <param name="target"></param> /// <param name="targetType"></param> /// <param name="memberMap"></param> /// <param name="memberName"></param> /// <param name="memberValue"></param> internal void SetMemberValue(object target, Type targetType, MemberMap memberMap, string memberName, object memberValue) { if (target == null) { return; } if (target is IDictionary<string, object>) { // needed for ExpandoObject which unfortunately does not implement IDictionary ((IDictionary<string, object>)target)[memberName] = memberValue; } else if (target is IDictionary) { ((IDictionary)target)[memberName] = memberValue; } #if NET40 && !WINDOWS_PHONE else if (target is System.Dynamic.DynamicObject) { // TODO: expand to all IDynamicMetaObjectProvider? ((System.Dynamic.DynamicObject)target).TrySetMember(new DynamicSetter(memberName), memberValue); } #endif else if (targetType != null #if !NETCF && targetType.GetInterface(TypeCoercionUtility.TypeGenericIDictionary, false) != null #endif ) { throw new TypeCoercionException(String.Format( TypeCoercionUtility.ErrorGenericIDictionary, targetType)); } else if (memberMap != null && memberMap.Setter != null) { memberMap.Setter(target, this.CoerceType(memberMap.Type, memberValue)); } // ignore non-applicable members } #endregion Object Manipulation Methods #region Coercion Methods /// <summary> /// Coerces the object value to Type <typeparamref name="T"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public T CoerceType<T>(object value) { return (T)this.CoerceType(typeof(T), value); } /// <summary> /// Coerces the object value to Type of <paramref name="targetType"/> /// </summary> /// <param name="targetType"></param> /// <param name="value"></param> /// <returns></returns> public object CoerceType(Type targetType, object value) { if (targetType == null || targetType == typeof(object)) { return value; } bool isNullable = TypeCoercionUtility.IsNullable(targetType); if (value == null) { // TODO: validate that this is what we want if (!this.AllowNullValueTypes && targetType.IsValueType && !isNullable) { throw new TypeCoercionException(String.Format( TypeCoercionUtility.ErrorNullValueType, targetType.FullName)); } return value; } if (isNullable) { // nullable types have a real underlying struct Type[] genericArgs = targetType.GetGenericArguments(); if (genericArgs.Length == 1) { targetType = genericArgs[0]; } } Type actualType = value.GetType(); if (targetType.IsAssignableFrom(actualType)) { return value; } if (targetType.IsEnum) { if (value is String) { if (!Enum.IsDefined(targetType, value)) { IDictionary<string, MemberMap> maps = this.ResolverCache.LoadMaps(targetType); if (maps != null && maps.ContainsKey((string)value)) { value = maps[(string)value].Name; } } return Enum.Parse(targetType, (string)value, false); } else { value = this.CoerceType(Enum.GetUnderlyingType(targetType), value); return Enum.ToObject(targetType, value); } } if (value is IDictionary<string, object>) { return this.CoerceType(targetType, (IDictionary<string, object>)value); } else if (value is IDictionary) { return this.CoerceType(targetType, (IDictionary)value); } if (typeof(IEnumerable).IsAssignableFrom(targetType) && typeof(IEnumerable).IsAssignableFrom(actualType)) { return this.CoerceList(targetType, actualType, (IEnumerable)value); } if (value is String) { if (targetType == typeof(DateTime)) { DateTime date; try{ date = DateTime.Parse( (string)value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind|DateTimeStyles.AllowWhiteSpaces|DateTimeStyles.NoCurrentDateDefault); if (date.Kind == DateTimeKind.Local) { return date.ToUniversalTime(); } return date; }catch(Exception){} if (JsonFx.Model.Filters.MSAjaxDateFilter.TryParseMSAjaxDate( (string)value, out date)) { return date; } } else if (targetType == typeof(Guid)) { // try-catch is pointless since will throw upon generic conversion return new Guid((string)value); } else if (targetType == typeof(Char)) { if (((string)value).Length == 1) { return ((string)value)[0]; } } else if (targetType == typeof(Uri)) { Uri uri; if (Uri.TryCreate((string)value, UriKind.RelativeOrAbsolute, out uri)) { return uri; } } else if (targetType == typeof(Version)) { // try-catch is pointless since will throw upon generic conversion return new Version((string)value); } else if (targetType == typeof(TimeSpan)) { try{ return TimeSpan.FromTicks(Int64.Parse((string)value)); }catch(Exception){} try{ return TimeSpan.Parse((string)value); }catch(Exception){} } } else if (targetType == typeof(TimeSpan)) { return new TimeSpan((long)this.CoerceType(typeof(Int64), value)); } #if !SILVERLIGHT TypeConverter converter = TypeDescriptor.GetConverter(targetType); if (converter.CanConvertFrom(actualType)) { return converter.ConvertFrom(value); } converter = TypeDescriptor.GetConverter(actualType); if (converter.CanConvertTo(targetType)) { return converter.ConvertTo(value, targetType); } #endif try { // fall back to basics return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new TypeCoercionException( String.Format( "Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex); } } /// <summary> /// Populates the properties of an object with the dictionary values. /// </summary> /// <param name="targetType"></param> /// <param name="value"></param> /// <returns></returns> private object CoerceType(Type targetType, IDictionary<string, object> value) { object newValue = this.InstantiateObject(targetType, value); IDictionary<string, MemberMap> maps = this.ResolverCache.LoadMaps(targetType); if (maps == null) { IDictionary<string, object> genericDictionary = newValue as IDictionary<string, object>; if (genericDictionary != null) { // copy all values into new object foreach (string memberName in value.Keys) { genericDictionary[memberName] = value[memberName]; } } else { IDictionary dictionary = newValue as IDictionary; if (dictionary != null) { // copy all values into new object foreach (string memberName in value.Keys) { dictionary[memberName] = value[memberName]; } } } } else { // copy any values into new object foreach (string memberName in value.Keys) { MemberMap map; if (maps.TryGetValue(memberName, out map) && map != null && map.Setter != null) { map.Setter(newValue, value[memberName]); } } } return newValue; } /// <summary> /// Populates the properties of an object with the dictionary values. /// </summary> /// <param name="targetType"></param> /// <param name="value"></param> /// <returns></returns> private object CoerceType(Type targetType, IDictionary value) { object newValue = this.InstantiateObject(targetType, value); IDictionary<string, MemberMap> maps = this.ResolverCache.LoadMaps(targetType); if (maps == null) { IDictionary<string, object> genericDictionary = newValue as IDictionary<string, object>; if (genericDictionary != null) { // copy all values into new object foreach (object key in value.Keys) { string memberName = Convert.ToString(key, CultureInfo.InvariantCulture); genericDictionary[memberName] = value[memberName]; } } else { IDictionary dictionary = newValue as IDictionary; if (dictionary != null) { // copy all values into new object foreach (object memberName in value.Keys) { dictionary[memberName] = value[memberName]; } } } } else { // copy any values into new object foreach (object key in value.Keys) { string memberName = Convert.ToString(key, CultureInfo.InvariantCulture); MemberMap map; if (maps.TryGetValue(memberName, out map) && map != null && map.Setter != null) { map.Setter(newValue, value[key]); } } } return newValue; } private object CoerceList(Type targetType, Type valueType, IEnumerable value) { targetType = TypeCoercionUtility.ResolveInterfaceType(targetType); if (targetType.IsArray) { // arrays are much simpler to create return this.CoerceArray(targetType.GetElementType(), value); } // targetType serializes as a JSON array but is not an array // assume is an ICollection or IEnumerable with AddRange, Add, // or custom Constructor with which we can populate it FactoryMap factory = this.ResolverCache.LoadFactory(targetType); if (factory == null) { throw new TypeCoercionException(String.Format( TypeCoercionUtility.ErrorCtor, targetType.FullName)); } foreach (Type argType in factory.ArgTypes) { if (argType.IsAssignableFrom(valueType)) { try { // invoke first constructor that can take this value as an argument return factory[argType](value); } catch { // there might exist a better match continue; } } } if (factory.Ctor == null) { throw new TypeCoercionException(String.Format( TypeCoercionUtility.ErrorCtor, targetType.FullName)); } // attempt bulk insert first as is most efficient if (factory.AddRange != null && factory.AddRangeType != null && factory.AddRangeType.IsAssignableFrom(valueType)) { object collection = factory.Ctor(); factory.AddRange(collection, value); return collection; } // attempt sequence of single inserts next if (factory.Add != null && factory.AddType != null) { object collection = factory.Ctor(); Type addType = factory.AddType; // loop through adding items to collection foreach (object item in value) { factory.Add(collection, this.CoerceType(addType, item)); } return collection; } try { // finally fall back to basics return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new TypeCoercionException( String.Format( "Error converting {0} to {1}", value.GetType().FullName, targetType.FullName), ex); } } internal object CoerceCollection(Type targetType, Type itemType, ICollection value) { if (targetType != null && targetType != typeof(object)) { // convert to requested type return this.CoerceList(targetType, value.GetType(), value); } // if all items are of same type then convert to array of that type Array array = Array.CreateInstance(itemType ?? typeof(object), value.Count); value.CopyTo(array, 0); return array; } /// <summary> /// Coerces an sequence of items into an array of Type elementType /// </summary> /// <param name="elementType"></param> /// <param name="value"></param> /// <returns></returns> private Array CoerceArray(Type itemType, IEnumerable value) { ICollection collection = value as ICollection; if (collection == null) { List<object> list = new List<object>(); foreach (object item in value) { // convert each as is added list.Add(this.CoerceType(itemType, item)); } collection = list; } // if all items are of same type then convert to array of that type Array array = Array.CreateInstance(itemType ?? typeof(object), collection.Count); collection.CopyTo(array, 0); return array; } #endregion Coercion Methods #region Type Methods /// <summary> /// Finds a suitable concrete class for common collection interface types /// </summary> /// <param name="targetType"></param> /// <returns></returns> private static Type ResolveInterfaceType(Type targetType) { if (targetType.IsInterface) { if (targetType.IsGenericType) { Type genericType = targetType.GetGenericTypeDefinition(); if (genericType == typeof(IList<>) || genericType == typeof(IEnumerable<>) || #if !NET20 && !NET30 && !WINDOWS_PHONE genericType == typeof(IQueryable<>) || genericType == typeof(IOrderedQueryable<>) || #endif genericType == typeof(ICollection<>)) { Type[] genericArgs = targetType.GetGenericArguments(); targetType = typeof(List<>).MakeGenericType(genericArgs); } else if (genericType == typeof(IDictionary<,>)) { Type[] genericArgs = targetType.GetGenericArguments(); if (genericArgs.Length == 2 && genericArgs[0] == typeof(string) && genericArgs[0] == typeof(object)) { // allow ExpandoObject in NET40, otherwise Dictionary<string, object> targetType = typeof(JsonObject); } else { targetType = typeof(Dictionary<,>).MakeGenericType(genericArgs); } } } else if (targetType == typeof(IList) || targetType == typeof(IEnumerable) || #if !NET20 && !NET30 && !WINDOWS_PHONE targetType == typeof(IQueryable) || targetType == typeof(IOrderedQueryable) || #endif targetType == typeof(ICollection)) { targetType = typeof(object[]); } else if (targetType == typeof(IDictionary)) { // <rant>cannot use ExpandoObject here because it does not implement IDictionary</rant> targetType = typeof(Dictionary<string, object>); } #if NET40 && !WINDOWS_PHONE else if (targetType == typeof(System.Dynamic.IDynamicMetaObjectProvider)) { targetType = typeof(System.Dynamic.ExpandoObject); } #endif } return targetType; } /// <summary> /// Allows specific IDictionary&lt;string, TVal&gt; to deserialize as TVal /// </summary> /// <param name="targetType">IDictionary&lt;string, TVal&gt; Type</param> /// <returns>TVal Type</returns> internal static Type GetDictionaryItemType(Type targetType) { if (targetType == null) { return null; } Type dictionaryType = null; #if !NETCF dictionaryType = targetType.GetInterface(TypeCoercionUtility.TypeGenericIDictionary, false); #endif if (dictionaryType == null) { // not an IDictionary<TKey, TVal> return null; } Type[] genericArgs = dictionaryType.GetGenericArguments(); if (genericArgs.Length != 2 || !genericArgs[0].IsAssignableFrom(typeof(string))) { if (typeof(IDictionary).IsAssignableFrom(targetType)) { // can build from non-generic IDictionary return null; } // only supports variants of IDictionary<string, TVal> throw new ArgumentException(String.Format( TypeCoercionUtility.ErrorGenericIDictionaryKeys, targetType)); } return genericArgs[1]; } internal static Type GetElementType(Type targetType) { if (targetType == null || targetType == typeof(string)) { // not array type return null; } if (targetType.HasElementType) { // found array element type return targetType.GetElementType(); } Type arrayType = null; #if !NETCF arrayType = targetType.GetInterface(TypeCoercionUtility.TypeGenericIEnumerable, false); #endif if (arrayType == null) { // not an IEnumerable<T> return null; } // found list or enumerable type Type[] genericArgs = arrayType.GetGenericArguments(); return (genericArgs.Length == 1) ? genericArgs[0] : null; } /// <summary> /// Returns a common type which can hold previous values and the new value /// </summary> /// <param name="itemType"></param> /// <param name="value"></param> /// <returns></returns> internal static Type FindCommonType(Type itemType, object value) { // establish if array is of common type if (value == null) { if (itemType != null && itemType.IsValueType) { // must use plain object to hold null itemType = typeof(object); } } else if (itemType == null) { // try out a hint type // if hasn't been set before itemType = value.GetType(); } else { Type valueType = value.GetType(); if (!itemType.IsAssignableFrom(valueType)) { if (valueType.IsAssignableFrom(itemType)) { // attempt to use the more general type itemType = valueType; } else { // use plain object to hold value // TODO: find a common ancestor? itemType = typeof(object); } } } return itemType; } /// <summary> /// Determines if type can be assigned a null value. /// </summary> /// <param name="type"></param> /// <returns></returns> private static bool IsNullable(Type type) { return type.IsGenericType && (typeof(Nullable<>) == type.GetGenericTypeDefinition()); } #endregion Type Methods #region Attribute Methods /// <summary> /// Gets the attribute T for the given value. /// </summary> /// <param name="value"></param> /// <typeparam name="T">Attribute Type</typeparam> /// <returns>true if defined</returns> internal static bool HasAttribute<T>(MemberInfo info) where T : Attribute { return (info != null && Attribute.IsDefined(info, typeof(T))); } /// <summary> /// Gets the attribute of Type <param name="type" /> for the given value. /// </summary> /// <param name="value"></param> /// <returns>true if defined</returns> internal static bool HasAttribute(MemberInfo info, Type type) { return (info != null && type != null && Attribute.IsDefined(info, type)); } /// <summary> /// Gets the attribute T for the given value. /// </summary> /// <param name="value"></param> /// <typeparam name="T">Attribute Type</typeparam> /// <returns>requested attribute or not if not defined</returns> internal static T GetAttribute<T>(MemberInfo info) where T : Attribute { if (info == null || !Attribute.IsDefined(info, typeof(T))) { return default(T); } return (T)Attribute.GetCustomAttribute(info, typeof(T)); } /// <summary> /// Gets the attribute of Type <param name="type" /> for the given value. /// </summary> /// <param name="value"></param> /// <returns>requested attribute or not if not defined</returns> internal static Attribute GetAttribute(MemberInfo info, Type type) { if (info == null || type == null || !Attribute.IsDefined(info, type)) { return default(Attribute); } return Attribute.GetCustomAttribute(info, type); } #endregion Attribute Methods #region IResolverCacheContainer Members ResolverCache IResolverCacheContainer.ResolverCache { get { return this.ResolverCache; } } #endregion IResolverCacheContainer Members } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Versioning; using FluentMigrator.Infrastructure.Extensions; namespace FluentMigrator.Runner { public class MigrationRunner : IMigrationRunner { private Assembly _migrationAssembly; private IAnnouncer _announcer; private IStopWatch _stopWatch; private bool _alreadyOutputPreviewOnlyModeWarning; private readonly MigrationValidator _migrationValidator; private readonly MigrationScopeHandler _migrationScopeHandler; /// <summary>The arbitrary application context passed to the task runner.</summary> public object ApplicationContext { get; private set; } public bool TransactionPerSession { get; private set; } public bool SilentlyFail { get; set; } public IMigrationProcessor Processor { get; private set; } public IMigrationInformationLoader MigrationLoader { get; set; } public IProfileLoader ProfileLoader { get; set; } public IMigrationConventions Conventions { get; private set; } public IList<Exception> CaughtExceptions { get; private set; } public IMigrationScope CurrentScope { get { return _migrationScopeHandler.CurrentScope; } set { _migrationScopeHandler.CurrentScope = value; } } public MigrationRunner(Assembly assembly, IRunnerContext runnerContext, IMigrationProcessor processor) { _migrationAssembly = assembly; _announcer = runnerContext.Announcer; Processor = processor; _stopWatch = runnerContext.StopWatch; ApplicationContext = runnerContext.ApplicationContext; TransactionPerSession = runnerContext.TransactionPerSession; SilentlyFail = false; CaughtExceptions = null; Conventions = new MigrationConventions(); if (!string.IsNullOrEmpty(runnerContext.WorkingDirectory)) Conventions.GetWorkingDirectory = () => runnerContext.WorkingDirectory; _migrationScopeHandler = new MigrationScopeHandler(Processor); _migrationValidator = new MigrationValidator(_announcer, Conventions); VersionLoader = new VersionLoader(this, _migrationAssembly, Conventions); MigrationLoader = new DefaultMigrationInformationLoader(Conventions, _migrationAssembly, runnerContext.Namespace, runnerContext.NestedNamespaces, runnerContext.Tags); ProfileLoader = new ProfileLoader(runnerContext, this, Conventions); } public IVersionLoader VersionLoader { get; set; } public void ApplyProfiles() { ProfileLoader.ApplyProfiles(); } public void MigrateUp() { MigrateUp(true); } public void MigrateUp(bool useAutomaticTransactionManagement) { var migrations = MigrationLoader.LoadMigrations(); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { foreach (var pair in migrations) { ApplyMigrationUp(pair.Value, useAutomaticTransactionManagement && pair.Value.TransactionBehavior == TransactionBehavior.Default); } ApplyProfiles(); scope.Complete(); } VersionLoader.LoadVersionInfo(); } public void MigrateUp(long targetVersion) { MigrateUp(targetVersion, true); } public void MigrateUp(long targetVersion, bool useAutomaticTransactionManagement) { var migrationInfos = GetUpMigrationsToApply(targetVersion); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { foreach (var migrationInfo in migrationInfos) { ApplyMigrationUp(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } scope.Complete(); } VersionLoader.LoadVersionInfo(); } private IEnumerable<IMigrationInfo> GetUpMigrationsToApply(long version) { var migrations = MigrationLoader.LoadMigrations(); return from pair in migrations where IsMigrationStepNeededForUpMigration(pair.Key, version) select pair.Value; } private bool IsMigrationStepNeededForUpMigration(long versionOfMigration, long targetVersion) { if (versionOfMigration <= targetVersion && !VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration)) { return true; } return false; } public void MigrateDown(long targetVersion) { MigrateDown(targetVersion, true); } public void MigrateDown(long targetVersion, bool useAutomaticTransactionManagement) { var migrationInfos = GetDownMigrationsToApply(targetVersion); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { foreach (var migrationInfo in migrationInfos) { ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } scope.Complete(); } VersionLoader.LoadVersionInfo(); } private IEnumerable<IMigrationInfo> GetDownMigrationsToApply(long targetVersion) { var migrations = MigrationLoader.LoadMigrations(); var migrationsToApply = (from pair in migrations where IsMigrationStepNeededForDownMigration(pair.Key, targetVersion) select pair.Value) .ToList(); return migrationsToApply.OrderByDescending(x => x.Version); } private bool IsMigrationStepNeededForDownMigration(long versionOfMigration, long targetVersion) { if (versionOfMigration > targetVersion && VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration)) { return true; } return false; } public virtual void ApplyMigrationUp(IMigrationInfo migrationInfo, bool useTransaction) { if (migrationInfo == null) throw new ArgumentNullException("migrationInfo"); if (!_alreadyOutputPreviewOnlyModeWarning && Processor.Options.PreviewOnly) { _announcer.Heading("PREVIEW-ONLY MODE"); _alreadyOutputPreviewOnlyModeWarning = true; } if (!migrationInfo.IsAttributed() || !VersionLoader.VersionInfo.HasAppliedMigration(migrationInfo.Version)) { var name = migrationInfo.GetName(); _announcer.Heading(string.Format("{0} migrating", name)); _stopWatch.Start(); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useTransaction)) { ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetUpExpressions(c)); if (migrationInfo.IsAttributed()) VersionLoader.UpdateVersionInfo(migrationInfo.Version); scope.Complete(); _stopWatch.Stop(); _announcer.Say(string.Format("{0} migrated", name)); _announcer.ElapsedTime(_stopWatch.ElapsedTime()); } } } public virtual void ApplyMigrationDown(IMigrationInfo migrationInfo, bool useTransaction) { if (migrationInfo == null) throw new ArgumentNullException("migrationInfo"); var name = migrationInfo.GetName(); _announcer.Heading(string.Format("{0} reverting", name)); _stopWatch.Start(); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useTransaction)) { ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetDownExpressions(c)); if (migrationInfo.IsAttributed()) VersionLoader.DeleteVersion(migrationInfo.Version); scope.Complete(); _stopWatch.Stop(); _announcer.Say(string.Format("{0} reverted", name)); _announcer.ElapsedTime(_stopWatch.ElapsedTime()); } } public void Rollback(int steps) { Rollback(steps, true); } public void Rollback(int steps, bool useAutomaticTransactionManagement) { var availableMigrations = MigrationLoader.LoadMigrations(); var migrationsToRollback = new List<IMigrationInfo>(); foreach (long version in VersionLoader.VersionInfo.AppliedMigrations()) { IMigrationInfo migrationInfo; if (availableMigrations.TryGetValue(version, out migrationInfo)) migrationsToRollback.Add(migrationInfo); } using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { foreach (IMigrationInfo migrationInfo in migrationsToRollback.Take(steps)) { ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } scope.Complete(); } VersionLoader.LoadVersionInfo(); if (!VersionLoader.VersionInfo.AppliedMigrations().Any()) VersionLoader.RemoveVersionTable(); } public void RollbackToVersion(long version) { RollbackToVersion(version, true); } public void RollbackToVersion(long version, bool useAutomaticTransactionManagement) { var availableMigrations = MigrationLoader.LoadMigrations(); var migrationsToRollback = new List<IMigrationInfo>(); foreach (long appliedVersion in VersionLoader.VersionInfo.AppliedMigrations()) { IMigrationInfo migrationInfo; if (availableMigrations.TryGetValue(appliedVersion, out migrationInfo)) migrationsToRollback.Add(migrationInfo); } using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { foreach (IMigrationInfo migrationInfo in migrationsToRollback) { if (version >= migrationInfo.Version) continue; ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } scope.Complete(); } VersionLoader.LoadVersionInfo(); if (version == 0 && !VersionLoader.VersionInfo.AppliedMigrations().Any()) VersionLoader.RemoveVersionTable(); } public Assembly MigrationAssembly { get { return _migrationAssembly; } } public void Up(IMigration migration) { var migrationInfoAdapter = new NonAttributedMigrationToMigrationInfoAdapter(migration); ApplyMigrationUp(migrationInfoAdapter, true); } private void ExecuteMigration(IMigration migration, Action<IMigration, IMigrationContext> getExpressions) { CaughtExceptions = new List<Exception>(); var context = new MigrationContext(Conventions, Processor, MigrationAssembly, ApplicationContext, Processor.ConnectionString); getExpressions(migration, context); _migrationValidator.ApplyConventionsToAndValidateExpressions(migration, context.Expressions); ExecuteExpressions(context.Expressions); } public void Down(IMigration migration) { var migrationInfoAdapter = new NonAttributedMigrationToMigrationInfoAdapter(migration); ApplyMigrationDown(migrationInfoAdapter, true); } /// <summary> /// execute each migration expression in the expression collection /// </summary> /// <param name="expressions"></param> protected void ExecuteExpressions(ICollection<IMigrationExpression> expressions) { long insertTicks = 0; int insertCount = 0; foreach (IMigrationExpression expression in expressions) { try { if (expression is InsertDataExpression) { insertTicks += _stopWatch.Time(() => expression.ExecuteWith(Processor)).Ticks; insertCount++; } else { AnnounceTime(expression.ToString(), () => expression.ExecuteWith(Processor)); } } catch (Exception er) { _announcer.Error(er.Message); //catch the error and move onto the next expression if (SilentlyFail) { CaughtExceptions.Add(er); continue; } throw; } } if (insertCount > 0) { var avg = new TimeSpan(insertTicks / insertCount); var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg); _announcer.Say(msg); } } private void AnnounceTime(string message, Action action) { _announcer.Say(message); _announcer.ElapsedTime(_stopWatch.Time(action)); } public void ValidateVersionOrder() { var unappliedVersions = MigrationLoader.LoadMigrations().Where(kvp => MigrationVersionLessThanGreatestAppliedMigration(kvp.Key)).ToList(); if (unappliedVersions.Any()) throw new VersionOrderInvalidException(unappliedVersions); _announcer.Say("Version ordering valid."); } public void ListMigrations() { IVersionInfo currentVersionInfo = this.VersionLoader.VersionInfo; long currentVersion = currentVersionInfo.Latest(); _announcer.Heading("Migrations"); foreach(KeyValuePair<long, IMigrationInfo> migration in MigrationLoader.LoadMigrations()) { string migrationName = migration.Value.GetName(); bool isCurrent = migration.Key == currentVersion; string message = string.Format("{0}{1}", migrationName, isCurrent ? " (current)" : string.Empty); if(isCurrent) _announcer.Emphasize(message); else _announcer.Say(message); } } private bool MigrationVersionLessThanGreatestAppliedMigration(long version) { return !VersionLoader.VersionInfo.HasAppliedMigration(version) && version < VersionLoader.VersionInfo.Latest(); } public IMigrationScope BeginScope() { return _migrationScopeHandler.BeginScope(); } } }
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using DriveProxy.API; using DriveProxy.Utils; namespace DriveProxy.Forms { partial class SettingsForm : Form { public SettingsForm() { InitializeComponent(); } private void SettingsForm_Load(object sender, EventArgs e) { try { lstLogTypes.SetItemCheckState(0, (DriveService.Settings.LogLevel & LogType.Error) == 0 ? CheckState.Unchecked : CheckState.Checked); lstLogTypes.SetItemCheckState(1, (DriveService.Settings.LogLevel & LogType.Warning) == 0 ? CheckState.Unchecked : CheckState.Checked); lstLogTypes.SetItemCheckState(2, (DriveService.Settings.LogLevel & LogType.Information) == 0 ? CheckState.Unchecked : CheckState.Checked); lstLogTypes.SetItemCheckState(3, (DriveService.Settings.LogLevel & LogType.Debug) == 0 ? CheckState.Unchecked : CheckState.Checked); lstLogTypes.SetItemCheckState(4, (DriveService.Settings.LogLevel & LogType.Performance) == 0 ? CheckState.Unchecked : CheckState.Checked); ComboBoxItem.AddItem(comboBoxFileReturnType, "Filter Google Files (Recommended)", FileReturnType.FilterGoogleFiles); ComboBoxItem.AddItem(comboBoxFileReturnType, "Ignore Google Files (Possible slow performance)", FileReturnType.IgnoreGoogleFiles); ComboBoxItem.AddItem(comboBoxFileReturnType, "Return All Google Files (Not recommended)", FileReturnType.ReturnAllGoogleFiles); ComboBoxItem.SetSelectedItem(comboBoxFileReturnType, DriveService.Settings.FileReturnType); checkBoxUseCaching.Checked = DriveService.Settings.UseCaching; checkBoxStartup.Checked = DriveService.Settings.IsStartingStartOnStartup; } catch (Exception exception) { Log.Error(exception, false); MessageBox.Show(this, exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void buttonOK_Click(object sender, EventArgs e) { try { var logLevel = LogType.None; if (lstLogTypes.GetItemChecked(0)) { logLevel |= LogType.Error; } if (lstLogTypes.GetItemChecked(1)) { logLevel |= LogType.Warning; } if (lstLogTypes.GetItemChecked(2)) { logLevel |= LogType.Information; } if (lstLogTypes.GetItemChecked(3)) { logLevel |= LogType.Debug; } if (lstLogTypes.GetItemChecked(4)) { logLevel |= LogType.Performance; } DriveService.Settings.LogLevel = logLevel; DriveService.Settings.FileReturnType = (FileReturnType)ComboBoxItem.GetSelectedItem(comboBoxFileReturnType); DriveService.Settings.UseCaching = checkBoxUseCaching.Checked; DriveService.Settings.IsStartingStartOnStartup = checkBoxStartup.Checked; DriveService.Settings.Save(); Close(); } catch (Exception exception) { Log.Error(exception, false); MessageBox.Show(this, exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void buttonCancel_Click(object sender, EventArgs e) { Close(); } private void comboBoxFileReturnType_DropDownStyleChanged(object sender, EventArgs e) { } private void comboBoxFileReturnType_DropDown(object sender, EventArgs e) { try { var comboBox = (ComboBox)sender; ComboBoxItem.DropDown(comboBox); } catch (Exception exception) { Log.Error(exception, false); MessageBox.Show(this, exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private class ComboBoxItem { public readonly string Text = ""; public readonly object Value; public ComboBoxItem(string text, object value) { Text = text; Value = value; } public override string ToString() { return Text; } public static void AddItem(ComboBox comboBox, string text, object value) { comboBox.Items.Add(new ComboBoxItem(text, value)); } public static object GetSelectedItem(ComboBox comboBox) { if (comboBox.SelectedItem == null) { return null; } var item = (ComboBoxItem)comboBox.SelectedItem; return item.Value; } public static void SetSelectedItem(ComboBox comboBox, object value) { int selectedIndex = -1; for (int i = 0; i < comboBox.Items.Count; i++) { var item = comboBox.Items[i] as ComboBoxItem; if (item != null) { if (item.Value.ToString() == value.ToString()) { selectedIndex = i; break; } } } comboBox.SelectedIndex = selectedIndex; } public static void DropDown(ComboBox comboBox) { if (comboBox.Tag != null) { return; } int width = comboBox.DropDownWidth; Graphics g = comboBox.CreateGraphics(); Font font = comboBox.Font; int vertScrollBarWidth = (comboBox.Items.Count > comboBox.MaxDropDownItems) ? SystemInformation.VerticalScrollBarWidth : 0; IEnumerable<string> itemsList = comboBox.Items.Cast<object>().Select(item => item.ToString()); foreach (var s in itemsList) { int newWidth = (int)g.MeasureString(s, font).Width + vertScrollBarWidth; if (width < newWidth) { width = newWidth; } } comboBox.DropDownWidth = width; comboBox.Tag = true; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.CommandLine; using System.Linq; using System.Threading; using Wyam.Common.IO; using Wyam.Common.Tracing; using Wyam.Configuration.Preprocessing; using Wyam.Hosting; using Wyam.Tracing; namespace Wyam.Commands { internal class BuildCommand : Command { private readonly ConcurrentQueue<string> _changedFiles = new ConcurrentQueue<string>(); private readonly AutoResetEvent _messageEvent = new AutoResetEvent(false); private readonly InterlockedBool _exit = new InterlockedBool(false); private readonly InterlockedBool _newEngine = new InterlockedBool(false); private readonly ConfigOptions _configOptions = new ConfigOptions(); private bool _preview = false; private int _previewPort = 5080; private DirectoryPath _previewVirtualDirectory = null; private bool _previewForceExtension = false; private FilePath _logFilePath = null; private bool _verifyConfig = false; private DirectoryPath _previewRoot = null; private bool _watch = false; private bool _noReload = false; public override string Description => "Runs the build process (this is the default command)."; public override string[] SupportedDirectives => new[] { "nuget", "nuget-source", "assembly", "recipe", "theme" }; protected override void ParseOptions(ArgumentSyntax syntax) { syntax.DefineOption("w|watch", ref _watch, "Watches the input folder for any changes."); _preview = syntax.DefineOption("p|preview", ref _previewPort, false, "Start the preview web server on the specified port (default is " + _previewPort + ").").IsSpecified; if (syntax.DefineOption("force-ext", ref _previewForceExtension, "Force the use of extensions in the preview web server (by default, extensionless URLs may be used).").IsSpecified && !_preview) { syntax.ReportError("force-ext can only be specified if the preview server is running."); } if (syntax.DefineOption("virtual-dir", ref _previewVirtualDirectory, DirectoryPathFromArg, "Serve files in the preview web server under the specified virtual directory.").IsSpecified && !_preview) { syntax.ReportError("virtual-dir can only be specified if the preview server is running."); } if (syntax.DefineOption("preview-root", ref _previewRoot, DirectoryPathFromArg, "The path to the root of the preview server, if not the output folder.").IsSpecified && !_preview) { syntax.ReportError("preview-root can only be specified if the preview server is running."); } if (syntax.DefineOption("noreload", ref _noReload, "Turns off LiveReload support in the preview server.").IsSpecified && (!_preview || !_watch)) { syntax.ReportError("noreload can only be specified if both the preview server is running and watching is enabled."); } syntax.DefineOptionList("i|input", ref _configOptions.InputPaths, DirectoryPathFromArg, "The path(s) of input files, can be absolute or relative to the current folder."); syntax.DefineOption("o|output", ref _configOptions.OutputPath, DirectoryPathFromArg, "The path to output files, can be absolute or relative to the current folder."); syntax.DefineOption("c|config", ref _configOptions.ConfigFilePath, FilePath.FromString, "Configuration file (by default, config.wyam is used)."); syntax.DefineOption("u|update-packages", ref _configOptions.UpdatePackages, "Check the NuGet server for more recent versions of each package and update them if applicable."); syntax.DefineOption("use-local-packages", ref _configOptions.UseLocalPackages, "Toggles the use of a local NuGet packages folder."); syntax.DefineOption("use-global-sources", ref _configOptions.UseGlobalSources, "Toggles the use of the global NuGet sources (default is false)."); syntax.DefineOption("packages-path", ref _configOptions.PackagesPath, DirectoryPathFromArg, "The packages path to use (only if use-local is true)."); syntax.DefineOption("output-script", ref _configOptions.OutputScript, "Outputs the config script after it's been processed for further debugging."); syntax.DefineOption("verify-config", ref _verifyConfig, false, "Compile the configuration but do not execute."); syntax.DefineOption("noclean", ref _configOptions.NoClean, "Prevents cleaning of the output path on each execution."); syntax.DefineOption("nocache", ref _configOptions.NoCache, "Prevents caching information during execution (less memory usage but slower execution)."); _logFilePath = $"wyam-{DateTime.Now:yyyyMMddHHmmssfff}.txt"; if (!syntax.DefineOption("l|log", ref _logFilePath, FilePath.FromString, false, "Log all trace messages to the specified log file (by default, wyam-[datetime].txt).").IsSpecified) { _logFilePath = null; } // Metadata // TODO: Remove this dictionary and initial/global options Dictionary<string, object> settingsDictionary = new Dictionary<string, object>(); IReadOnlyList<string> globalMetadata = null; if (syntax.DefineOptionList("g|global", ref globalMetadata, "Deprecated, do not use.").IsSpecified) { Trace.Warning("-g/--global is deprecated and will be removed in a future version. Please use -s/--setting instead."); AddSettings(settingsDictionary, globalMetadata); } IReadOnlyList<string> initialMetadata = null; if (syntax.DefineOptionList("initial", ref initialMetadata, "Deprecated, do not use.").IsSpecified) { Trace.Warning("--initial is deprecated and will be removed in a future version. Please use -s/--setting instead."); AddSettings(settingsDictionary, initialMetadata); } IReadOnlyList<string> settings = null; if (syntax.DefineOptionList("s|setting", ref settings, "Specifies a setting as a key=value pair. Use the syntax [x,y] to specify an array value.").IsSpecified) { // _configOptions.Settings = MetadataParser.Parse(settings); TODO: Use this when AddSettings() is removed AddSettings(settingsDictionary, settings); } if (settingsDictionary.Count > 0) { _configOptions.Settings = settingsDictionary; } } // TODO: Remove this method and the global/initial support in the parser private static void AddSettings(IDictionary<string, object> settings, IReadOnlyList<string> value) { foreach (KeyValuePair<string, object> kvp in MetadataParser.Parse(value)) { settings[kvp.Key] = kvp.Value; } } protected override void ParseParameters(ArgumentSyntax syntax) { ParseRootPathParameter(syntax, _configOptions); } protected override ExitCode RunCommand(Preprocessor preprocessor) { // Get the standard input stream _configOptions.Stdin = StandardInputReader.Read(); // Fix the root folder and other files DirectoryPath currentDirectory = Environment.CurrentDirectory; _configOptions.RootPath = _configOptions.RootPath == null ? currentDirectory : currentDirectory.Combine(_configOptions.RootPath); _logFilePath = _logFilePath == null ? null : _configOptions.RootPath.CombineFile(_logFilePath); _configOptions.ConfigFilePath = _configOptions.RootPath.CombineFile(_configOptions.ConfigFilePath ?? "config.wyam"); // Set up the log file if (_logFilePath != null) { Trace.AddListener(new SimpleFileTraceListener(_logFilePath.FullPath)); } // Get the engine and configurator EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions); if (engineManager == null) { return ExitCode.CommandLineError; } // Configure and execute if (!engineManager.Configure()) { return ExitCode.ConfigurationError; } if (_verifyConfig) { Trace.Information("No errors. Exiting."); return ExitCode.Normal; } TraceEnviornment(engineManager); if (!engineManager.Execute()) { return ExitCode.ExecutionError; } bool messagePump = false; // Start the preview server Server previewServer = null; if (_preview) { messagePump = true; DirectoryPath previewPath = _previewRoot == null ? engineManager.Engine.FileSystem.GetOutputDirectory().Path : engineManager.Engine.FileSystem.GetOutputDirectory(_previewRoot).Path; previewServer = PreviewServer.Start(previewPath, _previewPort, _previewForceExtension, _previewVirtualDirectory, _watch && !_noReload); } // Start the watchers IDisposable inputFolderWatcher = null; IDisposable configFileWatcher = null; if (_watch) { messagePump = true; Trace.Information("Watching paths(s) {0}", string.Join(", ", engineManager.Engine.FileSystem.InputPaths)); inputFolderWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, engineManager.Engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); if (_configOptions.ConfigFilePath != null) { Trace.Information("Watching configuration file {0}", _configOptions.ConfigFilePath); configFileWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, new[] { _configOptions.ConfigFilePath.Directory }, false, _configOptions.ConfigFilePath.FileName.FullPath, path => { FilePath filePath = new FilePath(path); if (_configOptions.ConfigFilePath.Equals(filePath)) { _newEngine.Set(); _messageEvent.Set(); } }); } } // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; if (messagePump) { // Only wait for a key if console input has not been redirected, otherwise it's on the caller to exit if (!Console.IsInputRedirected) { // Start the key listening thread Thread thread = new Thread(() => { Trace.Information("Hit any key to exit"); Console.ReadKey(); _exit.Set(); _messageEvent.Set(); }) { IsBackground = true }; thread.Start(); } // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // See if we need a new engine if (_newEngine) { // Get a new engine Trace.Information("Configuration file {0} has changed, re-running", _configOptions.ConfigFilePath); engineManager.Dispose(); engineManager = EngineManager.Get(preprocessor, _configOptions); // Configure and execute if (!engineManager.Configure()) { exitCode = ExitCode.ConfigurationError; break; } TraceEnviornment(engineManager); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } // Clear the changed files since we just re-ran string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { } _newEngine.Unset(); } else { // Execute if files have changed HashSet<string> changedFiles = new HashSet<string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } previewServer?.TriggerReload(); } } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit any key to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); engineManager.Dispose(); inputFolderWatcher?.Dispose(); configFileWatcher?.Dispose(); previewServer?.Dispose(); } return exitCode; } private void TraceEnviornment(EngineManager engineManager) { Trace.Information($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.RootPath}"); Trace.Information($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.FileSystem.InputPaths)}"); Trace.Information($"Output path:{Environment.NewLine} {engineManager.Engine.FileSystem.OutputPath}"); Trace.Information($"Temp path:{Environment.NewLine} {engineManager.Engine.FileSystem.TempPath}"); Trace.Information($"Settings:{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.Settings.Select(x => $"{x.Key}: {x.Value?.ToString() ?? "null"}"))}"); } } }
//------------------------------------------------------------------------------ // <copyright file="RegexFCD.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // This RegexFCD class is internal to the Regex package. // It builds a bunch of FC information (RegexFC) about // the regex for optimization purposes. // Implementation notes: // // This step is as simple as walking the tree and emitting // sequences of codes. namespace System.Text.RegularExpressions { using System.Collections; using System.Globalization; internal sealed class RegexFCD { private int[] _intStack; private int _intDepth; private RegexFC[] _fcStack; private int _fcDepth; private bool _skipAllChildren; // don't process any more children at the current level private bool _skipchild; // don't process the current child. private bool _failed = false; private const int BeforeChild = 64; private const int AfterChild = 128; // where the regex can be pegged internal const int Beginning = 0x0001; internal const int Bol = 0x0002; internal const int Start = 0x0004; internal const int Eol = 0x0008; internal const int EndZ = 0x0010; internal const int End = 0x0020; internal const int Boundary = 0x0040; internal const int ECMABoundary = 0x0080; /* * This is the one of the only two functions that should be called from outside. * It takes a RegexTree and computes the set of chars that can start it. */ internal static RegexPrefix FirstChars(RegexTree t) { RegexFCD s = new RegexFCD(); RegexFC fc = s.RegexFCFromRegexTree(t); if (fc == null || fc._nullable) return null; CultureInfo culture = ((t._options & RegexOptions.CultureInvariant) != 0) ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; return new RegexPrefix(fc.GetFirstChars(culture), fc.IsCaseInsensitive()); } /* * This is a related computation: it takes a RegexTree and computes the * leading substring if it see one. It's quite trivial and gives up easily. */ internal static RegexPrefix Prefix(RegexTree tree) { RegexNode curNode; RegexNode concatNode = null; int nextChild = 0; curNode = tree._root; for (;;) { switch (curNode._type) { case RegexNode.Concatenate: if (curNode.ChildCount() > 0) { concatNode = curNode; nextChild = 0; } break; case RegexNode.Greedy: case RegexNode.Capture: curNode = curNode.Child(0); concatNode = null; continue; case RegexNode.Oneloop: case RegexNode.Onelazy: if (curNode._m > 0) { string pref = String.Empty.PadRight(curNode._m, curNode._ch); return new RegexPrefix(pref, 0 != (curNode._options & RegexOptions.IgnoreCase)); } else return RegexPrefix.Empty; case RegexNode.One: return new RegexPrefix(curNode._ch.ToString(CultureInfo.InvariantCulture), 0 != (curNode._options & RegexOptions.IgnoreCase)); case RegexNode.Multi: return new RegexPrefix(curNode._str, 0 != (curNode._options & RegexOptions.IgnoreCase)); case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.ECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: case RegexNode.Empty: case RegexNode.Require: case RegexNode.Prevent: break; default: return RegexPrefix.Empty; } if (concatNode == null || nextChild >= concatNode.ChildCount()) return RegexPrefix.Empty; curNode = concatNode.Child(nextChild++); } } /* * Yet another related computation: it takes a RegexTree and computes the * leading anchors that it encounters. */ internal static int Anchors(RegexTree tree) { RegexNode curNode; RegexNode concatNode = null; int nextChild = 0; int result = 0; curNode = tree._root; for (;;) { switch (curNode._type) { case RegexNode.Concatenate: if (curNode.ChildCount() > 0) { concatNode = curNode; nextChild = 0; } break; case RegexNode.Greedy: case RegexNode.Capture: curNode = curNode.Child(0); concatNode = null; continue; case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.ECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: return result | AnchorFromType(curNode._type); case RegexNode.Empty: case RegexNode.Require: case RegexNode.Prevent: break; default: return result; } if (concatNode == null || nextChild >= concatNode.ChildCount()) return result; curNode = concatNode.Child(nextChild++); } } /* * Convert anchor type to anchor bit. */ private static int AnchorFromType(int type) { switch (type) { case RegexNode.Bol: return Bol; case RegexNode.Eol: return Eol; case RegexNode.Boundary: return Boundary; case RegexNode.ECMABoundary: return ECMABoundary; case RegexNode.Beginning: return Beginning; case RegexNode.Start: return Start; case RegexNode.EndZ: return EndZ; case RegexNode.End: return End; default: return 0; } } #if DBG internal static String AnchorDescription(int anchors) { StringBuilder sb = new StringBuilder(); if (0 != (anchors & Beginning)) sb.Append(", Beginning"); if (0 != (anchors & Start)) sb.Append(", Start"); if (0 != (anchors & Bol)) sb.Append(", Bol"); if (0 != (anchors & Boundary)) sb.Append(", Boundary"); if (0 != (anchors & ECMABoundary)) sb.Append(", ECMABoundary"); if (0 != (anchors & Eol)) sb.Append(", Eol"); if (0 != (anchors & End)) sb.Append(", End"); if (0 != (anchors & EndZ)) sb.Append(", EndZ"); if (sb.Length >= 2) return(sb.ToString(2, sb.Length - 2)); return "None"; } #endif /* * private constructor; can't be created outside */ private RegexFCD() { _fcStack = new RegexFC[32]; _intStack = new int[32]; } /* * To avoid recursion, we use a simple integer stack. * This is the push. */ private void PushInt(int I) { if (_intDepth >= _intStack.Length) { int [] expanded = new int[_intDepth * 2]; System.Array.Copy(_intStack, 0, expanded, 0, _intDepth); _intStack = expanded; } _intStack[_intDepth++] = I; } /* * True if the stack is empty. */ private bool IntIsEmpty() { return _intDepth == 0; } /* * This is the pop. */ private int PopInt() { return _intStack[--_intDepth]; } /* * We also use a stack of RegexFC objects. * This is the push. */ private void PushFC(RegexFC fc) { if (_fcDepth >= _fcStack.Length) { RegexFC[] expanded = new RegexFC[_fcDepth * 2]; System.Array.Copy(_fcStack, 0, expanded, 0, _fcDepth); _fcStack = expanded; } _fcStack[_fcDepth++] = fc; } /* * True if the stack is empty. */ private bool FCIsEmpty() { return _fcDepth == 0; } /* * This is the pop. */ private RegexFC PopFC() { return _fcStack[--_fcDepth]; } /* * This is the top. */ private RegexFC TopFC() { return _fcStack[_fcDepth - 1]; } /* * The main FC computation. It does a shortcutted depth-first walk * through the tree and calls CalculateFC to emits code before * and after each child of an interior node, and at each leaf. */ private RegexFC RegexFCFromRegexTree(RegexTree tree) { RegexNode curNode; int curChild; curNode = tree._root; curChild = 0; for (;;) { if (curNode._children == null) { // This is a leaf node CalculateFC(curNode._type, curNode, 0); } else if (curChild < curNode._children.Count && !_skipAllChildren) { // This is an interior node, and we have more children to analyze CalculateFC(curNode._type | BeforeChild, curNode, curChild); if (!_skipchild) { curNode = (RegexNode)curNode._children[curChild]; // this stack is how we get a depth first walk of the tree. PushInt(curChild); curChild = 0; } else { curChild++; _skipchild = false; } continue; } // This is an interior node where we've finished analyzing all the children, or // the end of a leaf node. _skipAllChildren = false; if (IntIsEmpty()) break; curChild = PopInt(); curNode = curNode._next; CalculateFC(curNode._type | AfterChild, curNode, curChild); if (_failed) return null; curChild++; } if (FCIsEmpty()) return null; return PopFC(); } /* * Called in Beforechild to prevent further processing of the current child */ private void SkipChild() { _skipchild = true; } /* * FC computation and shortcut cases for each node type */ private void CalculateFC(int NodeType, RegexNode node, int CurIndex) { bool ci = false; bool rtl = false; if (NodeType <= RegexNode.Ref) { if ((node._options & RegexOptions.IgnoreCase) != 0) ci = true; if ((node._options & RegexOptions.RightToLeft) != 0) rtl = true; } switch (NodeType) { case RegexNode.Concatenate | BeforeChild: case RegexNode.Alternate | BeforeChild: case RegexNode.Testref | BeforeChild: case RegexNode.Loop | BeforeChild: case RegexNode.Lazyloop | BeforeChild: break; case RegexNode.Testgroup | BeforeChild: if (CurIndex == 0) SkipChild(); break; case RegexNode.Empty: PushFC(new RegexFC(true)); break; case RegexNode.Concatenate | AfterChild: if (CurIndex != 0) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, true); } if (!TopFC()._nullable) _skipAllChildren = true; break; case RegexNode.Testgroup | AfterChild: if (CurIndex > 1) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, false); } break; case RegexNode.Alternate | AfterChild: case RegexNode.Testref | AfterChild: if (CurIndex != 0) { RegexFC child = PopFC(); RegexFC cumul = TopFC(); _failed = !cumul.AddFC(child, false); } break; case RegexNode.Loop | AfterChild: case RegexNode.Lazyloop | AfterChild: if (node._m == 0) TopFC()._nullable = true; break; case RegexNode.Group | BeforeChild: case RegexNode.Group | AfterChild: case RegexNode.Capture | BeforeChild: case RegexNode.Capture | AfterChild: case RegexNode.Greedy | BeforeChild: case RegexNode.Greedy | AfterChild: break; case RegexNode.Require | BeforeChild: case RegexNode.Prevent | BeforeChild: SkipChild(); PushFC(new RegexFC(true)); break; case RegexNode.Require | AfterChild: case RegexNode.Prevent | AfterChild: break; case RegexNode.One: case RegexNode.Notone: PushFC(new RegexFC(node._ch, NodeType == RegexNode.Notone, false, ci)); break; case RegexNode.Oneloop: case RegexNode.Onelazy: PushFC(new RegexFC(node._ch, false, node._m == 0, ci)); break; case RegexNode.Notoneloop: case RegexNode.Notonelazy: PushFC(new RegexFC(node._ch, true, node._m == 0, ci)); break; case RegexNode.Multi: if (node._str.Length == 0) PushFC(new RegexFC(true)); else if (!rtl) PushFC(new RegexFC(node._str[0], false, false, ci)); else PushFC(new RegexFC(node._str[node._str.Length - 1], false, false, ci)); break; case RegexNode.Set: PushFC(new RegexFC(node._str, false, ci)); break; case RegexNode.Setloop: case RegexNode.Setlazy: PushFC(new RegexFC(node._str, node._m == 0, ci)); break; case RegexNode.Ref: PushFC(new RegexFC(RegexCharClass.AnyClass, true, false)); break; case RegexNode.Nothing: case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.Nonboundary: case RegexNode.ECMABoundary: case RegexNode.NonECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: PushFC(new RegexFC(true)); break; default: throw new ArgumentException(SR.GetString(SR.UnexpectedOpcode, NodeType.ToString(CultureInfo.CurrentCulture))); } } } internal sealed class RegexFC { internal RegexCharClass _cc; internal bool _nullable; internal bool _caseInsensitive; internal RegexFC(bool nullable) { _cc = new RegexCharClass(); _nullable = nullable; } internal RegexFC(char ch, bool not, bool nullable, bool caseInsensitive) { _cc = new RegexCharClass(); if (not) { if (ch > 0) _cc.AddRange('\0', (char)(ch - 1)); if (ch < 0xFFFF) _cc.AddRange((char)(ch + 1), '\uFFFF'); } else { _cc.AddRange(ch, ch); } _caseInsensitive = caseInsensitive; _nullable = nullable; } internal RegexFC(String charClass, bool nullable, bool caseInsensitive) { _cc = RegexCharClass.Parse(charClass); _nullable = nullable; _caseInsensitive = caseInsensitive; } internal bool AddFC(RegexFC fc, bool concatenate) { if (!_cc.CanMerge || !fc._cc.CanMerge) { return false; } if (concatenate) { if (!_nullable) return true; if (!fc._nullable) _nullable = false; } else { if (fc._nullable) _nullable = true; } _caseInsensitive |= fc._caseInsensitive; _cc.AddCharClass(fc._cc); return true; } internal String GetFirstChars(CultureInfo culture) { if (_caseInsensitive) _cc.AddLowercase(culture); return _cc.ToStringClass(); } internal bool IsCaseInsensitive() { return _caseInsensitive; } } internal sealed class RegexPrefix { internal String _prefix; internal bool _caseInsensitive; internal static RegexPrefix _empty = new RegexPrefix(String.Empty, false); internal RegexPrefix(String prefix, bool ci) { _prefix = prefix; _caseInsensitive = ci; } internal String Prefix { get { return _prefix; } } internal bool CaseInsensitive { get { return _caseInsensitive; } } internal static RegexPrefix Empty { get { return _empty; } } } }
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using UnityEngine; namespace Menu {public class Menu : MonoBehaviour{ public static int frame; void Update () { Update(Time.deltaTime, this); frame++; } public bool JustEntered = true; public void Start() { WinConditionField = new CnvInputField("MenuUI/WinConditionText/InputField"); TurnDurationField = new CnvInputField("MenuUI/TurnDurationText/InputField"); StartingResourcesField = new CnvInputField("MenuUI/StartingResourcesText/InputField"); QuitButton = new CnvButton("MenuUI/QuitButton"); PlayerCountField = new CnvInputField("MenuUI/PlayerCountText/InputField"); PlayButton = new CnvButton("MenuUI/PlayButton"); Planet = new MenuPlanet("MenuPlanet"); MiningRateField = new CnvInputField("MenuUI/MiningRateText/InputField"); MessageCostField = new CnvInputField("MenuUI/MessageCostText/InputField"); MapSizeField = new CnvInputField("MenuUI/MapSizeText/InputField"); MapSeedField = new CnvInputField("MenuUI/MapSeedText/InputField"); LoadingText = new CnvText("MenuUI/LoadingText"); Loading = false; BlackScreen = new CnvPanel("MenuUI/LoadingCanvas/LoadingScreen"); } public CnvPanel BlackScreen; public System.Boolean Loading; public CnvText LoadingText; public CnvInputField MapSeedField; public CnvInputField MapSizeField; public CnvInputField MessageCostField; public CnvInputField MiningRateField; public MenuPlanet Planet; public CnvButton __PlayButton; public CnvButton PlayButton{ get { return __PlayButton; } set{ __PlayButton = value; if(!value.JustEntered) __PlayButton = value; else{ value.JustEntered = false; } } } public CnvInputField PlayerCountField; public CnvButton __QuitButton; public CnvButton QuitButton{ get { return __QuitButton; } set{ __QuitButton = value; if(!value.JustEntered) __QuitButton = value; else{ value.JustEntered = false; } } } public CnvInputField StartingResourcesField; public CnvInputField TurnDurationField; public CnvInputField WinConditionField; public System.Single ___lifetime00; public System.Int32 ___startingResources30; public System.Int32 ___turnDuration30; public System.Int32 ___playerCount30; public System.Int32 ___winCondition30; public System.Int32 ___messageCost30; public System.Int32 ___miningRate30; public System.Int32 ___mapSize30; public System.Int32 ___mapSize31; public System.Int32 ___mapSeed30; System.DateTime init_time = System.DateTime.Now; public void Update(float dt, Menu world) { var t = System.DateTime.Now; BlackScreen.Update(dt, world); LoadingText.Update(dt, world); MapSeedField.Update(dt, world); MapSizeField.Update(dt, world); MessageCostField.Update(dt, world); MiningRateField.Update(dt, world); Planet.Update(dt, world); PlayButton.Update(dt, world); PlayerCountField.Update(dt, world); QuitButton.Update(dt, world); StartingResourcesField.Update(dt, world); TurnDurationField.Update(dt, world); WinConditionField.Update(dt, world); this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); this.Rule5(dt, world); this.Rule6(dt, world); this.Rule7(dt, world); this.Rule8(dt, world); this.Rule9(dt, world); this.Rule10(dt, world); this.Rule11(dt, world); this.Rule12(dt, world); this.Rule13(dt, world); this.Rule14(dt, world); this.Rule15(dt, world); this.Rule16(dt, world); this.Rule17(dt, world); this.Rule18(dt, world); this.Rule19(dt, world); } int s0=-1; public void Rule0(float dt, Menu world){ switch (s0) { case -1: if(!(PlayButton.Clicked)) { s0 = -1; return; }else { goto case 6; } case 6: LoadingText.Alpha = LoadingText.Alpha; BlackScreen.Alpha = BlackScreen.Alpha; Loading = true; s0 = 5; return; case 5: ___lifetime00 = 2f; goto case 2; case 2: if(!(((1f) > (BlackScreen.Alpha)))) { goto case 1; }else { goto case 3; } case 3: LoadingText.Alpha = 0f; BlackScreen.Alpha = ((BlackScreen.Alpha) + (((((1f) / (___lifetime00))) * (dt)))); Loading = Loading; s0 = 2; return; case 1: LoadingText.Alpha = 1f; BlackScreen.Alpha = 1f; Loading = Loading; s0 = 0; return; case 0: if(!(false)) { s0 = 0; return; }else { s0 = -1; return; } default: return;}} int s1=-1; public void Rule1(float dt, Menu world){ switch (s1) { case -1: LoadingText.Alpha = 0f; s1 = 0; return; case 0: if(!(false)) { s1 = 0; return; }else { s1 = -1; return; } default: return;}} int s2=-1; public void Rule2(float dt, Menu world){ switch (s2) { case -1: if(!(((QuitButton.Clicked) && (!(Loading))))) { s2 = -1; return; }else { goto case 1; } case 1: QuitButton.Clicked = false; s2 = 0; return; case 0: UnityEngine.Application.Quit(); s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, Menu world){ switch (s3) { case -1: if(!(PlayButton.Clicked)) { s3 = -1; return; }else { goto case 12; } case 12: ___startingResources30 = GameUtils.StringToInt(StartingResourcesField.Text); ___turnDuration30 = GameUtils.StringToInt(TurnDurationField.Text); ___playerCount30 = GameUtils.StringToInt(PlayerCountField.Text); ___winCondition30 = GameUtils.StringToInt(WinConditionField.Text); ___messageCost30 = GameUtils.StringToInt(MessageCostField.Text); ___miningRate30 = GameUtils.StringToInt(MiningRateField.Text); ___mapSize30 = GameUtils.StringToInt(MapSizeField.Text); ___mapSize31 = UnityEngine.Mathf.Max(___mapSize30,___playerCount30); ___mapSeed30 = GameUtils.StringToInt(MapSeedField.Text); GameSettings.SetParameters(___startingResources30,___turnDuration30,___playerCount30,___winCondition30,___messageCost30,___miningRate30,___mapSize31,___mapSeed30); goto case 2; case 2: if(!(((((LoadingText.Alpha) == (1f))) && (((BlackScreen.Alpha) == (1f)))))) { s3 = 2; return; }else { goto case 1; } case 1: PlayButton.Clicked = false; s3 = 0; return; case 0: UnityEngine.Application.LoadLevel("contact"); s3 = -1; return; default: return;}} int s4=-1; public void Rule4(float dt, Menu world){ switch (s4) { case -1: MapSeedField.Text = GameUtils.IntToString(UnityEngine.Random.Range(0,100000)); s4 = 0; return; case 0: if(!(false)) { s4 = 0; return; }else { s4 = -1; return; } default: return;}} int s5=-1; public void Rule5(float dt, Menu world){ switch (s5) { case -1: MapSizeField.Text = GameUtils.IntToString(4); s5 = 0; return; case 0: if(!(false)) { s5 = 0; return; }else { s5 = -1; return; } default: return;}} int s6=-1; public void Rule6(float dt, Menu world){ switch (s6) { case -1: MiningRateField.Text = GameUtils.IntToString(25); s6 = 0; return; case 0: if(!(false)) { s6 = 0; return; }else { s6 = -1; return; } default: return;}} int s7=-1; public void Rule7(float dt, Menu world){ switch (s7) { case -1: MessageCostField.Text = GameUtils.IntToString(300); s7 = 0; return; case 0: if(!(false)) { s7 = 0; return; }else { s7 = -1; return; } default: return;}} int s8=-1; public void Rule8(float dt, Menu world){ switch (s8) { case -1: WinConditionField.Text = GameUtils.IntToString(500); s8 = 0; return; case 0: if(!(false)) { s8 = 0; return; }else { s8 = -1; return; } default: return;}} int s9=-1; public void Rule9(float dt, Menu world){ switch (s9) { case -1: PlayerCountField.Text = GameUtils.IntToString(4); s9 = 0; return; case 0: if(!(false)) { s9 = 0; return; }else { s9 = -1; return; } default: return;}} int s10=-1; public void Rule10(float dt, Menu world){ switch (s10) { case -1: TurnDurationField.Text = GameUtils.IntToString(120); s10 = 0; return; case 0: if(!(false)) { s10 = 0; return; }else { s10 = -1; return; } default: return;}} int s11=-1; public void Rule11(float dt, Menu world){ switch (s11) { case -1: StartingResourcesField.Text = GameUtils.IntToString(500); s11 = 0; return; case 0: if(!(false)) { s11 = 0; return; }else { s11 = -1; return; } default: return;}} int s12=-1; public void Rule12(float dt, Menu world){ switch (s12) { case -1: MapSeedField.MaxValue = 100000; MapSeedField.MinValue = 0; s12 = 0; return; case 0: if(!(false)) { s12 = 0; return; }else { s12 = -1; return; } default: return;}} int s13=-1; public void Rule13(float dt, Menu world){ switch (s13) { case -1: MapSizeField.MaxValue = 1000; MapSizeField.MinValue = 2; s13 = 0; return; case 0: if(!(false)) { s13 = 0; return; }else { s13 = -1; return; } default: return;}} int s14=-1; public void Rule14(float dt, Menu world){ switch (s14) { case -1: MiningRateField.MaxValue = 5000; MiningRateField.MinValue = 1; s14 = 0; return; case 0: if(!(false)) { s14 = 0; return; }else { s14 = -1; return; } default: return;}} int s15=-1; public void Rule15(float dt, Menu world){ switch (s15) { case -1: MessageCostField.MaxValue = 5000; MessageCostField.MinValue = 0; s15 = 0; return; case 0: if(!(false)) { s15 = 0; return; }else { s15 = -1; return; } default: return;}} int s16=-1; public void Rule16(float dt, Menu world){ switch (s16) { case -1: WinConditionField.MaxValue = 9000; WinConditionField.MinValue = 100; s16 = 0; return; case 0: if(!(false)) { s16 = 0; return; }else { s16 = -1; return; } default: return;}} int s17=-1; public void Rule17(float dt, Menu world){ switch (s17) { case -1: PlayerCountField.MaxValue = 100; PlayerCountField.MinValue = 2; s17 = 0; return; case 0: if(!(false)) { s17 = 0; return; }else { s17 = -1; return; } default: return;}} int s18=-1; public void Rule18(float dt, Menu world){ switch (s18) { case -1: TurnDurationField.MaxValue = 600; TurnDurationField.MinValue = 30; s18 = 0; return; case 0: if(!(false)) { s18 = 0; return; }else { s18 = -1; return; } default: return;}} int s19=-1; public void Rule19(float dt, Menu world){ switch (s19) { case -1: StartingResourcesField.MaxValue = 9000; StartingResourcesField.MinValue = 0; s19 = 0; return; case 0: if(!(false)) { s19 = 0; return; }else { s19 = -1; return; } default: return;}} } public class MenuPlanet{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public MenuPlanet(System.String n) {JustEntered = false; frame = Menu.frame; UnityPlanet = UnityPlanet.Find(n); RotationVelocity = new UnityEngine.Vector3(0f,3f,0f); } public System.Boolean ClickedOver{ get { return UnityPlanet.ClickedOver; } } public UnityEngine.Color OwnerColor{ get { return UnityPlanet.OwnerColor; } set{UnityPlanet.OwnerColor = value; } } public UnityEngine.Vector3 Position{ get { return UnityPlanet.Position; } set{UnityPlanet.Position = value; } } public UnityEngine.Quaternion Rotation{ get { return UnityPlanet.Rotation; } set{UnityPlanet.Rotation = value; } } public UnityEngine.Vector3 RotationVelocity; public System.Boolean Selected{ get { return UnityPlanet.Selected; } set{UnityPlanet.Selected = value; } } public UnityEngine.Color TargetingPlayerColor{ get { return UnityPlanet.TargetingPlayerColor; } set{UnityPlanet.TargetingPlayerColor = value; } } public UnityPlanet UnityPlanet; public UnityEngine.Animation animation{ get { return UnityPlanet.animation; } } public UnityEngine.AudioSource audio{ get { return UnityPlanet.audio; } } public UnityEngine.Camera camera{ get { return UnityPlanet.camera; } } public UnityEngine.Collider collider{ get { return UnityPlanet.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityPlanet.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityPlanet.constantForce; } } public System.Boolean enabled{ get { return UnityPlanet.enabled; } set{UnityPlanet.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityPlanet.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityPlanet.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityPlanet.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityPlanet.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityPlanet.hideFlags; } set{UnityPlanet.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityPlanet.hingeJoint; } } public UnityEngine.Light light{ get { return UnityPlanet.light; } } public System.String name{ get { return UnityPlanet.name; } set{UnityPlanet.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityPlanet.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityPlanet.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityPlanet.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityPlanet.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityPlanet.rigidbody2D; } } public System.String tag{ get { return UnityPlanet.tag; } set{UnityPlanet.tag = value; } } public UnityEngine.Transform transform{ get { return UnityPlanet.transform; } } public System.Boolean useGUILayout{ get { return UnityPlanet.useGUILayout; } set{UnityPlanet.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; this.Rule1(dt, world); this.Rule0(dt, world); } public void Rule1(float dt, Menu world) { Rotation = (UnityEngine.Quaternion.Euler((RotationVelocity) * (dt))) * (Rotation); } int s0=-1; public void Rule0(float dt, Menu world){ switch (s0) { case -1: OwnerColor = new UnityEngine.Color(0,0,0,0); TargetingPlayerColor = new UnityEngine.Color(0,0,0,0); s0 = 0; return; case 0: if(!(false)) { s0 = 0; return; }else { s0 = -1; return; } default: return;}} } public class CnvButton{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvButton(System.String n) {JustEntered = false; frame = Menu.frame; UnityButton = UnityButton.GetButton(n); } public System.Boolean Active{ get { return UnityButton.Active; } set{UnityButton.Active = value; } } public System.Boolean Clicked{ get { return UnityButton.Clicked; } set{UnityButton.Clicked = value; } } public System.Boolean Disabled{ get { return UnityButton.Disabled; } set{UnityButton.Disabled = value; } } public System.String ImageName{ get { return UnityButton.ImageName; } set{UnityButton.ImageName = value; } } public UnityButton UnityButton; public UnityEngine.Animation animation{ get { return UnityButton.animation; } } public UnityEngine.AudioSource audio{ get { return UnityButton.audio; } } public UnityEngine.Camera camera{ get { return UnityButton.camera; } } public UnityEngine.Collider collider{ get { return UnityButton.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityButton.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityButton.constantForce; } } public System.Boolean enabled{ get { return UnityButton.enabled; } set{UnityButton.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityButton.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityButton.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityButton.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityButton.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityButton.hideFlags; } set{UnityButton.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityButton.hingeJoint; } } public UnityEngine.Light light{ get { return UnityButton.light; } } public System.String name{ get { return UnityButton.name; } set{UnityButton.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityButton.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityButton.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityButton.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityButton.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityButton.rigidbody2D; } } public System.String tag{ get { return UnityButton.tag; } set{UnityButton.tag = value; } } public UnityEngine.Transform transform{ get { return UnityButton.transform; } } public System.Boolean useGUILayout{ get { return UnityButton.useGUILayout; } set{UnityButton.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvSelectionBox{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvSelectionBox(System.String n) {JustEntered = false; frame = Menu.frame; UnitySelectionBox = UnitySelectionBox.GetBox(n); } public System.Boolean Active{ get { return UnitySelectionBox.Active; } set{UnitySelectionBox.Active = value; } } public System.Boolean Clicked{ get { return UnitySelectionBox.Clicked; } set{UnitySelectionBox.Clicked = value; } } public System.Boolean Disabled{ get { return UnitySelectionBox.Disabled; } set{UnitySelectionBox.Disabled = value; } } public System.String ImageName{ get { return UnitySelectionBox.ImageName; } set{UnitySelectionBox.ImageName = value; } } public UnitySelectionBox UnitySelectionBox; public UnityEngine.Animation animation{ get { return UnitySelectionBox.animation; } } public UnityEngine.AudioSource audio{ get { return UnitySelectionBox.audio; } } public UnityEngine.Camera camera{ get { return UnitySelectionBox.camera; } } public UnityEngine.Collider collider{ get { return UnitySelectionBox.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnitySelectionBox.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnitySelectionBox.constantForce; } } public System.Boolean enabled{ get { return UnitySelectionBox.enabled; } set{UnitySelectionBox.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnitySelectionBox.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnitySelectionBox.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnitySelectionBox.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnitySelectionBox.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnitySelectionBox.hideFlags; } set{UnitySelectionBox.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnitySelectionBox.hingeJoint; } } public UnityEngine.Light light{ get { return UnitySelectionBox.light; } } public System.String name{ get { return UnitySelectionBox.name; } set{UnitySelectionBox.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnitySelectionBox.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnitySelectionBox.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnitySelectionBox.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnitySelectionBox.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnitySelectionBox.rigidbody2D; } } public System.String tag{ get { return UnitySelectionBox.tag; } set{UnitySelectionBox.tag = value; } } public UnityEngine.Transform transform{ get { return UnitySelectionBox.transform; } } public System.Boolean useGUILayout{ get { return UnitySelectionBox.useGUILayout; } set{UnitySelectionBox.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvText{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvText(System.String n) {JustEntered = false; frame = Menu.frame; UnityText = UnityText.GetText(n); } public System.Single Alpha{ get { return UnityText.Alpha; } set{UnityText.Alpha = value; } } public System.String Text{ get { return UnityText.Text; } set{UnityText.Text = value; } } public UnityText UnityText; public UnityEngine.Animation animation{ get { return UnityText.animation; } } public UnityEngine.AudioSource audio{ get { return UnityText.audio; } } public UnityEngine.Camera camera{ get { return UnityText.camera; } } public UnityEngine.Collider collider{ get { return UnityText.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityText.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityText.constantForce; } } public System.Boolean enabled{ get { return UnityText.enabled; } set{UnityText.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityText.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityText.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityText.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityText.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityText.hideFlags; } set{UnityText.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityText.hingeJoint; } } public UnityEngine.Light light{ get { return UnityText.light; } } public System.String name{ get { return UnityText.name; } set{UnityText.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityText.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityText.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityText.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityText.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityText.rigidbody2D; } } public System.String tag{ get { return UnityText.tag; } set{UnityText.tag = value; } } public UnityEngine.Transform transform{ get { return UnityText.transform; } } public System.Boolean useGUILayout{ get { return UnityText.useGUILayout; } set{UnityText.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class IconInstantiation{ public int frame; public bool JustEntered = true; private UnityEngine.Vector3 position; private System.String imageName; private System.String parentPath; public int ID; public IconInstantiation(UnityEngine.Vector3 position, System.String imageName, System.String parentPath) {JustEntered = false; frame = Menu.frame; Position = position; ParentPath = parentPath; ImageName = imageName; } public System.String ImageName; public System.String ParentPath; public UnityEngine.Vector3 Position; public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvIcon{ public int frame; public bool JustEntered = true; private System.String n; private Option<IconInstantiation> instantiate; public int ID; public CnvIcon(System.String n, Option<IconInstantiation> instantiate) {JustEntered = false; frame = Menu.frame; UnityIcon ___icon00; if(instantiate.IsSome) { ___icon00 = UnityIcon.Instantiate(n,instantiate.Value.ImageName,instantiate.Value.ParentPath,instantiate.Value.Position); }else { ___icon00 = UnityIcon.GetIcon(n); } UnityIcon = ___icon00; } public System.Boolean Active{ get { return UnityIcon.Active; } set{UnityIcon.Active = value; } } public UnityEngine.Color Color{ get { return UnityIcon.Color; } set{UnityIcon.Color = value; } } public System.Single Height{ get { return UnityIcon.Height; } } public System.String ImageName{ get { return UnityIcon.ImageName; } set{UnityIcon.ImageName = value; } } public UnityEngine.Vector2 Origin{ get { return UnityIcon.Origin; } set{UnityIcon.Origin = value; } } public System.String Text{ get { return UnityIcon.Text; } set{UnityIcon.Text = value; } } public UnityIcon UnityIcon; public System.Single Width{ get { return UnityIcon.Width; } } public UnityEngine.Animation animation{ get { return UnityIcon.animation; } } public UnityEngine.AudioSource audio{ get { return UnityIcon.audio; } } public UnityEngine.Camera camera{ get { return UnityIcon.camera; } } public UnityEngine.Collider collider{ get { return UnityIcon.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityIcon.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityIcon.constantForce; } } public System.Boolean enabled{ get { return UnityIcon.enabled; } set{UnityIcon.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityIcon.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityIcon.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityIcon.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityIcon.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityIcon.hideFlags; } set{UnityIcon.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityIcon.hingeJoint; } } public UnityEngine.Light light{ get { return UnityIcon.light; } } public System.String name{ get { return UnityIcon.name; } set{UnityIcon.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityIcon.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityIcon.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityIcon.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityIcon.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityIcon.rigidbody2D; } } public System.String tag{ get { return UnityIcon.tag; } set{UnityIcon.tag = value; } } public UnityEngine.Transform transform{ get { return UnityIcon.transform; } } public System.Boolean useGUILayout{ get { return UnityIcon.useGUILayout; } set{UnityIcon.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvFrame{ public int frame; public bool JustEntered = true; private System.String n; private Option<System.Single> offsetX; private Option<System.Single> offsetY; public int ID; public CnvFrame(System.String n, Option<System.Single> offsetX, Option<System.Single> offsetY) {JustEntered = false; frame = Menu.frame; System.Single ___offsetX00; if(offsetX.IsNone) { ___offsetX00 = 0f; }else { ___offsetX00 = offsetX.Value; } System.Single ___offsetY00; if(offsetY.IsNone) { ___offsetY00 = 0f; }else { ___offsetY00 = offsetY.Value; } UnityFrame = UnityFrame.GetFrame(n,___offsetX00,___offsetY00); } public System.Single Height{ get { return UnityFrame.Height; } } public System.Single OffsetX{ get { return UnityFrame.OffsetX; } set{UnityFrame.OffsetX = value; } } public System.Single OffsetY{ get { return UnityFrame.OffsetY; } set{UnityFrame.OffsetY = value; } } public UnityEngine.Vector2 Origin{ get { return UnityFrame.Origin; } } public UnityFrame UnityFrame; public System.Single Width{ get { return UnityFrame.Width; } } public UnityEngine.Animation animation{ get { return UnityFrame.animation; } } public UnityEngine.AudioSource audio{ get { return UnityFrame.audio; } } public UnityEngine.Camera camera{ get { return UnityFrame.camera; } } public UnityEngine.Collider collider{ get { return UnityFrame.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityFrame.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityFrame.constantForce; } } public System.Boolean enabled{ get { return UnityFrame.enabled; } set{UnityFrame.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityFrame.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityFrame.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityFrame.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityFrame.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityFrame.hideFlags; } set{UnityFrame.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityFrame.hingeJoint; } } public UnityEngine.Light light{ get { return UnityFrame.light; } } public System.String name{ get { return UnityFrame.name; } set{UnityFrame.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityFrame.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityFrame.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityFrame.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityFrame.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityFrame.rigidbody2D; } } public System.String tag{ get { return UnityFrame.tag; } set{UnityFrame.tag = value; } } public UnityEngine.Transform transform{ get { return UnityFrame.transform; } } public System.Boolean useGUILayout{ get { return UnityFrame.useGUILayout; } set{UnityFrame.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvToggle{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvToggle(System.String n) {JustEntered = false; frame = Menu.frame; UnityToggle = UnityToggle.GetToggle(n); } public System.Boolean IsOn{ get { return UnityToggle.IsOn; } set{UnityToggle.IsOn = value; } } public UnityToggle UnityToggle; public UnityEngine.Animation animation{ get { return UnityToggle.animation; } } public UnityEngine.AudioSource audio{ get { return UnityToggle.audio; } } public UnityEngine.Camera camera{ get { return UnityToggle.camera; } } public UnityEngine.Collider collider{ get { return UnityToggle.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityToggle.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityToggle.constantForce; } } public System.Boolean enabled{ get { return UnityToggle.enabled; } set{UnityToggle.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityToggle.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityToggle.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityToggle.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityToggle.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityToggle.hideFlags; } set{UnityToggle.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityToggle.hingeJoint; } } public UnityEngine.Light light{ get { return UnityToggle.light; } } public System.String name{ get { return UnityToggle.name; } set{UnityToggle.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityToggle.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityToggle.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityToggle.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityToggle.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityToggle.rigidbody2D; } } public System.String tag{ get { return UnityToggle.tag; } set{UnityToggle.tag = value; } } public UnityEngine.Transform transform{ get { return UnityToggle.transform; } } public System.Boolean useGUILayout{ get { return UnityToggle.useGUILayout; } set{UnityToggle.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvPanel{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvPanel(System.String n) {JustEntered = false; frame = Menu.frame; UnityPanel = UnityPanel.GetPanel(n); } public System.Single Alpha{ get { return UnityPanel.Alpha; } set{UnityPanel.Alpha = value; } } public UnityPanel UnityPanel; public UnityEngine.Animation animation{ get { return UnityPanel.animation; } } public UnityEngine.AudioSource audio{ get { return UnityPanel.audio; } } public UnityEngine.Camera camera{ get { return UnityPanel.camera; } } public UnityEngine.Collider collider{ get { return UnityPanel.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityPanel.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityPanel.constantForce; } } public System.Boolean enabled{ get { return UnityPanel.enabled; } set{UnityPanel.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityPanel.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityPanel.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityPanel.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityPanel.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityPanel.hideFlags; } set{UnityPanel.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityPanel.hingeJoint; } } public UnityEngine.Light light{ get { return UnityPanel.light; } } public System.String name{ get { return UnityPanel.name; } set{UnityPanel.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityPanel.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityPanel.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityPanel.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityPanel.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityPanel.rigidbody2D; } } public System.String tag{ get { return UnityPanel.tag; } set{UnityPanel.tag = value; } } public UnityEngine.Transform transform{ get { return UnityPanel.transform; } } public System.Boolean useGUILayout{ get { return UnityPanel.useGUILayout; } set{UnityPanel.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvInputField{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvInputField(System.String n) {JustEntered = false; frame = Menu.frame; UnityInputField = UnityInputField.Find(n); } public System.Int32 MaxValue{ get { return UnityInputField.MaxValue; } set{UnityInputField.MaxValue = value; } } public System.Int32 MinValue{ get { return UnityInputField.MinValue; } set{UnityInputField.MinValue = value; } } public System.String Text{ get { return UnityInputField.Text; } set{UnityInputField.Text = value; } } public UnityInputField UnityInputField; public UnityEngine.Animation animation{ get { return UnityInputField.animation; } } public UnityEngine.AudioSource audio{ get { return UnityInputField.audio; } } public UnityEngine.Camera camera{ get { return UnityInputField.camera; } } public UnityEngine.Collider collider{ get { return UnityInputField.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityInputField.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityInputField.constantForce; } } public System.Boolean enabled{ get { return UnityInputField.enabled; } set{UnityInputField.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityInputField.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityInputField.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityInputField.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityInputField.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityInputField.hideFlags; } set{UnityInputField.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityInputField.hingeJoint; } } public UnityEngine.Light light{ get { return UnityInputField.light; } } public System.String name{ get { return UnityInputField.name; } set{UnityInputField.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityInputField.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityInputField.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityInputField.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityInputField.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityInputField.rigidbody2D; } } public System.String tag{ get { return UnityInputField.tag; } set{UnityInputField.tag = value; } } public UnityEngine.Transform transform{ get { return UnityInputField.transform; } } public System.Boolean useGUILayout{ get { return UnityInputField.useGUILayout; } set{UnityInputField.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvComboBox{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvComboBox(System.String n) {JustEntered = false; frame = Menu.frame; ComboBox = ComboBox.Find(n); } public System.Single ButtonDistance{ get { return ComboBox.ButtonDistance; } } public ComboBox ComboBox; public UnityEngine.GameObject RootCanvas{ get { return ComboBox.RootCanvas; } } public System.String SelectionName{ get { return ComboBox.SelectionName; } } public UnityEngine.Animation animation{ get { return ComboBox.animation; } } public UnityEngine.AudioSource audio{ get { return ComboBox.audio; } } public UnityEngine.Camera camera{ get { return ComboBox.camera; } } public UnityEngine.Collider collider{ get { return ComboBox.collider; } } public UnityEngine.Collider2D collider2D{ get { return ComboBox.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return ComboBox.constantForce; } } public System.Boolean enabled{ get { return ComboBox.enabled; } set{ComboBox.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return ComboBox.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return ComboBox.guiElement; } } public UnityEngine.GUIText guiText{ get { return ComboBox.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return ComboBox.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return ComboBox.hideFlags; } set{ComboBox.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return ComboBox.hingeJoint; } } public UnityEngine.Light light{ get { return ComboBox.light; } } public System.String name{ get { return ComboBox.name; } set{ComboBox.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return ComboBox.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return ComboBox.particleSystem; } } public UnityEngine.Renderer renderer{ get { return ComboBox.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return ComboBox.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return ComboBox.rigidbody2D; } } public System.String tag{ get { return ComboBox.tag; } set{ComboBox.tag = value; } } public UnityEngine.Transform transform{ get { return ComboBox.transform; } } public System.Boolean useGUILayout{ get { return ComboBox.useGUILayout; } set{ComboBox.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } public class CnvComboList{ public int frame; public bool JustEntered = true; private System.String n; public int ID; public CnvComboList(System.String n) {JustEntered = false; frame = Menu.frame; ComboList = ComboList.Find(n); } public System.Single ButtonDistance{ get { return ComboList.ButtonDistance; } } public System.Collections.Generic.List<UnityEngine.GameObject> Buttons{ get { return ComboList.Buttons; } } public ComboList ComboList; public System.Int32 CurrentSelectionIndex{ get { return ComboList.CurrentSelectionIndex; } } public UnityEngine.GameObject RootCanvas{ get { return ComboList.RootCanvas; } } public System.String SelectionName{ get { return ComboList.SelectionName; } } public UnityEngine.Animation animation{ get { return ComboList.animation; } } public UnityEngine.AudioSource audio{ get { return ComboList.audio; } } public UnityEngine.Camera camera{ get { return ComboList.camera; } } public UnityEngine.Collider collider{ get { return ComboList.collider; } } public UnityEngine.Collider2D collider2D{ get { return ComboList.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return ComboList.constantForce; } } public System.Boolean enabled{ get { return ComboList.enabled; } set{ComboList.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return ComboList.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return ComboList.guiElement; } } public UnityEngine.GUIText guiText{ get { return ComboList.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return ComboList.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return ComboList.hideFlags; } set{ComboList.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return ComboList.hingeJoint; } } public UnityEngine.Light light{ get { return ComboList.light; } } public System.String name{ get { return ComboList.name; } set{ComboList.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return ComboList.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return ComboList.particleSystem; } } public UnityEngine.Renderer renderer{ get { return ComboList.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return ComboList.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return ComboList.rigidbody2D; } } public System.String tag{ get { return ComboList.tag; } set{ComboList.tag = value; } } public UnityEngine.Transform transform{ get { return ComboList.transform; } } public System.Boolean useGUILayout{ get { return ComboList.useGUILayout; } set{ComboList.useGUILayout = value; } } public void Update(float dt, Menu world) { frame = Menu.frame; } } }