context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace PhotoSharingApplication.Migrations { using PhotoSharingApplication.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Web; using System.Web.Hosting; internal sealed class Configuration : DbMigrationsConfiguration<PhotoSharingContext> { public Configuration() { AutomaticMigrationsEnabled = false; ContextKey = "PhotoSharingApplication.Models.PhotoSharingContext"; } protected override void Seed(PhotoSharingContext context) { base.Seed(context); if (context.Photos.Count() > 0) { return; } //Create some photos var photos = new List<Photo> { new Photo { Title = "Sample Photo 1", Description = "This is the first sample photo in the Adventure Works photo application", UserName = "AllisonBrown", PhotoFile = GetFileBytes(MapPath("~\\Images\\flower.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-5) }, new Photo { Title = "Sample Photo 2", Description = "This is the second sample photo in the Adventure Works photo application", UserName = "RogerLengel", PhotoFile = GetFileBytes(MapPath("~\\Images\\orchard.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-4) }, new Photo { Title = "Sample Photo 3", Description = "This is the third sample photo in the Adventure Works photo application", UserName = "AllisonBrown", PhotoFile = GetFileBytes(MapPath("~\\Images\\path.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-3) }, new Photo { Title = "Sample Photo 4", Description = "This is the forth sample photo in the Adventure Works photo application", UserName = "JimCorbin", PhotoFile = GetFileBytes(MapPath("~\\Images\\fungi.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-2) }, new Photo { Title = "Sample Photo 5", Description = "This is the fifth sample photo in the Adventure Works photo application", UserName = "JamieStark", PhotoFile = GetFileBytes(MapPath("~\\Images\\pinkflower.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-1) }, new Photo { Title = "Sample Photo 6", Description = "This is the sixth sample photo in the Adventure Works photo application", UserName = "JamieStark", PhotoFile = GetFileBytes(MapPath("~\\Images\\blackberries.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-11) }, new Photo { Title = "Sample Photo 7", Description = "This is the seventh sample photo in the Adventure Works photo application", UserName = "BernardDuerr", PhotoFile = GetFileBytes(MapPath("~\\Images\\coastalview.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-10) }, new Photo { Title = "Sample Photo 8", Description = "This is the eigth sample photo in the Adventure Works photo application", UserName = "FengHanYing", PhotoFile = GetFileBytes(MapPath("~\\Images\\headland.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-9) }, new Photo { Title = "Sample Photo 9", Description = "This is the ninth sample photo in the Adventure Works photo application", UserName = "FengHanYing", PhotoFile = GetFileBytes(MapPath("~\\Images\\pebbles.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-8) }, new Photo { Title = "Sample Photo 10", Description = "This is the tenth sample photo in the Adventure Works photo application", UserName = "SalmanMughal", PhotoFile = GetFileBytes(MapPath("~\\Images\\pontoon.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-7) }, new Photo { Title = "Sample Photo 11", Description = "This is the eleventh sample photo in the Adventure Works photo application", UserName = "JamieStark", PhotoFile = GetFileBytes(MapPath("~\\Images\\ripples.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-5) }, new Photo { Title = "Sample Photo 12", Description = "This is the twelth sample photo in the Adventure Works photo application", UserName = "JimCorbin", PhotoFile = GetFileBytes(MapPath("~\\Images\\rockpool.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-3) }, new Photo { Title = "Sample Photo 13", Description = "This is the thirteenth sample photo in the Adventure Works photo application", UserName = "AllisonBrown", PhotoFile = GetFileBytes(MapPath("~\\Images\\track.jpg")), ImageMimeType = "image/jpeg", CreatedDate = DateTime.Today.AddDays(-1) } }; photos.ForEach(s => context.Photos.Add(s)); context.SaveChanges(); //Create some comments var comments = new List<Comment> { new Comment { PhotoID = 1, UserName = "JamieStark", Subject = "Sample Comment 1", Body = "This is the first sample comment in the Adventure Works photo application" }, new Comment { PhotoID = 1, UserName = "JimCorbin", Subject = "Sample Comment 2", Body = "This is the second sample comment in the Adventure Works photo application" }, new Comment { PhotoID = 3, UserName = "RogerLengel", Subject = "Sample Comment 3", Body = "This is the third sample photo in the Adventure Works photo application" } }; comments.ForEach(s => context.Comments.Add(s)); context.SaveChanges(); } private static string MapPath(string seedFile) { // If debug is needed, uncomment /*if (!Debugger.IsAttached) { Debugger.Launch(); }*/ if (HttpContext.Current != null) { return HostingEnvironment.MapPath(seedFile); } var absolutePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; var directoryName = Path.GetDirectoryName(absolutePath); var path = Path.Combine(directoryName, ".." + seedFile.TrimStart('~').Replace('/', '\\')); Console.WriteLine("Mapping {0} to {1}", seedFile, path); return path; } //This gets a byte array for a file at the path specified //The path is relative to the route of the web site //It is used to seed images private static byte[] GetFileBytes(string path) { FileStream fileOnDisk = new FileStream(path, FileMode.Open); byte[] fileBytes; using (BinaryReader br = new BinaryReader(fileOnDisk)) { fileBytes = br.ReadBytes((int)fileOnDisk.Length); } return fileBytes; } } }
// // PermissionSetCollectionTest.cs // - NUnit Test Cases for PermissionSetCollection // // Author: // Sebastien Pouliot <[email protected]> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using NUnit.Framework; using System; using System.Collections; using System.Security; using System.Security.Permissions; namespace MonoTests.System.Security { // "alternate" IList implementation class TestList : IList { private IList l; public TestList () { l = (IList) new ArrayList (); } public int Add (object value) { return l.Add (value); } public void Clear () { l.Clear (); } public bool Contains (object value) { return l.Contains (value); } public int IndexOf (object value) { return l.IndexOf (value); } public void Insert (int index, object value) { l.Insert (index, value); } public bool IsFixedSize { get { return l.IsFixedSize; } } public bool IsReadOnly { get { return l.IsReadOnly; } } public void Remove (object value) { l.Remove (value); } public void RemoveAt (int index) { l.RemoveAt (index); } public object this [int index] { get { return l [index]; } set { l [index] = value; } } public void CopyTo (Array array, int index) { l.CopyTo (array, index); } public int Count { get { return l.Count; } } public bool IsSynchronized { get { return l.IsSynchronized; } } public object SyncRoot { get { return l.SyncRoot; } } public IEnumerator GetEnumerator () { return l.GetEnumerator (); } } [TestFixture] public class PermissionSetCollectionTest { [Test] public void Constructor () { PermissionSetCollection psc = new PermissionSetCollection (); Assert.AreEqual (0, psc.Count, "Count"); Assert.IsFalse (psc.IsSynchronized, "IsSynchronized"); Assert.AreEqual (0, psc.PermissionSets.Count, "PermissionSets.Count"); Assert.AreEqual (psc.ToXml ().ToString (), psc.ToString (), "ToXml().ToString()==ToString()"); Assert.IsNotNull (psc.GetEnumerator (), "GetEnumerator"); } [Test] [ExpectedException (typeof (NotSupportedException))] public void SyncRoot () { PermissionSetCollection psc = new PermissionSetCollection (); Assert.IsNull (psc.SyncRoot, "SyncRoot"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Add_Null () { PermissionSetCollection psc = new PermissionSetCollection (); psc.Add (null); } [Test] public void Add () { PermissionSet none = new PermissionSet (PermissionState.None); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); PermissionSetCollection psc = new PermissionSetCollection (); Assert.AreEqual (0, psc.PermissionSets.Count, "Count-0"); Assert.AreEqual (0, psc.Count, "Count-0"); psc.Add (none); Assert.AreEqual (1, psc.PermissionSets.Count, "Count-1"); // re-add same permissionset psc.Add (none); Assert.AreEqual (2, psc.PermissionSets.Count, "Count-2"); psc.Add (unr); Assert.AreEqual (3, psc.PermissionSets.Count, "Count-3"); Assert.AreEqual (3, psc.Count, "Count-3"); } [Test] public void Copy () { PermissionSet none = new PermissionSet (PermissionState.None); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); PermissionSetCollection psc = new PermissionSetCollection (); PermissionSetCollection copy = psc.Copy (); Assert.AreEqual (0, copy.PermissionSets.Count, "Count-0"); psc.Add (none); Assert.AreEqual (0, copy.PermissionSets.Count, "Count-0b"); copy = psc.Copy (); Assert.AreEqual (1, copy.PermissionSets.Count, "Count-1"); psc.Add (none); // re-add same permissionset Assert.AreEqual (1, copy.PermissionSets.Count, "Count-1b"); copy = psc.Copy (); Assert.AreEqual (2, copy.PermissionSets.Count, "Count-2"); psc.Add (unr); Assert.AreEqual (2, copy.PermissionSets.Count, "Count-2b"); copy = psc.Copy (); Assert.AreEqual (3, copy.PermissionSets.Count, "Count-3"); Assert.AreEqual (3, copy.Count, "Count-3"); } [Test] public void Copy_References () { PermissionSet none = new PermissionSet (PermissionState.None); PermissionSetCollection psc = new PermissionSetCollection (); psc.Add (none); PermissionSetCollection copy = psc.Copy (); Assert.AreEqual (1, copy.PermissionSets.Count, "Count-1"); string before = psc.ToString (); none.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion)); Assert.AreEqual (none.ToString (), psc.PermissionSets[0].ToString (), "psc"); Assert.AreEqual (before, copy.ToString (), "copy"); } [Test] [ExpectedException (typeof (NotSupportedException))] public void CopyTo () { PermissionSetCollection psc = new PermissionSetCollection (); psc.CopyTo (null, 0); } [Test] [ExpectedException (typeof (NotSupportedException))] public void CopyTo_ICollection () { PermissionSetCollection psc = new PermissionSetCollection (); ICollection c = (psc as ICollection); c.CopyTo (null, 0); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void FromXml_Null () { PermissionSetCollection psc = new PermissionSetCollection (); psc.FromXml (null); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromXml_BadName () { PermissionSetCollection psc = new PermissionSetCollection (); SecurityElement se = new SecurityElement ("PermissionZetCollection"); psc.FromXml (se); } [Test] public void FromXml_Roundtrip () { PermissionSetCollection psc = new PermissionSetCollection (); string expected = psc.ToString (); SecurityElement se = psc.ToXml (); psc.FromXml (se); string actual = psc.ToString (); Assert.AreEqual (expected, actual, "Empty"); PermissionSet none = new PermissionSet (PermissionState.None); psc.Add (none); expected = psc.ToString (); se = psc.ToXml (); psc.FromXml (se); actual = psc.ToString (); Assert.AreEqual (expected, actual, "1-None"); none.AddPermission (new SecurityPermission (SecurityPermissionFlag.Assertion)); expected = psc.ToString (); se = psc.ToXml (); psc.FromXml (se); actual = psc.ToString (); Assert.AreEqual (expected, actual, "1-Assertion"); Assert.AreEqual (1, psc.Count, "1"); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); psc.Add (unr); expected = psc.ToString (); se = psc.ToXml (); psc.FromXml (se); actual = psc.ToString (); Assert.AreEqual (expected, actual, "2-Assertion+Unrestricted"); Assert.AreEqual (2, psc.Count, "2"); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void GetSet_Negative () { PermissionSetCollection psc = new PermissionSetCollection (); psc.GetSet (-1); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void GetSet_Zero_Empty () { PermissionSetCollection psc = new PermissionSetCollection (); psc.GetSet (0); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void GetSet_MaxInt () { PermissionSetCollection psc = new PermissionSetCollection (); psc.GetSet (Int32.MaxValue); } [Test] public void GetSet () { PermissionSetCollection psc = new PermissionSetCollection (); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); psc.Add (unr); PermissionSet ps = psc.GetSet (0); Assert.AreEqual (unr.ToString (), ps.ToString (), "Same XML"); Assert.IsTrue (Object.ReferenceEquals (unr, ps), "Same Object Reference"); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void RemoveSet_Negative () { PermissionSetCollection psc = new PermissionSetCollection (); psc.RemoveSet (-1); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void RemoveSet_Zero_Empty () { PermissionSetCollection psc = new PermissionSetCollection (); psc.RemoveSet (0); } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void RemoveSet_MaxInt () { PermissionSetCollection psc = new PermissionSetCollection (); psc.RemoveSet (Int32.MaxValue); } [Test] public void RemoveSet () { PermissionSetCollection psc = new PermissionSetCollection (); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); psc.Add (unr); psc.RemoveSet (0); Assert.AreEqual (0, psc.Count, "Count"); } [Test] public void ToXml () { PermissionSetCollection psc = new PermissionSetCollection (); SecurityElement se = psc.ToXml (); Assert.IsNull (se.Children, "Children==null for 0"); PermissionSet unr = new PermissionSet (PermissionState.Unrestricted); psc.Add (unr); se = psc.ToXml (); Assert.AreEqual (1, se.Children.Count, "Children==1"); Assert.AreEqual (unr.ToString (), se.Children[0].ToString (), "XML"); } } } #endif
using System; using System.Security; using System.Runtime.InteropServices; using SFML.Window; using Vector2f = SFML.Graphics.Vector2; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// This class defines a graphical 2D text, that can be drawn on screen /// </summary> //////////////////////////////////////////////////////////// public class Text : Transformable, Drawable { //////////////////////////////////////////////////////////// /// <summary> /// Enumerate the string drawing styles /// </summary> //////////////////////////////////////////////////////////// [Flags] public enum Styles { /// <summary>Regular characters, no style</summary> Regular = 0, /// <summary> Characters are bold</summary> Bold = 1 << 0, /// <summary>Characters are in italic</summary> Italic = 1 << 1, /// <summary>Characters are underlined</summary> Underlined = 1 << 2 } //////////////////////////////////////////////////////////// /// <summary> /// Default constructor /// </summary> //////////////////////////////////////////////////////////// public Text() : this("", null) { } //////////////////////////////////////////////////////////// /// <summary> /// Construct the text from a string and a font /// </summary> /// <param name="str">String to display</param> /// <param name="font">Font to use</param> //////////////////////////////////////////////////////////// public Text(string str, Font font) : this(str, font, 30) { } //////////////////////////////////////////////////////////// /// <summary> /// Construct the text from a string, font and size /// </summary> /// <param name="str">String to display</param> /// <param name="font">Font to use</param> /// <param name="characterSize">Base characters size</param> //////////////////////////////////////////////////////////// public Text(string str, Font font, uint characterSize) : base(sfText_create()) { DisplayedString = str; Font = font; CharacterSize = characterSize; } //////////////////////////////////////////////////////////// /// <summary> /// Construct the text from another text /// </summary> /// <param name="copy">Text to copy</param> //////////////////////////////////////////////////////////// public Text(Text copy) : base(sfText_copy(copy.CPointer)) { Origin = copy.Origin; Position = copy.Position; Rotation = copy.Rotation; Scale = copy.Scale; Font = copy.Font; } //////////////////////////////////////////////////////////// /// <summary> /// Global color of the object /// </summary> //////////////////////////////////////////////////////////// public Color Color { get { return sfText_getColor(CPointer); } set { sfText_setColor(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// String which is displayed /// </summary> //////////////////////////////////////////////////////////// public string DisplayedString { get { // Get the number of characters // This is probably not the most optimized way; if anyone has a better solution... int length = Marshal.PtrToStringAnsi(sfText_getString(CPointer)).Length; // Copy the characters byte[] characters = new byte[length * 4]; Marshal.Copy(sfText_getUnicodeString(CPointer), characters, 0, characters.Length); // Convert from UTF-32 to String (UTF-16) return System.Text.Encoding.UTF32.GetString(characters); } set { // Convert from String (UTF-16) to UTF-32 int[] characters = new int[value.Length]; for (int i = 0; i < value.Length; ++i) characters[i] = Char.ConvertToUtf32(value, i); // Transform to raw and pass to the C API GCHandle handle = GCHandle.Alloc(characters, GCHandleType.Pinned); sfText_setUnicodeString(CPointer, handle.AddrOfPinnedObject()); handle.Free(); } } //////////////////////////////////////////////////////////// /// <summary> /// Font used to display the text /// </summary> //////////////////////////////////////////////////////////// public Font Font { get { return myFont; } set { myFont = value; sfText_setFont(CPointer, value != null ? value.CPointer : IntPtr.Zero); } } //////////////////////////////////////////////////////////// /// <summary> /// Base size of characters /// </summary> //////////////////////////////////////////////////////////// public uint CharacterSize { get { return sfText_getCharacterSize(CPointer); } set { sfText_setCharacterSize(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Style of the text (see Styles enum) /// </summary> //////////////////////////////////////////////////////////// public Styles Style { get { return sfText_getStyle(CPointer); } set { sfText_setStyle(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Return the visual position of the Index-th character of the text, /// in coordinates relative to the text /// (note : translation, origin, rotation and scale are not applied) /// </summary> /// <param name="index">Index of the character</param> /// <returns>Position of the Index-th character (end of text if Index is out of range)</returns> //////////////////////////////////////////////////////////// public Vector2f FindCharacterPos(uint index) { return sfText_findCharacterPos(CPointer, index); } //////////////////////////////////////////////////////////// /// <summary> /// Get the local bounding rectangle of the entity. /// /// The returned rectangle is in local coordinates, which means /// that it ignores the transformations (translation, rotation, /// scale, ...) that are applied to the entity. /// In other words, this function returns the bounds of the /// entity in the entity's coordinate system. /// </summary> /// <returns>Local bounding rectangle of the entity</returns> //////////////////////////////////////////////////////////// public FloatRect GetLocalBounds() { return sfText_getLocalBounds(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Get the global bounding rectangle of the entity. /// /// The returned rectangle is in global coordinates, which means /// that it takes in account the transformations (translation, /// rotation, scale, ...) that are applied to the entity. /// In other words, this function returns the bounds of the /// sprite in the global 2D world's coordinate system. /// </summary> /// <returns>Global bounding rectangle of the entity</returns> //////////////////////////////////////////////////////////// public FloatRect GetGlobalBounds() { // we don't use the native getGlobalBounds function, // because we override the object's transform return Transform.TransformRect(GetLocalBounds()); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[Text]" + " Color(" + Color + ")" + " String(" + DisplayedString + ")" + " Font(" + Font + ")" + " CharacterSize(" + CharacterSize + ")" + " Style(" + Style + ")"; } //////////////////////////////////////////////////////////// /// <summmary> /// Draw the object to a render target /// /// This is a pure virtual function that has to be implemented /// by the derived class to define how the drawable should be /// drawn. /// </summmary> /// <param name="target">Render target to draw to</param> /// <param name="states">Current render states</param> //////////////////////////////////////////////////////////// public void Draw(RenderTarget target, RenderStates states) { //states.Transform *= Transform; RenderStates.MarshalData marshaledStates = states.Marshal(Transform); // NetGore custom line if (target is RenderWindow) { sfRenderWindow_drawText(((RenderWindow)target).CPointer, CPointer, ref marshaledStates); } else if (target is RenderTexture) { sfRenderTexture_drawText(((RenderTexture)target).CPointer, CPointer, ref marshaledStates); } } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { sfText_destroy(CPointer); } private Font myFont = null; #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfText_create(); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfText_copy(IntPtr Text); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfText_destroy(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfText_setColor(IntPtr CPointer, Color Color); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Color sfText_getColor(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderWindow_drawText(IntPtr CPointer, IntPtr Text, ref RenderStates.MarshalData states); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_drawText(IntPtr CPointer, IntPtr Text, ref RenderStates.MarshalData states); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfText_setUnicodeString(IntPtr CPointer, IntPtr Text); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfText_setFont(IntPtr CPointer, IntPtr Font); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfText_setCharacterSize(IntPtr CPointer, uint Size); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfText_setStyle(IntPtr CPointer, Styles Style); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfText_getString(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfText_getUnicodeString(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfText_getCharacterSize(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Styles sfText_getStyle(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern FloatRect sfText_getRect(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2f sfText_findCharacterPos(IntPtr CPointer, uint Index); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern FloatRect sfText_getLocalBounds(IntPtr CPointer); #endregion } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Linq.Expressions; using System.Reflection; using InfluxDB.InfluxQL.Schema; using InfluxDB.InfluxQL.Syntax; using InfluxDB.InfluxQL.Syntax.Clauses; using InfluxDB.InfluxQL.Syntax.Expressions; using InfluxDB.InfluxQL.Syntax.Statements; namespace InfluxDB.InfluxQL.StatementBuilders.SelectStatement { public class Select<TValues, TFields> { private readonly Measurement measurement; private readonly SelectClause select; private readonly FromClause from; internal Select(Measurement measurement, FromClause from, LambdaExpression selectExpression) { this.measurement = measurement ?? throw new ArgumentNullException(nameof(measurement)); this.from = from ?? throw new ArgumentNullException(nameof(from)); if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } var columns = ParseExpression(selectExpression).ToArray(); this.select = new SelectClause(columns); } public SingleSeriesSelectStatement<TValues> Statement => new SingleSeriesSelectStatement<TValues>(select, from); public Where<TValues> Where(string predicate) { return new Where<TValues>(select, from, predicate); } public override string ToString() { return Statement.Text; } public static implicit operator SingleSeriesSelectStatement<TValues>(Select<TValues, TFields> builder) { return builder.Statement; } private IEnumerable<ColumnSelectionExpression> ParseExpression(LambdaExpression selectExpression) { Expression fieldsParameter = selectExpression.Parameters[0]; if (selectExpression.Body == fieldsParameter) { // Identity function so all fields selected. return measurement.FieldSet.Select(x => new FieldSelectionExpression(x.InfluxFieldName, x.DotNetAlias)); } switch (selectExpression.Body.NodeType) { case ExpressionType.New: return ParseProjection((NewExpression)selectExpression.Body, fieldsParameter); default: throw new NotImplementedException(); } } private IEnumerable<ColumnSelectionExpression> ParseProjection(NewExpression expression, Expression fieldsParameter) { for (var i = 0; i < expression.Arguments.Count; i++) { MemberInfo member = expression.Members[i]; var argument = expression.Arguments[i]; switch (argument.NodeType) { case ExpressionType.MemberAccess: yield return ParseColumnSelection((MemberExpression)argument, member, fieldsParameter); break; case ExpressionType.Call: var call = ((MethodCallExpression)argument); var fieldSelection = ParseColumnSelection((MemberExpression)call.Arguments[0], member, fieldsParameter); var aggregation = new FieldAggregationExpression(call.Method.Name); yield return new FieldSelectionExpression(fieldSelection, aggregation); break; default: throw new NotImplementedException(); } } } private FieldSelectionExpression ParseColumnSelection(MemberExpression argument, MemberInfo member, Expression fieldsParameter) { if (argument.Expression == fieldsParameter) { var field = measurement.FieldSet.Single(x => x.DotNetAlias == argument.Member.Name); return new FieldSelectionExpression(field.InfluxFieldName, member.Name); } throw new NotImplementedException(); } } public class Select<TValues, TFields, TTags> { private readonly TaggedMeasurement measurement; private readonly SelectClause select; private readonly FromClause from; internal Select(TaggedMeasurement measurement, FromClause from, LambdaExpression selectExpression) { this.measurement = measurement ?? throw new ArgumentNullException(nameof(measurement)); this.from = from ?? throw new ArgumentNullException(nameof(from)); if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } var columns = ParseExpression(selectExpression).ToImmutableList(); this.select = new SelectClause(columns); } public SingleSeriesSelectStatement<TValues> Statement => new SingleSeriesSelectStatement<TValues>(select, from); public Where<TValues, TTags> Where(string predicate) { return new Where<TValues, TTags>(measurement, select, from, predicate); } public GroupBy<TValues> GroupBy(TimeSpan timeInterval) { return new GroupBy<TValues>(select, from, timeInterval); } public GroupBy<TValues, TGroupBy> GroupBy<TGroupBy>(Expression<Func<TTags, TGroupBy>> tagSelection) { return new GroupBy<TValues, TGroupBy>(measurement, select, from, tagSelection); } public GroupBy<TValues, TGroupBy> GroupBy<TGroupBy>(TimeSpan timeInterval, Expression<Func<TTags, TGroupBy>> tagSelection) { return new GroupBy<TValues, TGroupBy>(measurement, select, from, tagSelection, timeInterval: timeInterval); } public OrderBy<TValues> OrderByTimeDesc() { return new OrderBy<TValues>(Statement); } public Limit<TValues> Limit(int n) { return new Limit<TValues>(Statement, n); } public Offset<TValues> Offset(int n) { return new Offset<TValues>(Statement, n); } public override string ToString() { return Statement.Text; } public static implicit operator SingleSeriesSelectStatement<TValues>(Select<TValues, TFields, TTags> builder) { return builder.Statement; } private IEnumerable<ColumnSelectionExpression> ParseExpression(LambdaExpression selectExpression) { Expression fieldsParameter = selectExpression.Parameters[0]; Expression tagsParameter = null; if (selectExpression.Parameters.Count == 2) { tagsParameter = selectExpression.Parameters[1]; } if (selectExpression.Body == fieldsParameter) { // Identity function so all fields selected. return measurement.FieldSet.Select(x => new FieldSelectionExpression(x.InfluxFieldName, x.DotNetAlias)); } switch (selectExpression.Body.NodeType) { case ExpressionType.New: return ParseProjection((NewExpression)selectExpression.Body, fieldsParameter, tagsParameter); default: throw new NotImplementedException(); } } private IEnumerable<ColumnSelectionExpression> ParseProjection(NewExpression expression, Expression fieldsParameter, Expression tagsParameter) { for (var i = 0; i < expression.Arguments.Count; i++) { var member = expression.Members[i]; var argument = expression.Arguments[i]; switch (argument.NodeType) { case ExpressionType.MemberAccess: if (((MemberExpression)argument).Expression == fieldsParameter) { yield return ParseFieldSelection((MemberExpression)argument, member, fieldsParameter); } else if (((MemberExpression)argument).Expression == tagsParameter) { var tag = measurement.TagSet.Single(x => x.DotNetAlias == ((MemberExpression)argument).Member.Name); yield return new TagSelectionExpression(tag.InfluxTagName, member.Name); } else { throw new NotImplementedException(); } break; case ExpressionType.Call: var call = ((MethodCallExpression)argument); var fieldSelection = ParseFieldSelection((MemberExpression)call.Arguments[0], member, fieldsParameter); var aggregation = new FieldAggregationExpression(call.Method.Name); yield return new FieldSelectionExpression(fieldSelection, aggregation); break; default: throw new NotImplementedException(); } } } private FieldSelectionExpression ParseFieldSelection(MemberExpression argument, MemberInfo member, Expression fieldsParameter) { if (argument.Expression == fieldsParameter) { var field = measurement.FieldSet.Single(x => x.DotNetAlias == argument.Member.Name); return new FieldSelectionExpression(field.InfluxFieldName, member.Name); } throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.IO; using BellRichM.Configuration; using BellRichM.Identity.Api.Data; using BellRichM.Identity.Api.Extensions; using BellRichM.Identity.Api.Repositories; using BellRichM.Identity.Api.Services; using BellRichM.Logging; using Machine.Specifications; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Serilog; namespace BellRichM.Identity.Api.Integration.Controllers { public class UserControllerSetupAndCleanup : IAssemblyContext, IDisposable { private IServiceProvider _serviceProvider; private IRoleRepository _roleRepository; private IUserRepository _userRepository; private User _testUser; private Role _adminRole; private User _adminUser; private TestServer _server; private bool disposed = false; public UserControllerSetupAndCleanup() { Configure(); _roleRepository = _serviceProvider.GetService<IRoleRepository>(); _userRepository = _serviceProvider.GetService<IUserRepository>(); } public void OnAssemblyStart() { var adminUserPw = "P@ssw0rd"; var adminUserName = "userAdmin"; var userAdminRoleName = "userAdminRole"; var testUserName = "userTest"; var testUserPw = "P@ssw0rd"; DeleteUser(adminUserName); DeleteRole(userAdminRoleName); DeleteUser(testUserName); _adminRole = CreateUserAdminRole(userAdminRoleName); List<Role> adminRoles = new List<Role>(); adminRoles.Add(_adminRole); _adminUser = CreateUser(adminUserName, adminUserPw, adminRoles); UserControllerTests.UserAdminJwt = GenerateJwt(_adminUser.UserName, adminUserPw); _testUser = CreateUser(testUserName, testUserPw, null); UserControllerTests.TestUser = _testUser; UserControllerTests.UserTestJwt = GenerateJwt(_testUser.UserName, testUserPw); var configurationManager = new ConfigurationManager("Development", System.AppDomain.CurrentDomain.BaseDirectory); var configuration = configurationManager.Create(); var logManager = new LogManager(configuration); var logger = logManager.Create(); var saveSeriloLogger = Log.Logger; Log.Logger = logger; _server = new TestServer( new WebHostBuilder() .UseStartup<StartupIntegration>() .ConfigureServices(s => s.AddSingleton(Log.Logger)) .ConfigureServices(s => s.AddSingleton(typeof(ILoggerAdapter<>), typeof(LoggerAdapter<>))) .UseConfiguration(configuration) .UseSerilog()); UserControllerTests.Client = _server.CreateClient(); Log.Logger = saveSeriloLogger; } public void OnAssemblyComplete() { DeleteUser(_adminUser.UserName); DeleteRole(_adminRole.Name); DeleteUser(_testUser.UserName); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { _server.Dispose(); } disposed = true; } } private void Configure() { var builder = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory + "../../..") .AddJsonFile("appsettings.Setup.json", optional: false, reloadOnChange: false) .AddEnvironmentVariables(); var configuration = builder.Build(); var logger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.File( "../../../logsTest/testLog.txt", rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: 10240, retainedFileCountLimit: 7) .CreateLogger(); Log.Logger = logger; var services = new ServiceCollection(); services.AddLogging(configure => configure.AddSerilog()); services.AddSingleton(typeof(ILoggerAdapter<>), typeof(LoggerAdapter<>)); services.AddIdentityServices(configuration); _serviceProvider = services.BuildServiceProvider(); } private Role CreateUserAdminRole(string roleName) { var claimValues = new List<ClaimValue>() { new ClaimValue { Type = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", Value = "CanUpdateUsers" }, new ClaimValue { Type = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", Value = "CanViewUsers" }, new ClaimValue { Type = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", Value = "CanCreateUsers" }, new ClaimValue { Type = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", Value = "CanDeleteUsers" } }; var role = new Role { Name = roleName, Description = "Administer the users", ClaimValues = claimValues }; var newAdminRole = _roleRepository.Create(role).Result; return newAdminRole; } private void DeleteRole(string roleName) { var role = _roleRepository.GetByName(roleName).Result; if (role != null) { _roleRepository.Delete(role.Id); } } private User CreateUser(string userName, string pW, IEnumerable<Role> roles) { var user = new User { UserName = userName, Roles = roles }; var newUser = _userRepository.Create(user, pW).Result; return newUser; } private void DeleteUser(string userName) { var user = _userRepository.GetByName(userName).Result; if (user != null) { _userRepository.Delete(user.Id); } } private string GenerateJwt(string userName, string userPw) { var jwtManager = _serviceProvider.GetService<IJwtManager>(); return jwtManager.GenerateToken(userName, userPw).Result; } } }
// 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, // MERCHANTABLITY 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 System.Security; using System.Text.RegularExpressions; using Microsoft.PythonTools.Interpreter; namespace CanopyInterpreter { /// <summary> /// Provides interpreter objects for a Canopy installation. /// /// The factory is responsible for managing the cached analysis database, /// which for Canopy consists of two independent databases. When we create /// the User database, we include modules from the base (App) database as /// well. /// /// Because we are using PythonTypeDatabase, we can use the default /// implementation of IPythonInterpreter. /// </summary> class CanopyInterpreterFactory : PythonInterpreterFactoryWithDatabase { private readonly PythonInterpreterFactoryWithDatabase _base; private PythonTypeDatabase _baseDb; private bool _baseHasRefreshed; /// <summary> /// Creates the factory for Canopy's base (App) interpreter. This /// factory is not displayed to the user, but is used to maintain the /// completion database. /// </summary> public static PythonInterpreterFactoryWithDatabase CreateBase( string basePath, string canopyVersion, Version languageVersion ) { var interpPath = FindFile(basePath, CanopyInterpreterFactoryConstants.ConsoleExecutable); var winInterpPath = FindFile(basePath, CanopyInterpreterFactoryConstants.WindowsExecutable); var libPath = Path.Combine(basePath, CanopyInterpreterFactoryConstants.LibrarySubPath); if (!File.Exists(interpPath)) { throw new FileNotFoundException(interpPath); } if (!File.Exists(winInterpPath)) { throw new FileNotFoundException(winInterpPath); } if (!Directory.Exists(libPath)) { throw new DirectoryNotFoundException(libPath); } // Detect the architecture and select the appropriate id var arch = NativeMethods.GetBinaryType(interpPath); var id = (arch == ProcessorArchitecture.Amd64) ? CanopyInterpreterFactoryConstants.BaseGuid64 : CanopyInterpreterFactoryConstants.BaseGuid32; // Make the description string look like "Base Canopy 1.1.0.46 (2.7 32-bit)" var description = "Base Canopy"; if (!string.IsNullOrEmpty(canopyVersion)) { description += " " + canopyVersion; } description += string.Format(" ({0} ", languageVersion); if (arch == ProcessorArchitecture.Amd64) { description += " 64-bit)"; } else { description += " 32-bit)"; } return InterpreterFactoryCreator.CreateInterpreterFactory( new InterpreterConfiguration( basePath, description, basePath, interpPath, winInterpPath, libPath, CanopyInterpreterFactoryConstants.PathEnvironmentVariableName, arch, languageVersion, InterpreterUIMode.SupportsDatabase ), new InterpreterFactoryCreationOptions { WatchLibraryForNewModules = true } ); } /// <summary> /// Creates the Canopy User interpreter. This handles layering of the /// User database on top of the App database, and ensures that refreshes /// work correctly. /// /// Because it is exposed as its own factory type, it can also be used /// as a base interpreter for DerivedInterpreterFactory (virtual /// environments). /// </summary> public static CanopyInterpreterFactory Create( PythonInterpreterFactoryWithDatabase baseFactory, string userPath, string canopyVersion ) { var interpPath = FindFile(userPath, CanopyInterpreterFactoryConstants.ConsoleExecutable); var winInterpPath = FindFile(userPath, CanopyInterpreterFactoryConstants.WindowsExecutable); var libPath = Path.Combine(userPath, CanopyInterpreterFactoryConstants.LibrarySubPath); if (!File.Exists(interpPath)) { throw new FileNotFoundException(interpPath); } if (!File.Exists(winInterpPath)) { throw new FileNotFoundException(winInterpPath); } if (!Directory.Exists(libPath)) { throw new DirectoryNotFoundException(libPath); } // Make the description string look like "Canopy 1.1.0.46 (2.7 32-bit)" var description = "Canopy "; if (!string.IsNullOrEmpty(canopyVersion)) { description += " " + canopyVersion; } description += string.Format(" ({0} ", baseFactory.Configuration.Version); if (baseFactory.Configuration.Architecture == ProcessorArchitecture.Amd64) { description += " 64-bit)"; } else { description += " 32-bit)"; } var config = new InterpreterConfiguration( userPath, description, userPath, interpPath, winInterpPath, libPath, CanopyInterpreterFactoryConstants.PathEnvironmentVariableName, baseFactory.Configuration.Architecture, baseFactory.Configuration.Version, InterpreterUIMode.SupportsDatabase ); return new CanopyInterpreterFactory(baseFactory, config); } private CanopyInterpreterFactory( PythonInterpreterFactoryWithDatabase baseFactory, InterpreterConfiguration config ) : base(config, true) { if (baseFactory == null) { throw new ArgumentNullException("baseFactory"); } _base = baseFactory; _base.IsCurrentChanged += OnIsCurrentChanged; _base.NewDatabaseAvailable += OnNewDatabaseAvailable; } protected override void Dispose(bool disposing) { _baseDb = null; _base.IsCurrentChanged -= OnIsCurrentChanged; _base.NewDatabaseAvailable -= OnNewDatabaseAvailable; base.Dispose(disposing); } private void OnIsCurrentChanged(object sender, EventArgs e) { // Raised if our base database's IsCurrent changes, which means that // ours may have as well. base.OnIsCurrentChanged(); } private void OnNewDatabaseAvailable(object sender, EventArgs e) { // Raised if our base database is updated, which means we need to // refresh our database too. if (_baseDb != null) { _baseDb = null; _baseHasRefreshed = true; } OnNewDatabaseAvailable(); OnIsCurrentChanged(); } // We could override MakeInterpreter() to return a different // implementation of IPythonInterpreter, but we don't need to here, as // the default implementation works well with PythonTypeDatabase. //public override IPythonInterpreter MakeInterpreter(PythonInterpreterFactoryWithDatabase factory) { // return base.MakeInterpreter(factory); //} /// <summary> /// Returns a new database that contains the database from our base /// interpreter. /// </summary> public override PythonTypeDatabase MakeTypeDatabase(string databasePath, bool includeSitePackages = true) { if (_baseDb == null && _base.IsCurrent) { _baseDb = _base.GetCurrentDatabase(ShouldIncludeGlobalSitePackages); } var paths = new List<string> { databasePath }; if (includeSitePackages) { try { paths.AddRange(Directory.EnumerateDirectories(databasePath)); } catch (ArgumentException) { } catch (IOException) { } catch (SecurityException) { } catch (UnauthorizedAccessException) { } } return new PythonTypeDatabase(this, paths, _baseDb); } /// <summary> /// Regenerates the database for this environment. If the base /// interpreter needs regenerating, it will also be regenerated. /// </summary> public override void GenerateDatabase(GenerateDatabaseOptions options, Action<int> onExit = null) { if (!Directory.Exists(Configuration.LibraryPath)) { return; } var req = new PythonTypeDatabaseCreationRequest { Factory = this, OutputPath = DatabasePath, SkipUnchanged = options.HasFlag(GenerateDatabaseOptions.SkipUnchanged) }; req.ExtraInputDatabases.Add(_base.DatabasePath); _baseHasRefreshed = false; if (_base.IsCurrent) { // The App database is already up to date, so start analyzing // the User database immediately. base.GenerateDatabase(req, onExit); } else { // The App database needs to be updated, so start both and wait // for the base to finish before analyzing User. // Specifying our base interpreter as 'WaitFor' allows the UI to // forward progress and status messages to the user, even though // the factory is not visible. req.WaitFor = _base; // Because the underlying analysis of the standard library has // changed, we must reanalyze the entire database. req.SkipUnchanged = false; // Clear out the existing base database, since we're going to // need to reload it again. This also means that when // NewDatabaseAvailable is raised, we are expecting it and won't // incorrectly set _baseHasRefreshed to true again. _baseDb = null; // Start our analyzer first, since we will wait up to a minute // for the base analyzer to start (which may cause a one minute // delay if it completes before we start, but that is unlikely). base.GenerateDatabase(req, onExit); _base.GenerateDatabase(GenerateDatabaseOptions.SkipUnchanged); } } public override bool IsCurrent { get { // The User database is only current if the App database is // current as well. return !_baseHasRefreshed && _base.IsCurrent && base.IsCurrent; } } public override void RefreshIsCurrent() { _base.RefreshIsCurrent(); base.RefreshIsCurrent(); } public override string GetFriendlyIsCurrentReason(IFormatProvider culture) { if (_baseHasRefreshed) { return "Base interpreter has been refreshed"; } else if (!_base.IsCurrent) { return string.Format(culture, "Base interpreter is out of date:{0}{0} {1}", Environment.NewLine, _base.GetFriendlyIsCurrentReason(culture)); } return base.GetFriendlyIsCurrentReason(culture); } public override string GetIsCurrentReason(IFormatProvider culture) { if (_baseHasRefreshed) { return "Base interpreter has been refreshed"; } else if (!_base.IsCurrent) { return string.Format(culture, "{0} is out of date:{1}{2}", _base.Configuration.FullDescription, Environment.NewLine, _base.GetIsCurrentReason(culture)); } return base.GetIsCurrentReason(culture); } private bool ShouldIncludeGlobalSitePackages { get { // Canopy by default includes global site-packages, but we // should check in case a user modifies this manually. var cfgFile = Path.Combine(Configuration.PrefixPath, "pyvenv.cfg"); if (File.Exists(cfgFile)) { try { var lines = File.ReadAllLines(cfgFile); return lines .Select(line => Regex.Match( line, "^include-system-site-packages\\s*=\\s*true", RegexOptions.IgnoreCase )) .Any(m => m != null && m.Success); } catch (IOException) { } catch (UnauthorizedAccessException) { } catch (SecurityException) { } } return false; } } /// <summary> /// Recursively searches for a file using breadth-first-search. This /// ensures that the result closest to <paramref name="root"/> is /// returned first. /// </summary> /// <param name="root"> /// Directory to start searching. /// </param> /// <param name="file"> /// Filename to find. Wildcards are not supported. /// </param> /// <param name="depthLimit"> /// The number of subdirectories to search in. /// </param> /// <returns> /// The full path to the file if found; otherwise, null. /// </returns> private static string FindFile(string root, string file, int depthLimit = 2) { var candidate = Path.Combine(root, file); if (File.Exists(candidate)) { return candidate; } // In our context, the file we a searching for is often in a // Scripts subdirectory, so prioritize that directory. candidate = Path.Combine(root, "Scripts", file); if (File.Exists(candidate)) { return candidate; } // Do a BFS of the filesystem to ensure we find the match closest to // the root directory. var dirQueue = new Queue<string>(); dirQueue.Enqueue(root); dirQueue.Enqueue("<EOD>"); while (dirQueue.Any()) { var dir = dirQueue.Dequeue(); if (dir == "<EOD>") { depthLimit -= 1; if (depthLimit <= 0) { return null; } continue; } var result = Directory.EnumerateFiles(dir, file, SearchOption.TopDirectoryOnly).FirstOrDefault(); if (result != null) { return result; } foreach (var subDir in Directory.EnumerateDirectories(dir)) { dirQueue.Enqueue(subDir); } dirQueue.Enqueue("<EOD>"); } return null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Codecs.Redis { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Text; using DotNetty.Buffers; using DotNetty.Codecs.Redis.Messages; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; public sealed class RedisDecoder : ByteToMessageDecoder { readonly IRedisMessagePool messagePool; readonly int maximumInlineMessageLength; readonly ToPositiveLongProcessor toPositiveLongProcessor = new ToPositiveLongProcessor(); enum State { DecodeType, DecodeInline, // SIMPLE_STRING, ERROR, INTEGER DecodeLength, // BULK_STRING, ARRAY_HEADER DecodeBulkStringEndOfLine, DecodeBulkStringContent, } // current decoding states State state = State.DecodeType; RedisMessageType messageType; int remainingBulkLength; public RedisDecoder() : this(RedisConstants.MaximumInlineMessageLength, FixedRedisMessagePool.Default) { } public RedisDecoder(int maximumInlineMessageLength, IRedisMessagePool messagePool) { Contract.Requires(maximumInlineMessageLength > 0 && maximumInlineMessageLength <= RedisConstants.MaximumMessageLength); Contract.Requires(messagePool != null); this.maximumInlineMessageLength = maximumInlineMessageLength; this.messagePool = messagePool; } protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output) { Contract.Requires(context != null); Contract.Requires(input != null); Contract.Requires(output != null); try { while (true) { switch (this.state) { case State.DecodeType: if (!this.DecodeType(input)) { return; } break; case State.DecodeInline: if (!this.DecodeInline(input, output)) { return; } break; case State.DecodeLength: if (!this.DecodeLength(input, output)) { return; } break; case State.DecodeBulkStringEndOfLine: if (!this.DecodeBulkStringEndOfLine(input, output)) { return; } break; case State.DecodeBulkStringContent: if (!this.DecodeBulkStringContent(input, output)) { return; } break; default: throw new RedisCodecException($"Unknown state: {this.state}"); } } } catch (RedisCodecException) { this.ResetDecoder(); throw; } catch (Exception exception) { this.ResetDecoder(); throw new RedisCodecException(exception); } } IRedisMessage ReadInlineMessage(RedisMessageType redisMessageType, IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); switch (redisMessageType) { case RedisMessageType.SimpleString: return this.GetSimpleStringMessage(byteBuffer); case RedisMessageType.Error: return this.GetErrorMessage(byteBuffer); case RedisMessageType.Integer: return this.GetIntegerMessage(byteBuffer); default: throw new RedisCodecException( $"Message type {redisMessageType} must be inline messageType of SimpleString, Error or Integer"); } } SimpleStringRedisMessage GetSimpleStringMessage(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); SimpleStringRedisMessage message; if (!this.messagePool.TryGetMessage(byteBuffer, out message)) { message = new SimpleStringRedisMessage(byteBuffer.ToString(Encoding.UTF8)); } return message; } ErrorRedisMessage GetErrorMessage(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); ErrorRedisMessage message; if (!this.messagePool.TryGetMessage(byteBuffer, out message)) { message = new ErrorRedisMessage(byteBuffer.ToString(Encoding.UTF8)); } return message; } IntegerRedisMessage GetIntegerMessage(IByteBuffer byteBuffer) { IntegerRedisMessage message; if (!this.messagePool.TryGetMessage(byteBuffer, out message)) { message = new IntegerRedisMessage(this.ParseNumber(byteBuffer)); } return message; } bool DecodeType(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); if (!byteBuffer.IsReadable()) { return false; } RedisMessageType redisMessageType = RedisCodecUtil.ParseMessageType(byteBuffer.ReadByte()); this.state = IsInline(redisMessageType) ? State.DecodeInline : State.DecodeLength; this.messageType = redisMessageType; return true; } static bool IsInline(RedisMessageType messageType) => messageType == RedisMessageType.SimpleString || messageType == RedisMessageType.Error || messageType == RedisMessageType.Integer; bool DecodeInline(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); IByteBuffer buffer = ReadLine(byteBuffer); if (buffer == null) { if (byteBuffer.ReadableBytes > this.maximumInlineMessageLength) { throw new RedisCodecException( $"Length: {byteBuffer.ReadableBytes} (expected: <= {this.maximumInlineMessageLength})"); } return false; } IRedisMessage message = this.ReadInlineMessage(this.messageType, buffer); output.Add(message); this.ResetDecoder(); return true; } bool DecodeLength(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); IByteBuffer lineByteBuffer = ReadLine(byteBuffer); if (lineByteBuffer == null) { return false; } long length = this.ParseNumber(lineByteBuffer); if (length < RedisConstants.NullValue) { throw new RedisCodecException( $"Length: {length} (expected: >= {RedisConstants.NullValue})"); } switch (this.messageType) { case RedisMessageType.ArrayHeader: output.Add(new ArrayHeaderRedisMessage(length)); this.ResetDecoder(); return true; case RedisMessageType.BulkString: if (length > RedisConstants.MaximumMessageLength) { throw new RedisCodecException( $"Length: {length} (expected: <= {RedisConstants.MaximumMessageLength})"); } this.remainingBulkLength = (int)length; // range(int) is already checked. return this.DecodeBulkString(byteBuffer, output); default: throw new RedisCodecException( $"Bad messageType: {this.messageType}, expecting ArrayHeader or BulkString."); } } bool DecodeBulkString(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); if (this.remainingBulkLength == RedisConstants.NullValue) // $-1\r\n { output.Add(FullBulkStringRedisMessage.Null); this.ResetDecoder(); return true; } if (this.remainingBulkLength == 0) { this.state = State.DecodeBulkStringEndOfLine; return this.DecodeBulkStringEndOfLine(byteBuffer, output); } // expectedBulkLength is always positive. output.Add(new BulkStringHeaderRedisMessage(this.remainingBulkLength)); this.state = State.DecodeBulkStringContent; return this.DecodeBulkStringContent(byteBuffer, output); } bool DecodeBulkStringContent(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); int readableBytes = byteBuffer.ReadableBytes; if (readableBytes == 0) { return false; } // if this is last frame. if (readableBytes >= this.remainingBulkLength + RedisConstants.EndOfLineLength) { IByteBuffer content = byteBuffer.ReadSlice(this.remainingBulkLength); ReadEndOfLine(byteBuffer); // Only call retain after readEndOfLine(...) as the method may throw an exception. output.Add(new LastBulkStringRedisContent((IByteBuffer)content.Retain())); this.ResetDecoder(); return true; } // chunked write. int toRead = Math.Min(this.remainingBulkLength, readableBytes); this.remainingBulkLength -= toRead; IByteBuffer buffer = byteBuffer.ReadSlice(toRead); output.Add(new BulkStringRedisContent((IByteBuffer)buffer.Retain())); return true; } // $0\r\n <here> \r\n bool DecodeBulkStringEndOfLine(IByteBuffer byteBuffer, ICollection<object> output) { Contract.Requires(byteBuffer != null); Contract.Requires(output != null); if (byteBuffer.ReadableBytes < RedisConstants.EndOfLineLength) { return false; } ReadEndOfLine(byteBuffer); output.Add(FullBulkStringRedisMessage.Empty); this.ResetDecoder(); return true; } static IByteBuffer ReadLine(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); if (!byteBuffer.IsReadable(RedisConstants.EndOfLineLength)) { return null; } int lfIndex = byteBuffer.ForEachByte(ByteProcessor.FindLF); if (lfIndex < 0) { return null; } IByteBuffer buffer = byteBuffer.ReadSlice(lfIndex - byteBuffer.ReaderIndex - 1); ReadEndOfLine(byteBuffer); return buffer; } static void ReadEndOfLine(IByteBuffer byteBuffer) { Contract.Requires(byteBuffer != null); short delim = byteBuffer.ReadShort(); if (RedisConstants.EndOfLine == delim) { return; } byte[] bytes = RedisCodecUtil.GetBytes(delim); throw new RedisCodecException($"delimiter: [{bytes[0]},{bytes[1]}] (expected: \\r\\n)"); } void ResetDecoder() { this.state = State.DecodeType; this.remainingBulkLength = 0; } long ParseNumber(IByteBuffer byteBuffer) { int readableBytes = byteBuffer.ReadableBytes; bool negative = readableBytes > 0 && byteBuffer.GetByte(byteBuffer.ReaderIndex) == '-'; int extraOneByteForNegative = negative ? 1 : 0; if (readableBytes <= extraOneByteForNegative) { throw new RedisCodecException( $"No number to parse: {byteBuffer.ToString(Encoding.ASCII)}"); } if (readableBytes > RedisConstants.PositiveLongValueMaximumLength + extraOneByteForNegative) { throw new RedisCodecException( $"Too many characters to be a valid RESP Integer: {byteBuffer.ToString(Encoding.ASCII)}"); } if (negative) { return -this.ParsePositiveNumber(byteBuffer.SkipBytes(extraOneByteForNegative)); } return this.ParsePositiveNumber(byteBuffer); } long ParsePositiveNumber(IByteBuffer byteBuffer) { this.toPositiveLongProcessor.Reset(); byteBuffer.ForEachByte(this.toPositiveLongProcessor); return this.toPositiveLongProcessor.Content; } class ToPositiveLongProcessor : IByteProcessor { public bool Process(byte value) { if (!char.IsDigit((char)value)) { throw new RedisCodecException($"Bad byte in number: {value}, expecting digits from 0 to 9"); } this.Content = this.Content * 10 + (value - '0'); return true; } public long Content { get; private set; } public void Reset() => this.Content = 0; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using OpenMetaverse; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Written to decode and encode a binary animation asset. /// The SecondLife Client reads in a BVH file and converts /// it to the format described here. This isn't /// </summary> public class BinBVHAnimation { /// <summary> /// Rotation Keyframe count (used internally) /// Don't use this, use the rotationkeys.Length on each joint /// </summary> private int rotationkeys; /// <summary> /// Position Keyframe count (used internally) /// Don't use this, use the positionkeys.Length on each joint /// </summary> private int positionkeys; public UInt16 unknown0; // Always 1 public UInt16 unknown1; // Always 0 /// <summary> /// Animation Priority /// </summary> public int Priority; /// <summary> /// The animation length in seconds. /// </summary> public Single Length; /// <summary> /// Expression set in the client. Null if [None] is selected /// </summary> public string ExpressionName; // "" (null) /// <summary> /// The time in seconds to start the animation /// </summary> public Single InPoint; /// <summary> /// The time in seconds to end the animation /// </summary> public Single OutPoint; /// <summary> /// Loop the animation /// </summary> public bool Loop; /// <summary> /// Meta data. Ease in Seconds. /// </summary> public Single EaseInTime; /// <summary> /// Meta data. Ease out seconds. /// </summary> public Single EaseOutTime; /// <summary> /// Meta Data for the Hand Pose /// </summary> public uint HandPose; /// <summary> /// Number of joints defined in the animation /// Don't use this.. use joints.Length /// </summary> private uint m_jointCount; /// <summary> /// Contains an array of joints /// </summary> public binBVHJoint[] Joints; public byte[] ToBytes() { byte[] outputbytes = new byte[0]; BinaryWriter iostream = new BinaryWriter(new MemoryStream()); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown0))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown1))); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(Length))); iostream.Write(BinBVHUtil.WriteNullTerminatedString(ExpressionName)); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(InPoint))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(OutPoint))); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Loop ? 1 : 0))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseInTime))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseOutTime))); iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes(HandPose))); iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes((uint)(Joints.Length)))); for (int i = 0; i < Joints.Length; i++) { Joints[i].WriteBytesToStream(iostream, InPoint, OutPoint); } iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(0))); MemoryStream ms = (MemoryStream)iostream.BaseStream; outputbytes = ms.ToArray(); ms.Close(); iostream.Close(); return outputbytes; } public BinBVHAnimation() { rotationkeys = 0; positionkeys = 0; unknown0 = 1; unknown1 = 0; Priority = 1; Length = 0; ExpressionName = string.Empty; InPoint = 0; OutPoint = 0; Loop = false; EaseInTime = 0; EaseOutTime = 0; HandPose = 1; m_jointCount = 0; Joints = new binBVHJoint[1]; Joints[0] = new binBVHJoint(); Joints[0].Name = "mPelvis"; Joints[0].Priority = 7; Joints[0].positionkeys = new binBVHJointKey[1]; Joints[0].rotationkeys = new binBVHJointKey[1]; Random rnd = new Random(); Joints[0].rotationkeys[0] = new binBVHJointKey(); Joints[0].rotationkeys[0].time = (0f); Joints[0].rotationkeys[0].key_element.X = ((float)rnd.NextDouble() * 2 - 1); Joints[0].rotationkeys[0].key_element.Y = ((float)rnd.NextDouble() * 2 - 1); Joints[0].rotationkeys[0].key_element.Z = ((float)rnd.NextDouble() * 2 - 1); Joints[0].positionkeys[0] = new binBVHJointKey(); Joints[0].positionkeys[0].time = (0f); Joints[0].positionkeys[0].key_element.X = ((float)rnd.NextDouble() * 2 - 1); Joints[0].positionkeys[0].key_element.Y = ((float)rnd.NextDouble() * 2 - 1); Joints[0].positionkeys[0].key_element.Z = ((float)rnd.NextDouble() * 2 - 1); } public BinBVHAnimation(byte[] animationdata) { int i = 0; if (!BitConverter.IsLittleEndian) { unknown0 = Utils.BytesToUInt16(BinBVHUtil.EndianSwap(animationdata,i,2)); i += 2; // Always 1 unknown1 = Utils.BytesToUInt16(BinBVHUtil.EndianSwap(animationdata, i, 2)); i += 2; // Always 0 Priority = Utils.BytesToInt(BinBVHUtil.EndianSwap(animationdata, i, 4)); i += 4; Length = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; } else { unknown0 = Utils.BytesToUInt16(animationdata, i); i += 2; // Always 1 unknown1 = Utils.BytesToUInt16(animationdata, i); i += 2; // Always 0 Priority = Utils.BytesToInt(animationdata, i); i += 4; Length = Utils.BytesToFloat(animationdata, i); i += 4; } ExpressionName = ReadBytesUntilNull(animationdata, ref i); if (!BitConverter.IsLittleEndian) { InPoint = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; OutPoint = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; Loop = (Utils.BytesToInt(BinBVHUtil.EndianSwap(animationdata, i, 4)) != 0); i += 4; EaseInTime = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; EaseOutTime = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; HandPose = Utils.BytesToUInt(BinBVHUtil.EndianSwap(animationdata, i, 4)); i += 4; // Handpose? m_jointCount = Utils.BytesToUInt(animationdata, i); i += 4; // Get Joint count } else { InPoint = Utils.BytesToFloat(animationdata, i); i += 4; OutPoint = Utils.BytesToFloat(animationdata, i); i += 4; Loop = (Utils.BytesToInt(animationdata, i) != 0); i += 4; EaseInTime = Utils.BytesToFloat(animationdata, i); i += 4; EaseOutTime = Utils.BytesToFloat(animationdata, i); i += 4; HandPose = Utils.BytesToUInt(animationdata, i); i += 4; // Handpose? m_jointCount = Utils.BytesToUInt(animationdata, i); i += 4; // Get Joint count } Joints = new binBVHJoint[m_jointCount]; // deserialize the number of joints in the animation. // Joints are variable length blocks of binary data consisting of joint data and keyframes for (int iter = 0; iter < m_jointCount; iter++) { binBVHJoint joint = readJoint(animationdata, ref i); Joints[iter] = joint; } } /// <summary> /// Variable length strings seem to be null terminated in the animation asset.. but.. /// use with caution, home grown. /// advances the index. /// </summary> /// <param name="data">The animation asset byte array</param> /// <param name="i">The offset to start reading</param> /// <returns>a string</returns> private static string ReadBytesUntilNull(byte[] data, ref int i) { char nterm = '\0'; // Null terminator int endpos = i; int startpos = i; // Find the null character for (int j = i; j < data.Length; j++) { char spot = Convert.ToChar(data[j]); if (spot == nterm) { endpos = j; break; } } // if we got to the end, then it's a zero length string if (i == endpos) { // advance the 1 null character i++; return string.Empty; } else { // We found the end of the string // append the bytes from the beginning of the string to the end of the string // advance i byte[] interm = new byte[endpos-i]; for (; i<endpos; i++) { interm[i-startpos] = data[i]; } i++; // advance past the null character return Utils.BytesToString(interm); } } /// <summary> /// Read in a Joint from an animation asset byte array /// Variable length Joint fields, yay! /// Advances the index /// </summary> /// <param name="data">animation asset byte array</param> /// <param name="i">Byte Offset of the start of the joint</param> /// <returns>The Joint data serialized into the binBVHJoint structure</returns> private binBVHJoint readJoint(byte[] data, ref int i) { binBVHJointKey[] positions; binBVHJointKey[] rotations; binBVHJoint pJoint = new binBVHJoint(); /* 109 84 111 114 114 111 0 <--- Null terminator */ pJoint.Name = ReadBytesUntilNull(data, ref i); // Joint name /* 2 <- Priority Revisited 0 0 0 */ /* 5 <-- 5 keyframes 0 0 0 ... 5 Keyframe data blocks */ /* 2 <-- 2 keyframes 0 0 0 .. 2 Keyframe data blocks */ if (!BitConverter.IsLittleEndian) { pJoint.Priority = Utils.BytesToInt(BinBVHUtil.EndianSwap(data, i, 4)); i += 4; // Joint Priority override? rotationkeys = Utils.BytesToInt(BinBVHUtil.EndianSwap(data, i, 4)); i += 4; // How many rotation keyframes } else { pJoint.Priority = Utils.BytesToInt(data, i); i += 4; // Joint Priority override? rotationkeys = Utils.BytesToInt(data, i); i += 4; // How many rotation keyframes } // argh! floats into two bytes!.. bad bad bad bad // After fighting with it for a while.. -1, to 1 seems to give the best results rotations = readKeys(data, ref i, rotationkeys, -1f, 1f); if (!BitConverter.IsLittleEndian) { positionkeys = Utils.BytesToInt(BinBVHUtil.EndianSwap(data, i, 4)); i += 4; // How many position keyframes } else { positionkeys = Utils.BytesToInt(data, i); i += 4; // How many position keyframes } // Read in position keyframes // argh! more floats into two bytes!.. *head desk* // After fighting with it for a while.. -5, to 5 seems to give the best results positions = readKeys(data, ref i, positionkeys, -5f, 5f); pJoint.rotationkeys = rotations; pJoint.positionkeys = positions; return pJoint; } /// <summary> /// Read Keyframes of a certain type /// advance i /// </summary> /// <param name="data">Animation Byte array</param> /// <param name="i">Offset in the Byte Array. Will be advanced</param> /// <param name="keycount">Number of Keyframes</param> /// <param name="min">Scaling Min to pass to the Uint16ToFloat method</param> /// <param name="max">Scaling Max to pass to the Uint16ToFloat method</param> /// <returns></returns> private binBVHJointKey[] readKeys(byte[] data, ref int i, int keycount, float min, float max) { float x; float y; float z; /* 0.o, Float values in Two bytes.. this is just wrong >:( 17 255 <-- Time Code 17 255 <-- Time Code 255 255 <-- X 127 127 <-- X 255 255 <-- Y 127 127 <-- Y 213 213 <-- Z 142 142 <---Z */ binBVHJointKey[] m_keys = new binBVHJointKey[keycount]; for (int j = 0; j < keycount; j++) { binBVHJointKey pJKey = new binBVHJointKey(); if (!BitConverter.IsLittleEndian) { pJKey.time = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, InPoint, OutPoint); i += 2; x = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, min, max); i += 2; y = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, min, max); i += 2; z = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, min, max); i += 2; } else { pJKey.time = Utils.UInt16ToFloat(data, i, InPoint, OutPoint); i += 2; x = Utils.UInt16ToFloat(data, i, min, max); i += 2; y = Utils.UInt16ToFloat(data, i, min, max); i += 2; z = Utils.UInt16ToFloat(data, i, min, max); i += 2; } pJKey.key_element = new Vector3(x, y, z); m_keys[j] = pJKey; } return m_keys; } } /// <summary> /// A Joint and it's associated meta data and keyframes /// </summary> public struct binBVHJoint { /// <summary> /// Name of the Joint. Matches the avatar_skeleton.xml in client distros /// </summary> public string Name; /// <summary> /// Joint Animation Override? Was the same as the Priority in testing.. /// </summary> public int Priority; /// <summary> /// Array of Rotation Keyframes in order from earliest to latest /// </summary> public binBVHJointKey[] rotationkeys; /// <summary> /// Array of Position Keyframes in order from earliest to latest /// This seems to only be for the Pelvis? /// </summary> public binBVHJointKey[] positionkeys; public void WriteBytesToStream(BinaryWriter iostream, float InPoint, float OutPoint) { iostream.Write(BinBVHUtil.WriteNullTerminatedString(Name)); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority))); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(rotationkeys.Length))); for (int i=0;i<rotationkeys.Length;i++) { rotationkeys[i].WriteBytesToStream(iostream, InPoint, OutPoint, -1f, 1f); } iostream.Write(BinBVHUtil.ES(Utils.IntToBytes((positionkeys.Length)))); for (int i = 0; i < positionkeys.Length; i++) { positionkeys[i].WriteBytesToStream(iostream, InPoint, OutPoint, -256f, 256f); } } } /// <summary> /// A Joint Keyframe. This is either a position or a rotation. /// </summary> public struct binBVHJointKey { // Time in seconds for this keyframe. public float time; /// <summary> /// Either a Vector3 position or a Vector3 Euler rotation /// </summary> public Vector3 key_element; public void WriteBytesToStream(BinaryWriter iostream, float InPoint, float OutPoint, float min, float max) { iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(time, InPoint, OutPoint)))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(key_element.X, min, max)))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(key_element.Y, min, max)))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(key_element.Z, min, max)))); } } /// <summary> /// Poses set in the animation metadata for the hands. /// </summary> public enum HandPose : uint { Spread = 0, Relaxed = 1, Point_Both = 2, Fist = 3, Relaxed_Left = 4, Point_Left = 5, Fist_Left = 6, Relaxed_Right = 7, Point_Right = 8, Fist_Right = 9, Salute_Right = 10, Typing = 11, Peace_Right = 12 } public static class BinBVHUtil { public const float ONE_OVER_U16_MAX = 1.0f / UInt16.MaxValue; public static UInt16 FloatToUInt16(float val, float lower, float upper) { UInt16 uival = 0; //m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue //0-1 // float difference = upper - lower; // we're trying to get a zero lower and modify all values equally so we get a percentage position if (lower > 0) { upper -= lower; val = val - lower; // start with 500 upper and 200 lower.. subtract 200 from the upper and the value } else //if (lower < 0 && upper > 0) { // double negative, 0 minus negative 5 is 5. upper += 0 - lower; lower += 0 - lower; val += 0 - lower; } if (upper == 0) val = 0; else { val /= upper; } uival = (UInt16)(val * UInt16.MaxValue); return uival; } /// <summary> /// Endian Swap /// Swaps endianness if necessary /// </summary> /// <param name="arr">Input array</param> /// <returns></returns> public static byte[] ES(byte[] arr) { if (!BitConverter.IsLittleEndian) Array.Reverse(arr); return arr; } public static byte[] EndianSwap(byte[] arr, int offset, int len) { byte[] bendian = new byte[offset + len]; Buffer.BlockCopy(arr, offset, bendian, 0, len); Array.Reverse(bendian); return bendian; } public static byte[] WriteNullTerminatedString(string str) { byte[] output = new byte[str.Length + 1]; Char[] chr = str.ToCharArray(); int i = 0; for (i = 0; i < chr.Length; i++) { output[i] = Convert.ToByte(chr[i]); } output[i] = Convert.ToByte('\0'); return output; } } } /* switch (jointname) { case "mPelvis": case "mTorso": case "mNeck": case "mHead": case "mChest": case "mHipLeft": case "mHipRight": case "mKneeLeft": case "mKneeRight": // XYZ->ZXY t = x; x = y; y = t; break; case "mCollarLeft": case "mCollarRight": case "mElbowLeft": case "mElbowRight": // YZX ->ZXY t = z; z = x; x = y; y = t; break; case "mWristLeft": case "mWristRight": case "mShoulderLeft": case "mShoulderRight": // ZYX->ZXY t = y; y = z; z = t; break; case "mAnkleLeft": case "mAnkleRight": // XYZ ->ZXY t = x; x = z; z = y; y = t; break; } */
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2009 Novell, Inc. (http://www.novell.com) // // Authors: // Mike Gorse <[email protected]> // using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; namespace Atspi { public class EventWindow : EventBase { private IEventWindow proxy; public EventWindow (Accessible accessible) : base (accessible) { proxy = Registry.Bus.GetObject<IEventWindow> (accessible.Application.Name, new ObjectPath (accessible.path)); } public event EventSimple Minimize { add { Registry.RegisterEventListener ("Window:Minimize"); proxy.Minimize += GetDelegate (value); } remove { proxy.Minimize -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Minimize"); } } public event EventSimple Maximize { add { Registry.RegisterEventListener ("Window:Maximize"); proxy.Maximize += GetDelegate (value); } remove { proxy.Maximize -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Maximize"); } } public event EventSimple Restore { add { Registry.RegisterEventListener ("Window:Restore"); proxy.Restore += GetDelegate (value); } remove { proxy.Restore -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Restore"); } } public event EventSimple Close { add { Registry.RegisterEventListener ("Window:Close"); proxy.Close += GetDelegate (value); } remove { proxy.Close -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Close"); } } public event EventSimple Create { add { Registry.RegisterEventListener ("Window:Create"); proxy.Create += GetDelegate (value); } remove { proxy.Create -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Create"); } } public event EventSimple Reparent { add { Registry.RegisterEventListener ("Window:Reparent"); proxy.Reparent += GetDelegate (value); } remove { proxy.Reparent -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Reparent"); } } public event EventSimple DesktopCreate { add { Registry.RegisterEventListener ("Window:DesktopCreate"); proxy.DesktopCreate += GetDelegate (value); } remove { proxy.DesktopCreate -= GetDelegate (value); Registry.DeregisterEventListener ("Window:DesktopCreate"); } } public event EventSimple DesktopDestroy { add { Registry.RegisterEventListener ("Window:DesktopDestroy"); proxy.DesktopDestroy += GetDelegate (value); } remove { proxy.DesktopDestroy -= GetDelegate (value); Registry.DeregisterEventListener ("Window:DesktopDestroy"); } } public event EventSimple Destroy { add { Registry.RegisterEventListener ("Window:Destroy"); proxy.Destroy += GetDelegate (value); } remove { proxy.Destroy -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Destroy"); } } public event EventSimple Activate { add { Registry.RegisterEventListener ("Window:Activate"); proxy.Activate += GetDelegate (value); } remove { proxy.Activate -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Activate"); } } public event EventSimple Deactivate { add { Registry.RegisterEventListener ("Window:Deactivate"); proxy.Deactivate += GetDelegate (value); } remove { proxy.Deactivate -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Deactivate"); } } public event EventSimple Raise { add { Registry.RegisterEventListener ("Window:Raise"); proxy.Raise += GetDelegate (value); } remove { proxy.Raise -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Raise"); } } public event EventSimple Lower { add { Registry.RegisterEventListener ("Window:Lower"); proxy.Lower += GetDelegate (value); } remove { proxy.Lower -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Lower"); } } public event EventSimple Move { add { Registry.RegisterEventListener ("Window:Move"); proxy.Move += GetDelegate (value); } remove { proxy.Move -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Move"); } } public event EventSimple Resize { add { Registry.RegisterEventListener ("Window:Resize"); proxy.Resize += GetDelegate (value); } remove { Registry.DeregisterEventListener ("Window:Resize"); proxy.Resize -= GetDelegate (value); } } public event EventSimple Shade { add { Registry.RegisterEventListener ("Window:Shade"); proxy.Shade += GetDelegate (value); } remove { proxy.Shade -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Shade"); } } public event EventSimple Unshade { add { Registry.RegisterEventListener ("Window:Unshade"); proxy.Unshade += GetDelegate (value); } remove { proxy.Unshade -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Unshade"); } } public event EventSimple Restyle { add { Registry.RegisterEventListener ("Window:Restyle"); proxy.Restyle += GetDelegate (value); } remove { proxy.Restyle -= GetDelegate (value); Registry.DeregisterEventListener ("Window:Restyle"); } } } [Interface ("org.a11y.atspi.Event.Window")] internal interface IEventWindow { event AtspiEventHandler Minimize; event AtspiEventHandler Maximize; event AtspiEventHandler Restore; event AtspiEventHandler Close; event AtspiEventHandler Create; event AtspiEventHandler Reparent; event AtspiEventHandler DesktopCreate; event AtspiEventHandler DesktopDestroy; event AtspiEventHandler Destroy; event AtspiEventHandler Activate; event AtspiEventHandler Deactivate; event AtspiEventHandler Raise; event AtspiEventHandler Lower; event AtspiEventHandler Move; event AtspiEventHandler Resize; event AtspiEventHandler Shade; event AtspiEventHandler Unshade; event AtspiEventHandler Restyle; } }
using System; using System.ComponentModel; using System.Linq; using System.Web.Mvc; using Telerik.Sitefinity.Mvc; using SitefinityWebApp.Mvc.Models; using Telerik.Sitefinity.DynamicModules.Model; using Telerik.Sitefinity.DynamicModules; using Telerik.Sitefinity.Utilities.TypeConverters; using Telerik.Sitefinity.Model; using Telerik.Sitefinity; using Telerik.Sitefinity.Versioning; using Telerik.Sitefinity.Data; using Telerik.Sitefinity.Security; using System.Text.RegularExpressions; namespace SitefinityWebApp.Mvc.Controllers { [ControllerToolboxItem(Name = "Projects", Title = "Projects", SectionName = "MvcWidgets")] [Telerik.Sitefinity.Web.UI.ControlDesign.ControlDesigner(typeof(WidgetDesigners.Projects.ProjectsDesigner))] public class ProjectsController : Controller { /// <summary> /// Gets or sets the message. /// </summary> [Category("String Properties")] public string Message { get; set; } #region Managers public DynamicModuleManager DynamicModuleManager { get { if (dynamicModuleManager == null) { dynamicModuleManager = DynamicModuleManager.GetManager(); } return dynamicModuleManager; } } #endregion /// <summary> /// This is the default Action. /// </summary> public ActionResult Index() { return View("Default", RetrieveCollectionOfProjects()); } public ActionResult Detail(string urlName) { var projectModel = new ProjectsModel(); DynamicContent project = RetrieveCollectionOfProjects().Where(p => p.UrlName == urlName).SingleOrDefault(); projectModel.Title = project.GetString("Title"); projectModel.Bugs = RetrieveCollectionOfBugs() .Where(b => b.SystemParentId == DynamicModuleManager.Lifecycle.GetMaster(project).Id); return View("Detail", projectModel); } public ActionResult Bugs(string urlName) { DynamicContent bug = RetrieveCollectionOfBugs() .Where(p => p.UrlName == urlName).SingleOrDefault(); return View("BugDetail", bug); } // Demonstrates how a collection of Projects can be retrieved public IQueryable<DynamicContent> RetrieveCollectionOfProjects() { // Set the provider name for the DynamicModuleManager here. All available providers are listed in // Administration -> Settings -> Advanced -> DynamicModules -> Providers var providerName = String.Empty; // Set a transaction name var transactionName = "someTransactionName"; DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName, transactionName); Type projectsType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BugTracking.Projects"); CreateProjectsItem(dynamicModuleManager, projectsType, transactionName); // This is how we get the collection of Project items var myCollection = dynamicModuleManager.GetDataItems(projectsType) .Where(p => p.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live && p.Visible == true); // At this point myCollection contains the items from type projectsType return myCollection; } // Creates a new projects item private void CreateProjectsItem(DynamicModuleManager dynamicModuleManager, Type projectsType, string transactionName) { DynamicContent projectsItem = dynamicModuleManager.CreateDataItem(projectsType); // This is how values for the properties are set projectsItem.SetValue("Title", "Some Title"); projectsItem.SetValue("Description", "Some Description"); projectsItem.SetString("UrlName", "SomeUrlName"); projectsItem.SetValue("Owner", SecurityManager.GetCurrentUserId()); projectsItem.SetValue("PublicationDate", DateTime.UtcNow); projectsItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft"); // Create a version and commit the transaction in order changes to be persisted to data store var versionManager = VersionManager.GetManager(null, transactionName); versionManager.CreateVersion(projectsItem, false); TransactionManager.CommitTransaction(transactionName); } //// Demonstrates how a collection of Projects can be retrieved //public IQueryable<DynamicContent> RetrieveCollectionOfProjects() //{ // // This is how we get the collection of Project items // var myCollection = dynamicModuleManager // .GetDataItems(projectsType) // .Where(p => p.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live && p.Visible == true); // // At this point myCollection contains the items from type projectsType // return myCollection; //} //private readonly Type projectsType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BugTracking.Projects"); private DynamicModuleManager dynamicModuleManager; // Demonstrates how a collection of Bugs can be retrieved public IQueryable<DynamicContent> RetrieveCollectionOfBugs() { // Set the provider name for the DynamicModuleManager here. All available providers are listed in // Administration -> Settings -> Advanced -> DynamicModules -> Providers var providerName = String.Empty; // Set a transaction name var transactionName = "someTransactionName"; DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName, transactionName); Type bugType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BugTracking.Bug"); CreateBugItem(dynamicModuleManager, bugType, transactionName); // This is how we get the collection of Bug items var myCollection = dynamicModuleManager.GetDataItems(bugType) .Where(p => p.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Live && p.Visible == true); // At this point myCollection contains the items from type bugType return myCollection; } // Creates a new bug item private void CreateBugItem(DynamicModuleManager dynamicModuleManager, Type bugType, string transactionName) { DynamicContent bugItem = dynamicModuleManager.CreateDataItem(bugType); // This is how values for the properties are set bugItem.SetValue("Title", "Some Title"); bugItem.SetValue("Description", "Some Description"); // Set the selected value bugItem.SetValue("Priority", "Option2"); bugItem.SetString("UrlName", "SomeUrlName"); bugItem.SetValue("Owner", SecurityManager.GetCurrentUserId()); bugItem.SetValue("PublicationDate", DateTime.UtcNow); bugItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft"); // Create a version and commit the transaction in order changes to be persisted to data store var versionManager = VersionManager.GetManager(null, transactionName); versionManager.CreateVersion(bugItem, false); TransactionManager.CommitTransaction(transactionName); } private readonly Type projectsType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BugTracking.Projects"); private readonly Type bugType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.BugTracking.Bug"); [HttpPost] public ActionResult CreateBug(BugsModel bug) { DynamicContent masterProject = DynamicModuleManager.GetDataItem(projectsType, bug.SystemParentId); var newBug = dynamicModuleManager.CreateDataItem(bugType); newBug.SetValue("Title", bug.Title); newBug.UrlName = Regex.Replace(bug.Title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-"); newBug.SetValue("Description", bug.Description); newBug.SetValue("SystemParentId", masterProject.OriginalContentId); newBug.ApprovalWorkflowState = "Published"; DynamicModuleManager.Lifecycle.Publish(newBug); DynamicModuleManager.SaveChanges(); return RedirectToAction("Detail", new { urlName = masterProject.UrlName }); } public ActionResult CreateBug(string projectUrlName) { BugsModel bugsModel = new BugsModel(); Guid liveProjectId = RetrieveCollectionOfProjects().Where(p => p.UrlName == projectUrlName).SingleOrDefault().Id; bugsModel.SystemParentId = liveProjectId; return View("BugForm", bugsModel); } } }
using System; namespace OTFontFile { /// <summary> /// Summary description for Table_GSUB. /// </summary> public class Table_GSUB : OTTable { /************************ * constructors */ public Table_GSUB(OTTag tag, MBOBuffer buf) : base(tag, buf) { } /************************ * field offset values */ public enum FieldOffsets { Version = 0, ScriptListOffset = 4, FeatureListOffset = 6, LookupListOffset = 8 } /************************ * classes */ // Lookup Type 1: Single Substitution Subtable public class SingleSubst : OTL.SubTable { public SingleSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetSingleSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0 } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { return 1; } // nested classes public class SingleSubstFormat1 { public SingleSubstFormat1(uint offset, MBOBuffer bufTable) { m_offsetSingleSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, DeltaGlyphID = 4 } public uint CalcLength() { return 6; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetSingleSubst + CoverageOffset, m_bufTable); } public ushort DeltaGlyphID { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.DeltaGlyphID);} } protected uint m_offsetSingleSubst; protected MBOBuffer m_bufTable; } public class SingleSubstFormat2 { public SingleSubstFormat2(uint offset, MBOBuffer bufTable) { m_offsetSingleSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, GlyphCount = 4, SubstituteGlyphIDs = 6 } public uint CalcLength() { return (uint)FieldOffsets.SubstituteGlyphIDs + (uint)GlyphCount*2; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetSingleSubst + CoverageOffset, m_bufTable); } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.GlyphCount);} } public ushort GetSubstituteGlyphID(uint i) { uint offset = m_offsetSingleSubst + (uint)FieldOffsets.SubstituteGlyphIDs + i*2; return m_bufTable.GetUshort(offset); } protected uint m_offsetSingleSubst; protected MBOBuffer m_bufTable; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetSingleSubst + (uint)FieldOffsets.SubstFormat);} } public SingleSubstFormat1 GetSingleSubstFormat1() { if (SubstFormat != 1) { throw new System.InvalidOperationException(); } return new SingleSubstFormat1(m_offsetSingleSubst, m_bufTable); } public SingleSubstFormat2 GetSingleSubstFormat2() { if (SubstFormat != 2) { throw new System.InvalidOperationException(); } return new SingleSubstFormat2(m_offsetSingleSubst, m_bufTable); } protected uint m_offsetSingleSubst; } // Lookup Type 2: Multiple Substitution Subtable public class MultipleSubst : OTL.SubTable { public MultipleSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetMultipleSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, SequenceCount = 4, SequenceOffsets = 6 } // public methods public uint CalcLength() { return (uint)FieldOffsets.SequenceOffsets + (uint)SequenceCount*2; } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { return 1; } // accessors public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetMultipleSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetMultipleSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetMultipleSubst + CoverageOffset, m_bufTable); } public ushort SequenceCount { get {return m_bufTable.GetUshort(m_offsetMultipleSubst + (uint)FieldOffsets.SequenceCount);} } public ushort GetSequenceOffset(uint i) { uint offset = m_offsetMultipleSubst + (uint)FieldOffsets.SequenceOffsets + i*2; return m_bufTable.GetUshort(offset); } public class SequenceTable { public SequenceTable(uint offset, MBOBuffer bufTable) { m_offsetSequence = offset; m_bufTable = bufTable; } public enum FieldOffsets { GlyphCount = 0, SubstituteGlyphIDs = 2 } public uint CalcLength() { return (uint)FieldOffsets.SubstituteGlyphIDs + (uint)GlyphCount*2; } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetSequence + (uint)FieldOffsets.GlyphCount);} } public ushort GetSubstituteGlyphID(uint i) { uint offset = m_offsetSequence + (uint)FieldOffsets.SubstituteGlyphIDs + i*2; return m_bufTable.GetUshort(offset); } protected uint m_offsetSequence; protected MBOBuffer m_bufTable; } public SequenceTable GetSequenceTable(uint i) { SequenceTable st = null; if (i < SequenceCount) { st = new SequenceTable(m_offsetMultipleSubst + GetSequenceOffset(i), m_bufTable); } return st; } protected uint m_offsetMultipleSubst; } // Lookup Type 3: Alternate Substitution Subtable public class AlternateSubst : OTL.SubTable { public AlternateSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetAlternateSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, AlternateSetCount = 4, AlternateSetOffsets = 6 } // public methods public uint CalcLength() { return (uint)FieldOffsets.AlternateSetOffsets + (uint)AlternateSetCount*2; } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { return 1; } // accessors public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetAlternateSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetAlternateSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetAlternateSubst + CoverageOffset, m_bufTable); } public ushort AlternateSetCount { get {return m_bufTable.GetUshort(m_offsetAlternateSubst + (uint)FieldOffsets.AlternateSetCount);} } public ushort GetAlternateSetOffset(uint i) { uint offset = m_offsetAlternateSubst + (uint)FieldOffsets.AlternateSetOffsets + i*2; return m_bufTable.GetUshort(offset); } public class AlternateSet { public AlternateSet(uint offset, MBOBuffer bufTable) { m_offsetAlternateSet = offset; m_bufTable = bufTable; } public enum FieldOffsets { GlyphCount = 0, AlternateGlyphIDs = 2 } public uint CalcLength() { return (uint)FieldOffsets.AlternateGlyphIDs + (uint)GlyphCount*2; } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetAlternateSet + (uint)FieldOffsets.GlyphCount);} } public ushort GetAlternateGlyphID(uint i) { uint offset = m_offsetAlternateSet + (uint)FieldOffsets.AlternateGlyphIDs + i*2; return m_bufTable.GetUshort(offset); } protected uint m_offsetAlternateSet; protected MBOBuffer m_bufTable; } public AlternateSet GetAlternateSetTable(uint i) { AlternateSet aset = null; if (i < AlternateSetCount) { aset = new AlternateSet(m_offsetAlternateSubst + GetAlternateSetOffset(i), m_bufTable); } return aset; } protected uint m_offsetAlternateSubst; } // Lookup Type 4: Ligature Substitution Subtable public class LigatureSubst : OTL.SubTable { public LigatureSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetLigatureSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, LigSetCount = 4, LigatureSetOffsets = 6 } // public methods public uint CalcLength() { return (uint)FieldOffsets.LigatureSetOffsets + (uint)LigSetCount*2; } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { uint nLength = 0; for (uint iLigatureSet=0; iLigatureSet<LigSetCount; iLigatureSet++) { LigatureSubst.LigatureSet ls = GetLigatureSetTable(iLigatureSet); for (uint iLigature=0; iLigature< ls.LigatureCount; iLigature++) { LigatureSubst.LigatureSet.Ligature lig = ls.GetLigatureTable(iLigature); if (lig.CompCount > nLength) { nLength = lig.CompCount; } } } return nLength; } // accessors public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetLigatureSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetLigatureSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetLigatureSubst + CoverageOffset, m_bufTable); } public ushort LigSetCount { get {return m_bufTable.GetUshort(m_offsetLigatureSubst + (uint)FieldOffsets.LigSetCount);} } public ushort GetLigatureSetOffset(uint i) { uint offset = m_offsetLigatureSubst + (uint)FieldOffsets.LigatureSetOffsets + i*2; return m_bufTable.GetUshort(offset); } public class LigatureSet { public LigatureSet(uint offset, MBOBuffer bufTable) { m_offsetLigatureSet = offset; m_bufTable = bufTable; } public enum FieldOffsets { LigatureCount = 0, LigatureOffsets = 2 } public uint CalcLength() { return (uint)FieldOffsets.LigatureOffsets + (uint)LigatureCount*2; } public ushort LigatureCount { get {return m_bufTable.GetUshort(m_offsetLigatureSet + (uint)FieldOffsets.LigatureCount);} } public ushort GetLigatureOffset(uint i) { uint offset = m_offsetLigatureSet + (uint)FieldOffsets.LigatureOffsets + i*2; return m_bufTable.GetUshort(offset); } public class Ligature { public Ligature(uint offset, MBOBuffer bufTable) { m_offsetLigature = offset; m_bufTable = bufTable; } public enum FieldOffsets { LigGlyph = 0, CompCount = 2, ComponentGlyphIDs = 4 } public uint CalcLength() { return (uint)FieldOffsets.ComponentGlyphIDs + (uint)(CompCount-1)*2; } public ushort LigGlyph { get {return m_bufTable.GetUshort(m_offsetLigature + (uint)FieldOffsets.LigGlyph);} } public ushort CompCount { get {return m_bufTable.GetUshort(m_offsetLigature + (uint)FieldOffsets.CompCount);} } public ushort GetComponentGlyphID(uint i) { uint offset = m_offsetLigature + (uint)FieldOffsets.ComponentGlyphIDs + i*2; return m_bufTable.GetUshort(offset); } protected uint m_offsetLigature; protected MBOBuffer m_bufTable; } public Ligature GetLigatureTable(uint i) { Ligature l = null; if (i < LigatureCount) { l = new Ligature(m_offsetLigatureSet + GetLigatureOffset(i), m_bufTable); } return l; } protected uint m_offsetLigatureSet; protected MBOBuffer m_bufTable; } public LigatureSet GetLigatureSetTable(uint i) { LigatureSet ls = null; if (i < LigSetCount) { ls = new LigatureSet(m_offsetLigatureSubst + GetLigatureSetOffset(i), m_bufTable); } return ls; } protected uint m_offsetLigatureSubst; } // Lookup Type 5: Contextual Substitution Subtable public class ContextSubst : OTL.SubTable { public ContextSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0 } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { uint nLength = 0; if (SubstFormat == 1) { ContextSubstFormat1 csf1 = GetContextSubstFormat1(); for (uint iSubRuleSet = 0; iSubRuleSet < csf1.SubRuleSetCount; iSubRuleSet++) { ContextSubstFormat1.SubRuleSet srs = csf1.GetSubRuleSetTable(iSubRuleSet); if (srs != null) { for (uint iSubRule = 0; iSubRule < srs.SubRuleCount; iSubRule++) { ContextSubstFormat1.SubRuleSet.SubRule sr = srs.GetSubRuleTable(iSubRule); if (sr.GlyphCount > nLength) { nLength = sr.GlyphCount; } } } } } else if (SubstFormat == 2) { ContextSubstFormat2 csf2 = GetContextSubstFormat2(); for (uint iSubClassSet = 0; iSubClassSet < csf2.SubClassSetCount; iSubClassSet ++) { ContextSubstFormat2.SubClassSet scs = csf2.GetSubClassSetTable(iSubClassSet); if (scs != null) { for (uint iSubClassRule = 0; iSubClassRule < scs.SubClassRuleCount; iSubClassRule++) { ContextSubstFormat2.SubClassSet.SubClassRule scr = scs.GetSubClassRuleTable(iSubClassRule); if (scr.GlyphCount > nLength) { nLength = scr.GlyphCount; } } } } } else if (SubstFormat == 3) { ContextSubstFormat3 csf3 = GetContextSubstFormat3(); if (csf3.GlyphCount > nLength) { nLength = csf3.GlyphCount; } } return nLength; } // nested classes public class SubstLookupRecord { public SubstLookupRecord(uint offset, MBOBuffer bufTable) { m_offsetSubstLookupRecord = offset; m_bufTable = bufTable; } public enum FieldOffsets { SequenceIndex = 0, LookupListIndex = 2 } public ushort SequenceIndex { get {return m_bufTable.GetUshort(m_offsetSubstLookupRecord + (uint)FieldOffsets.SequenceIndex);} } public ushort LookupListIndex { get {return m_bufTable.GetUshort(m_offsetSubstLookupRecord + (uint)FieldOffsets.LookupListIndex);} } protected uint m_offsetSubstLookupRecord; protected MBOBuffer m_bufTable; } public class ContextSubstFormat1 { public ContextSubstFormat1(uint offset, MBOBuffer bufTable) { m_offsetContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, SubRuleSetCount = 4, SubRuleSetOffsets = 6 } public uint CalcLength() { return (uint)FieldOffsets.SubRuleSetOffsets + (uint)SubRuleSetCount*2; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetContextSubst + CoverageOffset, m_bufTable); } public ushort SubRuleSetCount { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubRuleSetCount);} } public ushort GetSubRuleSetOffset(uint i) { return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubRuleSetOffsets + i*2); } public SubRuleSet GetSubRuleSetTable(uint i) { return new SubRuleSet(m_offsetContextSubst + GetSubRuleSetOffset(i), m_bufTable); } public class SubRuleSet { public SubRuleSet(uint offset, MBOBuffer bufTable) { m_offsetSubRuleSet = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubRuleCount = 0, SubRuleOffsets = 2 } public uint CalcLength() { return (uint)FieldOffsets.SubRuleOffsets + (uint)SubRuleCount*2; } public ushort SubRuleCount { get {return m_bufTable.GetUshort(m_offsetSubRuleSet + (uint)FieldOffsets.SubRuleCount);} } public ushort GetSubRuleOffset(uint i) { uint offset = m_offsetSubRuleSet + (uint)FieldOffsets.SubRuleOffsets + i*2; return m_bufTable.GetUshort(offset); } public class SubRule { public SubRule(uint offset, MBOBuffer bufTable) { m_offsetSubRule = offset; m_bufTable = bufTable; } public enum FieldOffsets { GlyphCount = 0, SubstCount = 2, InputGlyphIds = 4 } public uint CalcLength() { return (uint)FieldOffsets.InputGlyphIds + (uint)(GlyphCount-1)*2; } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetSubRule + (uint)FieldOffsets.GlyphCount);} } public ushort SubstCount { get {return m_bufTable.GetUshort(m_offsetSubRule + (uint)FieldOffsets.SubstCount);} } public ushort GetInputGlyphID(uint i) { uint offset = m_offsetSubRule + (uint)FieldOffsets.InputGlyphIds + i*2; return m_bufTable.GetUshort(offset); } public SubstLookupRecord GetSubstLookupRecord(uint i) { SubstLookupRecord slr = null; if (i < SubstCount) { uint offset = m_offsetSubRule + (uint)FieldOffsets.InputGlyphIds + (uint)(GlyphCount-1)*2 + i*4; slr = new SubstLookupRecord(offset, m_bufTable); } return slr; } protected uint m_offsetSubRule; protected MBOBuffer m_bufTable; } public SubRule GetSubRuleTable(uint i) { SubRule sr = null; if (i < SubRuleCount) { sr = new SubRule(m_offsetSubRuleSet + GetSubRuleOffset(i), m_bufTable); } return sr; } protected uint m_offsetSubRuleSet; protected MBOBuffer m_bufTable; } protected uint m_offsetContextSubst; protected MBOBuffer m_bufTable; } public class ContextSubstFormat2 { public ContextSubstFormat2(uint offset, MBOBuffer bufTable) { m_offsetContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, ClassDefOffset = 4, SubClassSetCount = 6, SubClassSetOffsets = 8 } public uint CalcLength() { return (uint)FieldOffsets.SubClassSetOffsets + (uint)SubClassSetCount*2; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetContextSubst + CoverageOffset, m_bufTable); } public ushort ClassDefOffset { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.ClassDefOffset);} } public OTL.ClassDefTable GetClassDefTable() { return new OTL.ClassDefTable(m_offsetContextSubst + ClassDefOffset, m_bufTable); } public ushort SubClassSetCount { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubClassSetCount);} } public ushort GetSubClassSetOffset(uint i) { uint offset = m_offsetContextSubst + (uint)FieldOffsets.SubClassSetOffsets + i*2; return m_bufTable.GetUshort(offset); } public SubClassSet GetSubClassSetTable(uint i) { SubClassSet scs = null; if (GetSubClassSetOffset(i) != 0) { scs = new SubClassSet(m_offsetContextSubst + GetSubClassSetOffset(i), m_bufTable); } return scs; } public class SubClassSet { public SubClassSet(uint offset, MBOBuffer bufTable) { m_offsetSubClassSet = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubClassRuleCount = 0, SubClassRuleOffsets = 2 } public uint CalcLength() { return (uint)FieldOffsets.SubClassRuleOffsets + (uint)SubClassRuleCount*2; } public ushort SubClassRuleCount { get {return m_bufTable.GetUshort(m_offsetSubClassSet + (uint)FieldOffsets.SubClassRuleCount);} } public ushort GetSubClassRuleOffset(uint i) { uint offset = m_offsetSubClassSet + (uint)FieldOffsets.SubClassRuleOffsets + i*2; return m_bufTable.GetUshort(offset); } public class SubClassRule { public SubClassRule(uint offset, MBOBuffer bufTable) { m_offsetSubClassRule = offset; m_bufTable = bufTable; } public enum FieldOffsets { GlyphCount = 0, SubstCount = 2, ClassArray = 4 } public uint CalcLength() { return (uint)FieldOffsets.ClassArray + (uint)(GlyphCount-1)*2 + (uint)SubstCount*4; } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetSubClassRule + (uint)FieldOffsets.GlyphCount);} } public ushort SubstCount { get {return m_bufTable.GetUshort(m_offsetSubClassRule + (uint)FieldOffsets.SubstCount);} } public ushort GetClass(uint i) { uint offset = m_offsetSubClassRule + (uint)FieldOffsets.ClassArray + i*2; return m_bufTable.GetUshort(offset); } public SubstLookupRecord GetSubstLookupRecord(uint i) { SubstLookupRecord slr = null; if (i < SubstCount) { uint offset = m_offsetSubClassRule + (uint)FieldOffsets.ClassArray + (uint)(GlyphCount-1)*2 + i*4; slr = new SubstLookupRecord(offset, m_bufTable); } return slr; } protected uint m_offsetSubClassRule; protected MBOBuffer m_bufTable; } public SubClassRule GetSubClassRuleTable(uint i) { SubClassRule scr = null; if (i < SubClassRuleCount) { scr = new SubClassRule(m_offsetSubClassSet + GetSubClassRuleOffset(i), m_bufTable); } return scr; } protected uint m_offsetSubClassSet; protected MBOBuffer m_bufTable; } protected uint m_offsetContextSubst; protected MBOBuffer m_bufTable; } public class ContextSubstFormat3 { public ContextSubstFormat3(uint offset, MBOBuffer bufTable) { m_offsetContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, GlyphCount = 2, SubstCount = 4, CoverageOffsets = 6 } public uint CalcLength() { return (uint)FieldOffsets.CoverageOffsets + (uint)GlyphCount*2 + (uint)SubstCount*4; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubstFormat);} } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.GlyphCount);} } public ushort SubstCount { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubstCount);} } public ushort GetCoverageOffset(uint i) { uint offset = m_offsetContextSubst + (uint)FieldOffsets.CoverageOffsets + i*2; return m_bufTable.GetUshort(offset); } public OTL.CoverageTable GetCoverageTable(uint i) { return new OTL.CoverageTable(m_offsetContextSubst + GetCoverageOffset(i), m_bufTable); } public SubstLookupRecord GetSubstLookupRecord(uint i) { SubstLookupRecord slr = null; if (i < SubstCount) { uint offset = m_offsetContextSubst + (uint)FieldOffsets.CoverageOffsets + (uint)GlyphCount*2 + i*4; slr = new SubstLookupRecord(offset, m_bufTable); } return slr; } protected uint m_offsetContextSubst; protected MBOBuffer m_bufTable; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetContextSubst + (uint)FieldOffsets.SubstFormat);} } public ContextSubstFormat1 GetContextSubstFormat1() { if (SubstFormat != 1) { throw new System.InvalidOperationException(); } return new ContextSubstFormat1(m_offsetContextSubst, m_bufTable); } public ContextSubstFormat2 GetContextSubstFormat2() { if (SubstFormat != 2) { throw new System.InvalidOperationException(); } return new ContextSubstFormat2(m_offsetContextSubst, m_bufTable); } public ContextSubstFormat3 GetContextSubstFormat3() { if (SubstFormat != 3) { throw new System.InvalidOperationException(); } return new ContextSubstFormat3(m_offsetContextSubst, m_bufTable); } protected uint m_offsetContextSubst; } // Lookup Type 6: Chaining Contextual Substitution Subtable public class ChainContextSubst : OTL.SubTable { public ChainContextSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetChainContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0 } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { uint nLength = 0; if (SubstFormat == 1) { ChainContextSubstFormat1 ccsf1 = GetChainContextSubstFormat1(); for (uint iChainSubRuleSet = 0; iChainSubRuleSet < ccsf1.ChainSubRuleSetCount; iChainSubRuleSet++) { ChainContextSubstFormat1.ChainSubRuleSet csrs = ccsf1.GetChainSubRuleSetTable(iChainSubRuleSet); if (csrs != null) { for (uint iChainSubRule = 0; iChainSubRule < csrs.ChainSubRuleCount; iChainSubRule++) { ChainContextSubstFormat1.ChainSubRuleSet.ChainSubRule csr = csrs.GetChainSubRuleTable(iChainSubRule); uint tempLength = (uint)(csr.InputGlyphCount + csr.LookaheadGlyphCount); if (tempLength > nLength) { nLength = tempLength; } } } } } else if (SubstFormat == 2) { ChainContextSubstFormat2 ccsf2 = GetChainContextSubstFormat2(); for (uint iChainSubClassSet = 0; iChainSubClassSet < ccsf2.ChainSubClassSetCount; iChainSubClassSet++) { ChainContextSubstFormat2.ChainSubClassSet cscs = ccsf2.GetChainSubClassSetTable(iChainSubClassSet); if (cscs != null) { for (uint iChainSubClassRule = 0; iChainSubClassRule < cscs.ChainSubClassRuleCount; iChainSubClassRule++) { ChainContextSubstFormat2.ChainSubClassSet.ChainSubClassRule cscr = cscs.GetChainSubClassRuleTable(iChainSubClassRule); uint tempLength = (uint)(cscr.InputGlyphCount + cscr.LookaheadGlyphCount); if (tempLength > nLength) { nLength = tempLength; } } } } } else if (SubstFormat == 3) { ChainContextSubstFormat3 ccsf3 = GetChainContextSubstFormat3(); uint tempLength = (uint)(ccsf3.InputGlyphCount + ccsf3.LookaheadGlyphCount); if (tempLength > nLength) { nLength = tempLength; } } return nLength; } // nested classes public class SubstLookupRecord { public SubstLookupRecord(uint offset, MBOBuffer bufTable) { m_offsetSubstLookupRecord = offset; m_bufTable = bufTable; } public enum FieldOffsets { SequenceIndex = 0, LookupListIndex = 2 } public ushort SequenceIndex { get {return m_bufTable.GetUshort(m_offsetSubstLookupRecord + (uint)FieldOffsets.SequenceIndex);} } public ushort LookupListIndex { get {return m_bufTable.GetUshort(m_offsetSubstLookupRecord + (uint)FieldOffsets.LookupListIndex);} } protected uint m_offsetSubstLookupRecord; protected MBOBuffer m_bufTable; } public class ChainContextSubstFormat1 { public ChainContextSubstFormat1(uint offset, MBOBuffer bufTable) { m_offsetChainContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, ChainSubRuleSetCount = 4, ChainSubRuleSetOffsets = 6 } public uint CalcLength() { return (uint)FieldOffsets.ChainSubRuleSetOffsets + (uint)ChainSubRuleSetCount*2; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetChainContextSubst + CoverageOffset, m_bufTable); } public ushort ChainSubRuleSetCount { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.ChainSubRuleSetCount);} } public ushort GetChainSubRuleSetOffset(uint i) { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.ChainSubRuleSetOffsets + i*2; return m_bufTable.GetUshort(offset); } public ChainSubRuleSet GetChainSubRuleSetTable(uint i) { return new ChainSubRuleSet(m_offsetChainContextSubst + GetChainSubRuleSetOffset(i), m_bufTable); } public class ChainSubRuleSet { public ChainSubRuleSet(uint offset, MBOBuffer bufTable) { m_offsetChainSubRuleSet = offset; m_bufTable = bufTable; } public enum FieldOffsets { ChainSubRuleCount = 0, ChainSubRuleOffsets = 2 } public uint CalcLength() { return (uint)FieldOffsets.ChainSubRuleOffsets + (uint)ChainSubRuleCount*2; } public ushort ChainSubRuleCount { get {return m_bufTable.GetUshort(m_offsetChainSubRuleSet + (uint)FieldOffsets.ChainSubRuleCount);} } public ushort GetChainSubRuleOffset(uint i) { uint offset = m_offsetChainSubRuleSet + (uint)FieldOffsets.ChainSubRuleOffsets + i*2; return m_bufTable.GetUshort(offset); } public class ChainSubRule { public ChainSubRule(uint offset, MBOBuffer bufTable) { m_offsetChainSubRule = offset; m_bufTable = bufTable; } public enum FieldOffsets { BacktrackGlyphCount = 0, BacktrackGlyphIDs = 2 } public uint CalcLength() { return (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + (uint)SubstCount*4; } public ushort BacktrackGlyphCount { get {return m_bufTable.GetUshort(m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphCount);} } public ushort GetBacktrackGlyphID(uint i) { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + i*2; return m_bufTable.GetUshort(offset); } public ushort InputGlyphCount { get { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2; return m_bufTable.GetUshort(offset); } } public ushort GetInputGlyphID(uint i) { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public ushort LookaheadGlyphCount { get { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2; return m_bufTable.GetUshort(offset); } } public ushort GetLookaheadGlyphID(uint i) { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public ushort SubstCount { get { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + (uint)LookaheadGlyphCount*2; return m_bufTable.GetUshort(offset); } } public SubstLookupRecord GetSubstLookupRecord(uint i) { SubstLookupRecord slr = null; if (i < SubstCount) { uint offset = m_offsetChainSubRule + (uint)FieldOffsets.BacktrackGlyphIDs + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + i*4; slr = new SubstLookupRecord(offset, m_bufTable); } return slr; } protected uint m_offsetChainSubRule; protected MBOBuffer m_bufTable; } public ChainSubRule GetChainSubRuleTable(uint i) { ChainSubRule csr = null; if (i < ChainSubRuleCount) { csr = new ChainSubRule(m_offsetChainSubRuleSet + GetChainSubRuleOffset(i), m_bufTable); } return csr; } protected uint m_offsetChainSubRuleSet; protected MBOBuffer m_bufTable; } protected uint m_offsetChainContextSubst; protected MBOBuffer m_bufTable; } public class ChainContextSubstFormat2 { public ChainContextSubstFormat2(uint offset, MBOBuffer bufTable) { m_offsetChainContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, BacktrackClassDefOffset = 4, InputClassDefOffset = 6, LookaheadClassDefOffset = 8, ChainSubClassSetCount = 10, ChainSubClassSetOffsets = 12 } public uint CalcLength() { return (uint)FieldOffsets.ChainSubClassSetOffsets + (uint)ChainSubClassSetCount*2; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetChainContextSubst + CoverageOffset, m_bufTable); } public ushort BacktrackClassDefOffset { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackClassDefOffset);} } public OTL.ClassDefTable GetBacktrackClassDefTable() { return new OTL.ClassDefTable(m_offsetChainContextSubst + BacktrackClassDefOffset, m_bufTable); } public ushort InputClassDefOffset { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.InputClassDefOffset);} } public OTL.ClassDefTable GetInputClassDefTable() { return new OTL.ClassDefTable(m_offsetChainContextSubst + InputClassDefOffset, m_bufTable); } public ushort LookaheadClassDefOffset { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.LookaheadClassDefOffset);} } public OTL.ClassDefTable GetLookaheadClassDefTable() { return new OTL.ClassDefTable(m_offsetChainContextSubst + LookaheadClassDefOffset, m_bufTable); } public ushort ChainSubClassSetCount { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.ChainSubClassSetCount);} } public ushort GetChainSubClassSetOffset(uint i) { return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.ChainSubClassSetOffsets + i*2); } public ChainSubClassSet GetChainSubClassSetTable(uint i) { ChainSubClassSet cscs = null; if (GetChainSubClassSetOffset(i) != 0) { cscs = new ChainSubClassSet(m_offsetChainContextSubst + GetChainSubClassSetOffset(i), m_bufTable); } return cscs; } public class ChainSubClassSet { public ChainSubClassSet(uint offset, MBOBuffer bufTable) { m_offsetChainSubClassSet = offset; m_bufTable = bufTable; } public enum FieldOffsets { ChainSubClassRuleCount = 0, ChainSubClassRuleOffsets = 2 } public uint CalcLength() { return (uint)FieldOffsets.ChainSubClassRuleOffsets + (uint)ChainSubClassRuleCount*2; } public ushort ChainSubClassRuleCount { get {return m_bufTable.GetUshort(m_offsetChainSubClassSet + (uint)FieldOffsets.ChainSubClassRuleCount);} } public ushort GetChainSubClassRuleOffset(uint i) { uint offset = m_offsetChainSubClassSet + (uint)FieldOffsets.ChainSubClassRuleOffsets + i*2; return m_bufTable.GetUshort(offset); } public class ChainSubClassRule { public ChainSubClassRule(uint offset, MBOBuffer bufTable) { m_offsetChainSubClassRule = offset; m_bufTable = bufTable; } public enum FieldOffsets { BacktrackGlyphCount = 0, BacktrackClasses = 2 } public uint CalcLength() { return (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + (uint)SubstCount*4; } public ushort BacktrackGlyphCount { get {return m_bufTable.GetUshort(m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackGlyphCount);} } public ushort GetBacktrackClass(uint i) { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + i*2; return m_bufTable.GetUshort(offset); } public ushort InputGlyphCount { get { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2; return m_bufTable.GetUshort(offset); } } public ushort GetInputClass(uint i) { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public ushort LookaheadGlyphCount { get { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2; return m_bufTable.GetUshort(offset); } } public ushort GetLookaheadClass(uint i) { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public ushort SubstCount { get { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + (uint)LookaheadGlyphCount*2; return m_bufTable.GetUshort(offset); } } public SubstLookupRecord GetSubstLookupRecord(uint i) { SubstLookupRecord slr = null; if (i < SubstCount) { uint offset = m_offsetChainSubClassRule + (uint)FieldOffsets.BacktrackClasses + (uint)BacktrackGlyphCount*2 + 2 + (uint)(InputGlyphCount-1)*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + i*4; slr = new SubstLookupRecord(offset, m_bufTable); } return slr; } protected uint m_offsetChainSubClassRule; protected MBOBuffer m_bufTable; } public ChainSubClassRule GetChainSubClassRuleTable(uint i) { ChainSubClassRule cscr = null; if (i < ChainSubClassRuleCount) { cscr = new ChainSubClassRule(m_offsetChainSubClassSet + GetChainSubClassRuleOffset(i), m_bufTable); } return cscr; } protected uint m_offsetChainSubClassSet; protected MBOBuffer m_bufTable; } protected uint m_offsetChainContextSubst; protected MBOBuffer m_bufTable; } public class ChainContextSubstFormat3 { public ChainContextSubstFormat3(uint offset, MBOBuffer bufTable) { m_offsetChainContextSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, BacktrackGlyphCount = 2, BacktrackCoverageOffsets = 4 } public uint CalcLength() { return (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)InputGlyphCount*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + (uint)SubstCount*4; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.SubstFormat);} } public ushort BacktrackGlyphCount { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackGlyphCount);} } public ushort GetBacktrackCoverageOffset(uint i) { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + i*2; return m_bufTable.GetUshort(offset); } public OTL.CoverageTable GetBacktrackCoverageTable(uint i) { uint offset = m_offsetChainContextSubst + (uint)GetBacktrackCoverageOffset(i); return new OTL.CoverageTable(offset, m_bufTable); } public ushort InputGlyphCount { get { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2; return m_bufTable.GetUshort(offset); } } public ushort GetInputCoverageOffset(uint i) { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public OTL.CoverageTable GetInputCoverageTable(uint i) { uint offset = m_offsetChainContextSubst + (uint)GetInputCoverageOffset(i); return new OTL.CoverageTable(offset, m_bufTable); } public ushort LookaheadGlyphCount { get { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)InputGlyphCount*2; return m_bufTable.GetUshort(offset); } } public ushort GetLookaheadCoverageOffset(uint i) { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)InputGlyphCount*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public OTL.CoverageTable GetLookaheadCoverageTable(uint i) { uint offset = m_offsetChainContextSubst + (uint)GetLookaheadCoverageOffset(i); return new OTL.CoverageTable(offset, m_bufTable); } public ushort SubstCount { get { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)InputGlyphCount*2 + 2 + (uint)LookaheadGlyphCount*2; return m_bufTable.GetUshort(offset); } } public SubstLookupRecord GetSubstLookupRecord(uint i) { SubstLookupRecord slr = null; if (i < SubstCount) { uint offset = m_offsetChainContextSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)InputGlyphCount*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + i*4; slr = new SubstLookupRecord(offset, m_bufTable); } return slr; } protected uint m_offsetChainContextSubst; protected MBOBuffer m_bufTable; } public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetChainContextSubst + (uint)FieldOffsets.SubstFormat);} } public ChainContextSubstFormat1 GetChainContextSubstFormat1() { if (SubstFormat != 1) { throw new System.InvalidOperationException(); } return new ChainContextSubstFormat1(m_offsetChainContextSubst, m_bufTable); } public ChainContextSubstFormat2 GetChainContextSubstFormat2() { if (SubstFormat != 2) { throw new System.InvalidOperationException(); } return new ChainContextSubstFormat2(m_offsetChainContextSubst, m_bufTable); } public ChainContextSubstFormat3 GetChainContextSubstFormat3() { if (SubstFormat != 3) { throw new System.InvalidOperationException(); } return new ChainContextSubstFormat3(m_offsetChainContextSubst, m_bufTable); } protected uint m_offsetChainContextSubst; } // Lookup Type 7: Extension Substitution Subtable public class ExtensionSubst : OTL.SubTable { public ExtensionSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetExtensionSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, ExtensionLookupType = 2, ExtensionOffset = 4 } // public methods public uint CalcLength() { return 8; } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { uint nLength = 0; OTL.SubTable st = null; switch (ExtensionLookupType) { case 1: st = new Table_GSUB.SingleSubst (m_offsetExtensionSubst + ExtensionOffset, m_bufTable); break; case 2: st = new Table_GSUB.MultipleSubst (m_offsetExtensionSubst + ExtensionOffset, m_bufTable); break; case 3: st = new Table_GSUB.AlternateSubst (m_offsetExtensionSubst + ExtensionOffset, m_bufTable); break; case 4: st = new Table_GSUB.LigatureSubst (m_offsetExtensionSubst + ExtensionOffset, m_bufTable); break; case 5: st = new Table_GSUB.ContextSubst (m_offsetExtensionSubst + ExtensionOffset, m_bufTable); break; case 6: st = new Table_GSUB.ChainContextSubst(m_offsetExtensionSubst + ExtensionOffset, m_bufTable); break; } if (st != null) { nLength = st.GetMaxContextLength(); } return nLength; } // accessors public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetExtensionSubst + (uint)FieldOffsets.SubstFormat);} } public ushort ExtensionLookupType { get {return m_bufTable.GetUshort(m_offsetExtensionSubst + (uint)FieldOffsets.ExtensionLookupType);} } public uint ExtensionOffset { get {return m_bufTable.GetUint(m_offsetExtensionSubst + (uint)FieldOffsets.ExtensionOffset);} } protected uint m_offsetExtensionSubst; } // Lookup Type 8: Reverse Chaining Contextual Single Substitution Subtable public class ReverseChainSubst : OTL.SubTable { public ReverseChainSubst(uint offset, MBOBuffer bufTable) : base (offset, bufTable) { m_offsetReverseChainSubst = offset; m_bufTable = bufTable; } public enum FieldOffsets { SubstFormat = 0, CoverageOffset = 2, BacktrackGlyphCount = 4, BacktrackCoverageOffsets = 6 } // public methods public uint CalcLength() { return 8; } // this is needed for calculating OS2.usMaxContext public override uint GetMaxContextLength() { uint nLength = 0; uint tempLength = (uint)(this.BacktrackGlyphCount + this.LookaheadGlyphCount); if (tempLength > nLength) { nLength = tempLength; } return nLength; } // accessors public ushort SubstFormat { get {return m_bufTable.GetUshort(m_offsetReverseChainSubst + (uint)FieldOffsets.SubstFormat);} } public ushort CoverageOffset { get {return m_bufTable.GetUshort(m_offsetReverseChainSubst + (uint)FieldOffsets.CoverageOffset);} } public OTL.CoverageTable GetCoverageTable() { return new OTL.CoverageTable(m_offsetReverseChainSubst + CoverageOffset, m_bufTable); } public ushort BacktrackGlyphCount { get {return m_bufTable.GetUshort(m_offsetReverseChainSubst + (uint)FieldOffsets.BacktrackGlyphCount);} } public ushort GetBacktrackCoverageOffset(uint i) { uint offset = m_offsetReverseChainSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + i*2; return m_bufTable.GetUshort(offset); } public OTL.CoverageTable GetBacktrackCoverageTable(uint i) { uint offset = m_offsetReverseChainSubst + (uint)GetBacktrackCoverageOffset(i); return new OTL.CoverageTable(offset, m_bufTable); } public ushort LookaheadGlyphCount { get { uint offset = m_offsetReverseChainSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2; return m_bufTable.GetUshort(offset); } } public ushort GetLookaheadCoverageOffset(uint i) { uint offset = m_offsetReverseChainSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } public OTL.CoverageTable GetLookaheadCoverageTable(uint i) { uint offset = m_offsetReverseChainSubst + (uint)GetLookaheadCoverageOffset(i); return new OTL.CoverageTable(offset, m_bufTable); } public ushort SubstituteGlyphCount { get { uint offset = m_offsetReverseChainSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)LookaheadGlyphCount*2 ; return m_bufTable.GetUshort(offset); } } public ushort GetSubstituteGlyphID(uint i) { uint offset = m_offsetReverseChainSubst + (uint)FieldOffsets.BacktrackCoverageOffsets + (uint)BacktrackGlyphCount*2 + 2 + (uint)LookaheadGlyphCount*2 + 2 + i*2; return m_bufTable.GetUshort(offset); } protected uint m_offsetReverseChainSubst; } /************************ * accessors */ public OTFixed Version { get {return m_bufTable.GetFixed((uint)FieldOffsets.Version);} } public ushort ScriptListOffset { get {return m_bufTable.GetUshort((uint)FieldOffsets.ScriptListOffset);} } public ushort FeatureListOffset { get {return m_bufTable.GetUshort((uint)FieldOffsets.FeatureListOffset);} } public ushort LookupListOffset { get {return m_bufTable.GetUshort((uint)FieldOffsets.LookupListOffset);} } public OTL.ScriptListTable GetScriptListTable() { return new OTL.ScriptListTable(ScriptListOffset, m_bufTable); } public OTL.FeatureListTable GetFeatureListTable() { return new OTL.FeatureListTable(FeatureListOffset, m_bufTable); } public OTL.LookupListTable GetLookupListTable() { return new OTL.LookupListTable(LookupListOffset, m_bufTable, m_tag); } // GetMaxContext is used by OS/2 validation public ushort GetMaxContext() { // return the max length of a target glyph context for any feature in the font ushort usMaxLength = 0; OTL.FeatureListTable flt = GetFeatureListTable(); if (flt != null) { for (uint iFeature=0; iFeature<flt.FeatureCount; iFeature++) { OTL.FeatureListTable.FeatureRecord fr = flt.GetFeatureRecord(iFeature); OTL.FeatureTable ft = flt.GetFeatureTable(fr); for (uint iLookup = 0; iLookup < ft.LookupCount; iLookup++) { ushort LookupIndex = ft.GetLookupListIndex(iLookup); ushort length = GetMaxContextFromLookup(LookupIndex); if (length > usMaxLength) { usMaxLength = length; } } } } return usMaxLength; } protected ushort GetMaxContextFromLookup(uint iLookup) { ushort length = 0; OTL.LookupListTable llt = GetLookupListTable(); if (llt != null) { OTL.LookupTable lt = llt.GetLookupTable(iLookup); for (uint iSubTable = 0; iSubTable < lt.SubTableCount; iSubTable++) { OTL.SubTable st = lt.GetSubTable(iSubTable); ushort tempLength = (ushort)st.GetMaxContextLength(); if (length < tempLength) { length = tempLength; } } } return length; } /************************ * DataCache class */ public override DataCache GetCache() { if (m_cache == null) { m_cache = new GSUB_cache(); } return m_cache; } public class GSUB_cache : DataCache { public override OTTable GenerateTable() { // not yet implemented! return null; } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookWorksheetNamesCollectionRequest. /// </summary> public partial class WorkbookWorksheetNamesCollectionRequest : BaseRequest, IWorkbookWorksheetNamesCollectionRequest { /// <summary> /// Constructs a new WorkbookWorksheetNamesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookWorksheetNamesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified WorkbookNamedItem to the collection via POST. /// </summary> /// <param name="workbookNamedItem">The WorkbookNamedItem to add.</param> /// <returns>The created WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> AddAsync(WorkbookNamedItem workbookNamedItem) { return this.AddAsync(workbookNamedItem, CancellationToken.None); } /// <summary> /// Adds the specified WorkbookNamedItem to the collection via POST. /// </summary> /// <param name="workbookNamedItem">The WorkbookNamedItem to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookNamedItem.</returns> public System.Threading.Tasks.Task<WorkbookNamedItem> AddAsync(WorkbookNamedItem workbookNamedItem, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<WorkbookNamedItem>(workbookNamedItem, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IWorkbookWorksheetNamesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IWorkbookWorksheetNamesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<WorkbookWorksheetNamesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Expand(Expression<Func<WorkbookNamedItem, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Select(Expression<Func<WorkbookNamedItem, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IWorkbookWorksheetNamesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; using Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable { private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance(); internal static readonly ImmutableArray<Alias> NoAliases = ImmutableArray<Alias>.Empty; public override void Dispose() { base.Dispose(); foreach (var instance in _runtimeInstances) { instance.Dispose(); } _runtimeInstances.Free(); } internal RuntimeInstance CreateRuntimeInstance( Compilation compilation, bool includeSymbols = true) { byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); return CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), references.AddIntrinsicAssembly(), exeBytes, includeSymbols ? new SymReader(pdbBytes, exeBytes) : null); } internal RuntimeInstance CreateRuntimeInstance( string assemblyName, ImmutableArray<MetadataReference> references, byte[] exeBytes, ISymUnmanagedReader symReader, bool includeLocalSignatures = true) { var exeReference = AssemblyMetadata.CreateFromImage(exeBytes).GetReference(display: assemblyName); var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance(); // Create modules for the references modulesBuilder.AddRange(references.Select(r => r.ToModuleInstance(fullImage: null, symReader: null, includeLocalSignatures: includeLocalSignatures))); // Create a module for the exe. modulesBuilder.Add(exeReference.ToModuleInstance(exeBytes, symReader, includeLocalSignatures: includeLocalSignatures)); var modules = modulesBuilder.ToImmutableAndFree(); modules.VerifyAllModules(); var instance = new RuntimeInstance(modules); _runtimeInstances.Add(instance); return instance; } internal static void GetContextState( RuntimeInstance runtime, string methodOrTypeName, out ImmutableArray<MetadataBlock> blocks, out Guid moduleVersionId, out ISymUnmanagedReader symReader, out int methodOrTypeToken, out int localSignatureToken) { var moduleInstances = runtime.Modules; blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock); var compilation = blocks.ToCompilation(); var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName); var module = (PEModuleSymbol)methodOrType.ContainingModule; var id = module.Module.GetModuleVersionIdOrThrow(); var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id); moduleVersionId = id; symReader = (ISymUnmanagedReader)moduleInstance.SymReader; EntityHandle methodOrTypeHandle; if (methodOrType.Kind == SymbolKind.Method) { methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle; localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle); } else { methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle; localSignatureToken = -1; } MetadataReader reader = null; // null should be ok methodOrTypeToken = reader.GetToken(methodOrTypeHandle); } internal static EvaluationContext CreateMethodContext( RuntimeInstance runtime, string methodName, int atLineNumber = -1) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber); return EvaluationContext.CreateMethodContext( default(CSharpMetadataContext), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); } internal static EvaluationContext CreateTypeContext( RuntimeInstance runtime, string typeName) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); return EvaluationContext.CreateTypeContext( default(CSharpMetadataContext), blocks, moduleVersionId, typeToken); } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, int atLineNumber = -1, bool includeSymbols = true) { ResultProperties resultProperties; string error; var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, includeSymbols); Assert.Null(error); return result; } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, out ResultProperties resultProperties, out string error, int atLineNumber = -1, bool includeSymbols = true) { var compilation0 = CreateCompilationWithMscorlib( source, options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe); var runtime = CreateRuntimeInstance(compilation0, includeSymbols); var context = CreateMethodContext(runtime, methodName, atLineNumber); var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return testData; } /// <summary> /// Verify all type parameters from the method /// are from that method or containing types. /// </summary> internal static void VerifyTypeParameters(MethodSymbol method) { Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType)); AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument)); AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type)); VerifyTypeParameters(method.ContainingType); } internal static void VerifyLocal( CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName = null, DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None, string expectedILOpt = null, bool expectedGeneric = false, [CallerFilePath]string expectedValueSourcePath = null, [CallerLineNumber]int expectedValueSourceLine = 0) { ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>( testData, typeName, localAndMethod, expectedMethodName, expectedLocalName, expectedLocalDisplayName ?? expectedLocalName, expectedFlags, VerifyTypeParameters, expectedILOpt, expectedGeneric, expectedValueSourcePath, expectedValueSourceLine); } /// <summary> /// Verify all type parameters from the type /// are from that type or containing types. /// </summary> internal static void VerifyTypeParameters(NamedTypeSymbol type) { AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument)); var container = type.ContainingType; if ((object)container != null) { VerifyTypeParameters(container); } } internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature) { string[] parameterTypeNames; var methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames); var candidates = compilation.GetMembers(methodOrTypeName); var methodOrType = (parameterTypeNames == null) ? candidates.FirstOrDefault() : candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.Type.Name))); Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'."); return methodOrType; } internal static Alias VariableAlias(string name, Type type = null) { return VariableAlias(name, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias VariableAlias(string name, string typeAssemblyQualifiedName) { return new Alias(DkmClrAliasKind.Variable, name, name, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias ObjectIdAlias(uint id, Type type = null) { return ObjectIdAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ObjectIdAlias(uint id, string typeAssemblyQualifiedName) { Assert.NotEqual(0u, id); // Not a valid id. var name = $"${id}"; return new Alias(DkmClrAliasKind.ObjectId, name, name, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias ReturnValueAlias(int id = -1, Type type = null) { return ReturnValueAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ReturnValueAlias(int id, string typeAssemblyQualifiedName) { var name = $"Method M{(id < 0 ? "" : id.ToString())} returned"; var fullName = id < 0 ? "$ReturnValue" : $"$ReturnValue{id}"; return new Alias(DkmClrAliasKind.ReturnValue, name, fullName, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias ExceptionAlias(Type type = null, bool stowed = false) { return ExceptionAlias((type ?? typeof(Exception)).AssemblyQualifiedName, stowed); } internal static Alias ExceptionAlias(string typeAssemblyQualifiedName, bool stowed = false) { var name = "Error"; var fullName = stowed ? "$stowedexception" : "$exception"; var kind = stowed ? DkmClrAliasKind.StowedException : DkmClrAliasKind.Exception; return new Alias(kind, name, fullName, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName, string type, CustomTypeInfo customTypeInfo) { return new Alias(kind, name, fullName, type, customTypeInfo); } } }
// 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.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.WebSockets; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net { public sealed unsafe partial class HttpListenerRequest { private Uri _requestUri; private ulong _requestId; internal ulong _connectionId; private SslStatus _sslStatus; private string _rawUrl; private string _cookedUrlHost; private string _cookedUrlPath; private string _cookedUrlQuery; private long _contentLength; private Stream _requestStream; private string _httpMethod; private bool? _keepAlive; private Version _version; private WebHeaderCollection _webHeaders; private IPEndPoint _localEndPoint; private IPEndPoint _remoteEndPoint; private BoundaryType _boundaryType; private ListenerClientCertState _clientCertState; private X509Certificate2 _clientCertificate; private int _clientCertificateError; private RequestContextBase _memoryBlob; private CookieCollection _cookies; private HttpListenerContext _httpContext; private bool _isDisposed = false; internal const uint CertBoblSize = 1500; private string _serviceName; private object _lock = new object(); private enum SslStatus : byte { Insecure, NoClientCert, ClientCert } internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"httpContext:${httpContext} memoryBlob {((IntPtr)memoryBlob.RequestBlob)}"); NetEventSource.Associate(this, httpContext); } _httpContext = httpContext; _memoryBlob = memoryBlob; _boundaryType = BoundaryType.None; // Set up some of these now to avoid refcounting on memory blob later. _requestId = memoryBlob.RequestBlob->RequestId; _connectionId = memoryBlob.RequestBlob->ConnectionId; _sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure : memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert : SslStatus.ClientCert; if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0) { _rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength); } Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl; if (cookedUrl.pHost != null && cookedUrl.HostLength > 0) { _cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2); } if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0) { _cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2); } if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0) { _cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2); } _version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion); _clientCertState = ListenerClientCertState.NotInitialized; _keepAlive = null; if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"RequestId:{RequestId} ConnectionId:{_connectionId} RawConnectionId:{memoryBlob.RequestBlob->RawConnectionId} UrlContext:{memoryBlob.RequestBlob->UrlContext} RawUrl:{_rawUrl} Version:{_version} Secure:{_sslStatus}"); NetEventSource.Info(this, $"httpContext:${httpContext} RequestUri:{RequestUri} Content-Length:{ContentLength64} HTTP Method:{HttpMethod}"); } // Log headers if (NetEventSource.IsEnabled) { StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n"); for (int i = 0; i < Headers.Count; i++) { sb.Append("\t"); sb.Append(Headers.GetKey(i)); sb.Append(" : "); sb.Append(Headers.Get(i)); sb.Append("\n"); } NetEventSource.Info(this, sb.ToString()); } } internal HttpListenerContext HttpListenerContext { get { return _httpContext; } } // Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer, // you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of // RequestBuffer. internal byte[] RequestBuffer { get { CheckDisposed(); return _memoryBlob.RequestBuffer; } } internal IntPtr OriginalBlobAddress { get { CheckDisposed(); return _memoryBlob.OriginalBlobAddress; } } // Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be // disposed. internal void DetachBlob(RequestContextBase memoryBlob) { if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob) { _memoryBlob = null; } } // Finalizes ownership of the memory blob. DetachBlob can't be called after this. internal void ReleasePins() { _memoryBlob.ReleasePins(); } internal ulong RequestId { get { return _requestId; } } public Guid RequestTraceIdentifier { get { Guid guid = new Guid(); *(1 + (ulong*)&guid) = RequestId; return guid; } } public string[] AcceptTypes { get { return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.Accept)); } } public Encoding ContentEncoding { get { if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) { string postDataCharset = Headers["x-up-devcap-post-charset"]; if (postDataCharset != null && postDataCharset.Length > 0) { try { return Encoding.GetEncoding(postDataCharset); } catch (ArgumentException) { } } } if (HasEntityBody) { if (ContentType != null) { string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset"); if (charSet != null) { try { return Encoding.GetEncoding(charSet); } catch (ArgumentException) { } } } } return Encoding.Default; } } public long ContentLength64 { get { if (_boundaryType == BoundaryType.None) { if (GetKnownHeader(HttpRequestHeader.TransferEncoding).Equals("chunked", StringComparison.OrdinalIgnoreCase)) { _boundaryType = BoundaryType.Chunked; _contentLength = -1; } else { _contentLength = 0; _boundaryType = BoundaryType.ContentLength; string length = GetKnownHeader(HttpRequestHeader.ContentLength); if (length != null) { bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength); if (!success) { _contentLength = 0; _boundaryType = BoundaryType.Invalid; } } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_contentLength:{_contentLength} _boundaryType:{_boundaryType}"); return _contentLength; } } public string ContentType { get { return GetKnownHeader(HttpRequestHeader.ContentType); } } public NameValueCollection Headers { get { if (_webHeaders == null) { _webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"webHeaders:{_webHeaders}"); return _webHeaders; } } public string HttpMethod { get { if (_httpMethod == null) { _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}"); return _httpMethod; } } public Stream InputStream { get { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (_requestStream == null) { _requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; } if (NetEventSource.IsEnabled) NetEventSource.Exit(this); return _requestStream; } } public bool IsAuthenticated { get { IPrincipal user = HttpListenerContext.User; return user != null && user.Identity != null && user.Identity.IsAuthenticated; } } public bool IsLocal { get { return LocalEndPoint.Address.Equals(RemoteEndPoint.Address); } } public bool IsSecureConnection { get { return _sslStatus != SslStatus.Insecure; } } public bool IsWebSocketRequest { get { if (!WebSocketProtocolComponent.IsSupported) { return false; } bool foundConnectionUpgradeHeader = false; if (string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Upgrade])) { return false; } foreach (string connection in this.Headers.GetValues(HttpKnownHeaderNames.Connection)) { if (string.Compare(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase) == 0) { foundConnectionUpgradeHeader = true; break; } } if (!foundConnectionUpgradeHeader) { return false; } foreach (string upgrade in this.Headers.GetValues(HttpKnownHeaderNames.Upgrade)) { if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } public NameValueCollection QueryString { get { NameValueCollection queryString = new NameValueCollection(); Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding); return queryString; } } public string RawUrl { get { return _rawUrl; } } public string ServiceName { get { return _serviceName; } internal set { _serviceName = value; } } public Uri Url { get { return RequestUri; } } public Uri UrlReferrer { get { string referrer = GetKnownHeader(HttpRequestHeader.Referer); if (referrer == null) { return null; } Uri urlReferrer; bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out urlReferrer); return success ? urlReferrer : null; } } public string UserAgent { get { return GetKnownHeader(HttpRequestHeader.UserAgent); } } public string UserHostAddress { get { return LocalEndPoint.ToString(); } } public string UserHostName { get { return GetKnownHeader(HttpRequestHeader.Host); } } public string[] UserLanguages { get { return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.AcceptLanguage)); } } public int ClientCertificateError { get { if (_clientCertState == ListenerClientCertState.NotInitialized) throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()")); else if (_clientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()")); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ClientCertificateError:{_clientCertificateError}"); return _clientCertificateError; } } internal X509Certificate2 ClientCertificate { set { _clientCertificate = value; } } internal ListenerClientCertState ClientCertState { set { _clientCertState = value; } } internal void SetClientCertificateError(int clientCertificateError) { _clientCertificateError = clientCertificateError; } public X509Certificate2 GetClientCertificate() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { ProcessClientCertificate(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{_clientCertificate}"); } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return _clientCertificate; } public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); return AsyncProcessClientCertificate(requestCallback, state); } public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); X509Certificate2 clientCertificate = null; try { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (clientCertAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate))); } clientCertAsyncResult.EndCalled = true; clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{_clientCertificate}"); } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return clientCertificate; } public Task<X509Certificate2> GetClientCertificateAsync() { return Task.Factory.FromAsync( (callback, state) => ((HttpListenerRequest)state).BeginGetClientCertificate(callback, state), iar => ((HttpListenerRequest)iar.AsyncState).EndGetClientCertificate(iar), null); } public TransportContext TransportContext { get { return new HttpListenerRequestContext(this); } } private CookieCollection ParseCookies(Uri uri, string setCookieHeader) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader); CookieContainer container = new CookieContainer(); container.SetCookies(uri, setCookieHeader); return container.GetCookies(uri); } public CookieCollection Cookies { get { if (_cookies == null) { string cookieString = GetKnownHeader(HttpRequestHeader.Cookie); if (cookieString != null && cookieString.Length > 0) { _cookies = ParseCookies(RequestUri, cookieString); } if (_cookies == null) { _cookies = new CookieCollection(); } } return _cookies; } } public Version ProtocolVersion { get { return _version; } } public bool HasEntityBody { get { // accessing the ContentLength property delay creates m_BoundaryType return (ContentLength64 > 0 && _boundaryType == BoundaryType.ContentLength) || _boundaryType == BoundaryType.Chunked || _boundaryType == BoundaryType.Multipart; } } public bool KeepAlive { get { if (!_keepAlive.HasValue) { string header = Headers[HttpKnownHeaderNames.ProxyConnection]; if (string.IsNullOrEmpty(header)) { header = GetKnownHeader(HttpRequestHeader.Connection); } if (string.IsNullOrEmpty(header)) { if (ProtocolVersion >= HttpVersion.Version11) { _keepAlive = true; } else { header = GetKnownHeader(HttpRequestHeader.KeepAlive); _keepAlive = !string.IsNullOrEmpty(header); } } else { header = header.ToLower(CultureInfo.InvariantCulture); _keepAlive = header.IndexOf("close", StringComparison.InvariantCultureIgnoreCase) < 0 || header.IndexOf("keep-alive", StringComparison.InvariantCultureIgnoreCase) >= 0; } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_keepAlive=" + _keepAlive); return _keepAlive.Value; } } public IPEndPoint RemoteEndPoint { get { if (_remoteEndPoint == null) { _remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint); return _remoteEndPoint; } } public IPEndPoint LocalEndPoint { get { if (_localEndPoint == null) { _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}"); return _localEndPoint; } } //should only be called from httplistenercontext internal void Close() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); RequestContextBase memoryBlob = _memoryBlob; if (memoryBlob != null) { memoryBlob.Close(); _memoryBlob = null; } _isDisposed = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } private ListenerClientCertAsyncResult AsyncProcessClientCertificate(AsyncCallback requestCallback, object state) { if (_clientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()")); _clientCertState = ListenerClientCertState.InProgress; ListenerClientCertAsyncResult asyncResult = null; //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the //initial SSL connection, server (HTTP.SYS) demands the client certificate // //Some apps may not want to demand the client cert at the beginning //perhaps server the default.htm. In this case the HTTP.SYS is configured //with a flag value other than 2, whcih means that the client certificate is //optional.So initially when SSL is established HTTP.SYS won't ask for client //certificate. This works fine for the default.htm in the case above //However, if the app wants to demand a client certficate at a later time //perhaps showing "YOUR ORDERS" page, then the server wans to demand //Client certs. this will inturn makes HTTP.SYS to do the //SEC_I_RENOGOTIATE through which the client cert demand is made // //THE BUG HERE IS THAT PRIOR TO QFE 4796, we call //GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with //flag = 2. Which means that apps using HTTPListener will not be able to //demand a client cert at a later point // //The fix here is to demand the client cert when the channel is NOT INSECURE //which means whether the client certs are requried at the beginning or not, //if this is an SSL connection, Call HttpReceiveClientCertificate, thus //starting the cert negotiation at that point // //NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get //ERROR_NOT_FOUND - which means the client did not provide the cert //If this is important, the server should respond with 403 forbidden //HTTP.SYS will not do this for you automatically *** //-------------------------------------------------------------------- if (_sslStatus != SslStatus.Insecure) { // at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate) // the cert, though might or might not be there. try to retrieve it // this number is the same that IIS decided to use uint size = CertBoblSize; asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, size); try { while (true) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size); uint bytesReceived = 0; uint statusCode = Interop.HttpApi.HttpReceiveClientCertificate( HttpListenerContext.RequestQueueHandle, _connectionId, (uint)Interop.HttpApi.HTTP_FLAGS.NONE, asyncResult.RequestBlob, size, &bytesReceived, asyncResult.NativeOverlapped); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived); if (statusCode == Interop.HttpApi.ERROR_MORE_DATA) { Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob; size = bytesReceived + pClientCertInfo->CertEncodedSize; asyncResult.Reset(size); continue; } if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) { // someother bad error, possible return values are: // ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED // Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required. throw new HttpListenerException((int)statusCode); } if (statusCode == Interop.HttpApi.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { asyncResult.IOCompleted(statusCode, bytesReceived); } break; } } catch { asyncResult?.InternalCleanup(); throw; } } else { asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, 0); asyncResult.InvokeCallback(); } return asyncResult; } private void ProcessClientCertificate() { if (_clientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()")); _clientCertState = ListenerClientCertState.InProgress; if (NetEventSource.IsEnabled) NetEventSource.Info(this); //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the //initial SSL connection, server (HTTP.SYS) demands the client certificate // //Some apps may not want to demand the client cert at the beginning //perhaps server the default.htm. In this case the HTTP.SYS is configured //with a flag value other than 2, whcih means that the client certificate is //optional.So initially when SSL is established HTTP.SYS won't ask for client //certificate. This works fine for the default.htm in the case above //However, if the app wants to demand a client certficate at a later time //perhaps showing "YOUR ORDERS" page, then the server wans to demand //Client certs. this will inturn makes HTTP.SYS to do the //SEC_I_RENOGOTIATE through which the client cert demand is made // //THE BUG HERE IS THAT PRIOR TO QFE 4796, we call //GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with //flag = 2. Which means that apps using HTTPListener will not be able to //demand a client cert at a later point // //The fix here is to demand the client cert when the channel is NOT INSECURE //which means whether the client certs are requried at the beginning or not, //if this is an SSL connection, Call HttpReceiveClientCertificate, thus //starting the cert negotiation at that point // //NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get //ERROR_NOT_FOUND - which means the client did not provide the cert //If this is important, the server should respond with 403 forbidden //HTTP.SYS will not do this for you automatically *** //-------------------------------------------------------------------- if (_sslStatus != SslStatus.Insecure) { // at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate) // the cert, though might or might not be there. try to retrieve it // this number is the same that IIS decided to use uint size = CertBoblSize; while (true) { byte[] clientCertInfoBlob = new byte[checked((int)size)]; fixed (byte* pClientCertInfoBlob = &clientCertInfoBlob[0]) { Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)pClientCertInfoBlob; if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size); uint bytesReceived = 0; uint statusCode = Interop.HttpApi.HttpReceiveClientCertificate( HttpListenerContext.RequestQueueHandle, _connectionId, (uint)Interop.HttpApi.HTTP_FLAGS.NONE, pClientCertInfo, size, &bytesReceived, null); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived); if (statusCode == Interop.HttpApi.ERROR_MORE_DATA) { size = bytesReceived + pClientCertInfo->CertEncodedSize; continue; } else if (statusCode == Interop.HttpApi.ERROR_SUCCESS) { if (pClientCertInfo != null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}"); if (pClientCertInfo->pCertEncoded != null) { try { byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length); _clientCertificate = new X509Certificate2(certEncoded); } catch (CryptographicException exception) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CryptographicException={exception}"); } catch (SecurityException exception) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SecurityException={exception}"); } } _clientCertificateError = (int)pClientCertInfo->CertFlags; } } else { Debug.Assert(statusCode == Interop.HttpApi.ERROR_NOT_FOUND, $"Call to Interop.HttpApi.HttpReceiveClientCertificate() failed with statusCode {statusCode}."); } } break; } } _clientCertState = ListenerClientCertState.Completed; } private string RequestScheme { get { return IsSecureConnection ? "https" : "http"; } } private Uri RequestUri { get { if (_requestUri == null) { _requestUri = HttpListenerRequestUriBuilder.GetRequestUri( _rawUrl, RequestScheme, _cookedUrlHost, _cookedUrlPath, _cookedUrlQuery); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_requestUri:{_requestUri}"); return _requestUri; } } private string GetKnownHeader(HttpRequestHeader header) { return Interop.HttpApi.GetKnownHeader(RequestBuffer, OriginalBlobAddress, (int)header); } internal ChannelBinding GetChannelBinding() { return HttpListenerContext.Listener.GetChannelBindingFromTls(_connectionId); } internal void CheckDisposed() { if (_isDisposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private static class Helpers { // // Get attribute off header value // internal static string GetAttributeFromHeader(string headerValue, string attrName) { if (headerValue == null) return null; int l = headerValue.Length; int k = attrName.Length; // find properly separated attribute name int i = 1; // start searching from 1 while (i < l) { i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase); if (i < 0) break; if (i + k >= l) break; char chPrev = headerValue[i - 1]; char chNext = headerValue[i + k]; if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext))) break; i += k; } if (i < 0 || i >= l) return null; // skip to '=' and the following whitespace i += k; while (i < l && char.IsWhiteSpace(headerValue[i])) i++; if (i >= l || headerValue[i] != '=') return null; i++; while (i < l && char.IsWhiteSpace(headerValue[i])) i++; if (i >= l) return null; // parse the value string attrValue = null; int j; if (i < l && headerValue[i] == '"') { if (i == l - 1) return null; j = headerValue.IndexOf('"', i + 1); if (j < 0 || j == i + 1) return null; attrValue = headerValue.Substring(i + 1, j - i - 1).Trim(); } else { for (j = i; j < l; j++) { if (headerValue[j] == ' ' || headerValue[j] == ',') break; } if (j == i) return null; attrValue = headerValue.Substring(i, j - i).Trim(); } return attrValue; } internal static string[] ParseMultivalueHeader(string s) { if (s == null) return null; int l = s.Length; // collect comma-separated values into list List<string> values = new List<string>(); int i = 0; while (i < l) { // find next , int ci = s.IndexOf(',', i); if (ci < 0) ci = l; // append corresponding server value values.Add(s.Substring(i, ci - i)); // move to next i = ci + 1; // skip leading space if (i < l && s[i] == ' ') i++; } // return list as array of strings int n = values.Count; string[] strings; // if n is 0 that means s was empty string if (n == 0) { strings = new string[1]; strings[0] = string.Empty; } else { strings = new string[n]; values.CopyTo(0, strings, 0, n); } return strings; } private static string UrlDecodeStringFromStringInternal(string s, Encoding e) { int count = s.Length; UrlDecoder helper = new UrlDecoder(count, e); // go through the string's chars collapsing %XX and %uXXXX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = s[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count - 2) { if (s[pos + 1] == 'u' && pos < count - 5) { int h1 = HexToInt(s[pos + 2]); int h2 = HexToInt(s[pos + 3]); int h3 = HexToInt(s[pos + 4]); int h4 = HexToInt(s[pos + 5]); if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0) { // valid 4 hex chars ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4); pos += 5; // only add as char helper.AddChar(ch); continue; } } else { int h1 = HexToInt(s[pos + 1]); int h2 = HexToInt(s[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } } internal string GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new string(_charBuffer, 0, _numChars); else return string.Empty; } } internal static void FillFromString(NameValueCollection nvc, string s, bool urlencoded, Encoding encoding) { int l = (s != null) ? s.Length : 0; int i = (s.Length > 0 && s[0] == '?') ? 1 : 0; while (i < l) { // find next & while noting first = on the way (and if there are more) int si = i; int ti = -1; while (i < l) { char ch = s[i]; if (ch == '=') { if (ti < 0) ti = i; } else if (ch == '&') { break; } i++; } // extract the name / value pair string name = null; string value = null; if (ti >= 0) { name = s.Substring(si, ti - si); value = s.Substring(ti + 1, i - ti - 1); } else { value = s.Substring(si, i - si); } // add name / value pair to the collection if (urlencoded) nvc.Add( name == null ? null : UrlDecodeStringFromStringInternal(name, encoding), UrlDecodeStringFromStringInternal(value, encoding)); else nvc.Add(name, value); // trailing '&' if (i == l - 1 && s[i] == '&') nvc.Add(null, ""); i++; } } } } }
using Lucene.Net.Documents; using Lucene.Net.Support; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { using Codec = Lucene.Net.Codecs.Codec; using Constants = Lucene.Net.Util.Constants; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using InfoStream = Lucene.Net.Util.InfoStream; using IOContext = Lucene.Net.Store.IOContext; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using TextField = TextField; using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper; /// <summary> /// JUnit adaptation of an older test case DocTest. </summary> [TestFixture] public class TestDoc : LuceneTestCase { private DirectoryInfo WorkDir; private DirectoryInfo IndexDir; private LinkedList<FileInfo> Files; /// <summary> /// Set the test case. this test case needs /// a few text files created in the current working directory. /// </summary> [SetUp] public override void SetUp() { base.SetUp(); if (VERBOSE) { Console.WriteLine("TEST: setUp"); } WorkDir = CreateTempDir("TestDoc"); IndexDir = CreateTempDir("testIndex"); Directory directory = NewFSDirectory(IndexDir); directory.Dispose(); Files = new LinkedList<FileInfo>(); Files.AddLast(CreateOutput("test.txt", "this is the first test file")); Files.AddLast(CreateOutput("test2.txt", "this is the second test file")); } private FileInfo CreateOutput(string name, string text) { //TextWriter fw = null; StreamWriter pw = null; try { FileInfo f = new FileInfo(Path.Combine(WorkDir.FullName, name)); if (f.Exists) { f.Delete(); } //fw = new StreamWriter(new FileOutputStream(f), IOUtils.CHARSET_UTF_8); pw = new StreamWriter(File.Open(f.FullName, FileMode.OpenOrCreate)); pw.WriteLine(text); return f; } finally { if (pw != null) { pw.Dispose(); } /*if (fw != null) { fw.Dispose(); }*/ } } /// <summary> /// this test executes a number of merges and compares the contents of /// the segments created when using compound file or not using one. /// /// TODO: the original test used to print the segment contents to System.out /// for visual validation. To have the same effect, a new method /// checkSegment(String name, ...) should be created that would /// assert various things about the segment. /// </summary> [Test] public virtual void TestIndexAndMerge() { MemoryStream sw = new MemoryStream(); StreamWriter @out = new StreamWriter(sw); Directory directory = NewFSDirectory(IndexDir, null); MockDirectoryWrapper wrapper = directory as MockDirectoryWrapper; if (wrapper != null) { // We create unreferenced files (we don't even write // a segments file): wrapper.AssertNoUnrefencedFilesOnClose = false; } IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetMaxBufferedDocs(-1).SetMergePolicy(NewLogMergePolicy(10))); SegmentCommitInfo si1 = IndexDoc(writer, "test.txt"); PrintSegment(@out, si1); SegmentCommitInfo si2 = IndexDoc(writer, "test2.txt"); PrintSegment(@out, si2); writer.Dispose(); SegmentCommitInfo siMerge = Merge(directory, si1, si2, "_merge", false); PrintSegment(@out, siMerge); SegmentCommitInfo siMerge2 = Merge(directory, si1, si2, "_merge2", false); PrintSegment(@out, siMerge2); SegmentCommitInfo siMerge3 = Merge(directory, siMerge, siMerge2, "_merge3", false); PrintSegment(@out, siMerge3); directory.Dispose(); @out.Dispose(); sw.Dispose(); string multiFileOutput = sw.ToString(); //System.out.println(multiFileOutput); sw = new MemoryStream(); @out = new StreamWriter(sw); directory = NewFSDirectory(IndexDir, null); wrapper = directory as MockDirectoryWrapper; if (wrapper != null) { // We create unreferenced files (we don't even write // a segments file): wrapper.AssertNoUnrefencedFilesOnClose = false; } writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE).SetMaxBufferedDocs(-1).SetMergePolicy(NewLogMergePolicy(10))); si1 = IndexDoc(writer, "test.txt"); PrintSegment(@out, si1); si2 = IndexDoc(writer, "test2.txt"); PrintSegment(@out, si2); writer.Dispose(); siMerge = Merge(directory, si1, si2, "_merge", true); PrintSegment(@out, siMerge); siMerge2 = Merge(directory, si1, si2, "_merge2", true); PrintSegment(@out, siMerge2); siMerge3 = Merge(directory, siMerge, siMerge2, "_merge3", true); PrintSegment(@out, siMerge3); directory.Dispose(); @out.Dispose(); sw.Dispose(); string singleFileOutput = sw.ToString(); Assert.AreEqual(multiFileOutput, singleFileOutput); } private SegmentCommitInfo IndexDoc(IndexWriter writer, string fileName) { FileInfo file = new FileInfo(Path.Combine(WorkDir.FullName, fileName)); Document doc = new Document(); StreamReader @is = new StreamReader(File.Open(file.FullName, FileMode.Open)); doc.Add(new TextField("contents", @is)); writer.AddDocument(doc); writer.Commit(); @is.Dispose(); return writer.NewestSegment(); } private SegmentCommitInfo Merge(Directory dir, SegmentCommitInfo si1, SegmentCommitInfo si2, string merged, bool useCompoundFile) { IOContext context = NewIOContext(Random()); SegmentReader r1 = new SegmentReader(si1, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, context); SegmentReader r2 = new SegmentReader(si2, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, context); Codec codec = Codec.Default; TrackingDirectoryWrapper trackingDir = new TrackingDirectoryWrapper(si1.Info.Dir); SegmentInfo si = new SegmentInfo(si1.Info.Dir, Constants.LUCENE_MAIN_VERSION, merged, -1, false, codec, null); SegmentMerger merger = new SegmentMerger(Arrays.AsList<AtomicReader>(r1, r2), si, InfoStream.Default, trackingDir, IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL, CheckAbort.NONE, new FieldInfos.FieldNumbers(), context, true); MergeState mergeState = merger.Merge(); r1.Dispose(); r2.Dispose(); SegmentInfo info = new SegmentInfo(si1.Info.Dir, Constants.LUCENE_MAIN_VERSION, merged, si1.Info.DocCount + si2.Info.DocCount, false, codec, null); info.SetFiles(new HashSet<string>(trackingDir.CreatedFiles)); if (useCompoundFile) { ICollection<string> filesToDelete = IndexWriter.CreateCompoundFile(InfoStream.Default, dir, CheckAbort.NONE, info, NewIOContext(Random())); info.UseCompoundFile = true; foreach (String fileToDelete in filesToDelete) { si1.Info.Dir.DeleteFile(fileToDelete); } } return new SegmentCommitInfo(info, 0, -1L, -1L); } private void PrintSegment(StreamWriter @out, SegmentCommitInfo si) { SegmentReader reader = new SegmentReader(si, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, NewIOContext(Random())); for (int i = 0; i < reader.NumDocs; i++) { @out.WriteLine(reader.Document(i)); } Fields fields = reader.Fields; foreach (string field in fields) { Terms terms = fields.GetTerms(field); Assert.IsNotNull(terms); TermsEnum tis = terms.GetIterator(null); while (tis.Next() != null) { @out.Write(" term=" + field + ":" + tis.Term); @out.WriteLine(" DF=" + tis.DocFreq); DocsAndPositionsEnum positions = tis.DocsAndPositions(reader.LiveDocs, null); while (positions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { @out.Write(" doc=" + positions.DocID); @out.Write(" TF=" + positions.Freq); @out.Write(" pos="); @out.Write(positions.NextPosition()); for (int j = 1; j < positions.Freq; j++) { @out.Write("," + positions.NextPosition()); } @out.WriteLine(""); } } } reader.Dispose(); } } }
/* Generated SBE (Simple Binary Encoding) message codec */ #pragma warning disable 1591 // disable warning on missing comments using System; using Adaptive.SimpleBinaryEncoding; namespace Adaptive.SimpleBinaryEncoding.Tests.Generated { public class QuoteRequest { public const ushort TemplateId = (ushort)11; public const byte TemplateVersion = (byte)1; public const ushort BlockLength = (ushort)31; public const string SematicType = "R"; private readonly QuoteRequest _parentMessage; private DirectBuffer _buffer; private int _offset; private int _limit; private int _actingBlockLength; private int _actingVersion; public int Offset { get { return _offset; } } public QuoteRequest() { _parentMessage = this; } public void WrapForEncode(DirectBuffer buffer, int offset) { _buffer = buffer; _offset = offset; _actingBlockLength = BlockLength; _actingVersion = TemplateVersion; Limit = offset + _actingBlockLength; } public void WrapForDecode(DirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { _buffer = buffer; _offset = offset; _actingBlockLength = actingBlockLength; _actingVersion = actingVersion; Limit = offset + _actingBlockLength; } public int Size { get { return _limit - _offset; } } public int Limit { get { return _limit; } set { _buffer.CheckLimit(_limit); _limit = value; } } public const int TransactTimeSchemaId = 60; public static string TransactTimeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "UTCTimestamp"; } return ""; } public const ulong TransactTimeNullValue = 0x8000000000000000UL; public const ulong TransactTimeMinValue = 0x0UL; public const ulong TransactTimeMaxValue = 0x7fffffffffffffffUL; public ulong TransactTime { get { return _buffer.Uint64GetLittleEndian(_offset + 0); } set { _buffer.Uint64PutLittleEndian(_offset + 0, value); } } public const int QuoteReqIDSchemaId = 131; public static string QuoteReqIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte QuoteReqIDNullValue = (byte)0; public const byte QuoteReqIDMinValue = (byte)32; public const byte QuoteReqIDMaxValue = (byte)126; public const int QuoteReqIDLength = 23; public byte GetQuoteReqID(int index) { if (index < 0 || index >= 23) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 8 + (index * 1)); } public void SetQuoteReqID(int index, byte value) { if (index < 0 || index >= 23) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 8 + (index * 1), value); } public const string QuoteReqIDCharacterEncoding = "UTF-8"; public int GetQuoteReqID(byte[] dst, int dstOffset) { const int length = 23; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 8, dst, dstOffset, length); return length; } public void SetQuoteReqID(byte[] src, int srcOffset) { const int length = 23; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 8, src, srcOffset, length); } private readonly NoRelatedSymGroup _noRelatedSym = new NoRelatedSymGroup(); public const long NoRelatedSymSchemaId = 146; public NoRelatedSymGroup NoRelatedSym { get { _noRelatedSym.WrapForDecode(_parentMessage, _buffer, _actingVersion); return _noRelatedSym; } } public NoRelatedSymGroup NoRelatedSymCount(int count) { _noRelatedSym.WrapForEncode(_parentMessage, _buffer, count); return _noRelatedSym; } public class NoRelatedSymGroup { private readonly GroupSize _dimensions = new GroupSize(); private QuoteRequest _parentMessage; private DirectBuffer _buffer; private int _blockLength; private int _actingVersion; private int _count; private int _index; private int _offset; public void WrapForDecode(QuoteRequest parentMessage, DirectBuffer buffer, int actingVersion) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, actingVersion); _count = _dimensions.NumInGroup; _blockLength = _dimensions.BlockLength; _actingVersion = actingVersion; _index = -1; _parentMessage.Limit = parentMessage.Limit + 3; } public void WrapForEncode(QuoteRequest parentMessage, DirectBuffer buffer, int count) { _parentMessage = parentMessage; _buffer = buffer; _dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion); _dimensions.NumInGroup = (byte)count; _dimensions.BlockLength = (ushort)30; _index = -1; _count = count; _blockLength = 30; parentMessage.Limit = parentMessage.Limit + 3; } public int Count { get { return _count; } } public bool HasNext { get { return _index + 1 < _count; } } public NoRelatedSymGroup Next() { if (_index + 1 >= _count) { throw new InvalidOperationException(); } _offset = _parentMessage.Limit; _parentMessage.Limit = _offset + _blockLength; ++_index; return this; } public const int SymbolSchemaId = 55; public static string SymbolMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "String"; } return ""; } public const byte SymbolNullValue = (byte)0; public const byte SymbolMinValue = (byte)32; public const byte SymbolMaxValue = (byte)126; public const int SymbolLength = 20; public byte GetSymbol(int index) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } return _buffer.CharGet(_offset + 0 + (index * 1)); } public void SetSymbol(int index, byte value) { if (index < 0 || index >= 20) { throw new IndexOutOfRangeException("index out of range: index=" + index); } _buffer.CharPut(_offset + 0 + (index * 1), value); } public const string SymbolCharacterEncoding = "UTF-8"; public int GetSymbol(byte[] dst, int dstOffset) { const int length = 20; if (dstOffset < 0 || dstOffset > (dst.Length - length)) { throw new IndexOutOfRangeException("dstOffset out of range for copy: offset=" + dstOffset); } _buffer.GetBytes(_offset + 0, dst, dstOffset, length); return length; } public void SetSymbol(byte[] src, int srcOffset) { const int length = 20; if (srcOffset < 0 || srcOffset > (src.Length - length)) { throw new IndexOutOfRangeException("srcOffset out of range for copy: offset=" + srcOffset); } _buffer.SetBytes(_offset + 0, src, srcOffset, length); } public const int SecurityIDSchemaId = 48; public static string SecurityIDMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const int SecurityIDNullValue = -2147483648; public const int SecurityIDMinValue = -2147483647; public const int SecurityIDMaxValue = 2147483647; public int SecurityID { get { return _buffer.Int32GetLittleEndian(_offset + 20); } set { _buffer.Int32PutLittleEndian(_offset + 20, value); } } public const int QuoteTypeSchemaId = 537; public static string QuoteTypeMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const sbyte QuoteTypeNullValue = (sbyte)-128; public const sbyte QuoteTypeMinValue = (sbyte)-127; public const sbyte QuoteTypeMaxValue = (sbyte)127; public sbyte QuoteType { get { return _buffer.Int8Get(_offset + 24); } set { _buffer.Int8Put(_offset + 24, value); } } public const int OrderQtySchemaId = 38; public static string OrderQtyMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "Qty"; } return ""; } public const uint OrderQtyNullValue = 4294967294U; public const uint OrderQtyMinValue = 0U; public const uint OrderQtyMaxValue = 4294967293U; public uint OrderQty { get { return _buffer.Uint32GetLittleEndian(_offset + 25); } set { _buffer.Uint32PutLittleEndian(_offset + 25, value); } } public const int SideSchemaId = 54; public static string SideMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.Epoch: return "unix"; case MetaAttribute.TimeUnit: return "nanosecond"; case MetaAttribute.SemanticType: return "int"; } return ""; } public const sbyte SideNullValue = (sbyte)127; public const sbyte SideMinValue = (sbyte)-127; public const sbyte SideMaxValue = (sbyte)127; public sbyte Side { get { return _buffer.Int8Get(_offset + 29); } set { _buffer.Int8Put(_offset + 29, value); } } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Windows.Forms.VisualStyles; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005DockPaneCaption : DockPaneCaptionBase { private sealed class InertButton : InertButtonBase { private Bitmap m_image, m_imageAutoHide; public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide) : base() { m_dockPaneCaption = dockPaneCaption; m_image = image; m_imageAutoHide = imageAutoHide; RefreshChanges(); } private VS2005DockPaneCaption m_dockPaneCaption; private VS2005DockPaneCaption DockPaneCaption { get { return m_dockPaneCaption; } } public bool IsAutoHide { get { return DockPaneCaption.DockPane.IsAutoHide; } } public override Bitmap Image { get { return IsAutoHide ? m_imageAutoHide : m_image; } } protected override void OnRefreshChanges() { if (DockPaneCaption.DockPane.DockPanel != null) { if (DockPaneCaption.TextColor != ForeColor) { ForeColor = DockPaneCaption.TextColor; Invalidate(); } } } } #region consts private const int _TextGapTop = 2; private const int _TextGapBottom = 0; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 1; private const int _ButtonGapBetween = 1; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; #endregion private static Bitmap _imageButtonClose; private static Bitmap ImageButtonClose { get { if (_imageButtonClose == null) _imageButtonClose = Resources.DockPane_Close; return _imageButtonClose; } } private InertButton m_buttonClose; private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap _imageButtonAutoHide; private static Bitmap ImageButtonAutoHide { get { if (_imageButtonAutoHide == null) _imageButtonAutoHide = Resources.DockPane_AutoHide; return _imageButtonAutoHide; } } private static Bitmap _imageButtonDock; private static Bitmap ImageButtonDock { get { if (_imageButtonDock == null) _imageButtonDock = Resources.DockPane_Dock; return _imageButtonDock; } } private InertButton m_buttonAutoHide; private InertButton ButtonAutoHide { get { if (m_buttonAutoHide == null) { m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide); m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide); m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); Controls.Add(m_buttonAutoHide); } return m_buttonAutoHide; } } private static Bitmap _imageButtonOptions; private static Bitmap ImageButtonOptions { get { if (_imageButtonOptions == null) _imageButtonOptions = Resources.DockPane_Option; return _imageButtonOptions; } } private InertButton m_buttonOptions; private InertButton ButtonOptions { get { if (m_buttonOptions == null) { m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions); m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions); m_buttonOptions.Click += new EventHandler(Options_Click); Controls.Add(m_buttonOptions); } return m_buttonOptions; } } private IContainer m_components; private IContainer Components { get { return m_components; } } private ToolTip m_toolTip; public VS2005DockPaneCaption(DockPane pane) : base(pane) { SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) Components.Dispose(); base.Dispose(disposing); } private static int TextGapTop { get { return _TextGapTop; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private static int TextGapBottom { get { return _TextGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int ButtonGapTop { get { return _ButtonGapTop; } } private static int ButtonGapBottom { get { return _ButtonGapBottom; } } private static int ButtonGapLeft { get { return _ButtonGapLeft; } } private static int ButtonGapRight { get { return _ButtonGapRight; } } private static int ButtonGapBetween { get { return _ButtonGapBetween; } } private static string _toolTipClose; private static string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneCaption_ToolTipClose; return _toolTipClose; } } private static string _toolTipOptions; private static string ToolTipOptions { get { if (_toolTipOptions == null) _toolTipOptions = Strings.DockPaneCaption_ToolTipOptions; return _toolTipOptions; } } private static string _toolTipAutoHide; private static string ToolTipAutoHide { get { if (_toolTipAutoHide == null) _toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide; return _toolTipAutoHide; } } private static Blend _activeBackColorGradientBlend; private static Blend ActiveBackColorGradientBlend { get { if (_activeBackColorGradientBlend == null) { Blend blend = new Blend(2); blend.Factors = new float[]{0.5F, 1.0F}; blend.Positions = new float[]{0.0F, 1.0F}; _activeBackColorGradientBlend = blend; } return _activeBackColorGradientBlend; } } private Color TextColor { get { if (DockPane.IsActivated) return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; } } private static TextFormatFlags _textFormat = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; private TextFormatFlags TextFormat { get { if (RightToLeft == RightToLeft.No) return _textFormat; else return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; } } protected internal override int MeasureHeight() { int height = TextFont.Height + TextGapTop + TextGapBottom; if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom) height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom; return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); DrawCaption(e.Graphics); } private void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) return; if (DockPane.IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, ClientRectangle); } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } } Rectangle rectCaption = ClientRectangle; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; if (HasTabPageContextMenu) rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; if ( DockPane.ActiveContent != null ) { var icon = DockPane.ActiveContent.DockHandler.Icon; if ( icon != null && DockPane.DockPanel.ShowDocumentIcon ) { int offset = ( rectCaption.Height - 16 ) / 2; g.DrawIcon( icon, new Rectangle( offset, offset, 16, 16 ) ); rectCaptionText.X += 16 + offset; rectCaptionText.Width -= 16 + offset; } } Color colorText; if (DockPane.IsActivated) colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat); } protected override void OnLayout(LayoutEventArgs levent) { SetButtonsPosition(); base.OnLayout (levent); } protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private bool CloseButtonEnabled { get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; } } /// <summary> /// Determines whether the close button is visible on the content /// </summary> private bool CloseButtonVisible { get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; } } private bool ShouldShowAutoHideButton { get { return !DockPane.IsFloat; } } private void SetButtons() { ButtonClose.Enabled = CloseButtonEnabled; ButtonClose.Visible = CloseButtonVisible; ButtonAutoHide.Visible = ShouldShowAutoHideButton; ButtonOptions.Visible = HasTabPageContextMenu; ButtonClose.RefreshChanges(); ButtonAutoHide.RefreshChanges(); ButtonOptions.RefreshChanges(); SetButtonsPosition(); } private void SetButtonsPosition() { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the auto hide button overtop. // Otherwise it is drawn to the left of the close button. if (CloseButtonVisible) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); if (ShouldShowAutoHideButton) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { if ( !DockPane.DockPanel.AllowChangeLayout ) return; DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (DockHelper.IsDockStateAutoHide(DockPane.DockState)) { DockPane.DockPanel.ActiveAutoHideContent = null; DockPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(DockPane); } } private void Options_Click(object sender, EventArgs e) { ShowTabPageContextMenu(PointToClient(Control.MousePosition)); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class GridServicesConnector : IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public GridServicesConnector() { } public GridServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public GridServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["GridService"]; if (gridConfig == null) { m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini"); throw new Exception("Grid connector init error"); } string serviceURI = gridConfig.GetString("GridServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService"); throw new Exception("Grid connector init error"); } m_ServerURI = serviceURI; } #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs(); Dictionary<string, object> sendData = new Dictionary<string,object>(); foreach (KeyValuePair<string, object> kvp in rinfo) sendData[kvp.Key] = (string)kvp.Value; sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "register"; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/grid"; // m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "success")) { return String.Empty; } else if (replyData.ContainsKey("Result")&& (replyData["Result"].ToString().ToLower() == "failure")) { m_log.ErrorFormat( "[GRID CONNECTOR]: Registration failed: {0} when contacting {1}", replyData["Message"], uri); return replyData["Message"].ToString(); } else if (!replyData.ContainsKey("Result")) { m_log.ErrorFormat( "[GRID CONNECTOR]: reply data does not contain result field when contacting {0}", uri); } else { m_log.ErrorFormat( "[GRID CONNECTOR]: unexpected result {0} when contacting {1}", replyData["Result"], uri); return "Unexpected result " + replyData["Result"].ToString(); } } else { m_log.ErrorFormat( "[GRID CONNECTOR]: RegisterRegion received null reply when contacting grid server at {0}", uri); } } catch (Exception e) { m_log.ErrorFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); } return string.Format("Error communicating with the grid service at {0}", uri); } public bool DeregisterRegion(UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "deregister"; string uri = m_ServerURI + "/grid"; try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success")) return true; } else m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply"); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); } return false; } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "get_neighbours"; List<GridRegion> rinfos = new List<GridRegion>(); string reqString = ServerUtils.BuildQueryString(sendData); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; //m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count); foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response", scopeID, regionID); return rinfos; } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "get_region_by_uuid"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return null; } GridRegion rinfo = null; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]); //else // m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response", // scopeID, regionID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response", scopeID, regionID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply"); return rinfo; } public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["X"] = x.ToString(); sendData["Y"] = y.ToString(); sendData["METHOD"] = "get_region_by_position"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return null; } GridRegion rinfo = null; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]); //else // m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received no region", // scopeID, x, y); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response", scopeID, x, y); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply"); return rinfo; } public GridRegion GetRegionByName(UUID scopeID, string regionName) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["NAME"] = regionName; sendData["METHOD"] = "get_region_by_name"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return null; } GridRegion rinfo = null; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response", scopeID, regionName); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply"); return rinfo; } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["NAME"] = name; sendData["MAX"] = maxNumber.ToString(); sendData["METHOD"] = "get_regions_by_name"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response", scopeID, name, maxNumber); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply"); return rinfos; } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["XMIN"] = xmin.ToString(); sendData["XMAX"] = xmax.ToString(); sendData["YMIN"] = ymin.ToString(); sendData["YMAX"] = ymax.ToString(); sendData["METHOD"] = "get_region_range"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response", scopeID, xmin, xmax, ymin, ymax); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply"); return rinfos; } public List<GridRegion> GetDefaultRegions(UUID scopeID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["METHOD"] = "get_default_regions"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions {0} received null response", scopeID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetDefaultRegions received null reply"); return rinfos; } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["X"] = x.ToString(); sendData["Y"] = y.ToString(); sendData["METHOD"] = "get_fallback_regions"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions {0}, {1}-{2} received null response", scopeID, x, y); } else m_log.DebugFormat("[GRID CONNECTOR]: GetFallbackRegions received null reply"); return rinfos; } public List<GridRegion> GetHyperlinks(UUID scopeID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["METHOD"] = "get_hyperlinks"; List<GridRegion> rinfos = new List<GridRegion>(); string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return rinfos; } if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { Dictionary<string, object>.ValueCollection rinfosList = replyData.Values; foreach (object r in rinfosList) { if (r is Dictionary<string, object>) { GridRegion rinfo = new GridRegion((Dictionary<string, object>)r); rinfos.Add(rinfo); } } } else m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks {0} received null response", scopeID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks received null reply"); return rinfos; } public int GetRegionFlags(UUID scopeID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["SCOPEID"] = scopeID.ToString(); sendData["REGIONID"] = regionID.ToString(); sendData["METHOD"] = "get_region_flags"; string reply = string.Empty; string uri = m_ServerURI + "/grid"; try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, ServerUtils.BuildQueryString(sendData)); } catch (Exception e) { m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message); return -1; } int flags = -1; if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { Int32.TryParse((string)replyData["result"], out flags); //else // m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received wrong type {2}", // scopeID, regionID, replyData["result"].GetType()); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags {0}, {1} received null response", scopeID, regionID); } else m_log.DebugFormat("[GRID CONNECTOR]: GetRegionFlags received null reply"); return flags; } #endregion } }
using System; using System.Linq; using System.Security.Claims; using UnicornStore.Models; using UnicornStore.Models.Identity; using UnicornStore.Models.UnicornStore; using UnicornStore.ViewModels.Cart; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity; namespace UnicornStore.Controllers { [Authorize] public class CartController : Controller { private UserManager<ApplicationUser> userManager; private UnicornStoreContext db; private ApplicationDbContext identityDb; private CategoryCache categoryCache; public CartController(UserManager<ApplicationUser> manager, UnicornStoreContext context, ApplicationDbContext identityContext, CategoryCache cache) { userManager = manager; db = context; identityDb = identityContext; categoryCache = cache; } public IActionResult Index(IndexMessage message = IndexMessage.None) { var userId = userManager.GetUserId(User); var items = db.CartItems .Where(i => i.UserId == userId) .Include(i => i.Product) .ToList(); return View(new IndexViewModel { CartItems = items, TopLevelCategories = categoryCache.TopLevel(), Message = message }); } public IActionResult Add(int productId, int quantity = 1) { var userId = userManager.GetUserId(User); var product = db.Products .SingleOrDefault(p => p.ProductId == productId); if (product == null) { return new StatusCodeResult(404); } var item = db.CartItems .SingleOrDefault(i => i.ProductId == product.ProductId && i.UserId == userId); if (item != null) { item.Quantity += quantity; item.PricePerUnit = product.CurrentPrice; item.PriceCalculated = DateTime.Now.ToUniversalTime(); } else { item = new CartItem { ProductId = product.ProductId, PricePerUnit = product.CurrentPrice, Quantity = quantity, UserId = userId, PriceCalculated = DateTime.Now.ToUniversalTime() }; db.CartItems.Add(item); } db.SaveChanges(); return RedirectToAction("Index", new { message = IndexMessage.ItemAdded }); } public IActionResult Remove(int productId) { var userId = userManager.GetUserId(User); var item = db.CartItems .SingleOrDefault(i => i.ProductId == productId && i.UserId == userId); if (item == null) { return new StatusCodeResult(404); } db.CartItems.Remove(item); db.SaveChanges(); return RedirectToAction("Index", new { message = IndexMessage.ItemRemoved }); } public IActionResult Checkout() { var userId = userManager.GetUserId(User); var items = db.CartItems .Where(i => i.UserId == userId) .Include(i => i.Product) .ToList(); var order = new Order { CheckoutBegan = DateTime.Now.ToUniversalTime(), UserId = userId, Total = items.Sum(i => i.PricePerUnit * i.Quantity), State = OrderState.CheckingOut, Lines = items.Select(i => new OrderLine { ProductId = i.ProductId, Product = i.Product, Quantity = i.Quantity, PricePerUnit = i.PricePerUnit, }).ToList() }; db.Orders.Add(order); db.SaveChanges(); // TODO workaround for https://github.com/aspnet/EntityFramework/issues/1449 var orderFixed = db.Orders .AsNoTracking() .Include(o => o.Lines).ThenInclude(ol => ol.Product) .Single(o => o.OrderId == order.OrderId); orderFixed.ShippingDetails = new OrderShippingDetails(); var addresses = identityDb.UserAddresses .Where(a => a.UserId == User.Identity.Name) .ToList(); return View(new CheckoutViewModel { Order = orderFixed, UserAddresses = addresses }); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Checkout(CheckoutViewModel formOrder) { var userId = userManager.GetUserId(User); var order = db.Orders .Include(o => o.Lines) .SingleOrDefault(o => o.OrderId == formOrder.Order.OrderId); if (order == null) { return new StatusCodeResult(404); } if (order.UserId != userId) { return new StatusCodeResult(403); } if (order.State != OrderState.CheckingOut) { return new StatusCodeResult(400); } // Place order order.ShippingDetails = formOrder.Order.ShippingDetails.CloneTo<OrderShippingDetails>(); order.State = OrderState.Placed; order.OrderPlaced = DateTime.Now.ToUniversalTime(); db.SaveChanges(); if(formOrder.RememberAddress) { var address = formOrder.Order.ShippingDetails.CloneTo<UserAddress>(); address.UserId = userId; identityDb.UserAddresses.Add(address); identityDb.SaveChanges(); } // Remove items from cart var cartItems = db.CartItems .Where(i => i.UserId == userId) .ToList(); foreach (var item in cartItems) { if (order.Lines.Any(l => l.ProductId == item.ProductId)) { db.CartItems.Remove(item); } } db.SaveChanges(); return RedirectToAction("Details", "Orders", new { orderId = order.OrderId, showConfirmation = 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 Xunit; using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace Test { public class TaskContinueWith_ContFuncAndActionWithArgsTests { #region Member Variables private static TaskContinuationOptions s_onlyOnRanToCompletion = TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted; private static TaskContinuationOptions s_onlyOnCanceled = TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.NotOnFaulted; private static TaskContinuationOptions s_onlyOnFaulted = TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.NotOnCanceled; #endregion #region Test Methods [Fact] public static void RunContinueWithTaskTask_State() { RunContinueWithTaskTask_State(TaskContinuationOptions.None); RunContinueWithTaskTask_State(s_onlyOnRanToCompletion); RunContinueWithTaskTask_State(TaskContinuationOptions.ExecuteSynchronously); RunContinueWithTaskTask_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithTaskFuture_State() { RunContinueWithTaskFuture_State(TaskContinuationOptions.None); RunContinueWithTaskFuture_State(s_onlyOnRanToCompletion); RunContinueWithTaskFuture_State(TaskContinuationOptions.ExecuteSynchronously); RunContinueWithTaskFuture_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithFutureTask_State() { RunContinueWithFutureTask_State(TaskContinuationOptions.None); RunContinueWithFutureTask_State(s_onlyOnRanToCompletion); RunContinueWithFutureTask_State(TaskContinuationOptions.ExecuteSynchronously); RunContinueWithFutureTask_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithFutureFuture_State() { RunContinueWithFutureFuture_State(TaskContinuationOptions.None); RunContinueWithFutureFuture_State(s_onlyOnRanToCompletion); RunContinueWithFutureFuture_State(TaskContinuationOptions.ExecuteSynchronously); RunContinueWithFutureFuture_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithTaskTask_State_FaultedCanceled() { RunContinueWithTaskTask_State(s_onlyOnCanceled); RunContinueWithTaskTask_State(s_onlyOnFaulted); RunContinueWithTaskTask_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously); RunContinueWithTaskTask_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithTaskFuture_State_FaultedCanceled() { RunContinueWithTaskFuture_State(s_onlyOnCanceled); RunContinueWithTaskFuture_State(s_onlyOnFaulted); RunContinueWithTaskFuture_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously); RunContinueWithTaskFuture_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithFutureTask_State_FaultedCanceled() { RunContinueWithFutureTask_State(s_onlyOnCanceled); RunContinueWithFutureTask_State(s_onlyOnFaulted); RunContinueWithFutureTask_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously); RunContinueWithFutureTask_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithFutureFuture_State_FaultedCanceled() { RunContinueWithFutureFuture_State(s_onlyOnCanceled); RunContinueWithFutureFuture_State(s_onlyOnFaulted); RunContinueWithFutureFuture_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously); RunContinueWithFutureFuture_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously); } [Fact] public static void RunContinueWithTaskTask_State_OnException() { RunContinueWithTaskTask_State(TaskContinuationOptions.None, true); RunContinueWithTaskTask_State(s_onlyOnRanToCompletion, true); RunContinueWithTaskTask_State(TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithTaskTask_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithTaskFuture_State_OnException() { RunContinueWithTaskFuture_State(TaskContinuationOptions.None, true); RunContinueWithTaskFuture_State(s_onlyOnRanToCompletion, true); RunContinueWithTaskFuture_State(TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithTaskFuture_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithFutureTask_State_OnException() { RunContinueWithFutureTask_State(TaskContinuationOptions.None, true); RunContinueWithFutureTask_State(s_onlyOnRanToCompletion, true); RunContinueWithFutureTask_State(TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithFutureTask_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithFutureFuture_State_OnException() { RunContinueWithFutureFuture_State(TaskContinuationOptions.None, true); RunContinueWithFutureFuture_State(s_onlyOnRanToCompletion, true); RunContinueWithFutureFuture_State(TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithFutureFuture_State(s_onlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithTaskTask_State_FaultedCanceled_OnException() { RunContinueWithTaskTask_State(s_onlyOnCanceled, true); RunContinueWithTaskTask_State(s_onlyOnFaulted, true); RunContinueWithTaskTask_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithTaskTask_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithTaskFuture_State_FaultedCanceled_OnException() { RunContinueWithTaskFuture_State(s_onlyOnCanceled, true); RunContinueWithTaskFuture_State(s_onlyOnFaulted, true); RunContinueWithTaskFuture_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithTaskFuture_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithFutureTask_State_FaultedCanceled_OnException() { RunContinueWithFutureTask_State(s_onlyOnCanceled, true); RunContinueWithFutureTask_State(s_onlyOnFaulted, true); RunContinueWithFutureTask_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithFutureTask_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithFutureFuture_State_FaultedCanceled_OnException() { RunContinueWithFutureFuture_State(s_onlyOnCanceled, true); RunContinueWithFutureFuture_State(s_onlyOnFaulted, true); RunContinueWithFutureFuture_State(s_onlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously, true); RunContinueWithFutureFuture_State(s_onlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, true); } [Fact] public static void RunContinueWithPreCancelTests_State() { Action<Task, bool, string> EnsureCompletionStatus = delegate (Task task, bool shouldBeCompleted, string message) { if (task.IsCompleted != shouldBeCompleted) { Assert.True(false, string.Format(string.Format("RunContinueWithPreCancelTests_State: > FAILED. {0}.", message))); } }; CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); ManualResetEvent mres = new ManualResetEvent(false); // Pre-increment the dontCounts for pre-canceled continuations to make final check easier // (i.e., all counts should be 1 at end). int[] doneCount = { 0, 0, 1, 0, 1, 0 }; string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true Task t1 = new Task(delegate { doneCount[0]++; }); Task c1 = t1.ContinueWith((_, obj) => { doneCount[1]++; }, stateParam); Task c2 = c1.ContinueWith((_, obj) => { mres.WaitOne(); doneCount[2]++; }, stateParam, cts.Token); Task c3 = c2.ContinueWith((_, obj) => { mres.WaitOne(); doneCount[3]++; }, stateParam); Task c4 = c3.ContinueWith((_, obj) => { mres.WaitOne(); doneCount[4]++; }, stateParam, cts.Token, TaskContinuationOptions.LazyCancellation, TaskScheduler.Default); Task c5 = c4.ContinueWith((_, obj) => { mres.WaitOne(); doneCount[5]++; }, stateParam); EnsureCompletionStatus(c2, true, " c2 should have completed (canceled) upon construction"); EnsureCompletionStatus(c4, false, " c4 should NOT have completed (canceled) upon construction"); EnsureCompletionStatus(t1, false, " t1 should NOT have completed before being started"); EnsureCompletionStatus(c1, false, " c1 should NOT have completed before antecedent completed"); EnsureCompletionStatus(c3, false, " c3 should NOT have completed before mres was set"); EnsureCompletionStatus(c5, false, " c5 should NOT have completed before mres was set"); // These should be done already. And Faulted. Exception exception = null; try { c2.Wait(); Assert.True(false, string.Format("RunContinueWithPreCancelTests_State: Expected c2.Wait to throw AE/TCE")); } catch (Exception ex) { exception = ex; } EnsureExceptionIsAEofTCE(exception, "RunContinueWithPreCancelTests_State: Expected c2.Wait to throw AE/TCE"); mres.Set(); Debug.WriteLine("RunContinueWithPreCancelTests_State: Waiting for tasks to complete... if we hang here, something went wrong."); c3.Wait(); try { c4.Wait(); Assert.True(false, string.Format("RunContinueWithPreCancelTests_State: Expected c4.Wait to throw AE/TCE")); } catch (Exception ex) { exception = ex; } EnsureExceptionIsAEofTCE(exception, "RunContinueWithPreCancelTests_State: Expected c4.Wait to throw AE/TCE"); c5.Wait(); EnsureCompletionStatus(t1, false, " t1 should NOT have completed (post-mres.Set()) before being started"); EnsureCompletionStatus(c1, false, " c1 should NOT have completed (post-mres.Set()) before antecedent completed"); t1.Start(); c1.Wait(); for (int i = 0; i < 6; i++) { if (doneCount[i] != 1) { Assert.True(false, string.Format("RunContinueWithPreCancelTests_State: > FAILED. doneCount[{0}] should be 1, is {1}", i, doneCount[i])); } } } [Fact] public static void RunContinuationChainingTest_State() { int x = 0; int y = 0; string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true Task t1 = new Task(delegate { x = 1; }); Task t2 = t1.ContinueWith(delegate (Task t, Object obj) { y = 1; }, stateParam); Task<int> t3 = t2.ContinueWith(delegate (Task t, Object obj) { return 5; }, stateParam); Task<int> t4 = t3.ContinueWith(delegate (Task<int> t, Object obj) { return Task<int>.Factory.StartNew(delegate { return 10; }); }, stateParam).Unwrap(); Task<string> t5 = t4.ContinueWith(delegate (Task<int> t, Object obj) { return Task<string>.Factory.StartNew(delegate { for (int i = 0; i < 400; i++) ; return "worked"; }); }, stateParam).Unwrap(); try { t1.Start(); if (!t5.Result.Equals("worked")) { Assert.True(false, string.Format("RunContinuationChainingTest_State: > FAILED! t5.Result should be \"worked\", is {0}", t5.Result)); } if (t4.Result != 10) { Assert.True(false, string.Format("RunContinuationChainingTest_State: > FAILED! t4.Result should be 10, is {0}", t4.Result)); } if (t3.Result != 5) { Assert.True(false, string.Format("RunContinuationChainingTest_State: > FAILED! t3.Result should be 5, is {0}", t3.Result)); } if (y != 1) { Assert.True(false, string.Format("RunContinuationChainingTest_State: > FAILED! y should be 1, is {0}", y)); } if (x != 1) { Assert.True(false, string.Format("RunContinuationChainingTest_State: > FAILED! x should be 1, is {0}", x)); } } catch (Exception e) { Assert.True(false, string.Format("RunContinuationChainingTest_State: > FAILED! Exception = {0}", e)); } } [Fact] public static void RunContinueWithOnDisposedTaskTest_State() { Task t1 = Task.Factory.StartNew(delegate { }); t1.Wait(); //t1.Dispose(); try { string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true Task t2 = t1.ContinueWith((completedTask, obj) => { }, stateParam); } catch { Assert.True(false, string.Format("RunContinueWithOnDisposedTaskTest_State: > FAILED! should NOT have seen an exception.")); } } [Fact] public static void RunContinueWithParamsTest_State_Cancellation() { string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true // // Test whether parentage/cancellation is working correctly // Task c1b = null, c1c = null; Task c2b = null, c2c = null; Task container = new Task(delegate { CancellationTokenSource cts = new CancellationTokenSource(); Task child1 = new Task(delegate { }, cts.Token, TaskCreationOptions.AttachedToParent); Task child2 = new Task(delegate { }, TaskCreationOptions.AttachedToParent); c1b = child1.ContinueWith((_, obj) => { }, stateParam, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.AttachedToParent); c1c = child1.ContinueWith((_, obj) => { }, stateParam, TaskContinuationOptions.AttachedToParent); c2b = child2.ContinueWith((_, obj) => { }, stateParam, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.AttachedToParent); c2c = child2.ContinueWith((_, obj) => { }, stateParam, TaskContinuationOptions.AttachedToParent); cts.Cancel(); // should cancel the unstarted child task child2.Start(); }); container.Start(); try { container.Wait(); } catch { } if (c1b.Status != TaskStatus.Canceled) { Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Continuation task w/NotOnCanceled should have been canceled when antecedent was canceled.")); } if (c1c.Status != TaskStatus.RanToCompletion) { Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Continuation task w/ canceled antecedent should have run to completion.")); } if (c2b.Status != TaskStatus.Canceled) { Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Continuation task w/NotOnRanToCompletion should have been canceled when antecedent completed.")); } c2c.Wait(); if (c2c.Status != TaskStatus.RanToCompletion) { Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Continuation task w/ completed antecedent should have run to completion.")); } } [Fact] public static void RunContinueWithParamsTest_State_IllegalParameters() { Task t1 = new Task(delegate { }); string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true try { Task t2 = t1.ContinueWith((ooo, obj) => { }, stateParam, (TaskContinuationOptions)0x1000000); Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Should have seen exception from illegal continuation options.")); } catch { } try { Task t2 = t1.ContinueWith((ooo, obj) => { }, stateParam, TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously); Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Should have seen exception when combining LongRunning and ExecuteSynchronously")); } catch { } try { Task t2 = t1.ContinueWith((ooo, obj) => { }, stateParam, TaskContinuationOptions.NotOnRanToCompletion | TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.NotOnCanceled); Assert.True(false, string.Format("RunContinueWithParamsTest_State > FAILED. Should have seen exception from illegal NotOnAny continuation options.")); } catch (Exception) { } t1.Start(); t1.Wait(); } #endregion #region Helper Methods // Chains a Task continuation to a Task. public static void RunContinueWithTaskTask_State(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true if (runNegativeCases) { RunContinueWithBase_ExceptionCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith(delegate (Task f, object obj) { Debug.WriteLine("Inside"); ran = true; }, stateParam, options); }, delegate { return ran; }, false ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith(delegate (Task f, object obj) { Debug.WriteLine("Inside"); ran = true; }, stateParam, options); }, delegate { return ran; }, false ); } } // Chains a Task<T> continuation to a Task, with a Func<Task, T>. public static void RunContinueWithTaskFuture_State(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; Debug.WriteLine("* RunContinueWithTaskFuture_StateA(Object, options={0})", options); string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true if (runNegativeCases) { RunContinueWithBase_ExceptionCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f, object obj) { ran = true; return 5; }, stateParam, options); }, delegate { return ran; }, false ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f, object obj) { ran = true; return 5; }, stateParam, options); }, delegate { return ran; }, false ); } } // Chains a Task continuation to a Task<T>. public static void RunContinueWithFutureTask_State(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; Debug.WriteLine("* RunContinueWithFutureTask_State(Object, options={0})", options); string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true if (runNegativeCases) { RunContinueWithBase_ExceptionCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith(delegate (Task f, object obj) { ran = true; }, stateParam, options); }, delegate { return ran; }, true ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith(delegate (Task f, object obj) { ran = true; }, stateParam, options); }, delegate { return ran; }, true ); } } // Chains a Task<U> continuation to a Task<T>, with a Func<Task<T>, U>. public static void RunContinueWithFutureFuture_State(TaskContinuationOptions options, bool runNegativeCases = false) { bool ran = false; Debug.WriteLine("* RunContinueWithFutureFuture_StateA(Object, options={0})", options); string stateParam = "test"; //used as a state parametr for the continuation if the useStateParam is true if (runNegativeCases) { RunContinueWithBase_ExceptionCases(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f, Object obj) { ran = true; return 5; }, stateParam, options); }, delegate { return ran; }, true ); } else { RunContinueWithBase(options, delegate { ran = false; }, delegate (Task t) { return t.ContinueWith<int>(delegate (Task f, Object obj) { ran = true; return 5; }, stateParam, options); }, delegate { return ran; }, true ); } } // Base logic for RunContinueWithXXXYYY() methods public static void RunContinueWithBase( TaskContinuationOptions options, Action initRan, Func<Task, Task> continuationMaker, Func<bool> ranValue, bool taskIsFuture) { Debug.WriteLine(" >> (1) ContinueWith after task finishes Successfully."); { bool expect = (options & TaskContinuationOptions.NotOnRanToCompletion) == 0; Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(() => ""); else task = Task.Factory.StartNew(delegate { }); task.Wait(); initRan(); Debug.WriteLine("Init Action Ran"); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } Debug.WriteLine("Finished Wait"); if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (2) ContinueWith before task finishes Successfully."); { bool expect = (options & TaskContinuationOptions.NotOnRanToCompletion) == 0; ManualResetEvent mre = new ManualResetEvent(false); Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(() => { mre.WaitOne(); return ""; }); else task = Task.Factory.StartNew(delegate { mre.WaitOne(); }); initRan(); bool cancel = false; Task cont = continuationMaker(task); mre.Set(); task.Wait(); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } } // Base logic for RunContinueWithXXXYYY() methods public static void RunContinueWithBase_ExceptionCases( TaskContinuationOptions options, Action initRan, Func<Task, Task> continuationMaker, Func<bool> ranValue, bool taskIsFuture) { Debug.WriteLine(" >> (3) ContinueWith after task finishes Exceptionally."); { bool expect = (options & TaskContinuationOptions.NotOnFaulted) == 0; Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(delegate { throw new Exception("Boom"); }); else task = Task.Factory.StartNew(delegate { throw new Exception("Boom"); }); try { task.Wait(); } catch (AggregateException) { /*swallow(ouch)*/ } Debug.WriteLine("S3 caught e1."); initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } Debug.WriteLine("S3 finished wait"); if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (4) ContinueWith before task finishes Exceptionally."); { bool expect = (options & TaskContinuationOptions.NotOnFaulted) == 0; ManualResetEvent mre = new ManualResetEvent(false); Task task; if (taskIsFuture) task = Task<string>.Factory.StartNew(delegate { mre.WaitOne(); throw new Exception("Boom"); }); else task = Task.Factory.StartNew(delegate { mre.WaitOne(); throw new Exception("Boom"); }); initRan(); bool cancel = false; Task cont = continuationMaker(task); mre.Set(); try { task.Wait(); } catch (AggregateException) { /*swallow(ouch)*/ } try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } Debug.WriteLine(" >> (5) ContinueWith after task becomes Aborted."); { bool expect = (options & TaskContinuationOptions.NotOnCanceled) == 0; // Create a task that will transition into Canceled state CancellationTokenSource cts = new CancellationTokenSource(); Task task; ManualResetEvent cancellationMRE = new ManualResetEvent(false); if (taskIsFuture) task = Task<string>.Factory.StartNew(() => { cancellationMRE.WaitOne(); throw new OperationCanceledException(cts.Token); }, cts.Token); else task = Task.Factory.StartNew(delegate { cancellationMRE.WaitOne(); throw new OperationCanceledException(cts.Token); }, cts.Token); cts.Cancel(); cancellationMRE.Set(); initRan(); bool cancel = false; Task cont = continuationMaker(task); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue, cancel)); } } Debug.WriteLine(" >> (6) ContinueWith before task becomes Aborted."); { bool expect = (options & TaskContinuationOptions.NotOnCanceled) == 0; // Create a task that will transition into Canceled state Task task; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; ManualResetEvent cancellationMRE = new ManualResetEvent(false); if (taskIsFuture) task = Task<string>.Factory.StartNew(() => { cancellationMRE.WaitOne(); throw new OperationCanceledException(ct); }, ct); else task = Task.Factory.StartNew(delegate { cancellationMRE.WaitOne(); throw new OperationCanceledException(ct); }, ct); initRan(); bool cancel = false; Task cont = continuationMaker(task); cts.Cancel(); cancellationMRE.Set(); try { cont.Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions[0] is TaskCanceledException) cancel = true; } if (expect != ranValue() || expect == cancel) { Assert.True(false, string.Format("RunContinueWithBase: >> Failed: continuation didn't run or get canceled when expected: ran = {0}, cancel = {1}", ranValue(), cancel)); } } } // Ensures that the specified exception is an AggregateException wrapping a TaskCanceledException public static void EnsureExceptionIsAEofTCE(Exception exception, string message) { if (exception == null) { Assert.True(false, string.Format(message + " (no exception thrown)")); ; } else if (exception.GetType() != typeof(AggregateException)) { Assert.True(false, string.Format(message + " (didn't throw aggregate exception)")); } else if (((AggregateException)exception).InnerException.GetType() != typeof(TaskCanceledException)) { exception = ((AggregateException)exception).InnerException; Assert.True(false, string.Format(message + " (threw " + exception.GetType().Name + " instead of TaskCanceledException)")); } } #endregion } }
using UnityEngine; [System.Serializable] public class ResourceAsset { public string GUID; public string path; protected Object cachedObject; protected ResourceRequest resourceRequest; public T Get<T>() where T : Object { if( cachedObject == null ){ Load<T>(); } return cachedObject as T; } public void Load<T>() where T : Object { if( string.IsNullOrEmpty( path ) ){ Debug.LogWarning("No asset linked to this ResourceAsset"); return; } cachedObject = Resources.Load<T>(path); } public ResourceRequest LoadAsync<T>() where T:Object { if( string.IsNullOrEmpty( path ) ){ Debug.LogWarning("No asset linked to this ResourceAsset"); return null; } return resourceRequest = Resources.LoadAsync<T>(path); } public void Unload() { if (cachedObject != null) { if( cachedObject is Sprite ){ Sprite cachedSprite = cachedObject as Sprite; if(cachedSprite!=null){ Resources.UnloadAsset(cachedSprite.texture); } } if( !( cachedObject is GameObject ) ){ Resources.UnloadAsset(cachedObject); if( resourceRequest != null ) Resources.UnloadAsset(resourceRequest.asset); } cachedObject = null; resourceRequest = null; } } public static System.Type AssetType() { return typeof(Object); } } [System.Serializable] public class ResourceAsset<T> : ResourceAsset where T : Object { public T Get() { return Get<T>(); } } [System.Serializable] public class ResourceGameObject : ResourceAsset { public GameObject Get() { return Get<GameObject>(); } public ResourceRequest LoadAsync() { return LoadAsync<GameObject>(); } new public static System.Type AssetType() { return typeof(GameObject); } } [System.Serializable] public class ResourceAudioClip : ResourceAsset { public AudioClip Get() { return Get<AudioClip>(); } public ResourceRequest LoadAsync() { return LoadAsync<AudioClip>(); } new public static System.Type AssetType() { return typeof(AudioClip); } } [System.Serializable] public class ResourceTextAsset : ResourceAsset { public TextAsset Get() { return Get<TextAsset>(); } public ResourceRequest LoadAsync() { return LoadAsync<TextAsset>(); } new public static System.Type AssetType() { return typeof(TextAsset); } } [System.Serializable] public class ResourceTexture : ResourceAsset { public Texture Get() { return Get<Texture>(); } public ResourceRequest LoadAsync() { return LoadAsync<Texture>(); } new public static System.Type AssetType() { return typeof(Texture); } } [System.Serializable] public class ResourceSprite : ResourceAsset { public Sprite Get() { return Get<Sprite>(); } public ResourceRequest LoadAsync() { return LoadAsync<Sprite>(); } new public static System.Type AssetType() { return typeof(Sprite); } } [System.Serializable] public class ResourceRuntimeAnimatorController : ResourceAsset { public RuntimeAnimatorController Get() { return Get<RuntimeAnimatorController>(); } public ResourceRequest LoadAsync() { return LoadAsync<RuntimeAnimatorController>(); } new public static System.Type AssetType() { return typeof(RuntimeAnimatorController); } } [System.Serializable] public class ResourceScriptableObject : ResourceAsset { public ScriptableObject Get() { return Get<ScriptableObject>(); } public ResourceRequest LoadAsync() { return LoadAsync<ScriptableObject>(); } new public static System.Type AssetType() { return typeof(ScriptableObject); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Common; namespace Sleet { public static class PushCommand { public const int DefaultBatchSize = 4096; public static async Task<bool> RunAsync(LocalSettings settings, ISleetFileSystem source, List<string> inputs, bool force, bool skipExisting, ILogger log) { var token = CancellationToken.None; var now = DateTimeOffset.UtcNow; var success = false; var perfTracker = source.LocalCache.PerfTracker; await log.LogAsync(LogLevel.Minimal, $"Reading feed {source.BaseURI.AbsoluteUri}"); using (var timer = PerfEntryWrapper.CreateSummaryTimer("Total execution time: {0}", perfTracker)) { // Partition package inputs to avoid reading 100K nuspecs at the same time. var packagePaths = GetPackagePaths(inputs); var inputBatches = packagePaths.Partition(DefaultBatchSize); ISleetFileSystemLock feedLock = null; try { for (var i = 0; i < inputBatches.Count; i++) { var inputBatch = inputBatches[i]; if (inputBatches.Count > 1) { await log.LogAsync(LogLevel.Minimal, $"Pushing {inputBatch.Count} packages. Batch: {i + 1} / {inputBatches.Count}"); } // Read packages before locking the feed the first time. var packages = new List<PackageInput>(await GetPackageInputs(inputBatch, now, perfTracker, log)); if (feedLock == null) { string lockMessage = null; if (packages.Count > 0) { lockMessage = $"Push of {packages[0].Identity.ToString()}"; } // Create and initialize the feed if it is new. // Lock the feed before running push. feedLock = await SourceUtility.InitAndLock(settings, source, lockMessage, autoCreateBucket: true, autoInit: true, log: log, token: token); // Validate source await SourceUtility.ValidateFeedForClient(source, log, token); } // Push success = await PushPackages(settings, source, packages, force, skipExisting, log, token); } } finally { // Unlock the feed feedLock?.Dispose(); } } // Write out perf summary await perfTracker.LogSummary(log); return success; } /// <summary> /// Push packages to a feed. /// This assumes the feed is already locked. /// </summary> public static async Task<bool> PushPackages(LocalSettings settings, ISleetFileSystem source, List<string> inputs, bool force, bool skipExisting, ILogger log, CancellationToken token) { var now = DateTimeOffset.UtcNow; var success = true; var packagePaths = GetPackagePaths(inputs); // Partition input files to avoid reading 100K nuspec files at once. foreach (var inputSegment in packagePaths.Partition(DefaultBatchSize)) { var packages = new List<PackageInput>(); // Get packages packages.AddRange(await GetPackageInputs(inputSegment, now, source.LocalCache.PerfTracker, log)); // Add packages success &= await PushPackages(settings, source, packages, force, skipExisting, log, token); } return success; } /// <summary> /// Push packages to a feed. /// This assumes the feed is already locked. /// </summary> public static async Task<bool> PushPackages(LocalSettings settings, ISleetFileSystem source, List<PackageInput> packages, bool force, bool skipExisting, ILogger log, CancellationToken token) { var exitCode = true; var now = DateTimeOffset.UtcNow; // Verify no duplicate packages CheckForDuplicates(packages); // Get sleet.settings.json await log.LogAsync(LogLevel.Minimal, "Reading feed"); var sourceSettings = await FeedSettingsUtility.GetSettingsOrDefault(source, log, token); // Settings context used for all operations var context = new SleetContext() { LocalSettings = settings, SourceSettings = sourceSettings, Log = log, Source = source, Token = token, PerfTracker = source.LocalCache.PerfTracker }; await log.LogAsync(LogLevel.Verbose, "Reading existing package index"); // Push var packageIndex = new PackageIndex(context); var existingPackageSets = await packageIndex.GetPackageSetsAsync(); await PushPackages(packages, context, existingPackageSets, force, skipExisting, log); // Prune packages await PrunePackages(packages, context); // Save all await log.LogAsync(LogLevel.Minimal, $"Committing changes to {source.BaseURI.AbsoluteUri}"); await source.Commit(log, token); if (exitCode) { await log.LogAsync(LogLevel.Minimal, "Successfully pushed packages."); } else { await log.LogAsync(LogLevel.Error, "Failed to push packages."); } return exitCode; } private static async Task PrunePackages(List<PackageInput> packages, SleetContext context) { // Run only if the package retention settings are present for the feed if (context.SourceSettings.RetentionMaxStableVersions > 0 && context.SourceSettings.RetentionMaxPrereleaseVersions > 0) { // Prune if prune is enabled for the feed var pruneContext = new RetentionPruneCommandContext(); // Do not prune packages that were just pushed pruneContext.PinnedPackages.UnionWith(packages.Select(e => e.Identity)); // Only prune package ids that were pushed pruneContext.PackageIds.UnionWith(packages.Select(e => e.Identity.Id)); // Run prune against the local files await RetentionPruneCommand.PrunePackagesNoCommit(context, pruneContext); } } private static async Task PushPackages(List<PackageInput> packageInputs, SleetContext context, PackageSets existingPackageSets, bool force, bool skipExisting, ILogger log) { var toAdd = new List<PackageInput>(); var toRemove = new List<PackageInput>(); foreach (var package in packageInputs) { var packageString = $"{package.Identity.Id} {package.Identity.Version.ToFullString()}"; if (package.IsSymbolsPackage) { packageString += " Symbols"; if (!context.SourceSettings.SymbolsEnabled) { await log.LogAsync(LogLevel.Warning, $"Skipping {packageString}, to push symbols packages enable the symbols server on this feed."); // Skip this package continue; } } var exists = false; if (package.IsSymbolsPackage) { exists = existingPackageSets.Symbols.Exists(package.Identity); } else { exists = existingPackageSets.Packages.Exists(package.Identity); } if (exists) { if (skipExisting) { await log.LogAsync(LogLevel.Minimal, $"Skip existing package: {packageString}"); continue; } else if (force) { toRemove.Add(package); await log.LogAsync(LogLevel.Information, $"Replace existing package: {packageString}"); } else { throw new InvalidOperationException($"Package already exists: {packageString}."); } } else { await log.LogAsync(LogLevel.Minimal, $"Add new package: {packageString}"); } // Add to list of packages to push toAdd.Add(package); } await log.LogAsync(LogLevel.Minimal, $"Processing feed changes"); // Add/Remove packages var changeContext = SleetOperations.Create(existingPackageSets, toAdd, toRemove); await SleetUtility.ApplyPackageChangesAsync(context, changeContext); } /// <summary> /// Parse input arguments for nupkg paths. /// </summary> private static async Task<List<PackageInput>> GetPackageInputs(List<string> packagePaths, DateTimeOffset now, IPerfTracker perfTracker, ILogger log) { using (var timer = PerfEntryWrapper.CreateSummaryTimer("Loaded package nuspecs in {0}", perfTracker)) { var tasks = packagePaths.Select(e => new Func<Task<PackageInput>>(() => GetPackageInput(e, log))); var packageInputs = await TaskUtils.RunAsync(tasks, useTaskRun: true, token: CancellationToken.None); var packagesSorted = packageInputs.OrderBy(e => e).ToList(); return packagesSorted; } } private static List<string> GetPackagePaths(List<string> inputs) { // Check inputs if (inputs.Count < 1) { throw new ArgumentException("No packages found."); } // Get package inputs return inputs.SelectMany(GetFiles) .Distinct(PathUtility.GetStringComparerBasedOnOS()) .ToList(); } private static void CheckForDuplicates(List<PackageInput> packages) { PackageInput lastPackage = null; foreach (var package in packages.OrderBy(e => e)) { if (package.Equals(lastPackage)) { throw new InvalidOperationException($"Duplicate packages detected for '{package.Identity}'."); } lastPackage = package; } } private static Task<PackageInput> GetPackageInput(string file, ILogger log) { // Validate package log.LogVerbose($"Reading {file}"); PackageInput packageInput = null; try { // Read basic info from the package and verify that it isn't broken. packageInput = PackageInput.Create(file); } catch { log.LogError($"Invalid package '{file}'."); throw; } // Display a message for non-normalized packages if (packageInput.Identity.Version.ToString() != packageInput.Identity.Version.ToNormalizedString()) { var message = $"Package '{packageInput.PackagePath}' does not contain a normalized version. Normalized: '{packageInput.Identity.Version.ToNormalizedString()}' Nuspec version: '{packageInput.Identity.Version.ToString()}'. See https://semver.org/ for details."; log.LogVerbose(message); } return Task.FromResult(packageInput); } private static IEnumerable<string> GetFiles(string input) { var inputFile = Path.GetFullPath(input); if (File.Exists(inputFile)) { yield return inputFile; } else if (Directory.Exists(inputFile)) { var directoryFiles = Directory.GetFiles(inputFile, "*.nupkg", SearchOption.AllDirectories); if (directoryFiles.Length < 1) { throw new FileNotFoundException($"Unable to find nupkgs in '{inputFile}'."); } foreach (var file in directoryFiles) { yield return file; } } else { throw new FileNotFoundException($"Unable to find '{inputFile}'."); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; namespace System.Data.SqlClient { public sealed partial class SqlConnection : DbConnection { private bool _AsyncCommandInProgress; // SQLStatistics support internal SqlStatistics _statistics; private bool _collectstats; private bool _fireInfoMessageEventOnUserErrors; // False by default // root task associated with current async invocation private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion; private string _connectionString; private int _connectRetryCount; // connection resiliency private object _reconnectLock = new object(); internal Task _currentReconnectionTask; private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections private Guid _originalConnectionId = Guid.Empty; private CancellationTokenSource _reconnectionCancellationSource; internal SessionData _recoverySessionData; internal bool _supressStateChangeForReconnection; private int _reconnectCount; // diagnostics listener private readonly static DiagnosticListener s_diagnosticListener = new DiagnosticListener(SqlClientDiagnosticListenerExtensions.DiagnosticListenerName); // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened // using SqlConnection.Open() method. internal bool _applyTransientFaultHandling = false; public SqlConnection(string connectionString) : this() { ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available CacheConnectionStringProperties(); } // This method will be called once connection string is set or changed. private void CacheConnectionStringProperties() { SqlConnectionString connString = ConnectionOptions as SqlConnectionString; if (connString != null) { _connectRetryCount = connString.ConnectRetryCount; } } // // PUBLIC PROPERTIES // // used to start/stop collection of statistics data and do verify the current state // // devnote: start/stop should not performed using a property since it requires execution of code // // start statistics // set the internal flag (_statisticsEnabled) to true. // Create a new SqlStatistics object if not already there. // connect the parser to the object. // if there is no parser at this time we need to connect it after creation. // public bool StatisticsEnabled { get { return (_collectstats); } set { { if (value) { // start if (ConnectionState.Open == State) { if (null == _statistics) { _statistics = new SqlStatistics(); ADP.TimerCurrent(out _statistics._openTimestamp); } // set statistics on the parser // update timestamp; Debug.Assert(Parser != null, "Where's the parser?"); Parser.Statistics = _statistics; } } else { // stop if (null != _statistics) { if (ConnectionState.Open == State) { // remove statistics from parser // update timestamp; TdsParser parser = Parser; Debug.Assert(parser != null, "Where's the parser?"); parser.Statistics = null; ADP.TimerCurrent(out _statistics._closeTimestamp); } } } _collectstats = value; } } } internal bool AsyncCommandInProgress { get { return (_AsyncCommandInProgress); } set { _AsyncCommandInProgress = value; } } internal SqlConnectionString.TypeSystem TypeSystem { get { return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion; } } internal int ConnectRetryInterval { get { return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval; } } override public string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(new SqlConnectionPoolKey(value)); _connectionString = value; // Change _connectionString value only after value is validated CacheConnectionStringProperties(); } } override public int ConnectionTimeout { get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); } } override public string Database { // if the connection is open, we need to ask the inner connection what it's // current catalog is because it may have gotten changed, otherwise we can // just return what the connection string had. get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); } return result; } } override public string DataSource { get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); } return result; } } public int PacketSize { // if the connection is open, we need to ask the inner connection what it's // current packet size is because it may have gotten changed, otherwise we // can just return what the connection string had. get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; if (null != innerConnection) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); } return result; } } public Guid ClientConnectionId { get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null != innerConnection) { return innerConnection.ClientConnectionId; } else { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return _originalConnectionId; } return Guid.Empty; } } } override public string ServerVersion { get { return GetOpenTdsConnection().ServerVersion; } } override public ConnectionState State { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return ConnectionState.Open; } return InnerConnection.State; } } internal SqlStatistics Statistics { get { return _statistics; } } public string WorkstationId { get { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; string result = ((null != constr) ? constr.WorkstationId : string.Empty); return result; } } // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication // // PUBLIC EVENTS // public event SqlInfoMessageEventHandler InfoMessage; public bool FireInfoMessageEventOnUserErrors { get { return _fireInfoMessageEventOnUserErrors; } set { _fireInfoMessageEventOnUserErrors = value; } } // Approx. number of times that the internal connection has been reconnected internal int ReconnectCount { get { return _reconnectCount; } } internal bool ForceNewConnection { get; set; } protected override void OnStateChange(StateChangeEventArgs stateChange) { if (!_supressStateChangeForReconnection) { base.OnStateChange(stateChange); } } // // PUBLIC METHODS // new public SqlTransaction BeginTransaction() { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(IsolationLevel.Unspecified, null); } new public SqlTransaction BeginTransaction(IsolationLevel iso) { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(iso, null); } public SqlTransaction BeginTransaction(string transactionName) { // Use transaction names only on the outermost pair of nested // BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names // are ignored for nested BEGIN's. The only way to rollback a nested // transaction is to have a save point from a SAVE TRANSACTION call. return BeginTransaction(IsolationLevel.Unspecified, transactionName); } [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName) { WaitForPendingReconnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); SqlTransaction transaction; bool isFirstAttempt = true; do { transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt"); isFirstAttempt = false; } while (transaction.InternalTransaction.ConnectionHasBeenRestored); // The GetOpenConnection line above doesn't keep a ref on the outer connection (this), // and it could be collected before the inner connection can hook it to the transaction, resulting in // a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen. GC.KeepAlive(this); return transaction; } finally { SqlStatistics.StopTimer(statistics); } } override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); try { statistics = SqlStatistics.StartTimer(Statistics); InnerConnection.ChangeDatabase(database); } finally { SqlStatistics.StopTimer(statistics); } } static public void ClearAllPools() { SqlConnectionFactory.SingletonInstance.ClearAllPools(); } static public void ClearPool(SqlConnection connection) { ADP.CheckArgumentNull(connection, nameof(connection)); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; if (null != connectionOptions) { SqlConnectionFactory.SingletonInstance.ClearPool(connection); } } private void CloseInnerConnection() { // CloseConnection() now handles the lock // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and // the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is // outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock. InnerConnection.CloseConnection(this, ConnectionFactory); } override public void Close() { ConnectionState previousState = State; Guid operationId; Guid clientConnectionId; // during the call to Dispose() there is a redundant call to // Close(). because of this, the second time Close() is invoked the // connection is already in a closed state. this doesn't seem to be a // problem except for logging, as we'll get duplicate Before/After/Error // log entries if (previousState != ConnectionState.Closed) { operationId = s_diagnosticListener.WriteConnectionCloseBefore(this); // we want to cache the ClientConnectionId for After/Error logging, as when the connection // is closed then we will lose this identifier // // note: caching this is only for diagnostics logging purposes clientConnectionId = ClientConnectionId; } SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { CancellationTokenSource cts = _reconnectionCancellationSource; if (cts != null) { cts.Cancel(); } AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection if (State != ConnectionState.Open) {// if we cancelled before the connection was opened OnStateChange(DbConnectionInternal.StateChangeClosed); } } CancelOpenAndWait(); CloseInnerConnection(); GC.SuppressFinalize(this); if (null != Statistics) { ADP.TimerCurrent(out _statistics._closeTimestamp); } } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); // we only want to log this if the previous state of the // connection is open, as that's the valid use-case if (previousState != ConnectionState.Closed) { if (e != null) { s_diagnosticListener.WriteConnectionCloseError(operationId, clientConnectionId, this, e); } else { s_diagnosticListener.WriteConnectionCloseAfter(operationId, clientConnectionId, this); } } } } new public SqlCommand CreateCommand() { return new SqlCommand(null, this); } private void DisposeMe(bool disposing) { if (!disposing) { // For non-pooled connections we need to make sure that if the SqlConnection was not closed, // then we release the GCHandle on the stateObject to allow it to be GCed // For pooled connections, we will rely on the pool reclaiming the connection var innerConnection = (InnerConnection as SqlInternalConnectionTds); if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling)) { var parser = innerConnection.Parser; if ((parser != null) && (parser._physicalStateObj != null)) { parser._physicalStateObj.DecrementPendingCallbacks(release: false); } } } } override public void Open() { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; Exception e = null; try { statistics = SqlStatistics.StartTimer(Statistics); if (!TryOpen(null)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } catch (Exception ex) { e = ex; throw; } finally { SqlStatistics.StopTimer(statistics); if (e != null) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, e); } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); } } } internal void RegisterWaitingForReconnect(Task waitingTask) { if (((SqlConnectionString)ConnectionOptions).MARS) { return; } Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null); if (_asyncWaitingForReconnection != waitingTask) { // somebody else managed to register throw SQL.MARSUnspportedOnConnection(); } } private async Task ReconnectAsync(int timeout) { try { long commandTimeoutExpiration = 0; if (timeout > 0) { commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout); } CancellationTokenSource cts = new CancellationTokenSource(); _reconnectionCancellationSource = cts; CancellationToken ctoken = cts.Token; int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string for (int attempt = 0; attempt < retryCount; attempt++) { if (ctoken.IsCancellationRequested) { return; } try { try { ForceNewConnection = true; await OpenAsync(ctoken).ConfigureAwait(false); // On success, increment the reconnect count - we don't really care if it rolls over since it is approx. _reconnectCount = unchecked(_reconnectCount + 1); #if DEBUG Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !"); #endif } finally { ForceNewConnection = false; } return; } catch (SqlException e) { if (attempt == retryCount - 1) { throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) { throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId); } } await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false); } } finally { _recoverySessionData = null; _supressStateChangeForReconnection = false; } Debug.Assert(false, "Should not reach this point"); } internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { Task runningReconnect = _currentReconnectionTask; // This loop in the end will return not completed reconnect task or null while (runningReconnect != null && runningReconnect.IsCompleted) { // clean current reconnect task (if it is the same one we checked Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect); // make sure nobody started new task (if which case we did not clean it) runningReconnect = _currentReconnectionTask; } if (runningReconnect == null) { if (_connectRetryCount > 0) { SqlInternalConnectionTds tdsConn = GetOpenTdsConnection(); if (tdsConn._sessionRecoveryAcknowledged) { TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj; if (!stateObj.ValidateSNIConnection()) { if (tdsConn.Parser._sessionPool != null) { if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0) { // >1 MARS session if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null); } } SessionData cData = tdsConn.CurrentSessionData; cData.AssertUnrecoverableStateCountIsCorrect(); if (cData._unrecoverableStatesCount == 0) { bool callDisconnect = false; lock (_reconnectLock) { runningReconnect = _currentReconnectionTask; // double check after obtaining the lock if (runningReconnect == null) { if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; _recoverySessionData = cData; if (beforeDisconnect != null) { beforeDisconnect(); } try { _supressStateChangeForReconnection = true; tdsConn.DoomThisConnection(); } catch (SqlException) { } runningReconnect = Task.Run(() => ReconnectAsync(timeout)); // if current reconnect is not null, somebody already started reconnection task - some kind of race condition Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected"); _currentReconnectionTask = runningReconnect; } } else { callDisconnect = true; } } if (callDisconnect && beforeDisconnect != null) { beforeDisconnect(); } } else { if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null); } } // ValidateSNIConnection } // sessionRecoverySupported } // connectRetryCount>0 } else { // runningReconnect = null if (beforeDisconnect != null) { beforeDisconnect(); } } return runningReconnect; } // this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request partial void RepairInnerConnection() { WaitForPendingReconnection(); if (_connectRetryCount == 0) { return; } SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds; if (tdsConn != null) { tdsConn.ValidateConnectionForExecute(null); tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this); } } private void WaitForPendingReconnection() { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); } } private void CancelOpenAndWait() { // copy from member to avoid changes by background thread var completion = _currentCompletion; if (completion != null) { completion.Item1.TrySetCanceled(); ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne(); } Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source"); } public override Task OpenAsync(CancellationToken cancellationToken) { Guid operationId = s_diagnosticListener.WriteConnectionOpenBefore(this); PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(); TaskCompletionSource<object> result = new TaskCompletionSource<object>(); if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlErrorOpenConnection)) { result.Task.ContinueWith((t) => { if (t.Exception != null) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, t.Exception); } else { s_diagnosticListener.WriteConnectionOpenAfter(operationId, this); } }, TaskScheduler.Default); } if (cancellationToken.IsCancellationRequested) { result.SetCanceled(); return result.Task; } bool completed; try { completed = TryOpen(completion); } catch (Exception e) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, e); result.SetException(e); return result.Task; } if (completed) { result.SetResult(null); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(s => ((TaskCompletionSource<DbConnectionInternal>)s).TrySetCanceled(), completion); } OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration); _currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task); completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default); return result.Task; } return result.Task; } catch (Exception ex) { s_diagnosticListener.WriteConnectionOpenError(operationId, this, ex); throw; } finally { SqlStatistics.StopTimer(statistics); } } private class OpenAsyncRetry { private SqlConnection _parent; private TaskCompletionSource<DbConnectionInternal> _retry; private TaskCompletionSource<object> _result; private CancellationTokenRegistration _registration; public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration) { _parent = parent; _retry = retry; _result = result; _registration = registration; } internal void Retry(Task<DbConnectionInternal> retryTask) { _registration.Dispose(); try { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(_parent.Statistics); if (retryTask.IsFaulted) { Exception e = retryTask.Exception.InnerException; _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(retryTask.Exception.InnerException); } else if (retryTask.IsCanceled) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetCanceled(); } else { bool result; // protect continuation from races with close and cancel lock (_parent.InnerConnection) { result = _parent.TryOpen(_retry); } if (result) { _parent._currentCompletion = null; _result.SetResult(null); } else { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending))); } } } finally { SqlStatistics.StopTimer(statistics); } } catch (Exception e) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(e); } } } private void PrepareStatisticsForNewConnection() { if (StatisticsEnabled || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection)) { if (null == _statistics) { _statistics = new SqlStatistics(); } else { _statistics.ContinueOnNewConnection(); } } } private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry) { SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions; _applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0); if (ForceNewConnection) { if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } else { if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } // does not require GC.KeepAlive(this) because of OnStateChange var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection; Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?"); if (!tdsInnerConnection.ConnectionOptions.Pooling) { // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles GC.ReRegisterForFinalize(this); } if (StatisticsEnabled || s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand)) { ADP.TimerCurrent(out _statistics._openTimestamp); tdsInnerConnection.Parser.Statistics = _statistics; } else { tdsInnerConnection.Parser.Statistics = null; _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence } return true; } // // INTERNAL PROPERTIES // internal bool HasLocalTransaction { get { return GetOpenTdsConnection().HasLocalTransaction; } } internal bool HasLocalTransactionFromAPI { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return false; //we will not go into reconnection if we are inside the transaction } return GetOpenTdsConnection().HasLocalTransactionFromAPI; } } internal bool IsKatmaiOrNewer { get { if (_currentReconnectionTask != null) { // holds true even if task is completed return true; // if CR is enabled, connection, if established, will be Katmai+ } return GetOpenTdsConnection().IsKatmaiOrNewer; } } internal TdsParser Parser { get { SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection(); return tdsConnection.Parser; } } // // INTERNAL METHODS // internal void ValidateConnectionForExecute(string method, SqlCommand command) { Task asyncWaitingForReconnection = _asyncWaitingForReconnection; if (asyncWaitingForReconnection != null) { if (!asyncWaitingForReconnection.IsCompleted) { throw SQL.MARSUnspportedOnConnection(); } else { Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection); } } if (_currentReconnectionTask != null) { Task currentReconnectionTask = _currentReconnectionTask; if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted) { return; // execution will wait for this task later } } SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method); innerConnection.ValidateConnectionForExecute(command); } // Surround name in brackets and then escape any end bracket to protect against SQL Injection. // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well // as native OleDb and Odbc. static internal string FixupDatabaseTransactionName(string name) { if (!string.IsNullOrEmpty(name)) { return SqlServerEscapeHelper.EscapeIdentifier(name); } else { return name; } } // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter // The close action also supports being run asynchronously internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) { Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!"); if (breakConnection && (ConnectionState.Open == State)) { if (wrapCloseInAction != null) { int capturedCloseCount = _closeCount; Action closeAction = () => { if (capturedCloseCount == _closeCount) { Close(); } }; wrapCloseInAction(closeAction); } else { Close(); } } if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) { // It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error, // below TdsEnums.MIN_ERROR_CLASS denotes an info message. throw exception; } else { // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler this.OnInfoMessage(new SqlInfoMessageEventArgs(exception)); } } // // PRIVATE METHODS // internal SqlInternalConnectionTds GetOpenTdsConnection() { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.ClosedConnectionError(); } return innerConnection; } internal SqlInternalConnectionTds GetOpenTdsConnection(string method) { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.OpenConnectionRequired(method, InnerConnection.State); } return innerConnection; } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) { bool notified; OnInfoMessage(imevent, out notified); } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { notified = true; try { handler(this, imevent); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } } } else { notified = false; } } // // SQL DEBUGGING SUPPORT // // this only happens once per connection // SxS: using named file mapping APIs internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag) { // Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect outerTask = outerTask.ContinueWith(task => { RemoveWeakReference(value); return task; }, TaskScheduler.Default).Unwrap(); } public void ResetStatistics() { if (null != Statistics) { Statistics.Reset(); if (ConnectionState.Open == State) { // update timestamp; ADP.TimerCurrent(out _statistics._openTimestamp); } } } public IDictionary RetrieveStatistics() { if (null != Statistics) { UpdateStatistics(); return Statistics.GetDictionary(); } else { return new SqlStatistics().GetDictionary(); } } private void UpdateStatistics() { if (ConnectionState.Open == State) { // update timestamp ADP.TimerCurrent(out _statistics._closeTimestamp); } // delegate the rest of the work to the SqlStatistics class Statistics.UpdateStatistics(); } } // SqlConnection } // System.Data.SqlClient namespace
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using Newtonsoft.Json; namespace Jarvis.ConfigurationService.Host.Support { internal class ParameterManager { internal class ReplaceResult { public Boolean HasReplaced { get; set; } public HashSet<String> MissingParams { get; set; } public ReplaceResult() { MissingParams = new HashSet<string>(); } internal void Merge(ReplaceResult result) { HasReplaced = HasReplaced || result.HasReplaced; foreach (var missingParam in result.MissingParams) { MissingParams.Add(missingParam); } } } private String _missingParametersToken; /// <summary> /// /// </summary> /// <param name="missingParametersToken">If a parameter is missing we can /// substituite this token to the missing parameter instead of marking the /// parameter as missing.</param> public ParameterManager(String missingParametersToken = null) { _missingParametersToken = missingParametersToken; } /// <summary> /// it is used to retrieve parameters settings from config file. /// </summary> /// <param name="settingName"></param> /// <param name="parameterObject"></param> /// <returns></returns> internal String GetParameterValue(string settingName, JObject parameterObject) { var path = settingName.Split('.'); JObject current = parameterObject; for (int i = 0; i < path.Length - 1; i++) { if (current[path[i]] == null) return _missingParametersToken; current = (JObject)current[path[i]]; } if (current[path.Last()] == null) return _missingParametersToken; return current[path.Last()].ToString(); } internal ReplaceResult ReplaceParameters(JObject source, JObject parameterObject) { ReplaceResult result = new ReplaceResult(); foreach (var property in source.Properties()) { if (property.Value is JObject) { var replaceReturn = ReplaceParameters((JObject)property.Value, parameterObject); result.Merge(replaceReturn); } else if (property.Value is JArray) { ReplaceParametersInArray(parameterObject, result, property.Value as JArray); } else if (property.Value is JToken) { source[property.Name] = ManageParametersInJToken(parameterObject, result, property.Value); } } return result; } internal String ReplaceParametersInString(String source, JObject parameterObject) { ReplaceResult result = new ReplaceResult(); var newValue = Regex.Replace( source, @"(?<!%)%(?!%)(?<match>.+?)(?<!%)%(?!%)", new MatchEvaluator(m => { var parameterName = m.Groups["match"].Value.Trim('{', '}'); var paramValue = GetParameterValue(parameterName, parameterObject); if (paramValue == null) { result.MissingParams.Add(parameterName); return "%" + parameterName + "%"; } result.HasReplaced = true; return paramValue; })); if (result.MissingParams.Count > 0) { throw new ConfigurationErrorsException("Missing parameters: " + result.MissingParams.Aggregate((s1, s2) => s1 + ", " + s2)); } if (newValue.Contains("%%")) { newValue = newValue.Replace("%%", "%"); } return newValue; } private void ReplaceParametersInArray( JObject parameterObject, ReplaceResult result, JArray array) { for (int i = 0; i < array.Count; i++) { var element = array[i]; if (element is JObject) { var replaceReturn = ReplaceParameters((JObject)element, parameterObject); result.Merge(replaceReturn); } else if (element is JArray) { ReplaceParametersInArray(parameterObject, result, element as JArray); } else if (element is JToken) { array[i] = ManageParametersInJToken(parameterObject, result, element); } } } private JToken ManageParametersInJToken( JObject parameterObject, ReplaceResult result, JToken token) { String value = token.ToString(); Boolean objectParameter = value.StartsWith("%{") && value.EndsWith("}%"); if (Regex.IsMatch(value, "(?<!%)%(?!%).+?(?<!%)%(?!%)")) { String newValue = Regex.Replace( value, @"(?<!%)%(?!%)(?<match>.+?)(?<!%)%(?!%)", new MatchEvaluator(m => { var parameterName = m.Groups["match"].Value.Trim('{', '}'); var paramValue = GetParameterValue(parameterName, parameterObject); if (paramValue == null) { result.MissingParams.Add(parameterName); return objectParameter ? value : "%" + parameterName + "%"; } result.HasReplaced = true; return paramValue; })); if (objectParameter) { if (newValue == value) return newValue; //object parameter that is missing try { return (JToken)JsonConvert.DeserializeObject(newValue); } catch (Exception ex) { //parameters has some error, maybe it is malformed, treat as if parameter is missing. return "Parameter " + value + " is an object parameter and cannot be parsed: " + newValue; } } else { return newValue; } } return token; } internal void UnescapePercentage(JObject source) { foreach (var property in source.Properties()) { if (property.Value is JObject) { UnescapePercentage((JObject)property.Value); } else if (property.Value is JToken && property.Value.ToString().Contains("%%")) { source[property.Name] = property.Value.ToString().Replace("%%", "%"); } } } } }
// 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 MS.Utility; using System; using System.Runtime.InteropServices; using System.Security; using System.Globalization; using System.Windows; using System.Windows.Input; using System.Collections.Generic; using System.Windows.Ink; using MS.Internal.Ink.InkSerializedFormat; using System.Diagnostics; using SR = MS.Internal.PresentationCore.SR; using SRID = MS.Internal.PresentationCore.SRID; namespace MS.Internal.Ink.InkSerializedFormat { /// <summary> /// HuffCodec /// </summary> internal class HuffCodec { /// <summary> /// HuffCodec /// </summary> /// <param name="defaultIndex"></param> internal HuffCodec(uint defaultIndex) { HuffBits bits = new HuffBits(); bits.InitBits(defaultIndex); InitHuffTable(bits); } /// <summary> /// InitHuffTable /// </summary> /// <param name="huffBits"></param> private void InitHuffTable(HuffBits huffBits) { _huffBits = huffBits; uint bitSize = _huffBits.GetSize(); int lowerBound = 1; _mins[0] = 0; for (uint n = 1; n < bitSize; n++) { _mins[n] = (uint)lowerBound; lowerBound += (1 << (_huffBits.GetBitsAtIndex(n) - 1)); } } /// <summary> /// Compress /// </summary> /// <param name="dataXf">can be null</param> /// <param name="input">input array to compress</param> /// <param name="compressedData"></param> internal void Compress(DataXform dataXf, int[] input, List<byte> compressedData) { // // use the writer to write to the list<byte> // BitStreamWriter writer = new BitStreamWriter(compressedData); if (null != dataXf) { dataXf.ResetState(); int xfData = 0; int xfExtra = 0; for (uint i = 0; i < input.Length; i++) { dataXf.Transform(input[i], ref xfData, ref xfExtra); Encode(xfData, xfExtra, writer); } } else { for (uint i = 0; i < input.Length; i++) { Encode(input[i], 0, writer); } } } /// <summary> /// Uncompress /// </summary> /// <param name="dtxf"></param> /// <param name="input"></param> /// <param name="startIndex"></param> /// <param name="outputBuffer"></param> internal uint Uncompress(DataXform dtxf, byte[] input, int startIndex, int[] outputBuffer) { Debug.Assert(input != null); Debug.Assert(input.Length >= 2); Debug.Assert(startIndex == 1); Debug.Assert(outputBuffer != null); Debug.Assert(outputBuffer.Length != 0); BitStreamReader reader = new BitStreamReader(input, startIndex); int xfExtra = 0, xfData = 0; int outputBufferIndex = 0; if (null != dtxf) { dtxf.ResetState(); while (!reader.EndOfStream) { Decode(ref xfData, ref xfExtra, reader); int uncompressed = dtxf.InverseTransform(xfData, xfExtra); Debug.Assert(outputBufferIndex < outputBuffer.Length); outputBuffer[outputBufferIndex++] = uncompressed; if (outputBufferIndex == outputBuffer.Length) { //only write as much as the outputbuffer can hold //this is assumed by calling code break; } } } else { while (!reader.EndOfStream) { Decode(ref xfData, ref xfExtra, reader); Debug.Assert(outputBufferIndex < outputBuffer.Length); outputBuffer[outputBufferIndex++] = xfData; if (outputBufferIndex == outputBuffer.Length) { //only write as much as the outputbuffer can hold //this is assumed by calling code break; } } } return (uint)((reader.CurrentIndex + 1) - startIndex); //we include startIndex in the read count } /// <summary> /// Encode /// </summary> /// <param name="data"></param> /// <param name="extra"></param> /// <param name="writer"></param> /// <returns>number of bits encoded, 0 for failure</returns> internal byte Encode(int data, int extra, BitStreamWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } if (data == 0) { writer.Write((byte)0, 1); //more efficent return (byte)1; } // First, encode extra if non-ZERO uint bitSize = _huffBits.GetSize(); if (0 != extra) { // Prefix lenght is 1 more than table size byte extraPrefixLength = (byte)(bitSize + 1); int extraPrefix = ((1 << extraPrefixLength) - 2); writer.Write((uint)extraPrefix, (int)extraPrefixLength); // Encode the extra data first byte extraCodeLength = Encode(extra, 0, writer); // Encode the actual data next byte dataCodeLength = Encode(data, 0, writer); // Return the total code lenght return (byte)((int)extraPrefixLength + (int)extraCodeLength + (int)dataCodeLength); } // Find the absolute value of the data // IMPORTANT : It is extremely important that nData is uint, and NOT int // If it is int, the LONG_MIN will be encoded erroneaouly uint nData = (uint)MathHelper.AbsNoThrow(data); // Find the prefix lenght byte nPrefLen = 1; for (; (nPrefLen < bitSize) && (nData >= _mins[nPrefLen]); ++nPrefLen) ; // Get the data length uint nDataLen = _huffBits.GetBitsAtIndex((uint)nPrefLen - 1); // Find the prefix int nPrefix = ((1 << nPrefLen) - 2); // Append the prefix to the bit stream writer.Write((uint)nPrefix, (int)nPrefLen); // Find the data offset by lower bound // and append sign bit at LSB Debug.Assert(nDataLen > 0 && nDataLen - 1 <= Int32.MaxValue); int dataLenMinusOne = (int)(nDataLen - 1); //can't left shift by a uint, we need to thunk to an int nData = ((((nData - _mins[nPrefLen - 1]) & (uint)((1 << dataLenMinusOne) - 1)) << 1) | (uint)((data < 0) ? 1 : 0)); // Append data into the bit streamdataLenMinusOne Debug.Assert(nDataLen <= Int32.MaxValue); writer.Write(nData, (int)nDataLen); return (byte)((uint)nPrefLen + nDataLen); } /// <summary> /// Decode /// </summary> /// <param name="data"></param> /// <param name="extra"></param> /// <param name="reader"></param> /// <returns>number of bits decoded, 0 for error</returns> internal void Decode(ref int data, ref int extra, BitStreamReader reader) { // Find the prefix length byte prefIndex = 0; while (reader.ReadBit()) { prefIndex++; } // First indicate there is no extra data extra = 0; // More efficient for 0 if (0 == prefIndex) { data = 0; return; } else if (prefIndex < _huffBits.GetSize()) { // Find the data lenght uint nDataLen = _huffBits.GetBitsAtIndex(prefIndex); // Extract the offset data by lower dound with sign bit at LSB long nData = reader.ReadUInt64((int)(byte)nDataLen); // Find the sign bit bool bNeg = ((nData & 0x01) != 0); // Construct the data nData = (nData >> 1) + _mins[prefIndex]; // Adjust the sign bit data = bNeg ? -((int)nData) : (int)nData; // return the bit count read from stream return; } else if (prefIndex == _huffBits.GetSize()) { // This is the special prefix for extra data. // Decode the prefix first int extra2 = 0; int extra2Ignored = 0; Decode(ref extra2, ref extra2Ignored, reader); extra = extra2; // Following is the actual data int data2 = 0; Decode(ref data2, ref extra2Ignored, reader); data = data2; return; } throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("invalid huffman encoded data")); } /// <summary> /// Privates /// </summary> private HuffBits _huffBits; private uint[] _mins = new uint[MaxBAASize]; /// <summary> /// Private statics /// </summary> private static readonly byte MaxBAASize = 10; /// <summary> /// Private helper class /// </summary> private class HuffBits { /// <summary> /// HuffBits /// </summary> internal HuffBits() { _size = 2; _bits[0] = 0; _bits[1] = 32; _matchIndex = 0; _prefixCount = 1; //_findMatch = true; } /// <summary> /// InitBits /// </summary> /// <param name="defaultIndex"></param> /// <returns></returns> internal bool InitBits(uint defaultIndex) { if (defaultIndex < DefaultBAACount && DefaultBAASize[defaultIndex] <= MaxBAASize) { _size = DefaultBAASize[defaultIndex]; _matchIndex = defaultIndex; _prefixCount = _size; //_findMatch = true; _bits = DefaultBAAData[defaultIndex]; return true; } return false; } /// <summary> /// GetSize /// </summary> internal uint GetSize() { return _size; } /// <summary> /// GetBitsAtIndex /// </summary> internal byte GetBitsAtIndex(uint index) { return _bits[(int)index]; } /// <summary> /// Privates /// </summary> private byte[] _bits = new byte[MaxBAASize]; private uint _size; private uint _matchIndex; private uint _prefixCount; //private bool _findMatch; /// <summary> /// Private statics /// </summary> private static readonly byte MaxBAASize = 10; private static readonly byte DefaultBAACount = 8; private static readonly byte[][] DefaultBAAData = new byte[][] { new byte[]{0, 1, 2, 4, 6, 8, 12, 16, 24, 32}, new byte[]{0, 1, 1, 2, 4, 8, 12, 16, 24, 32}, new byte[]{0, 1, 1, 1, 2, 4, 8, 14, 22, 32}, new byte[]{0, 2, 2, 3, 5, 8, 12, 16, 24, 32}, new byte[]{0, 3, 4, 5, 8, 12, 16, 24, 32, 0}, new byte[]{0, 4, 6, 8, 12, 16, 24, 32, 0, 0}, new byte[]{0, 6, 8, 12, 16, 24, 32, 0, 0, 0}, new byte[]{0, 7, 8, 12, 16, 24, 32, 0, 0, 0}, }; private static readonly byte[] DefaultBAASize = new byte[] { 10, 10, 10, 10, 9, 8, 7, 7 }; } } }
#region OMIT_VIRTUALTABLE #if !OMIT_VIRTUALTABLE using System; using System.Diagnostics; using System.Text; namespace Core { public class VTableContext { public VTable VTable; // The virtual table being constructed public Table Table; // The Table object to which the virtual table belongs } public partial class VTable { public static RC CreateModule(Context ctx, string name, ITableModule imodule, object aux, Action<object> destroy) { RC rc = RC.OK; MutexEx.Enter(ctx.Mutex); int nameLength = name.Length; if (ctx.Modules.Find(name, nameLength, (TableModule)null) != null) rc = SysEx.MISUSE_BKPT(); else { TableModule module = new TableModule(); //: _tagalloc(ctx, sizeof(TableModule) + nameLength + 1) if (module != null) { var nameCopy = name; module.Name = nameCopy; module.IModule = imodule; module.Aux = aux; module.Destroy = destroy; TableModule del = (TableModule)ctx.Modules.Insert(nameCopy, nameLength, module); Debug.Assert(del == null && del == module); if (del != null) { ctx.MallocFailed = true; C._tagfree(ctx, ref del); } } } rc = SysEx.ApiExit(ctx, rc); if (rc != RC.OK && destroy != null) destroy(aux); MutexEx.Leave(ctx.Mutex); return rc; } public void Lock() { Refs++; } public static VTable GetVTable(Context ctx, Table table) { Debug.Assert(E.IsVirtual(table)); VTable vtable; for (vtable = table.VTables; vtable != null && vtable.Ctx != ctx; vtable = vtable.Next) ; return vtable; } public void Unlock() { Context ctx = Ctx; Debug.Assert(ctx != null); Debug.Assert(Refs > 0); Debug.Assert(ctx.Magic == MAGIC.OPEN || ctx.Magic == MAGIC.ZOMBIE); Refs--; if (Refs == 0) { if (IVTable != null) IVTable.IModule.Disconnect(IVTable); //C._tagfree(ctx, ref this); } } static VTable VTableDisconnectAll(Context ctx, Table table) { // Assert that the mutex (if any) associated with the BtShared database that contains table p is held by the caller. See header comments // above function sqlite3VtabUnlockList() for an explanation of why this makes it safe to access the sqlite3.pDisconnect list of any // database connection that may have an entry in the p->pVTable list. Debug.Assert(ctx == null || Btree.SchemaMutexHeld(ctx, 0, table.Schema)); VTable r = null; VTable vtable = table.VTables; table.VTables = null; while (vtable != null) { VTable next = vtable.Next; Context ctx2 = vtable.Ctx; Debug.Assert(ctx2 != null); if (ctx2 == ctx) { r = vtable; table.VTables = r; r.Next = null; } else { vtable.Next = ctx2.Disconnect; ctx2.Disconnect = vtable; } vtable = next; } Debug.Assert(ctx == null || r != null); return r; } public static void Disconnect(Context ctx, Table table) { Debug.Assert(E.IsVirtual(table)); Debug.Assert(Btree.HoldsAllMutexes(ctx)); Debug.Assert(MutexEx.Held(ctx.Mutex)); for (VTable pvtable = table.VTables; pvtable != null; pvtable = pvtable.Next) if (pvtable.Ctx == ctx) { VTable vtable = pvtable; vtable = vtable.Next; vtable.Unlock(); break; } } public static void UnlockList(Context ctx) { Debug.Assert(Btree.HoldsAllMutexes(ctx)); Debug.Assert(MutexEx.Held(ctx.Mutex)); VTable vtable = ctx.Disconnect; ctx.Disconnect = null; if (vtable != null) { Vdbe.ExpirePreparedStatements(ctx); do { VTable next = vtable.Next; vtable.Unlock(); vtable = next; } while (vtable != null); } } public static void Clear(Context ctx, Table table) { if (ctx == null || ctx.BytesFreed == 0) VTableDisconnectAll(null, table); if (table.ModuleArgs.data != null) { for (int i = 0; i < table.ModuleArgs.length; i++) C._tagfree(ctx, ref table.ModuleArgs.data[i]); C._tagfree(ctx, ref table.ModuleArgs.data); } } static void AddModuleArgument(Context ctx, Table table, string arg) { int i = table.ModuleArgs.length++; //: int bytes = sizeof(char*) * (1 + table->ModuleArgs.length); //: char** moduleArgs = (char**)_tagrealloc(ctx, table->ModuleArgs, bytes); if (table.ModuleArgs.data == null || table.ModuleArgs.data.Length < table.ModuleArgs.length) Array.Resize(ref table.ModuleArgs.data, 3 + table.ModuleArgs.length); if (table.ModuleArgs.data == null) { for (int j = 0; j < i; j++) C._tagfree(ctx, ref table.ModuleArgs.data[j]); C._tagfree(ctx, ref arg); C._tagfree(ctx, ref table.ModuleArgs.data); table.ModuleArgs.length = 0; } else { table.ModuleArgs[i] = arg; //: table.ModuleArgs[i + 1] = null; } //: table.ModuleArgs.data = moduleArgs; } public static void BeginParse(Parse parse, Token name1, Token name2, Token moduleName, bool ifNotExists) { parse.StartTable(name1, name2, false, false, true, false); Table table = parse.NewTable; // The new virtual table if (table == null) return; Debug.Assert(table.Index == null); Context ctx = parse.Ctx; // Database connection int db = Prepare.SchemaToIndex(ctx, table.Schema); // The database the table is being created in Debug.Assert(db >= 0); table.TabFlags |= TF.Virtual; table.ModuleArgs.length = 0; AddModuleArgument(ctx, table, Parse.NameFromToken(ctx, moduleName)); AddModuleArgument(ctx, table, null); AddModuleArgument(ctx, table, table.Name); parse.NameToken.length = (uint)parse.NameToken.data.Length; //: (int)(&moduleName[moduleName->length] - name1); #if !OMIT_AUTHORIZATION // Creating a virtual table invokes the authorization callback twice. The first invocation, to obtain permission to INSERT a row into the // sqlite_master table, has already been made by sqlite3StartTable(). The second call, to obtain permission to create the table, is made now. if (table.ModuleArgs.data != null) Auth.Check(parse, AUTH.CREATE_VTABLE, table.Name, table.ModuleArgs[0], ctx.DBs[db].Name); #endif } static void AddArgumentToVtab(Parse parse) { if (parse.Arg.data != null && C._ALWAYS(parse.NewTable != null)) { string z = parse.Arg.data.Substring(0, (int)parse.Arg.length); //: uint length = parse.Arg.length; Context ctx = parse.Ctx; AddModuleArgument(ctx, parse.NewTable, z); } } public static void FinishParse(Parse parse, Token end) { Table table = parse.NewTable; // The table being constructed Context ctx = parse.Ctx; // The database connection if (table == null) return; AddArgumentToVtab(parse); parse.Arg.data = null; if (table.ModuleArgs.length < 1) return; // If the CREATE VIRTUAL TABLE statement is being entered for the first time (in other words if the virtual table is actually being // created now instead of just being read out of sqlite_master) then do additional initialization work and store the statement text // in the sqlite_master table. if (!ctx.Init.Busy) { // Compute the complete text of the CREATE VIRTUAL TABLE statement if (end != null) parse.NameToken.length = (uint)parse.NameToken.data.Length; //: (int)(end->data - parse->NameToken) + end->length; string stmt = C._mtagprintf(ctx, "CREATE VIRTUAL TABLE %T", parse.NameToken); //.Z.Substring(0, parse.NameToken.length)); // A slot for the record has already been allocated in the SQLITE_MASTER table. We just need to update that slot with all // the information we've collected. // // The VM register number pParse->regRowid holds the rowid of an entry in the sqlite_master table tht was created for this vtab // by sqlite3StartTable(). int db = Prepare.SchemaToIndex(ctx, table.Schema); parse.NestedParse("UPDATE %Q.%s SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q WHERE rowid=#%d", ctx.DBs[db].Name, E.SCHEMA_TABLE(db), table.Name, table.Name, stmt, parse.RegRowid ); C._tagfree(ctx, ref stmt); Vdbe v = parse.GetVdbe(); parse.ChangeCookie(db); v.AddOp2(OP.Expire, 0, 0); string where_ = C._mtagprintf(ctx, "name='%q' AND type='table'", table.Name); v.AddParseSchemaOp(db, where_); v.AddOp4(OP.VCreate, db, 0, 0, table.Name, (Vdbe.P4T)table.Name.Length + 1); } // If we are rereading the sqlite_master table create the in-memory record of the table. The xConnect() method is not called until // the first time the virtual table is used in an SQL statement. This allows a schema that contains virtual tables to be loaded before // the required virtual table implementations are registered. else { Schema schema = table.Schema; string name = table.Name; int nameLength = name.Length; Debug.Assert(Btree.SchemaMutexHeld(ctx, 0, schema)); Table oldTable = schema.TableHash.Insert(name, nameLength, table); if (oldTable != null) { ctx.MallocFailed = true; Debug.Assert(table == oldTable); // Malloc must have failed inside HashInsert() return; } parse.NewTable = null; } } public static void ArgInit(Parse parse) { AddArgumentToVtab(parse); parse.Arg.data = null; parse.Arg.length = 0; } public static void ArgExtend(Parse parse, Token token) { Token arg = parse.Arg; if (arg.data == null) { arg.data = token.data; arg.length = token.length; } else { //: Debug.Assert(arg < token); arg.length += token.length + 1; //: (int)(&token[token->length] - arg); } } public delegate RC Construct_t(Context ctx, object aux, int argsLength, string[] args, out IVTable vtable, out string error); static RC VTableCallConstructor(Context ctx, Table table, TableModule module, Construct_t construct, ref string errorOut) { string moduleName = table.Name; if (moduleName == null) return RC.NOMEM; VTable vtable = new VTable(); if (vtable == null) { C._tagfree(ctx, ref moduleName); return RC.NOMEM; } vtable.Ctx = ctx; vtable.Module = module; int db = sqlite3SchemaToIndex(ctx, table.Schema); table.ModuleArgs[1] = ctx.DBs[db].Name; // Invoke the virtual table constructor Debug.Assert(ctx.VTableCtx != null); Debug.Assert(construct != null); VTableContext sVtableCtx = new VTableContext(); sVtableCtx.Table = table; sVtableCtx.VTable = vtable; VTableContext priorCtx = ctx.VTableCtx; ctx.VTableCtx = sVtableCtx; string[] args = table.ModuleArgs.data; int argsLength = table.ModuleArgs.length; string error = null; RC rc = construct(ctx, module.Aux, argsLength, args, out vtable.IVTable, out error); ctx.VTableCtx = null; if (rc == RC.NOMEM) ctx.MallocFailed = true; if (rc != RC.OK) { if (error == null) errorOut = C._mtagprintf(ctx, "vtable constructor failed: %s", moduleName); else { errorOut = error; error = null; //: _free(error); } C._tagfree(ctx, ref vtable); } else if (C._ALWAYS(vtable.IVTable != null)) { // Justification of ALWAYS(): A correct vtab constructor must allocate the sqlite3_vtab object if successful. vtable.IVTable.IModule = module.IModule; vtable.Refs = 1; if (sVtableCtx.Table != null) { errorOut = C._mtagprintf(ctx, "vtable constructor did not declare schema: %s", table.Name); vtable.Unlock(); rc = RC.ERROR; } else { // If everything went according to plan, link the new VTable structure into the linked list headed by pTab->pVTable. Then loop through the // columns of the table to see if any of them contain the token "hidden". If so, set the Column COLFLAG_HIDDEN flag and remove the token from // the type string. vtable.Next = table.VTables; table.VTables = vtable; for (int col = 0; col < table.Cols.length; col++) { string type = table.Cols[col].Type; if (type == null) continue; int typeLength = type.Length; int i = 0; if (string.Compare("hidden", 0, type, 0, 6, StringComparison.OrdinalIgnoreCase) == 0 || (type.Length > 6 && type[6] != ' ')) { for (i = 0; i < typeLength; i++) if (string.Compare(" hidden", 0, type, i, 7, StringComparison.OrdinalIgnoreCase) == 0 && (i + 7 == type.Length || (type[i + 7] == '\0' || type[i + 7] == ' '))) { i++; break; } } if (i < typeLength) { StringBuilder type2 = new StringBuilder(type); int del = 6 + (type2.Length > i + 6 ? 1 : 0); int j; for (j = i; (j + del) < typeLength; j++) type2[j] = type2[j + del]; if (type2[i] == '\0' && i > 0) { Debug.Assert(type[i - 1] == ' '); type2.Length = i; //: type[i - 1] = '\0'; } table.Cols[col].ColFlags |= COLFLAG.HIDDEN; table.Cols[col].Type = type.ToString().Substring(0, j); } } } } C._tagfree(ctx, ref moduleName); return rc; } public static RC CallConnect(Parse parse, Table table) { Debug.Assert(table != null); Context ctx = parse.Ctx; if ((table.TabFlags & TF.Virtual) == 0 || GetVTable(ctx, table) != null) return RC.OK; // Locate the required virtual table module string moduleName = table.ModuleArgs[0]; TableModule module = (TableModule)ctx.Modules.Find(moduleName, moduleName.Length, (TableModule)null); if (module == null) { parse.ErrorMsg("no such module: %s", moduleName); return RC.ERROR; } string error = null; RC rc = VTableCallConstructor(ctx, table, module, module.IModule.Connect, ref error); if (rc != RC.OK) parse.ErrorMsg("%s", error); C._tagfree(ctx, ref error); return rc; } static RC GrowVTrans(Context ctx) { const int ARRAY_INCR = 5; // Grow the sqlite3.aVTrans array if required if ((ctx.VTrans.length % ARRAY_INCR) == 0) { //: int bytes = sizeof(IVTable*) * (ctx->VTrans.length + ARRAY_INCR); //: VTable** vtrans = (VTable**)_tagrealloc(ctx, (void*)ctx->VTrans, bytes); //: if (!vtrans) //: return RC_NOMEM; //: _memset(&vtrans[ctx->VTrans.length], 0, sizeof(IVTable*) * ARRAY_INCR); //: ctx->VTrans = vtrans; Array.Resize(ref ctx.VTrans.data, ctx.VTrans.length + ARRAY_INCR); } return RC.OK; } static void AddToVTrans(Context ctx, VTable vtable) { // Add pVtab to the end of sqlite3.aVTrans ctx.VTrans[ctx.VTrans.length++] = vtable; vtable.Lock(); } public static RC CallCreate(Context ctx, int db, string tableName, ref string errorOut) { Table table = Parse.FindTable(ctx, tableName, ctx.DBs[db].Name); Debug.Assert(table != null && (table.TabFlags & TF.Virtual) != 0 && table.VTables == null); // Locate the required virtual table module string moduleName = table.ModuleArgs[0]; TableModule module = (TableModule)ctx.Modules.Find(moduleName, moduleName.Length, (TableModule)null); // If the module has been registered and includes a Create method, invoke it now. If the module has not been registered, return an // error. Otherwise, do nothing. RC rc = RC.OK; if (module == null) { errorOut = C._mtagprintf(ctx, "no such module: %s", moduleName); rc = RC.ERROR; } else rc = VTableCallConstructor(ctx, table, module, module.IModule.Create, ref errorOut); // Justification of ALWAYS(): The xConstructor method is required to create a valid sqlite3_vtab if it returns SQLITE_OK. if (rc == RC.OK && C._ALWAYS(GetVTable(ctx, table) != null)) { rc = GrowVTrans(ctx); if (rc == RC.OK) AddToVTrans(ctx, GetVTable(ctx, table)); } return rc; } public static RC DeclareVTable(Context ctx, string createTableName) { MutexEx.Enter(ctx.Mutex); Table table; if (ctx.VTableCtx == null || (table = ctx.VTableCtx.Table) == null) { sqlite3Error(ctx, RC.MISUSE, null); MutexEx.Leave(ctx.Mutex); return SysEx.MISUSE_BKPT(); } Debug.Assert((table.TabFlags & TF.Virtual) != 0); RC rc = RC.OK; Parse parse = new Parse(); //: _scratchalloc(ctx, sizeof(Parse)); if (parse == null) rc = RC.NOMEM; else { parse.DeclareVTable = true; parse.Ctx = ctx; parse.QueryLoops = 1; string error = null; if (sqlite3RunParser(parse, createTableName, ref error) == RC.OK && parse.NewTable != null && !ctx.MallocFailed && parse.NewTable.Select == null && (parse.NewTable.TabFlags & TF.Virtual) == 0) { if (table.Cols.data == null) { table.Cols.data = parse.NewTable.Cols.data; table.Cols.length = parse.NewTable.Cols.length; parse.NewTable.Cols.length = 0; parse.NewTable.Cols.data = null; } ctx.VTableCtx.Table = null; } else { sqlite3Error(ctx, RC.ERROR, (error != null ? "%s" : null), error); C._tagfree(ctx, ref error); rc = RC.ERROR; } parse.DeclareVTable = false; if (parse.V != null) parse.V.Finalize(); Parse.DeleteTable(ctx, ref parse.NewTable); parse = null; //: C._scratchfree(ctx, parse); } Debug.Assert(((int)rc & 0xff) == (int)rc); rc = SysEx.ApiExit(ctx, rc); MutexEx.Leave(ctx.Mutex); return rc; } public static RC CallDestroy(Context ctx, int db, string tableName) { RC rc = RC.OK; Table table = Parse.FindTable(ctx, tableName, ctx.DBs[db].Name); if (C._ALWAYS(table != null && table.VTables != null)) { VTable vtable = VTableDisconnectAll(ctx, table); Debug.Assert(rc == RC.OK); rc = vtable.Module.IModule.Destroy(vtable.IVTable); // Remove the sqlite3_vtab* from the aVTrans[] array, if applicable if (rc == RC.OK) { Debug.Assert(table.VTables == vtable && vtable.Next == null); vtable.IVTable = null; table.VTables = null; vtable.Unlock(); } } return rc; } static void CallFinaliser(Context ctx, int offset) { if (ctx.VTrans.data != null) { for (int i = 0; i < ctx.VTrans.length; i++) { VTable vtable = ctx.VTrans[i]; IVTable ivtable = vtable.IVTable; if (ivtable != null) { Func<IVTable, int> x = null; if (offset == 0) x = ivtable.IModule.Rollback; else if (offset == 1) x = ivtable.IModule.Commit; else throw new InvalidOperationException(); if (x != null) x(ivtable); } vtable.Savepoints = 0; vtable.Unlock(); } C._tagfree(ctx, ref ctx.VTrans.data); ctx.VTrans.length = 0; ctx.VTrans.data = null; } } public static RC Sync(Context ctx, ref string errorOut) { RC rc = RC.OK; VTable[] vtrans = ctx.VTrans.data; ctx.VTrans.data = null; for (int i = 0; rc == RC.OK && i < ctx.VTrans.length; i++) { Func<IVTable, int> x = null; IVTable ivtable = vtrans[i].IVTable; if (ivtable != null && (x = ivtable.IModule.Sync) != null) { rc = (RC)x(ivtable); C._tagfree(ctx, ref errorOut); errorOut = ivtable.ErrMsg; C._free(ref ivtable.ErrMsg); } } ctx.VTrans.data = vtrans; return rc; } public static RC Rollback(Context ctx) { CallFinaliser(ctx, 0); //: offsetof(IVTable, Rollback) return RC.OK; } public static RC Commit(Context ctx) { CallFinaliser(ctx, 1); //: offsetof(IVTable, Commit) return RC.OK; } public static RC Begin(Context ctx, VTable vtable) { // Special case: If ctx->aVTrans is NULL and ctx->nVTrans is greater than zero, then this function is being called from within a // virtual module xSync() callback. It is illegal to write to virtual module tables in this case, so return SQLITE_LOCKED. if (InSync(ctx)) return RC.LOCKED; if (vtable == null) return RC.OK; RC rc = RC.OK; ITableModule imodule = vtable.IVTable.IModule; if (imodule.Begin != null) { // If pVtab is already in the aVTrans array, return early for (int i = 0; i < ctx.VTrans.length; i++) if (ctx.VTrans[i] == vtable) return RC.OK; // Invoke the xBegin method. If successful, add the vtab to the sqlite3.aVTrans[] array. rc = GrowVTrans(ctx); if (rc == RC.OK) { rc = imodule.Begin(vtable.IVTable); if (rc == RC.OK) AddToVTrans(ctx, vtable); } } return rc; } public static RC Savepoint(Context ctx, IPager.SAVEPOINT op, int savepoint) { Debug.Assert(op == IPager.SAVEPOINT.RELEASE || op == IPager.SAVEPOINT.ROLLBACK || op == IPager.SAVEPOINT.BEGIN); Debug.Assert(savepoint >= 0); RC rc = RC.OK; if (ctx.VTrans.data != null) for (int i = 0; rc == RC.OK && i < ctx.VTrans.length; i++) { VTable vtable = ctx.VTrans[i]; ITableModule itablemodule = vtable.Module.IModule; if (vtable.IVTable != null && itablemodule.Version >= 2) { Func<VTable, int, int> method = null; switch (op) { case IPager.SAVEPOINT.BEGIN: method = itablemodule.Savepoint; vtable.Savepoints = savepoint + 1; break; case IPager.SAVEPOINT.ROLLBACK: method = itablemodule.RollbackTo; break; default: method = itablemodule.Release; break; } if (method != null && vtable.Savepoints > savepoint) rc = (RC)method(vtable.IVTable, savepoint); } } return rc; } public static FuncDef OverloadFunction(Context ctx, FuncDef def, int argsLength, Expr expr) { // Check to see the left operand is a column in a virtual table if (C._NEVER(expr == null)) return def; if (expr.OP != TK.COLUMN) return def; Table table = expr.Table; if (C._NEVER(table == null)) return def; if ((table.TabFlags & TF.Virtual) == 0) return def; IVTable ivtable = GetVTable(ctx, table).IVTable; Debug.Assert(ivtable != null); Debug.Assert(ivtable.IModule != null); ITableModule imodule = (ITableModule)ivtable.IModule; if (imodule.FindFunction == null) return def; // Call the xFindFunction method on the virtual table implementation to see if the implementation wants to overload this function string lowerName = def.Name; RC rc = RC.OK; Action<FuncContext, int, Mem[]> func = null; object[] args = null; if (lowerName != null) { lowerName = lowerName.ToLowerInvariant(); rc = imodule.FindFunction(ivtable, argsLength, lowerName, func, args); C._tagfree(ctx, ref lowerName); } if (rc == RC.OK) return def; // Create a new ephemeral function definition for the overloaded function FuncDef newFunc = new FuncDef();//: (FuncDef*)_tagalloc(ctx, sizeof(FuncDef) + _strlen(def->Name) + 1, true); if (newFunc == null) return def; newFunc = def._memcpy(); newFunc.Name = def.Name; newFunc.Func = func; newFunc.UserData = args; newFunc.Flags |= FUNC.EPHEM; return newFunc; } public static void MakeWritable(Parse parse, Table table) { Debug.Assert(E.IsVirtual(table)); Parse toplevel = parse.Toplevel(); for (int i = 0; i < toplevel.VTableLocks.length; i++) if (table == toplevel.VTableLocks[i]) return; int newSize = (toplevel.VTableLocks.data == null ? 1 : toplevel.VTableLocks.length + 1); //: (toplevel->VTableLocks.length + 1) * sizeof(toplevel->VTableLocks[0]); Array.Resize(ref toplevel.VTableLocks.data, newSize); //: Table vtablelocks = (Table **)_realloc(toplevel->VTableLocks, newSize); if (true) //vtablelocks != null) { //: toplevel.VTableLocks = vtablelocks; toplevel.VTableLocks[toplevel.VTableLocks.length++] = table; } else toplevel.Ctx.MallocFailed = true; } static CONFLICT[] _map = new[] { CONFLICT.ROLLBACK, CONFLICT.ABORT, CONFLICT.FAIL, CONFLICT.IGNORE, CONFLICT.REPLACE }; public static CONFLICT OnConflict(Context ctx) { Debug.Assert((int)OE.Rollback == 1 && (int)OE.Abort == 2 && (int)OE.Fail == 3); Debug.Assert((int)OE.Ignore == 4 && (int)OE.Replace == 5); Debug.Assert(ctx.VTableOnConflict >= 1 && ctx.VTableOnConflict <= 5); return _map[ctx.VTableOnConflict - 1]; } public static RC Config(Context ctx, VTABLECONFIG op, object arg1) { RC rc = RC.OK; MutexEx.Enter(ctx.Mutex); switch (op) { case VTABLECONFIG.CONSTRAINT: { VTableContext p = ctx.VTableCtx; if (p == null) rc = SysEx.MISUSE_BKPT(); else { Debug.Assert(p.Table == null || (p.Table.TabFlags & TF.Virtual) != 0); p.VTable.Constraint = (bool)arg1; } break; } default: rc = SysEx.MISUSE_BKPT(); break; } if (rc != RC.OK) DataEx.Error(ctx, rc, null); MutexEx.Leave(ctx.Mutex); return rc; } } } #endif #endregion
using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// FreddieMac /// </summary> public sealed partial class FreddieMac : DirtyExtensibleObject, IIdentifiable { private DirtyValue<StringEnumValue<AffordableProduct>>? _affordableProduct; private DirtyValue<decimal?>? _alimonyAsIncomeReduction; private DirtyValue<decimal?>? _allMonthlyPayments; private DirtyValue<bool?>? _allowsNegativeAmortizationIndicator; private DirtyValue<string?>? _amountOfFinancedMI; private DirtyValue<string?>? _aPNCity; private DirtyValue<bool?>? _armsLengthTransactionIndicator; private DirtyValue<bool?>? _borrowerQualifiesAsVeteranIndicator; private DirtyValue<string?>? _brokerOriginated; private DirtyValue<StringEnumValue<BuydownContributor>>? _buydownContributor; private DirtyValue<StringEnumValue<CondoClass>>? _condoClass; private DirtyValue<decimal?>? _convertibleFeeAmount; private DirtyValue<decimal?>? _convertibleFeePercent; private DirtyValue<decimal?>? _convertibleMaxRateAdjPercent; private DirtyValue<decimal?>? _convertibleMinRateAdjPercent; private DirtyValue<string?>? _correspondentAssignmentID; private DirtyValue<string?>? _county; private DirtyValue<StringEnumValue<CreditReportCompany>>? _creditReportCompany; private DirtyValue<decimal?>? _financingConcessions; private DirtyValue<string?>? _freddieFiel11; private DirtyValue<string?>? _freddieFiel12; private DirtyValue<string?>? _freddieFiel13; private DirtyValue<string?>? _freddieFiel14; private DirtyValue<string?>? _freddieFiel15; private DirtyValue<string?>? _freddieField3; private DirtyValue<string?>? _freddieField7; private DirtyValue<string?>? _freddieMacOwnedMessage; private DirtyValue<string?>? _hELOCActualBalance; private DirtyValue<string?>? _hELOCCreditLimit; private DirtyValue<string?>? _id; private DirtyValue<string?>? _lenderAltPhone; private DirtyValue<string?>? _lenderRegistration; private DirtyValue<string?>? _loanProspectorID; private DirtyValue<StringEnumValue<LoanToConduitCode>>? _loanToConduitCode; private DirtyValue<string?>? _longLegalDescription; private DirtyValue<StringEnumValue<LossCoverage>>? _lossCoverage; private DirtyValue<string?>? _lPKeyNumber; private DirtyValue<StringEnumValue<MIRefundOption>>? _mIRefundOption; private DirtyValue<StringEnumValue<MortgageInsuranceCompany>>? _mortgageInsuranceCompany; private DirtyValue<decimal?>? _netPurchasePrice; private DirtyValue<StringEnumValue<NewConstructionType>>? _newConstructionType; private DirtyValue<StringEnumValue<NoAppraisalMAF>>? _noAppraisalMAF; private DirtyValue<decimal?>? _nonOccupantNonHousingDebt; private DirtyValue<decimal?>? _nonOccupantPresentHE; private DirtyValue<bool?>? _orderCreditEvaluationIndicator; private DirtyValue<bool?>? _orderMergedCreditReportIndicator; private DirtyValue<StringEnumValue<OrderMortgageInsurance>>? _orderMortgageInsurance; private DirtyValue<bool?>? _orderRiskGradeEvaluationIndicator; private DirtyValue<decimal?>? _originalIntRate; private DirtyValue<string?>? _originateID; private DirtyValue<StringEnumValue<PaymentFrequency>>? _paymentFrequency; private DirtyValue<StringEnumValue<PaymentOption>>? _paymentOption; private DirtyValue<decimal?>? _personIncomeForSelfEmployment1; private DirtyValue<decimal?>? _personIncomeForSelfEmployment2; private DirtyValue<int?>? _personPercentOfBusinessOwned1; private DirtyValue<int?>? _personPercentOfBusinessOwned2; private DirtyValue<StringEnumValue<PremiumSource>>? _premiumSource; private DirtyValue<decimal?>? _presentHousingExpense; private DirtyValue<StringEnumValue<ProcessingPoint>>? _processingPoint; private DirtyValue<StringEnumValue<FreddieMacPropertyType>>? _propertyType; private DirtyValue<StringEnumValue<FreddieMacPurposeOfLoan>>? _purposeOfLoan; private DirtyValue<StringEnumValue<RenewalOption>>? _renewalOption; private DirtyValue<StringEnumValue<RenewalType>>? _renewalType; private DirtyValue<StringEnumValue<RequiredDocumentType>>? _requiredDocumentType; private DirtyValue<decimal?>? _reserves; private DirtyValue<bool?>? _retailLoanIndicator; private DirtyValue<StringEnumValue<FreddieMacRiskClass>>? _riskClass; private DirtyValue<StringEnumValue<RiskGradeEvaluationType>>? _riskGradeEvaluationType; private DirtyValue<decimal?>? _salesConcessions; private DirtyValue<StringEnumValue<SecondaryFinancingType>>? _secondaryFinancingType; private DirtyValue<bool?>? _secondTrustRefiIndicator; private DirtyValue<decimal?>? _simulatedPITI; private DirtyValue<string?>? _sizeOfHousehold; private DirtyValue<string?>? _specialInstruction1; private DirtyValue<string?>? _specialInstruction2; private DirtyValue<string?>? _specialInstruction3; private DirtyValue<string?>? _specialInstruction4; private DirtyValue<string?>? _specialInstruction5; private DirtyValue<string?>? _state; private DirtyValue<bool?>? _transferLoanToConduitIndicator; private DirtyValue<StringEnumValue<YearsOfCoverage>>? _yearsOfCoverage; /// <summary> /// Freddie Mac Lender Affordable Product [CASASRN.X114] /// </summary> public StringEnumValue<AffordableProduct> AffordableProduct { get => _affordableProduct; set => SetField(ref _affordableProduct, value); } /// <summary> /// Freddie Mac FHA/VA Alimony as Inc Reduc [CASASRN.X159] /// </summary> public decimal? AlimonyAsIncomeReduction { get => _alimonyAsIncomeReduction; set => SetField(ref _alimonyAsIncomeReduction, value); } /// <summary> /// Freddie Mac Total All Mo Pymts [CASASRN.X99] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? AllMonthlyPayments { get => _allMonthlyPayments; set => SetField(ref _allMonthlyPayments, value); } /// <summary> /// Freddie Mac Lender Allows Neg Amort [CASASRN.X85] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Allows Negative Amortization\"}")] public bool? AllowsNegativeAmortizationIndicator { get => _allowsNegativeAmortizationIndicator; set => SetField(ref _allowsNegativeAmortizationIndicator, value); } /// <summary> /// Freddie Mac Amt Financed MI [CASASRN.X169] /// </summary> public string? AmountOfFinancedMI { get => _amountOfFinancedMI; set => SetField(ref _amountOfFinancedMI, value); } /// <summary> /// Freddie Mac Lender APN City [CASASRN.X17] /// </summary> public string? APNCity { get => _aPNCity; set => SetField(ref _aPNCity, value); } /// <summary> /// Freddie Mac Lender Arms-Length Trans [CASASRN.X81] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Arms-Length Transaction\"}")] public bool? ArmsLengthTransactionIndicator { get => _armsLengthTransactionIndicator; set => SetField(ref _armsLengthTransactionIndicator, value); } /// <summary> /// Borr Qualifies as Veteran [156] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"One or more borrowers qualifies as a veteran\"}")] public bool? BorrowerQualifiesAsVeteranIndicator { get => _borrowerQualifiesAsVeteranIndicator; set => SetField(ref _borrowerQualifiesAsVeteranIndicator, value); } /// <summary> /// Freddie Mac Broker Originated [CASASRN.X165] /// </summary> public string? BrokerOriginated { get => _brokerOriginated; set => SetField(ref _brokerOriginated, value); } /// <summary> /// Freddie Mac Buydown Contributor [CASASRN.X141] /// </summary> public StringEnumValue<BuydownContributor> BuydownContributor { get => _buydownContributor; set => SetField(ref _buydownContributor, value); } /// <summary> /// Freddie Mac Lender Condo Class [CASASRN.X84] /// </summary> public StringEnumValue<CondoClass> CondoClass { get => _condoClass; set => SetField(ref _condoClass, value); } /// <summary> /// Conversion Option Fee Amount [CnvrOpt.FeeAmt] /// </summary> public decimal? ConvertibleFeeAmount { get => _convertibleFeeAmount; set => SetField(ref _convertibleFeeAmount, value); } /// <summary> /// Conversion Option Fee Percent [CnvrOpt.FeePct] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? ConvertibleFeePercent { get => _convertibleFeePercent; set => SetField(ref _convertibleFeePercent, value); } /// <summary> /// Conversion Option Max. Rate Adj. [CnvrOpt.MaxRateAdj] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? ConvertibleMaxRateAdjPercent { get => _convertibleMaxRateAdjPercent; set => SetField(ref _convertibleMaxRateAdjPercent, value); } /// <summary> /// Conversion Option Min. Rate Adj. [CnvrOpt.MinRateAdj] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? ConvertibleMinRateAdjPercent { get => _convertibleMinRateAdjPercent; set => SetField(ref _convertibleMinRateAdjPercent, value); } /// <summary> /// Freddie Mac Correspondent Assignment Center ID [CASASRN.X203] /// </summary> public string? CorrespondentAssignmentID { get => _correspondentAssignmentID; set => SetField(ref _correspondentAssignmentID, value); } /// <summary> /// Freddie Mac Lender County [977] /// </summary> public string? County { get => _county; set => SetField(ref _county, value); } /// <summary> /// Freddie Mac Merged Credit Rpt Source [CASASRN.X2] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<CreditReportCompany> CreditReportCompany { get => _creditReportCompany; set => SetField(ref _creditReportCompany, value); } /// <summary> /// Freddie Mac Financing Concessions [CASASRN.X20] /// </summary> public decimal? FinancingConcessions { get => _financingConcessions; set => SetField(ref _financingConcessions, value); } /// <summary> /// Freddie Mac AccountChek Asset ID (Bor) [CASASRN.X31] /// </summary> public string? FreddieFiel11 { get => _freddieFiel11; set => SetField(ref _freddieFiel11, value); } /// <summary> /// Freddie Mac AccountChek Asset ID (CoBor) [CASASRN.X32] /// </summary> public string? FreddieFiel12 { get => _freddieFiel12; set => SetField(ref _freddieFiel12, value); } /// <summary> /// Freddie Mac Freddie Field 13 [CASASRN.X33] /// </summary> public string? FreddieFiel13 { get => _freddieFiel13; set => SetField(ref _freddieFiel13, value); } /// <summary> /// Freddie Mac Risk Class [CASASRN.X34] /// </summary> public string? FreddieFiel14 { get => _freddieFiel14; set => SetField(ref _freddieFiel14, value); } /// <summary> /// Correspondent Assignment Name [CASASRN.X35] /// </summary> public string? FreddieFiel15 { get => _freddieFiel15; set => SetField(ref _freddieFiel15, value); } /// <summary> /// Freddie Mac Freddie Field 3 [CASASRN.X162] /// </summary> public string? FreddieField3 { get => _freddieField3; set => SetField(ref _freddieField3, value); } /// <summary> /// LoanBeam [CASASRN.X166] /// </summary> public string? FreddieField7 { get => _freddieField7; set => SetField(ref _freddieField7, value); } /// <summary> /// Freddie Mac Owned Message [CASASRN.X204] /// </summary> public string? FreddieMacOwnedMessage { get => _freddieMacOwnedMessage; set => SetField(ref _freddieMacOwnedMessage, value); } /// <summary> /// Freddie Mac HELOC Actual Bal [CASASRN.X167] /// </summary> public string? HELOCActualBalance { get => _hELOCActualBalance; set => SetField(ref _hELOCActualBalance, value); } /// <summary> /// Freddie Mac HELOC Credit Limit [CASASRN.X168] /// </summary> public string? HELOCCreditLimit { get => _hELOCCreditLimit; set => SetField(ref _hELOCCreditLimit, value); } /// <summary> /// FreddieMac Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Freddie Mac Lender Alt Phone [CASASRN.X80] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? LenderAltPhone { get => _lenderAltPhone; set => SetField(ref _lenderAltPhone, value); } /// <summary> /// Freddie Mac Lender Registration # [CASASRN.X161] /// </summary> public string? LenderRegistration { get => _lenderRegistration; set => SetField(ref _lenderRegistration, value); } /// <summary> /// Freddie Mac Loan Prospector ID [CASASRN.X200] /// </summary> public string? LoanProspectorID { get => _loanProspectorID; set => SetField(ref _loanProspectorID, value); } /// <summary> /// Freddie Mac Conduit [CASASRN.X106] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<LoanToConduitCode> LoanToConduitCode { get => _loanToConduitCode; set => SetField(ref _loanToConduitCode, value); } /// <summary> /// Freddie Mac Long Legal Descr [CASASRN.X41] /// </summary> public string? LongLegalDescription { get => _longLegalDescription; set => SetField(ref _longLegalDescription, value); } /// <summary> /// Freddie Mac Loss Coverage Est [CASASRN.X160] /// </summary> public StringEnumValue<LossCoverage> LossCoverage { get => _lossCoverage; set => SetField(ref _lossCoverage, value); } /// <summary> /// Freddie Mac LP Key # [CASASRN.X13] /// </summary> public string? LPKeyNumber { get => _lPKeyNumber; set => SetField(ref _lPKeyNumber, value); } /// <summary> /// Freddie Mac MI Refundable Option [CASASRN.X146] /// </summary> public StringEnumValue<MIRefundOption> MIRefundOption { get => _mIRefundOption; set => SetField(ref _mIRefundOption, value); } /// <summary> /// Freddie Mac MI Souce [CASASRN.X3] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<MortgageInsuranceCompany> MortgageInsuranceCompany { get => _mortgageInsuranceCompany; set => SetField(ref _mortgageInsuranceCompany, value); } /// <summary> /// Freddie Mac Lender Net Purch Price [CASASRN.X109] /// </summary> public decimal? NetPurchasePrice { get => _netPurchasePrice; set => SetField(ref _netPurchasePrice, value); } /// <summary> /// Freddie Mac New Construction Type [CASASRN.X197] /// </summary> public StringEnumValue<NewConstructionType> NewConstructionType { get => _newConstructionType; set => SetField(ref _newConstructionType, value); } /// <summary> /// Freddie Mac No-Appraisal MAF [CASASRN.X164] /// </summary> public StringEnumValue<NoAppraisalMAF> NoAppraisalMAF { get => _noAppraisalMAF; set => SetField(ref _noAppraisalMAF, value); } /// <summary> /// Freddie Mac Total Debt [CASASRN.X174] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? NonOccupantNonHousingDebt { get => _nonOccupantNonHousingDebt; set => SetField(ref _nonOccupantNonHousingDebt, value); } /// <summary> /// Freddie Mac Total Non-Occ Pres Housing Exp [CASASRN.X131] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? NonOccupantPresentHE { get => _nonOccupantPresentHE; set => SetField(ref _nonOccupantPresentHE, value); } /// <summary> /// Freddie Mac Order Credit [CASASRN.X1] /// </summary> [LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Order Credit Evaluation\"}")] public bool? OrderCreditEvaluationIndicator { get => _orderCreditEvaluationIndicator; set => SetField(ref _orderCreditEvaluationIndicator, value); } /// <summary> /// Freddie Mac Order Merged Credit Rpt [CASASRN.X88] /// </summary> [LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Order Merged Credit Report\"}")] public bool? OrderMergedCreditReportIndicator { get => _orderMergedCreditReportIndicator; set => SetField(ref _orderMergedCreditReportIndicator, value); } /// <summary> /// Freddie Mac Order MI [CASASRN.X89] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<OrderMortgageInsurance> OrderMortgageInsurance { get => _orderMortgageInsurance; set => SetField(ref _orderMortgageInsurance, value); } /// <summary> /// Freddie Mac Order Risk Grade Eval [CASASRN.X4] /// </summary> [LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Order Risk Grade Evaluation\"}")] public bool? OrderRiskGradeEvaluationIndicator { get => _orderRiskGradeEvaluationIndicator; set => SetField(ref _orderRiskGradeEvaluationIndicator, value); } /// <summary> /// Freddie Mac Lender Orig Interest Rate [CASASRN.X142] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? OriginalIntRate { get => _originalIntRate; set => SetField(ref _originalIntRate, value); } /// <summary> /// Freddie Mac FHA/VA Originate ID [CASASRN.X27] /// </summary> public string? OriginateID { get => _originateID; set => SetField(ref _originateID, value); } /// <summary> /// Freddie Mac MI Pymt Frequency [CASASRN.X154] /// </summary> public StringEnumValue<PaymentFrequency> PaymentFrequency { get => _paymentFrequency; set => SetField(ref _paymentFrequency, value); } /// <summary> /// Freddie Mac MI Pymt Option [CASASRN.X152] /// </summary> public StringEnumValue<PaymentOption> PaymentOption { get => _paymentOption; set => SetField(ref _paymentOption, value); } /// <summary> /// Freddie Mac Borr Income from Self Emp [CASASRN.X178] /// </summary> public decimal? PersonIncomeForSelfEmployment1 { get => _personIncomeForSelfEmployment1; set => SetField(ref _personIncomeForSelfEmployment1, value); } /// <summary> /// Freddie Mac Co-Borr Income from Self Emp [CASASRN.X179] /// </summary> public decimal? PersonIncomeForSelfEmployment2 { get => _personIncomeForSelfEmployment2; set => SetField(ref _personIncomeForSelfEmployment2, value); } /// <summary> /// Freddie Mac Borr % of Business Owned [CASASRN.X176] /// </summary> public int? PersonPercentOfBusinessOwned1 { get => _personPercentOfBusinessOwned1; set => SetField(ref _personPercentOfBusinessOwned1, value); } /// <summary> /// Freddie Mac Co-Borr % of Business Owned [CASASRN.X177] /// </summary> public int? PersonPercentOfBusinessOwned2 { get => _personPercentOfBusinessOwned2; set => SetField(ref _personPercentOfBusinessOwned2, value); } /// <summary> /// Freddie Mac MI Premium Source [CASASRN.X158] /// </summary> public StringEnumValue<PremiumSource> PremiumSource { get => _premiumSource; set => SetField(ref _premiumSource, value); } /// <summary> /// Freddie Mac Total Present Housing Expense [CASASRN.X16] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? PresentHousingExpense { get => _presentHousingExpense; set => SetField(ref _presentHousingExpense, value); } /// <summary> /// Freddie Mac Lender Processing Point [CASASRN.X107] /// </summary> public StringEnumValue<ProcessingPoint> ProcessingPoint { get => _processingPoint; set => SetField(ref _processingPoint, value); } /// <summary> /// Freddie Mac Lender Property Type [CASASRN.X14] /// </summary> public StringEnumValue<FreddieMacPropertyType> PropertyType { get => _propertyType; set => SetField(ref _propertyType, value); } /// <summary> /// Freddie Mac Lender Loan Purpose [CASASRN.X29] /// </summary> public StringEnumValue<FreddieMacPurposeOfLoan> PurposeOfLoan { get => _purposeOfLoan; set => SetField(ref _purposeOfLoan, value); } /// <summary> /// Freddie Mac MI Renewal Option [CASASRN.X150] /// </summary> public StringEnumValue<RenewalOption> RenewalOption { get => _renewalOption; set => SetField(ref _renewalOption, value); } /// <summary> /// Freddie Mac MI Renewal Type [CASASRN.X148] /// </summary> public StringEnumValue<RenewalType> RenewalType { get => _renewalType; set => SetField(ref _renewalType, value); } /// <summary> /// Freddie Mac Lender Requiredd Doc Type [CASASRN.X144] /// </summary> public StringEnumValue<RequiredDocumentType> RequiredDocumentType { get => _requiredDocumentType; set => SetField(ref _requiredDocumentType, value); } /// <summary> /// Freddie Mac Total Reserves [CASASRN.X78] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? Reserves { get => _reserves; set => SetField(ref _reserves, value); } /// <summary> /// Freddie Mac Lender Retail Loan [CASASRN.X77] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Retail loan\"}")] public bool? RetailLoanIndicator { get => _retailLoanIndicator; set => SetField(ref _retailLoanIndicator, value); } /// <summary> /// Freddie Mac Risk Class [CASASRN.X98] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<FreddieMacRiskClass> RiskClass { get => _riskClass; set => SetField(ref _riskClass, value); } /// <summary> /// Freddie Mac Order Risk Grade Eval Source [CASASRN.X173] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<RiskGradeEvaluationType> RiskGradeEvaluationType { get => _riskGradeEvaluationType; set => SetField(ref _riskGradeEvaluationType, value); } /// <summary> /// Freddie Mac Lender Sales Concessions [CASASRN.X19] /// </summary> public decimal? SalesConcessions { get => _salesConcessions; set => SetField(ref _salesConcessions, value); } /// <summary> /// Freddie Mac Lender Secondary Finance [CASASRN.X112] /// </summary> public StringEnumValue<SecondaryFinancingType> SecondaryFinancingType { get => _secondaryFinancingType; set => SetField(ref _secondaryFinancingType, value); } /// <summary> /// Freddie Mac Lender 2nd Trust Pd on Closing [CASASRN.X30] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Second Trust Paid on closing\"}")] public bool? SecondTrustRefiIndicator { get => _secondTrustRefiIndicator; set => SetField(ref _secondTrustRefiIndicator, value); } /// <summary> /// Freddie Mac Lender Simulated PITI [CASASRN.X15] /// </summary> public decimal? SimulatedPITI { get => _simulatedPITI; set => SetField(ref _simulatedPITI, value); } /// <summary> /// Freddie Mac FHA/VA Info Houshld Size [CASASRN.X145] /// </summary> public string? SizeOfHousehold { get => _sizeOfHousehold; set => SetField(ref _sizeOfHousehold, value); } /// <summary> /// Freddie Mac Special Instructions 1 [CASASRN.X100] /// </summary> public string? SpecialInstruction1 { get => _specialInstruction1; set => SetField(ref _specialInstruction1, value); } /// <summary> /// Freddie Mac Special Instructions 2 [CASASRN.X101] /// </summary> public string? SpecialInstruction2 { get => _specialInstruction2; set => SetField(ref _specialInstruction2, value); } /// <summary> /// Freddie Mac Special Instructions 3 [CASASRN.X102] /// </summary> public string? SpecialInstruction3 { get => _specialInstruction3; set => SetField(ref _specialInstruction3, value); } /// <summary> /// Freddie Mac Special Instructions 4 [CASASRN.X103] /// </summary> public string? SpecialInstruction4 { get => _specialInstruction4; set => SetField(ref _specialInstruction4, value); } /// <summary> /// Freddie Mac Special Instructions 5 [CASASRN.X104] /// </summary> public string? SpecialInstruction5 { get => _specialInstruction5; set => SetField(ref _specialInstruction5, value); } /// <summary> /// Freddie Mac Lender APN State [CASASRN.X18] /// </summary> public string? State { get => _state; set => SetField(ref _state, value); } /// <summary> /// Freddie Mac Transfer Loan to Conduit [CASASRN.X10] /// </summary> [LoanFieldProperty(ReadOnly = true, OptionsJson = "{\"Y\":\"Transfer Loan to Conduit\"}")] public bool? TransferLoanToConduitIndicator { get => _transferLoanToConduitIndicator; set => SetField(ref _transferLoanToConduitIndicator, value); } /// <summary> /// Freddie Mac MI Yrs Coverage [CASASRN.X156] /// </summary> public StringEnumValue<YearsOfCoverage> YearsOfCoverage { get => _yearsOfCoverage; set => SetField(ref _yearsOfCoverage, value); } } }
// // AudioFile.cs: // // Authors: // Miguel de Icaza ([email protected]) // // Copyright 2009 Novell, Inc // Copyright 2011, 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.CoreFoundation; using OSStatus = System.Int32; using AudioFileStreamID = System.IntPtr; namespace MonoMac.AudioToolbox { [Flags] public enum AudioFileStreamPropertyFlag { PropertyIsCached = 1, CacheProperty = 2, } public enum AudioFileStreamStatus { Ok = 0, UnsupportedFileType=0x7479703f, UnsupportedDataFormat=0x666d743f, UnsupportedProperty=0x7074793f, BadPropertySize=0x2173697a, NotOptimized=0x6f70746d, InvalidPacketOffset=0x70636b3f, InvalidFile=0x6474613f, ValueUnknown=0x756e6b3f, DataUnavailable=0x6d6f7265, IllegalOperation=0x6e6f7065, UnspecifiedError=0x7768743f, DiscontinuityCantRecover=0x64736321, } public enum AudioFileStreamProperty { ReadyToProducePackets=0x72656479, FileFormat=0x66666d74, DataFormat=0x64666d74, FormatList=0x666c7374, MagicCookieData=0x6d676963, AudioDataByteCount=0x62636e74, AudioDataPacketCount=0x70636e74, MaximumPacketSize=0x70737a65, DataOffset=0x646f6666, ChannelLayout=0x636d6170, PacketToFrame=0x706b6672, FrameToPacket=0x6672706b, PacketToByte=0x706b6279, ByteToPacket=0x6279706b, PacketTableInfo=0x706e666f, PacketSizeUpperBound=0x706b7562, AverageBytesPerPacket=0x61627070, BitRate=0x62726174 } public class PropertyFoundEventArgs : EventArgs { public PropertyFoundEventArgs (AudioFileStreamProperty propertyID, AudioFileStreamPropertyFlag ioFlags) { Property = propertyID; Flags = ioFlags; } public AudioFileStreamProperty Property { get; private set; } public AudioFileStreamPropertyFlag Flags { get; set; } public override string ToString () { return String.Format ("AudioFileStreamProperty ({0})", Property); } } public class PacketReceivedEventArgs : EventArgs { public PacketReceivedEventArgs (int numberOfBytes, IntPtr inputData, AudioStreamPacketDescription [] packetDescriptions) { this.Bytes = numberOfBytes; this.InputData = inputData; this.PacketDescriptions = packetDescriptions; } public int Bytes { get; private set; } public IntPtr InputData { get; private set; } public AudioStreamPacketDescription [] PacketDescriptions { get; private set;} public override string ToString () { return String.Format ("Packet (Bytes={0} InputData={1} PacketDescriptions={2}", Bytes, InputData, PacketDescriptions.Length); } } public class AudioFileStream : IDisposable { IntPtr handle; GCHandle gch; ~AudioFileStream () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public void Close () { Dispose (); } protected virtual void Dispose (bool disposing) { if (disposing){ if (gch.IsAllocated) gch.Free (); } if (handle != IntPtr.Zero){ AudioFileStreamClose (handle); handle = IntPtr.Zero; } } delegate void AudioFileStream_PropertyListenerProc(IntPtr clientData, AudioFileStreamID audioFileStream, AudioFileStreamProperty propertyID, ref AudioFileStreamPropertyFlag ioFlags); delegate void AudioFileStream_PacketsProc (IntPtr clientData, int numberBytes, int numberPackets, IntPtr inputData, IntPtr packetDescriptions); [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamOpen ( IntPtr clientData, AudioFileStream_PropertyListenerProc propertyListenerProc, AudioFileStream_PacketsProc packetsProc, AudioFileType fileTypeHint, out IntPtr file_id); static AudioFileStream_PacketsProc dInPackets; static AudioFileStream_PropertyListenerProc dPropertyListener; static AudioFileStream () { dInPackets = InPackets; dPropertyListener = PropertyListener; } [MonoPInvokeCallback(typeof(AudioFileStream_PacketsProc))] static void InPackets (IntPtr clientData, int numberBytes, int numberPackets, IntPtr inputData, IntPtr packetDescriptions) { GCHandle handle = GCHandle.FromIntPtr (clientData); var afs = handle.Target as AudioFileStream; var desc = AudioFile.PacketDescriptionFrom (numberPackets, packetDescriptions); afs.OnPacketDecoded (numberBytes, inputData, desc); } public EventHandler<PacketReceivedEventArgs> PacketDecoded; protected virtual void OnPacketDecoded (int numberOfBytes, IntPtr inputData, AudioStreamPacketDescription [] packetDescriptions) { var p = PacketDecoded; if (p != null) p (this, new PacketReceivedEventArgs (numberOfBytes, inputData, packetDescriptions)); } public EventHandler<PropertyFoundEventArgs> PropertyFound; protected virtual void OnPropertyFound (AudioFileStreamProperty propertyID, ref AudioFileStreamPropertyFlag ioFlags) { var p = PropertyFound; if (p != null){ var pf = new PropertyFoundEventArgs (propertyID, ioFlags); p (this, pf); ioFlags = pf.Flags; } } [MonoPInvokeCallback(typeof(AudioFileStream_PropertyListenerProc))] static void PropertyListener (IntPtr clientData, AudioFileStreamID audioFileStream, AudioFileStreamProperty propertyID, ref AudioFileStreamPropertyFlag ioFlags) { GCHandle handle = GCHandle.FromIntPtr (clientData); var afs = handle.Target as AudioFileStream; afs.OnPropertyFound (propertyID, ref ioFlags); } public AudioFileStream (AudioFileType fileTypeHint) { IntPtr h; gch = GCHandle.Alloc (this); var code = AudioFileStreamOpen (GCHandle.ToIntPtr (gch), dPropertyListener, dInPackets, fileTypeHint, out h); if (code == 0){ handle = h; return; } throw new Exception (String.Format ("Unable to create AudioFileStream, code: 0x{0:x}", code)); } [DllImport (Constants.AudioToolboxLibrary)] extern static AudioFileStreamStatus AudioFileStreamParseBytes ( AudioFileStreamID inAudioFileStream, int inDataByteSize, IntPtr inData, UInt32 inFlags); public AudioFileStreamStatus ParseBytes (int size, IntPtr data, bool discontinuity) { return AudioFileStreamParseBytes (handle, size, data, discontinuity ? (uint) 1 : (uint) 0); } public AudioFileStreamStatus ParseBytes (byte [] bytes, bool discontinuity) { if (bytes == null) throw new ArgumentNullException ("bytes"); unsafe { fixed (byte *bp = &bytes[0]){ return AudioFileStreamParseBytes (handle, bytes.Length, (IntPtr) bp, discontinuity ? (uint) 1 : (uint) 0); } } } public AudioFileStreamStatus ParseBytes (byte [] bytes, int offset, int count, bool discontinuity) { if (bytes == null) throw new ArgumentNullException ("bytes"); if (offset < 0) throw new ArgumentException ("offset"); if (count < 0) throw new ArgumentException ("count"); if (offset+count > bytes.Length) throw new ArgumentException ("offset+count"); unsafe { fixed (byte *bp = &bytes[0]){ return AudioFileStreamParseBytes (handle, count, (IntPtr) (bp + offset) , discontinuity ? (uint) 1 : (uint) 0); } } } [DllImport (Constants.AudioToolboxLibrary)] extern static AudioFileStreamStatus AudioFileStreamSeek(AudioFileStreamID inAudioFileStream, long inPacketOffset, out long outDataByteOffset, ref int ioFlags); public AudioFileStreamStatus Seek (long packetOffset, out long dataByteOffset, out bool isEstimate) { int v = 0; var code = AudioFileStreamSeek (handle, packetOffset, out dataByteOffset, ref v); if (code != AudioFileStreamStatus.Ok){ isEstimate = false; return code; } isEstimate = (v & 1) == 1; return code; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamGetPropertyInfo( AudioFileStreamID inAudioFileStream, AudioFileStreamProperty inPropertyID, out int outPropertyDataSize, out int isWritable); [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamGetProperty( AudioFileStreamID inAudioFileStream, AudioFileStreamProperty inPropertyID, ref int ioPropertyDataSize, IntPtr outPropertyData); public bool GetProperty (AudioFileStreamProperty property, ref int dataSize, IntPtr outPropertyData) { return AudioFileStreamGetProperty (handle, property, ref dataSize, outPropertyData) == 0; } public IntPtr GetProperty (AudioFileStreamProperty property, out int size) { int writable; var r = AudioFileStreamGetPropertyInfo (handle, property, out size, out writable); if (r != 0) return IntPtr.Zero; var buffer = Marshal.AllocHGlobal (size); if (buffer == IntPtr.Zero) return IntPtr.Zero; r = AudioFileStreamGetProperty (handle, property, ref size, buffer); if (r == 0) return buffer; Marshal.FreeHGlobal (buffer); return IntPtr.Zero; } int GetInt (AudioFileStreamProperty property) { unsafe { int val = 0; int size = 4; if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } double GetDouble (AudioFileStreamProperty property) { unsafe { double val = 0; int size = 8; if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } long GetLong (AudioFileStreamProperty property) { unsafe { long val = 0; int size = 8; if (AudioFileStreamGetProperty (handle, property, ref size, (IntPtr) (&val)) == 0) return val; return 0; } } T? GetProperty<T> (AudioFileStreamProperty property) where T : struct { int size, writable; if (AudioFileStreamGetPropertyInfo (handle, property, out size, out writable) != 0) return null; var buffer = Marshal.AllocHGlobal (size); if (buffer == IntPtr.Zero) return null; try { var r = AudioFileStreamGetProperty (handle, property, ref size, buffer); if (r == 0) return (T) Marshal.PtrToStructure (buffer, typeof (T)); return null; } finally { Marshal.FreeHGlobal (buffer); } } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamSetProperty( AudioFileStreamID inAudioFileStream, AudioFileStreamProperty inPropertyID, int inPropertyDataSize, IntPtr inPropertyData); public bool SetProperty (AudioFileStreamProperty property, int dataSize, IntPtr propertyData) { return AudioFileStreamSetProperty (handle, property, dataSize, propertyData) == 0; } [DllImport (Constants.AudioToolboxLibrary)] extern static OSStatus AudioFileStreamClose(AudioFileStreamID inAudioFileStream); public bool ReadyToProducePackets { get { return GetInt (AudioFileStreamProperty.ReadyToProducePackets) == 1; } } public AudioFileType FileType { get { return (AudioFileType) GetInt (AudioFileStreamProperty.FileFormat); } } [Obsolete ("Use DataFormat")] public AudioStreamBasicDescription StreamBasicDescription { get { return DataFormat; } } public AudioStreamBasicDescription DataFormat { get { return GetProperty<AudioStreamBasicDescription> (AudioFileStreamProperty.DataFormat) ?? default (AudioStreamBasicDescription); } } public unsafe AudioFormat [] FormatList { get { int size; var r = GetProperty (AudioFileStreamProperty.FormatList, out size); var records = (AudioFormat *) r; if (r == IntPtr.Zero) return null; int itemSize = sizeof (AudioFormat); int items = size/itemSize; var ret = new AudioFormat [items]; for (int i = 0; i < items; i++) ret [i] = records [i]; Marshal.FreeHGlobal (r); return ret; } } public AudioFilePacketTableInfo? PacketTableInfo { get { return GetProperty<AudioFilePacketTableInfo> (AudioFileStreamProperty.PacketTableInfo); } } public byte [] MagicCookie { get { int size; var h = GetProperty (AudioFileStreamProperty.MagicCookieData, out size); if (h == IntPtr.Zero) return new byte [0]; byte [] cookie = new byte [size]; for (int i = 0; i < cookie.Length; i++) cookie [i] = Marshal.ReadByte (h, i); Marshal.FreeHGlobal (h); return cookie; } } public long DataByteCount { get { return GetLong (AudioFileStreamProperty.AudioDataByteCount); } } public long DataPacketCount { get { return GetLong (AudioFileStreamProperty.AudioDataPacketCount); } } public int MaximumPacketSize { get { return GetInt (AudioFileStreamProperty.MaximumPacketSize); } } public long DataOffset { get { return GetLong (AudioFileStreamProperty.DataOffset); } } public AudioChannelLayout ChannelLayout { get { int size; var h = GetProperty (AudioFileStreamProperty.ChannelLayout, out size); if (h == IntPtr.Zero) return null; var layout = AudioChannelLayout.FromHandle (h); Marshal.FreeHGlobal (h); return layout; } } public long PacketToFrame (long packet) { AudioFramePacketTranslation buffer; buffer.Packet = packet; unsafe { AudioFramePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToFrame, ref size, (IntPtr) p) == 0) return buffer.Frame; return -1; } } public long FrameToPacket (long frame, out int frameOffsetInPacket) { AudioFramePacketTranslation buffer; buffer.Frame = frame; unsafe { AudioFramePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.FrameToPacket, ref size, (IntPtr) p) == 0){ frameOffsetInPacket = buffer.FrameOffsetInPacket; return buffer.Packet; } frameOffsetInPacket = 0; return -1; } } public long PacketToByte (long packet, out bool isEstimate) { AudioBytePacketTranslation buffer; buffer.Packet = packet; unsafe { AudioBytePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.PacketToByte, ref size, (IntPtr) p) == 0){ isEstimate = (buffer.Flags & BytePacketTranslationFlags.IsEstimate) != 0; return buffer.Byte; } isEstimate = false; return -1; } } public long ByteToPacket (long byteval, out int byteOffsetInPacket, out bool isEstimate) { AudioBytePacketTranslation buffer; buffer.Byte = byteval; unsafe { AudioBytePacketTranslation *p = &buffer; int size = Marshal.SizeOf (buffer); if (AudioFileStreamGetProperty (handle, AudioFileStreamProperty.ByteToPacket, ref size, (IntPtr) p) == 0){ isEstimate = (buffer.Flags & BytePacketTranslationFlags.IsEstimate) != 0; byteOffsetInPacket = buffer.ByteOffsetInPacket; return buffer.Packet; } byteOffsetInPacket = 0; isEstimate = false; return -1; } } public int BitRate { get { return GetInt (AudioFileStreamProperty.BitRate); } } public int PacketSizeUpperBound { get { return GetInt (AudioFileStreamProperty.PacketSizeUpperBound); } } public double AverageBytesPerPacket { get { return GetDouble (AudioFileStreamProperty.AverageBytesPerPacket); } } } }
using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using CavemanTools; namespace System { public static class TypeExtensions { /// <summary> /// Orders an enumerable using [Order] or specified ordering function. /// </summary> /// <param name="types"></param> /// <param name="other">Optional ascending ordering function</param> /// <returns></returns> public static IEnumerable<Type> OrderByAttribute(this IEnumerable<Type> types,Func<Type,int> other=null) { return types.OrderBy(t => { var attrib = t.GetSingleAttribute<OrderAttribute>(); if (attrib != null) { return attrib.Value; } if (other != null) { return other(t); } return Int32.MaxValue; }); } /// <summary> /// Usually get properties returns first the properties declared on the type, then properties declared on the base types. /// This method will return properties as you expect it /// </summary> /// <param name="tp"></param> /// <returns></returns> public static IEnumerable<PropertyInfo> GetPropertiesInOrder(this Type tp) { return GetPropertiesInOrder(tp, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); } /// <summary> /// Usually get properties returns first the properties declared on the type, then properties declared on the base types. /// This method will return properties as you expect it /// </summary> /// <param name="tp"></param> /// <returns></returns> public static IEnumerable<PropertyInfo> GetPropertiesInOrder(this Type tp,BindingFlags flags) { var props = new List<PropertyInfo>(); var baseTP = tp; while (baseTP != null) { props.AddRange(baseTP.GetProperties(flags).Select(d => tp.GetProperties().First(f => f.Name == d.Name)).Reverse()); baseTP = baseTP.GetTypeInfo().BaseType; } props.Reverse(); return props.Distinct(); } /// <summary> /// Orders an enumerable using [Order] /// </summary> /// <param name="objects"></param> /// <param name="defValue">Default value if the attribute is missing</param> /// <returns></returns> public static IEnumerable<T> OrderByAttribute<T>(this IEnumerable<T> objects,int defValue=0) { return objects.OrderBy(t => { var tp=(t is Type)?t as Type:t.GetType(); var attrib = tp.GetSingleAttribute<OrderAttribute>(); if (attrib != null) { return attrib.Value; } return defValue; }); } /// <summary> /// Used for checking if a class implements an interface /// </summary> /// <typeparam name="T">Interface</typeparam> /// <param name="type">Class Implementing the interface</param> /// <returns></returns> public static bool Implements<T>(this Type type) { type.MustNotBeNull(); return type.Implements(typeof (T)); } /// <summary> /// Creates a new instance of type using a public parameterless constructor /// </summary> /// <param name="type"></param> /// <returns></returns> public static object CreateInstance(this Type type) { type.MustNotBeNull(); return type.GetFactory()(); } /// <summary> /// Used for checking if a class implements an interface /// </summary> /// <param name="type">Class Implementing the interface</param> /// <param name="interfaceType">Type of an interface</param> /// <returns></returns> public static bool Implements(this Type type,Type interfaceType) { type.MustNotBeNull(); interfaceType.MustNotBeNull(); if (!interfaceType.GetTypeInfo().IsInterface) throw new ArgumentException("The generic type '{0}' is not an interface".ToFormat(interfaceType)); return interfaceType.IsAssignableFrom(type); } /// <summary> /// True if the type implements of extends T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <returns></returns> public static bool DerivesFrom<T>(this Type type) { return type.DerivesFrom(typeof (T)); } /// <summary> /// True if the type implements of extends parent. /// Doesn't work with generics /// </summary> /// <param name="type"></param> /// <param name="parent"></param> /// <returns></returns> public static bool DerivesFrom(this Type type, Type parent) { type.MustNotBeNull(); parent.MustNotBeNull(); return parent.IsAssignableFrom(type); } public static bool CheckIfAnonymousType(this Type type) { if (type == null) throw new ArgumentNullException("type"); var info = type.GetTypeInfo(); return info.HasCustomAttribute<CompilerGeneratedAttribute>() && info.IsGenericType && type.Name.Contains("AnonymousType") && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$")) && (info.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic; } public static bool ImplementsGenericInterfaceOf<T>(this Type type, params Type[] genericArgs) { return type.ImplementsGenericInterface(typeof (T), genericArgs); } /// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="genericInterfaceType">It can be an open or close generics interface</param> /// <returns></returns> public static bool ImplementsGenericInterface(this Type type, Type genericInterfaceType,params Type[] genericArgs) { var interf = type.GetInterfaces().Where(t => t.Name == genericInterfaceType.Name).ToArray(); if (interf.IsNullOrEmpty()) return false; return interf.Any(i => { var comparer = genericInterfaceType.GenericTypeArguments().Any() ? genericInterfaceType.GenericTypeArguments() : genericArgs; if (comparer.Length > 0) { return i.GenericTypeArguments().HasTheSameElementsAs(comparer); } return true; }); } public static bool InheritsGenericType(this Type tp, Type genericType, params Type[] genericArgs) { tp.MustNotBeNull(); var info = tp.GetTypeInfo(); genericType.GetTypeInfo().Must(t => t.IsGenericType, "Type must be a generic type"); if (info.BaseType == null) return false; var baseType = info.BaseType; var baseInfo = info.BaseType.GetTypeInfo(); bool found = false; if (baseInfo.IsGenericType) { if (baseInfo.Name == genericType.Name) { var comparer = genericType.GenericTypeArguments().Any() ? genericType.GenericTypeArguments() : genericArgs; if (comparer.Length > 0) { found = baseType.GenericTypeArguments().HasTheSameElementsAs(comparer); } else { return true; } } } if (!found) return baseType.InheritsGenericType(genericType); return true; } /// <summary> /// /// </summary> /// <param name="tp">Generic type</param> /// <param name="index">0 based index of the generic argument</param> /// <exception cref="InvalidOperationException">When the type is not generic</exception> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <returns></returns> public static Type GetGenericArgument(this Type tp, int index = 0) { tp.MustNotBeNull(); if (!tp.GetTypeInfo().IsGenericType) throw new InvalidOperationException("Provided type is not generic"); return tp.GenericTypeArguments()[index]; } static Type[] GenericTypeArguments(this Type type) { type.MustBeGeneric(); return type.GenericTypeArguments; } /// <summary> /// Checks if type is a reference but also not /// a string, array, Nullable, enum /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsUserDefinedClass(this Type type) { type.MustNotBeNull(); var info = type.GetTypeInfo(); if (!info.IsClass) return false; if (type.GetTypeCode() != TypeCode.Object) return false; if (type.IsArray) return false; if (type.IsNullable()) return false; return true; } public static TypeCode GetTypeCode(this Type type) { if (type == null) return TypeCode.Empty; if (type == typeof(bool)) return TypeCode.Boolean; if (type == typeof(char)) return TypeCode.Char; if (type == typeof(sbyte)) return TypeCode.SByte; if (type == typeof(byte)) return TypeCode.Byte; if (type == typeof(short)) return TypeCode.Int16; if (type == typeof(ushort)) return TypeCode.UInt16; if (type == typeof(int)) return TypeCode.Int32; if (type == typeof(uint)) return TypeCode.UInt32; if (type == typeof(long)) return TypeCode.Int64; if (type == typeof(ulong)) return TypeCode.UInt64; if (type == typeof(float)) return TypeCode.Single; if (type == typeof(double)) return TypeCode.Double; if (type == typeof(decimal)) return TypeCode.Decimal; if (type == typeof(DateTime)) return TypeCode.DateTime; if (type == typeof(string)) return TypeCode.String; if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return TypeCode.Object; } /// <summary> /// This always returns false if the type is taken from an instance. /// That is always use typeof /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsNullable(this Type type) { type.MustNotBeNull(); return (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>)); } public static bool IsNullableOf(this Type type, Type other) { type.MustNotBeNull(); other.MustNotBeNull(); return type.IsNullable() && type.GetGenericArguments()[0].Equals(other); } public static bool IsNullableOf<T>(this Type type) { return type.IsNullableOf(typeof (T)); } public static bool CanBeCastTo<T>(this Type type) { if (type == null) return false; return CanBeCastTo(type, typeof(T)); } public static bool CanBeInstantiated(this Type type) { var info = type.GetTypeInfo(); return !info.IsAbstract && !info.IsInterface; } public static bool CanBeCastTo(this Type type, Type other) { if (type == null) return false; if (type == other) return true; return other.IsAssignableFrom(type); } /// <summary> /// Returns the version of assembly containing type /// </summary> /// <returns></returns> public static Version AssemblyVersion(this Type tp) => tp.GetTypeInfo().Assembly.Version(); /// <summary> /// Returns the full name of type, including assembly but not version, public key etc, i.e: namespace.type, assembly /// </summary> /// <param name="t">Type</param> /// <returns></returns> public static string GetFullTypeName(this Type t) { if (t == null) throw new ArgumentNullException("t"); return $"{t.FullName}, {t.Assembly.GetName().Name}"; } public static object GetDefault(this Type type) { if (type.GetTypeInfo().IsValueType) return Activator.CreateInstance(type); return null; } /// <summary> /// Returns namespace without the assembly name /// </summary> /// <param name="type"></param> /// <returns></returns> public static string StripNamespaceAssemblyName(this Type type) { var asmName = type.GetTypeInfo().Assembly.GetName().Name; return type.Namespace.Substring(asmName.Length + 1); } } }
#region MIT License /* MIT License Copyright (c) 2018-2019 Darin Higgins Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using Microsoft.Build.Evaluation; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace GenerateLineMap.MsBuild.Task { // project properties // http://stackoverflow.com/questions/2772426/how-to-access-the-msbuild-s-properties-list-when-coding-a-custom-task // dependencies // http://stackoverflow.com/questions/8849289/get-dependent-assemblies public class GenerateLineMapTask : Microsoft.Build.Utilities.Task { #region Public Properties (These are supplied by MSBuild, see the .targets files) [Required] public string SolutionDir { get; set; } public string SolutionPath { get; set; } [Required] public string ProjectDir { get; set; } public string ProjectFileName { get; set; } public string ProjectPath { get; set; } public string TargetDir { get; set; } public string TargetPath { get; set; } [Required] public string TargetFileName { get; set; } public virtual ITaskItem[] InputAssemblies { get; set; } public string TargetFrameworkVersion { get; set; } public string TargetArchitecture { get; set; } public string KeyFile { get; set; } [Required] public string ConfigurationFilePath { get; set; } #endregion #region Constructors public GenerateLineMapTask() { this.InputAssemblies = new ITaskItem[0]; } #endregion #region Public Methods /// <summary> /// This actual Generation of the LineMap is performed here /// </summary> /// <returns></returns> public override bool Execute() { LogInputVariables(); string jsonConfig; string exePath; Settings settings = null; // try to read configuration if file exists if (!ReadConfigFile(out jsonConfig)) return false; // replace tokens if applicable if (!string.IsNullOrWhiteSpace(jsonConfig)) { jsonConfig = ReplaceTokens(jsonConfig); } // if json config exists, try to deserialize into settings object if (!string.IsNullOrWhiteSpace(jsonConfig) && !DeserializeJsonConfig(jsonConfig, out settings)) { return false; } // create instance if settings still null which indicates a custom json config was not used settings = settings ?? new Settings(); // apply defaults SetDefaults(settings); if (settings.General.AlternativeGenerateLineMapPath.IsNotNullOrWhiteSpace()) { if (!File.Exists(settings.General.AlternativeGenerateLineMapPath)) { Log.LogError($"An alternative path for GenerateLineMap.exe was provided but the file was not found: {settings.General.AlternativeGenerateLineMapPath}"); return false; } else { exePath = settings.General.AlternativeGenerateLineMapPath; Log.LogMessage("Using alternative GenerateLineMap path: {0}", settings.General.AlternativeGenerateLineMapPath); } } else { exePath = this.GetGenerateLineMapPath(); } return GenerateLineMapBasedOn(settings); } #endregion #region Private Methods private void LogInputVariables() { Log.LogMessage($"SolutionDir: {SolutionDir}"); Log.LogMessage($"SolutionPath: {SolutionPath}"); Log.LogMessage($"ProjectDir: {ProjectDir}"); Log.LogMessage($"ProjectFileName: {ProjectFileName}"); Log.LogMessage($"ProjectPath: {ProjectPath}"); Log.LogMessage($"TargetDir: {TargetDir}"); Log.LogMessage($"TargetPath: {TargetPath}"); Log.LogMessage($"TargetFileName: {TargetFileName}"); Log.LogMessage($"TargetFrameworkVersion: {TargetFrameworkVersion}"); Log.LogMessage($"TargetArchitecture: {TargetArchitecture}"); Log.LogMessage($"KeyFile: {KeyFile}"); Log.LogMessage($"ConfigurationFilePath: {ConfigurationFilePath}"); } private bool DeserializeJsonConfig(string jsonConfig, out Settings settings) { settings = null; bool success = true; if (string.IsNullOrWhiteSpace(jsonConfig)) { Log.LogError("Unable to deserialize configuration. Configuration string is null or empty."); return false; } try { Log.LogMessage("Deserializing configuration."); settings = Settings.FromJson(jsonConfig); Log.LogMessage("Configuration file deserialized successfully."); } catch (Exception ex) { Log.LogError("Error deserializing configuration."); Log.LogErrorFromException(ex); success = false; } return success; } private string ReplaceTokens(string jsonConfig) { return jsonConfig .Replace("$(SolutionDir)", EscapePath(this.SolutionDir)) .Replace("$(SolutionPath)", EscapePath(this.SolutionPath)) .Replace("$(ProjectDir)", EscapePath(this.ProjectDir)) .Replace("$(ProjectFileName)", EscapePath(this.ProjectFileName)) .Replace("$(ProjectPath)", EscapePath(this.ProjectPath)) .Replace("$(TargetDir)", EscapePath(this.TargetDir)) .Replace("$(TargetPath)", EscapePath(this.TargetPath)) .Replace("$(TargetFileName)", EscapePath(this.TargetFileName)) .Replace("$(AssemblyOriginatorKeyFile)", EscapePath(this.KeyFile)); } private void SetDefaults(Settings settings) { if (settings.IsNull()) throw new ArgumentNullException(nameof(settings)); settings.General = settings.General ?? new GeneralSettings(); settings.Advanced = settings.Advanced ?? new AdvancedSettings(); //Not using persistent settings right now. Eventually... //if (settings.General.OutputFile.IsNullOrWhiteSpace()) //{ // settings.General.OutputFile = Path.Combine(this.TargetDir, "GenerateLineMap", this.TargetFileName); // Log.LogMessage("Applying default value for OutputFile."); //} } private bool GenerateLineMapBasedOn(Settings settings) { Log.LogMessage("Setting up GenerateLineMap."); bool success = true; //for debugging //Assembly ilmerge = LoadILMerge(mergerPath); //Type ilmergeType = ilmerge.GetType("ILMerging.ILMerge", true, true); //if (ilmergeType.IsNull()) throw new InvalidOperationException("Cannot find 'ILMerging.ILMerge' in executable."); //string[] tp = settings.General.TargetPlatform.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); try { //Not using these settings right now //string outputDir = Path.GetDirectoryName(settings.General.OutputFile); //if (!Directory.Exists(outputDir)) //{ // Log.LogWarning($"Output directory not found. An attempt to create the directory will be made: {outputDir}"); // Directory.CreateDirectory(outputDir); // Log.LogMessage("Output directory created."); //} var outfile = string.Format("/out:\"{0}\"", this.TargetPath); var cmdline = string.Format("GenerateLineMap {0} {1}", outfile, this.TargetPath); Log.LogMessage("Effectively executing command line: " + cmdline); //pass on our MSBuild logger to let GenerateLineMap use it GenerateLineMap.Program.MSBuildLogger = Log; //and actually perform the line map generation GenerateLineMap.Program.Main(new string[] { "{ignoredpathargument}", outfile, this.TargetPath }); //TODO Eventually support fix ups to replace any strong name and signing that had been performed //if (merger.StrongNameLost) // Log.LogMessage(MessageImportance.High, "StrongNameLost = true"); } catch (Exception exception) { Log.LogErrorFromException(exception); success = false; } return success; } private bool ReadConfigFile(out string jsonConfig) { jsonConfig = string.Empty; bool success = true; if (string.IsNullOrWhiteSpace(ConfigurationFilePath)) { Log.LogWarning("Path for configuration file is empty. Default values will be applied."); } else { if (!File.Exists(ConfigurationFilePath)) { Log.LogMessage($"Using default configuration. A custom configuration file was not found at: {ConfigurationFilePath}"); } else { try { Log.LogMessage($"Loading configuration from: {ConfigurationFilePath}"); jsonConfig = File.ReadAllText(ConfigurationFilePath, Encoding.UTF8); Log.LogMessage($"Configuration file loaded successfully."); } catch (Exception ex) { Log.LogError($"Error reading configuration file."); Log.LogErrorFromException(ex); success = false; } } } return success; } public string GetGenerateLineMapPath() { string exePath = null; string errMsg; var failedPaths = new List<string>(); // look at same directory as this assembly (task dll); if (ExeLocationHelper.TryValidateGenerateLineMapPath(Path.GetDirectoryName(this.GetType().Assembly.Location), out exePath)) { Log.LogMessage($"GenerateLineMap.exe found at (task location): {Path.GetDirectoryName(this.GetType().Assembly.Location)}"); return exePath; } errMsg = $"GenerateLineMap.exe not found at (task location): {Path.GetDirectoryName(this.GetType().Assembly.Location)}"; failedPaths.Add(errMsg); Log.LogMessage(errMsg); // look at target dir; if (!string.IsNullOrWhiteSpace(TargetDir)) { if (ExeLocationHelper.TryValidateGenerateLineMapPath(this.TargetDir, out exePath)) { Log.LogMessage($"GenerateLineMap.exe found at (target dir): {this.TargetDir}"); return exePath; } errMsg = $"GenerateLineMap.exe not found at (target dir): {this.TargetDir}"; failedPaths.Add(errMsg); Log.LogMessage(errMsg); } // look for "packages" folder at the solution root and if one is found, look for DotNetLineNumbers package folder if (!string.IsNullOrWhiteSpace(this.SolutionDir)) { if (ExeLocationHelper.TryGenerateLineMapInSolutionDir(this.SolutionDir, out exePath)) { Log.LogMessage($"GenerateLineMap.exe found at (solution dir): {this.SolutionDir}"); return exePath; } errMsg = $"GenerateLineMap.exe not found at (solution dir): {this.SolutionDir}"; failedPaths.Add(errMsg); Log.LogMessage(errMsg); } // get the location of the this assembly (task dll) and assumes it is under the packages folder. // use this information to determine the possible location of the executable. if (ExeLocationHelper.TryLocatePackagesFolder(Log, out exePath)) { Log.LogMessage($"GenerateLineMap.exe found at custom package location: {exePath}"); return exePath; } foreach (var err in failedPaths) { Log.LogWarning(err); } Log.LogWarning($"Unable to determine custom package location or, location was determined but a DotNetLineNumbers package folder was not found."); return exePath; } private string ToAbsolutePath(string relativePath) { // if path is not rooted assume it is relative. // convert relative to absolute using project dir as root. if (string.IsNullOrWhiteSpace(relativePath)) throw new ArgumentNullException(relativePath); if (Path.IsPathRooted(relativePath)) { return relativePath; } return Path.GetFullPath(Path.Combine(ProjectDir, relativePath)); } private string EscapePath(string path) { return Regex.Replace(path ?? "", @"\\", @"\\"); } #endregion } }
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Generic; using System.Text; using Antlr4.Runtime; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime { /// <summary> /// This implementation of /// <see cref="ITokenStream"/> /// loads tokens from a /// <see cref="ITokenSource"/> /// on-demand, and places the tokens in a buffer to provide /// access to any previous token by index. /// <p> /// This token stream ignores the value of /// <see cref="IToken.Channel()"/> /// . If your /// parser requires the token stream filter tokens to only those on a particular /// channel, such as /// <see cref="TokenConstants.DefaultChannel"/> /// or /// <see cref="TokenConstants.HiddenChannel"/> /// , use a filtering token stream such a /// <see cref="CommonTokenStream"/> /// .</p> /// </summary> public class BufferedTokenStream : ITokenStream { /// <summary> /// The /// <see cref="ITokenSource"/> /// from which tokens for this stream are fetched. /// </summary> [NotNull] private ITokenSource _tokenSource; /// <summary>A collection of all tokens fetched from the token source.</summary> /// <remarks> /// A collection of all tokens fetched from the token source. The list is /// considered a complete view of the input once /// <see cref="fetchedEOF"/> /// is set /// to /// <see langword="true"/> /// . /// </remarks> protected internal IList<IToken> tokens = new List<IToken>(100); /// <summary> /// The index into /// <see cref="tokens"/> /// of the current token (next token to /// <see cref="Consume()"/> /// ). /// <see cref="tokens"/> /// <c>[</c> /// <see cref="p"/> /// <c>]</c> /// should be /// <see cref="LT(int)">LT(1)</see> /// . /// <p>This field is set to -1 when the stream is first constructed or when /// <see cref="SetTokenSource(ITokenSource)"/> /// is called, indicating that the first token has /// not yet been fetched from the token source. For additional information, /// see the documentation of /// <see cref="IIntStream"/> /// for a description of /// Initializing Methods.</p> /// </summary> protected internal int p = -1; /// <summary> /// Indicates whether the /// <see cref="TokenConstants.EOF"/> /// token has been fetched from /// <see cref="_tokenSource"/> /// and added to /// <see cref="tokens"/> /// . This field improves /// performance for the following cases: /// <ul> /// <li> /// <see cref="Consume()"/> /// : The lookahead check in /// <see cref="Consume()"/> /// to prevent /// consuming the EOF symbol is optimized by checking the values of /// <see cref="fetchedEOF"/> /// and /// <see cref="p"/> /// instead of calling /// <see cref="LA(int)"/> /// .</li> /// <li> /// <see cref="Fetch(int)"/> /// : The check to prevent adding multiple EOF symbols into /// <see cref="tokens"/> /// is trivial with this field.</li> /// </ul> /// </summary> protected internal bool fetchedEOF; public BufferedTokenStream(ITokenSource tokenSource) { if (tokenSource == null) { throw new ArgumentNullException("tokenSource cannot be null"); } this._tokenSource = tokenSource; } public virtual ITokenSource TokenSource { get { return _tokenSource; } } public virtual int Index { get { return p; } } public virtual int Mark() { return 0; } public virtual void Release(int marker) { } // no resources to release public virtual void Reset() { Seek(0); } public virtual void Seek(int index) { LazyInit(); p = AdjustSeekIndex(index); } public virtual int Size { get { return tokens.Count; } } public virtual void Consume() { bool skipEofCheck; if (p >= 0) { if (fetchedEOF) { // the last token in tokens is EOF. skip check if p indexes any // fetched token except the last. skipEofCheck = p < tokens.Count - 1; } else { // no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = p < tokens.Count; } } else { // not yet initialized skipEofCheck = false; } if (!skipEofCheck && LA(1) == IntStreamConstants.EOF) { throw new InvalidOperationException("cannot consume EOF"); } if (Sync(p + 1)) { p = AdjustSeekIndex(p + 1); } } /// <summary> /// Make sure index /// <paramref name="i"/> /// in tokens has a token. /// </summary> /// <returns> /// /// <see langword="true"/> /// if a token is located at index /// <paramref name="i"/> /// , otherwise /// <see langword="false"/> /// . /// </returns> /// <seealso cref="Get(int)"/> protected internal virtual bool Sync(int i) { System.Diagnostics.Debug.Assert(i >= 0); int n = i - tokens.Count + 1; // how many more elements we need? //System.out.println("sync("+i+") needs "+n); if (n > 0) { int fetched = Fetch(n); return fetched >= n; } return true; } /// <summary> /// Add /// <paramref name="n"/> /// elements to buffer. /// </summary> /// <returns>The actual number of elements added to the buffer.</returns> protected internal virtual int Fetch(int n) { if (fetchedEOF) { return 0; } for (int i = 0; i < n; i++) { IToken t = _tokenSource.NextToken(); if (t is IWritableToken) { ((IWritableToken)t).TokenIndex = tokens.Count; } tokens.Add(t); if (t.Type == TokenConstants.EOF) { fetchedEOF = true; return i + 1; } } return n; } public virtual IToken Get(int i) { if (i < 0 || i >= tokens.Count) { throw new ArgumentOutOfRangeException("token index " + i + " out of range 0.." + (tokens.Count - 1)); } return tokens[i]; } /// <summary>Get all tokens from start..stop inclusively.</summary> /// <remarks>Get all tokens from start..stop inclusively.</remarks> public virtual IList<IToken> Get(int start, int stop) { if (start < 0 || stop < 0) { return null; } LazyInit(); IList<IToken> subset = new List<IToken>(); if (stop >= tokens.Count) { stop = tokens.Count - 1; } for (int i = start; i <= stop; i++) { IToken t = tokens[i]; if (t.Type == TokenConstants.EOF) { break; } subset.Add(t); } return subset; } public virtual int LA(int i) { return LT(i).Type; } protected internal virtual IToken Lb(int k) { if ((p - k) < 0) { return null; } return tokens[p - k]; } [return: NotNull] public virtual IToken LT(int k) { LazyInit(); if (k == 0) { return null; } if (k < 0) { return Lb(-k); } int i = p + k - 1; Sync(i); if (i >= tokens.Count) { // return EOF token // EOF must be last token return tokens[tokens.Count - 1]; } // if ( i>range ) range = i; return tokens[i]; } /// <summary> /// Allowed derived classes to modify the behavior of operations which change /// the current stream position by adjusting the target token index of a seek /// operation. /// </summary> /// <remarks> /// Allowed derived classes to modify the behavior of operations which change /// the current stream position by adjusting the target token index of a seek /// operation. The default implementation simply returns /// <paramref name="i"/> /// . If an /// exception is thrown in this method, the current stream index should not be /// changed. /// <p>For example, /// <see cref="CommonTokenStream"/> /// overrides this method to ensure that /// the seek target is always an on-channel token.</p> /// </remarks> /// <param name="i">The target token index.</param> /// <returns>The adjusted target token index.</returns> protected internal virtual int AdjustSeekIndex(int i) { return i; } protected internal void LazyInit() { if (p == -1) { Setup(); } } protected internal virtual void Setup() { Sync(0); p = AdjustSeekIndex(0); } /// <summary>Reset this token stream by setting its token source.</summary> /// <remarks>Reset this token stream by setting its token source.</remarks> public virtual void SetTokenSource(ITokenSource tokenSource) { this._tokenSource = tokenSource; tokens.Clear(); p = -1; } public virtual IList<IToken> GetTokens() { return tokens; } public virtual IList<IToken> GetTokens(int start, int stop) { return GetTokens(start, stop, null); } /// <summary> /// Given a start and stop index, return a /// <c>List</c> /// of all tokens in /// the token type /// <c>BitSet</c> /// . Return /// <see langword="null"/> /// if no tokens were found. This /// method looks at both on and off channel tokens. /// </summary> public virtual IList<IToken> GetTokens(int start, int stop, BitSet types) { LazyInit(); if (start < 0 || stop >= tokens.Count || stop < 0 || start >= tokens.Count) { throw new ArgumentOutOfRangeException("start " + start + " or stop " + stop + " not in 0.." + (tokens.Count - 1)); } if (start > stop) { return null; } // list = tokens[start:stop]:{T t, t.getType() in types} IList<IToken> filteredTokens = new List<IToken>(); for (int i = start; i <= stop; i++) { IToken t = tokens[i]; if (types == null || types.Get(t.Type)) { filteredTokens.Add(t); } } if (filteredTokens.Count == 0) { filteredTokens = null; } return filteredTokens; } public virtual IList<IToken> GetTokens(int start, int stop, int ttype) { BitSet s = new BitSet(ttype); s.Set(ttype); return GetTokens(start, stop, s); } /// <summary>Given a starting index, return the index of the next token on channel.</summary> /// <remarks> /// Given a starting index, return the index of the next token on channel. /// Return /// <paramref name="i"/> /// if /// <c>tokens[i]</c> /// is on channel. Return the index of /// the EOF token if there are no tokens on channel between /// <paramref name="i"/> /// and /// EOF. /// </remarks> protected internal virtual int NextTokenOnChannel(int i, int channel) { Sync(i); if (i >= Size) { return Size - 1; } IToken token = tokens[i]; while (token.Channel != channel) { if (token.Type == TokenConstants.EOF) { return i; } i++; Sync(i); token = tokens[i]; } return i; } /// <summary> /// Given a starting index, return the index of the previous token on /// channel. /// </summary> /// <remarks> /// Given a starting index, return the index of the previous token on /// channel. Return /// <paramref name="i"/> /// if /// <c>tokens[i]</c> /// is on channel. Return -1 /// if there are no tokens on channel between /// <paramref name="i"/> /// and 0. /// <p> /// If /// <paramref name="i"/> /// specifies an index at or after the EOF token, the EOF token /// index is returned. This is due to the fact that the EOF token is treated /// as though it were on every channel.</p> /// </remarks> protected internal virtual int PreviousTokenOnChannel(int i, int channel) { Sync(i); if (i >= Size) { // the EOF token is on every channel return Size - 1; } while (i >= 0) { IToken token = tokens[i]; if (token.Type == TokenConstants.EOF || token.Channel == channel) { return i; } i--; } return i; } /// <summary> /// Collect all tokens on specified channel to the right of /// the current token up until we see a token on /// <see cref="Lexer.DefaultTokenChannel"/> /// or /// EOF. If /// <paramref name="channel"/> /// is /// <c>-1</c> /// , find any non default channel token. /// </summary> public virtual IList<IToken> GetHiddenTokensToRight(int tokenIndex, int channel) { LazyInit(); if (tokenIndex < 0 || tokenIndex >= tokens.Count) { throw new ArgumentOutOfRangeException(tokenIndex + " not in 0.." + (tokens.Count - 1)); } int nextOnChannel = NextTokenOnChannel(tokenIndex + 1, Lexer.DefaultTokenChannel); int to; int from = tokenIndex + 1; // if none onchannel to right, nextOnChannel=-1 so set to = last token if (nextOnChannel == -1) { to = Size - 1; } else { to = nextOnChannel; } return FilterForChannel(from, to, channel); } /// <summary> /// Collect all hidden tokens (any off-default channel) to the right of /// the current token up until we see a token on /// <see cref="Lexer.DefaultTokenChannel"/> /// or EOF. /// </summary> public virtual IList<IToken> GetHiddenTokensToRight(int tokenIndex) { return GetHiddenTokensToRight(tokenIndex, -1); } /// <summary> /// Collect all tokens on specified channel to the left of /// the current token up until we see a token on /// <see cref="Lexer.DefaultTokenChannel"/> /// . /// If /// <paramref name="channel"/> /// is /// <c>-1</c> /// , find any non default channel token. /// </summary> public virtual IList<IToken> GetHiddenTokensToLeft(int tokenIndex, int channel) { LazyInit(); if (tokenIndex < 0 || tokenIndex >= tokens.Count) { throw new ArgumentOutOfRangeException(tokenIndex + " not in 0.." + (tokens.Count - 1)); } if (tokenIndex == 0) { // obviously no tokens can appear before the first token return null; } int prevOnChannel = PreviousTokenOnChannel(tokenIndex - 1, Lexer.DefaultTokenChannel); if (prevOnChannel == tokenIndex - 1) { return null; } // if none onchannel to left, prevOnChannel=-1 then from=0 int from = prevOnChannel + 1; int to = tokenIndex - 1; return FilterForChannel(from, to, channel); } /// <summary> /// Collect all hidden tokens (any off-default channel) to the left of /// the current token up until we see a token on /// <see cref="Lexer.DefaultTokenChannel"/> /// . /// </summary> public virtual IList<IToken> GetHiddenTokensToLeft(int tokenIndex) { return GetHiddenTokensToLeft(tokenIndex, -1); } protected internal virtual IList<IToken> FilterForChannel(int from, int to, int channel) { IList<IToken> hidden = new List<IToken>(); for (int i = from; i <= to; i++) { IToken t = tokens[i]; if (channel == -1) { if (t.Channel != Lexer.DefaultTokenChannel) { hidden.Add(t); } } else { if (t.Channel == channel) { hidden.Add(t); } } } if (hidden.Count == 0) { return null; } return hidden; } public virtual string SourceName { get { return _tokenSource.SourceName; } } /// <summary>Get the text of all tokens in this buffer.</summary> /// <remarks>Get the text of all tokens in this buffer.</remarks> [return: NotNull] public virtual string GetText() { Fill(); return GetText(Interval.Of(0, Size - 1)); } [return: NotNull] public virtual string GetText(Interval interval) { int start = interval.a; int stop = interval.b; if (start < 0 || stop < 0) { return string.Empty; } LazyInit(); if (stop >= tokens.Count) { stop = tokens.Count - 1; } StringBuilder buf = new StringBuilder(); for (int i = start; i <= stop; i++) { IToken t = tokens[i]; if (t.Type == TokenConstants.EOF) { break; } buf.Append(t.Text); } return buf.ToString(); } [return: NotNull] public virtual string GetText(RuleContext ctx) { return GetText(ctx.SourceInterval); } [return: NotNull] public virtual string GetText(IToken start, IToken stop) { if (start != null && stop != null) { return GetText(Interval.Of(start.TokenIndex, stop.TokenIndex)); } return string.Empty; } /// <summary>Get all tokens from lexer until EOF.</summary> /// <remarks>Get all tokens from lexer until EOF.</remarks> public virtual void Fill() { LazyInit(); int blockSize = 1000; while (true) { int fetched = Fetch(blockSize); if (fetched < blockSize) { return; } } } } }
using System; using System.Collections.Generic; using System.Linq; using OrchardVNext.Environment.Extensions.Models; using OrchardVNext.Utility.Extensions; using System.IO; using OrchardVNext.FileSystems.WebSite; using OrchardVNext.Localization; namespace OrchardVNext.Environment.Extensions.Folders { public class ExtensionHarvester : IExtensionHarvester { private const string NameSection = "name"; private const string PathSection = "path"; private const string DescriptionSection = "description"; private const string VersionSection = "version"; private const string OrchardVersionSection = "orchardversion"; private const string AuthorSection = "author"; private const string WebsiteSection = "website"; private const string TagsSection = "tags"; private const string AntiForgerySection = "antiforgery"; private const string ZonesSection = "zones"; private const string BaseThemeSection = "basetheme"; private const string DependenciesSection = "dependencies"; private const string CategorySection = "category"; private const string FeatureDescriptionSection = "featuredescription"; private const string FeatureNameSection = "featurename"; private const string PrioritySection = "priority"; private const string FeaturesSection = "features"; private const string SessionStateSection = "sessionstate"; private readonly IWebSiteFolder _webSiteFolder; public ExtensionHarvester(IWebSiteFolder webSiteFolder) { _webSiteFolder = webSiteFolder; T = NullLocalizer.Instance; } public Localizer T { get; set; } public bool DisableMonitoring { get; set; } public IEnumerable<ExtensionDescriptor> HarvestExtensions(IEnumerable<string> paths, string extensionType, string manifestName, bool manifestIsOptional) { return paths .SelectMany(path => HarvestExtensions(path, extensionType, manifestName, manifestIsOptional)) .ToList(); } private IEnumerable<ExtensionDescriptor> HarvestExtensions(string path, string extensionType, string manifestName, bool manifestIsOptional) { string key = string.Format("{0}-{1}-{2}", path, manifestName, extensionType); return AvailableExtensionsInFolder(path, extensionType, manifestName, manifestIsOptional).ToReadOnlyCollection(); } private List<ExtensionDescriptor> AvailableExtensionsInFolder(string path, string extensionType, string manifestName, bool manifestIsOptional) { Logger.Information("Start looking for extensions in '{0}'...", path); var subfolderPaths = _webSiteFolder.ListDirectories(path); var localList = new List<ExtensionDescriptor>(); foreach (var subfolderPath in subfolderPaths) { var extensionId = Path.GetFileName(subfolderPath.TrimEnd('/', '\\')); var manifestPath = Path.Combine(subfolderPath, manifestName); try { var descriptor = GetExtensionDescriptor(path, extensionId, extensionType, manifestPath, manifestIsOptional); if (descriptor == null) continue; if (descriptor.Path != null && !descriptor.Path.IsValidUrlSegment()) { Logger.Error("The module '{0}' could not be loaded because it has an invalid Path ({1}). It was ignored. The Path if specified must be a valid URL segment. The best bet is to stick with letters and numbers with no spaces.", extensionId, descriptor.Path); continue; } if (descriptor.Path == null) { descriptor.Path = descriptor.Name.IsValidUrlSegment() ? descriptor.Name : descriptor.Id; } localList.Add(descriptor); } catch (Exception ex) { // Ignore invalid module manifests Logger.Error(ex, "The module '{0}' could not be loaded. It was ignored.", extensionId); } } Logger.Information("Done looking for extensions in '{0}': {1}", path, string.Join(", ", localList.Select(d => d.Id))); return localList; } public static ExtensionDescriptor GetDescriptorForExtension(string locationPath, string extensionId, string extensionType, string manifestText) { Dictionary<string, string> manifest = ParseManifest(manifestText); var extensionDescriptor = new ExtensionDescriptor { Location = locationPath, Id = extensionId, ExtensionType = extensionType, Name = GetValue(manifest, NameSection) ?? extensionId, Path = GetValue(manifest, PathSection), Description = GetValue(manifest, DescriptionSection), Version = GetValue(manifest, VersionSection), OrchardVersion = GetValue(manifest, OrchardVersionSection), Author = GetValue(manifest, AuthorSection), WebSite = GetValue(manifest, WebsiteSection), Tags = GetValue(manifest, TagsSection), AntiForgery = GetValue(manifest, AntiForgerySection), Zones = GetValue(manifest, ZonesSection), BaseTheme = GetValue(manifest, BaseThemeSection), SessionState = GetValue(manifest, SessionStateSection) }; extensionDescriptor.Features = GetFeaturesForExtension(manifest, extensionDescriptor); return extensionDescriptor; } private ExtensionDescriptor GetExtensionDescriptor(string locationPath, string extensionId, string extensionType, string manifestPath, bool manifestIsOptional) { var manifestText = _webSiteFolder.ReadFile(manifestPath); if (manifestText == null) { if (manifestIsOptional) { manifestText = string.Format("Id: {0}", extensionId); } else { return null; } } return GetDescriptorForExtension(locationPath, extensionId, extensionType, manifestText); } private static Dictionary<string, string> ParseManifest(string manifestText) { var manifest = new Dictionary<string, string>(); using (StringReader reader = new StringReader(manifestText)) { string line; while ((line = reader.ReadLine()) != null) { string[] field = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int fieldLength = field.Length; if (fieldLength != 2) continue; for (int i = 0; i < fieldLength; i++) { field[i] = field[i].Trim(); } switch (field[0].ToLowerInvariant()) { case NameSection: manifest.Add(NameSection, field[1]); break; case PathSection: manifest.Add(PathSection, field[1]); break; case DescriptionSection: manifest.Add(DescriptionSection, field[1]); break; case VersionSection: manifest.Add(VersionSection, field[1]); break; case OrchardVersionSection: manifest.Add(OrchardVersionSection, field[1]); break; case AuthorSection: manifest.Add(AuthorSection, field[1]); break; case WebsiteSection: manifest.Add(WebsiteSection, field[1]); break; case TagsSection: manifest.Add(TagsSection, field[1]); break; case AntiForgerySection: manifest.Add(AntiForgerySection, field[1]); break; case ZonesSection: manifest.Add(ZonesSection, field[1]); break; case BaseThemeSection: manifest.Add(BaseThemeSection, field[1]); break; case DependenciesSection: manifest.Add(DependenciesSection, field[1]); break; case CategorySection: manifest.Add(CategorySection, field[1]); break; case FeatureDescriptionSection: manifest.Add(FeatureDescriptionSection, field[1]); break; case FeatureNameSection: manifest.Add(FeatureNameSection, field[1]); break; case PrioritySection: manifest.Add(PrioritySection, field[1]); break; case SessionStateSection: manifest.Add(SessionStateSection, field[1]); break; case FeaturesSection: manifest.Add(FeaturesSection, reader.ReadToEnd()); break; } } } return manifest; } private static IEnumerable<FeatureDescriptor> GetFeaturesForExtension(IDictionary<string, string> manifest, ExtensionDescriptor extensionDescriptor) { var featureDescriptors = new List<FeatureDescriptor>(); // Default feature FeatureDescriptor defaultFeature = new FeatureDescriptor { Id = extensionDescriptor.Id, Name = GetValue(manifest, FeatureNameSection) ?? extensionDescriptor.Name, Priority = GetValue(manifest, PrioritySection) != null ? int.Parse(GetValue(manifest, PrioritySection)) : 0, Description = GetValue(manifest, FeatureDescriptionSection) ?? GetValue(manifest, DescriptionSection) ?? string.Empty, Dependencies = ParseFeatureDependenciesEntry(GetValue(manifest, DependenciesSection)), Extension = extensionDescriptor, Category = GetValue(manifest, CategorySection) }; featureDescriptors.Add(defaultFeature); // Remaining features string featuresText = GetValue(manifest, FeaturesSection); if (featuresText != null) { FeatureDescriptor featureDescriptor = null; using (StringReader reader = new StringReader(featuresText)) { string line; while ((line = reader.ReadLine()) != null) { if (IsFeatureDeclaration(line)) { if (featureDescriptor != null) { if (!featureDescriptor.Equals(defaultFeature)) { featureDescriptors.Add(featureDescriptor); } featureDescriptor = null; } string[] featureDeclaration = line.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries); string featureDescriptorId = featureDeclaration[0].Trim(); if (String.Equals(featureDescriptorId, extensionDescriptor.Id, StringComparison.OrdinalIgnoreCase)) { featureDescriptor = defaultFeature; featureDescriptor.Name = extensionDescriptor.Name; } else { featureDescriptor = new FeatureDescriptor { Id = featureDescriptorId, Extension = extensionDescriptor }; } } else if (IsFeatureFieldDeclaration(line)) { if (featureDescriptor != null) { string[] featureField = line.Split(new[] { ":" }, 2, StringSplitOptions.None); int featureFieldLength = featureField.Length; if (featureFieldLength != 2) continue; for (int i = 0; i < featureFieldLength; i++) { featureField[i] = featureField[i].Trim(); } switch (featureField[0].ToLowerInvariant()) { case NameSection: featureDescriptor.Name = featureField[1]; break; case DescriptionSection: featureDescriptor.Description = featureField[1]; break; case CategorySection: featureDescriptor.Category = featureField[1]; break; case PrioritySection: featureDescriptor.Priority = int.Parse(featureField[1]); break; case DependenciesSection: featureDescriptor.Dependencies = ParseFeatureDependenciesEntry(featureField[1]); break; } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } else { string message = string.Format("The line {0} in manifest for extension {1} was ignored", line, extensionDescriptor.Id); throw new ArgumentException(message); } } if (featureDescriptor != null && !featureDescriptor.Equals(defaultFeature)) featureDescriptors.Add(featureDescriptor); } } return featureDescriptors; } private static bool IsFeatureFieldDeclaration(string line) { if (line.StartsWith("\t\t") || line.StartsWith("\t ") || line.StartsWith(" ") || line.StartsWith(" \t")) return true; return false; } private static bool IsFeatureDeclaration(string line) { int lineLength = line.Length; if (line.StartsWith("\t") && lineLength >= 2) { return !Char.IsWhiteSpace(line[1]); } if (line.StartsWith(" ") && lineLength >= 5) return !Char.IsWhiteSpace(line[4]); return false; } private static IEnumerable<string> ParseFeatureDependenciesEntry(string dependenciesEntry) { if (string.IsNullOrEmpty(dependenciesEntry)) return Enumerable.Empty<string>(); var dependencies = new List<string>(); foreach (var s in dependenciesEntry.Split(',')) { dependencies.Add(s.Trim()); } return dependencies; } private static string GetValue(IDictionary<string, string> fields, string key) { string value; return fields.TryGetValue(key, out value) ? value : null; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using System.Text; using Newtonsoft.Json.Converters; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Linq; using System.IO; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; using Newtonsoft.Json.Utilities; #endif namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JTokenTests : TestFixtureBase { [Test] public void ReadFrom() { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.AreEqual(true, (bool)o["pie"]); JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]"))); Assert.AreEqual(1, (int)a[0]); Assert.AreEqual(2, (int)a[1]); Assert.AreEqual(3, (int)a[2]); JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}")); reader.Read(); reader.Read(); JProperty p = (JProperty)JToken.ReadFrom(reader); Assert.AreEqual("pie", p.Name); Assert.AreEqual(true, (bool)p.Value); JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)"))); Assert.AreEqual("Date", c.Name); Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0))); JValue v; v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue"""))); Assert.AreEqual("stringvalue", (string)v); v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1"))); Assert.AreEqual(1, (int)v); v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1"))); Assert.AreEqual(1.1, (double)v); #if !NET20 v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31""")) { DateParseHandling = DateParseHandling.DateTimeOffset }); Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType()); Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value); #endif } [Test] public void Load() { JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}"))); Assert.AreEqual(true, (bool)o["pie"]); } [Test] public void Parse() { JObject o = (JObject)JToken.Parse("{'pie':true}"); Assert.AreEqual(true, (bool)o["pie"]); } [Test] public void Parent() { JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20))); Assert.AreEqual(null, v.Parent); JObject o = new JObject( new JProperty("Test1", v), new JProperty("Test2", "Test2Value"), new JProperty("Test3", "Test3Value"), new JProperty("Test4", null) ); Assert.AreEqual(o.Property("Test1"), v.Parent); JProperty p = new JProperty("NewProperty", v); // existing value should still have same parent Assert.AreEqual(o.Property("Test1"), v.Parent); // new value should be cloned Assert.AreNotSame(p.Value, v); Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value); Assert.AreEqual(v, o["Test1"]); Assert.AreEqual(null, o.Parent); JProperty o1 = new JProperty("O1", o); Assert.AreEqual(o, o1.Value); Assert.AreNotEqual(null, o.Parent); JProperty o2 = new JProperty("O2", o); Assert.AreNotSame(o1.Value, o2.Value); Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count()); Assert.AreEqual(false, JToken.DeepEquals(o1, o2)); Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value)); } [Test] public void Next() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); JToken next = a[0].Next; Assert.AreEqual(6, (int)next); next = next.Next; Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), next)); next = next.Next; Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), next)); next = next.Next; Assert.IsNull(next); } [Test] public void Previous() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); JToken previous = a[3].Previous; Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), previous)); previous = previous.Previous; Assert.AreEqual(6, (int)previous); previous = previous.Previous; Assert.AreEqual(5, (int)previous); previous = previous.Previous; Assert.IsNull(previous); } [Test] public void Children() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.AreEqual(4, a.Count()); Assert.AreEqual(3, a.Children<JArray>().Count()); } [Test] public void BeforeAfter() { JArray a = new JArray( 5, new JArray(1, 2, 3), new JArray(1, 2, 3), new JArray(1, 2, 3) ); Assert.AreEqual(5, (int)a[1].Previous); Assert.AreEqual(2, a[2].BeforeSelf().Count()); //Assert.AreEqual(2, a[2].AfterSelf().Count()); } [Test] public void Casting() { Assert.AreEqual(1L, (long)(new JValue(1))); Assert.AreEqual(2L, (long)new JArray(1, 2, 3)[1]); Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20))); #if !NET20 Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 0, 0, 0, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTime(2000, 12, 20, 0, 0, 0, DateTimeKind.Utc))); Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero))); Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null)); Assert.AreEqual(null, (DateTimeOffset?)(JValue)null); #endif Assert.AreEqual(true, (bool)new JValue(true)); Assert.AreEqual(true, (bool?)new JValue(true)); Assert.AreEqual(null, (bool?)((JValue)null)); Assert.AreEqual(null, (bool?)new JValue((object)null)); Assert.AreEqual(10, (long)new JValue(10)); Assert.AreEqual(null, (long?)new JValue((long?)null)); Assert.AreEqual(null, (long?)(JValue)null); Assert.AreEqual(null, (int?)new JValue((int?)null)); Assert.AreEqual(null, (int?)(JValue)null); Assert.AreEqual(null, (DateTime?)new JValue((DateTime?)null)); Assert.AreEqual(null, (DateTime?)(JValue)null); Assert.AreEqual(null, (short?)new JValue((short?)null)); Assert.AreEqual(null, (short?)(JValue)null); Assert.AreEqual(null, (float?)new JValue((float?)null)); Assert.AreEqual(null, (float?)(JValue)null); Assert.AreEqual(null, (double?)new JValue((double?)null)); Assert.AreEqual(null, (double?)(JValue)null); Assert.AreEqual(null, (decimal?)new JValue((decimal?)null)); Assert.AreEqual(null, (decimal?)(JValue)null); Assert.AreEqual(null, (uint?)new JValue((uint?)null)); Assert.AreEqual(null, (uint?)(JValue)null); Assert.AreEqual(null, (sbyte?)new JValue((sbyte?)null)); Assert.AreEqual(null, (sbyte?)(JValue)null); Assert.AreEqual(null, (byte?)new JValue((byte?)null)); Assert.AreEqual(null, (byte?)(JValue)null); Assert.AreEqual(null, (ulong?)new JValue((ulong?)null)); Assert.AreEqual(null, (ulong?)(JValue)null); Assert.AreEqual(null, (uint?)new JValue((uint?)null)); Assert.AreEqual(null, (uint?)(JValue)null); Assert.AreEqual(11.1f, (float)new JValue(11.1)); Assert.AreEqual(float.MinValue, (float)new JValue(float.MinValue)); Assert.AreEqual(1.1, (double)new JValue(1.1)); Assert.AreEqual(uint.MaxValue, (uint)new JValue(uint.MaxValue)); Assert.AreEqual(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue)); Assert.AreEqual(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue))); Assert.AreEqual(null, (string)new JValue((string)null)); Assert.AreEqual(5m, (decimal)(new JValue(5L))); Assert.AreEqual(5m, (decimal?)(new JValue(5L))); Assert.AreEqual(5f, (float)(new JValue(5L))); Assert.AreEqual(5f, (float)(new JValue(5m))); Assert.AreEqual(5f, (float?)(new JValue(5m))); Assert.AreEqual(5, (byte)(new JValue(5))); Assert.AreEqual(null, (sbyte?)new JValue((object)null)); Assert.AreEqual("1", (string)(new JValue(1))); Assert.AreEqual("1", (string)(new JValue(1.0))); Assert.AreEqual("1.0", (string)(new JValue(1.0m))); Assert.AreEqual("True", (string)(new JValue(true))); Assert.AreEqual(null, (string)(new JValue((object)null))); Assert.AreEqual(null, (string)(JValue)null); Assert.AreEqual("12/12/2000 12:12:12", (string)(new JValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc)))); #if !NET20 Assert.AreEqual("12/12/2000 12:12:12 +00:00", (string)(new JValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero)))); #endif Assert.AreEqual(true, (bool)(new JValue(1))); Assert.AreEqual(true, (bool)(new JValue(1.0))); Assert.AreEqual(true, (bool)(new JValue("true"))); Assert.AreEqual(true, (bool)(new JValue(true))); Assert.AreEqual(1, (int)(new JValue(1))); Assert.AreEqual(1, (int)(new JValue(1.0))); Assert.AreEqual(1, (int)(new JValue("1"))); Assert.AreEqual(1, (int)(new JValue(true))); Assert.AreEqual(1m, (decimal)(new JValue(1))); Assert.AreEqual(1m, (decimal)(new JValue(1.0))); Assert.AreEqual(1m, (decimal)(new JValue("1"))); Assert.AreEqual(1m, (decimal)(new JValue(true))); Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue(TimeSpan.FromMinutes(1)))); Assert.AreEqual("00:01:00", (string)(new JValue(TimeSpan.FromMinutes(1)))); Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue("00:01:00"))); Assert.AreEqual("46efe013-b56a-4e83-99e4-4dce7678a5bc", (string)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")))); Assert.AreEqual("http://www.google.com/", (string)(new JValue(new Uri("http://www.google.com")))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")))); Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue("http://www.google.com"))); Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue(new Uri("http://www.google.com")))); Assert.AreEqual(null, (Uri)(new JValue((object)null))); Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")), (string)(new JValue(Encoding.UTF8.GetBytes("hi")))); CollectionAssert.AreEquivalent((byte[])Encoding.UTF8.GetBytes("hi"), (byte[])(new JValue(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi"))))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray()))); Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray()))); Assert.AreEqual((sbyte?)1, (sbyte?)(new JValue((short?)1))); Assert.AreEqual(null, (Uri)(JValue)null); Assert.AreEqual(null, (int?)(JValue)null); Assert.AreEqual(null, (uint?)(JValue)null); Assert.AreEqual(null, (Guid?)(JValue)null); Assert.AreEqual(null, (TimeSpan?)(JValue)null); Assert.AreEqual(null, (byte[])(JValue)null); Assert.AreEqual(null, (bool?)(JValue)null); Assert.AreEqual(null, (char?)(JValue)null); Assert.AreEqual(null, (DateTime?)(JValue)null); #if !NET20 Assert.AreEqual(null, (DateTimeOffset?)(JValue)null); #endif Assert.AreEqual(null, (short?)(JValue)null); Assert.AreEqual(null, (ushort?)(JValue)null); Assert.AreEqual(null, (byte?)(JValue)null); Assert.AreEqual(null, (byte?)(JValue)null); Assert.AreEqual(null, (sbyte?)(JValue)null); Assert.AreEqual(null, (sbyte?)(JValue)null); Assert.AreEqual(null, (long?)(JValue)null); Assert.AreEqual(null, (ulong?)(JValue)null); Assert.AreEqual(null, (double?)(JValue)null); Assert.AreEqual(null, (float?)(JValue)null); byte[] data = new byte[0]; Assert.AreEqual(data, (byte[])(new JValue(data))); Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase))); #if !(NET20 || NET35 || PORTABLE || PORTABLE40) string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990"; Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value); Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(bigIntegerText)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(long.MaxValue), (new JValue(long.MaxValue)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(4.5d), (new JValue((4.5d))).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(4.5f), (new JValue((4.5f))).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(byte.MaxValue), (new JValue(byte.MaxValue)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>()); Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger?>()); Assert.AreEqual(null, (new JValue((object)null)).ToObject<BigInteger?>()); byte[] intData = BigInteger.Parse(bigIntegerText).ToByteArray(); Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(intData)).ToObject<BigInteger>()); Assert.AreEqual(4.0d, (double)(new JValue(new BigInteger(4.5d)))); Assert.AreEqual(true, (bool)(new JValue(new BigInteger(1)))); Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(long.MaxValue)))); Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 })))); Assert.AreEqual("9223372036854775807", (string)(new JValue(new BigInteger(long.MaxValue)))); intData = (byte[])(new JValue(new BigInteger(long.MaxValue))); CollectionAssert.AreEqual(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, intData); #endif } [Test] public void FailedCasting() { ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to DateTime.", () => { var i = (DateTime)new JValue(true); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to DateTime.", () => { var i = (DateTime)new JValue(1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to DateTime.", () => { var i = (DateTime)new JValue(1.1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to DateTime.", () => { var i = (DateTime)new JValue(1.1m); }); ExceptionAssert.Throws<ArgumentException>("Can not convert TimeSpan to DateTime.", () => { var i = (DateTime)new JValue(TimeSpan.Zero); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to DateTime.", () => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Null to DateTime.", () => { var i = (DateTime)new JValue((object)null); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to DateTime.", () => { var i = (DateTime)new JValue(Guid.NewGuid()); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to Uri.", () => { var i = (Uri)new JValue(true); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to Uri.", () => { var i = (Uri)new JValue(1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Uri.", () => { var i = (Uri)new JValue(1.1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Uri.", () => { var i = (Uri)new JValue(1.1m); }); ExceptionAssert.Throws<ArgumentException>("Can not convert TimeSpan to Uri.", () => { var i = (Uri)new JValue(TimeSpan.Zero); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to Uri.", () => { var i = (Uri)new JValue(Guid.NewGuid()); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Uri.", () => { var i = (Uri)new JValue(DateTime.Now); }); #if !NET20 ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Uri.", () => { var i = (Uri)new JValue(DateTimeOffset.Now); }); #endif ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to TimeSpan.", () => { var i = (TimeSpan)new JValue(true); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to TimeSpan.", () => { var i = (TimeSpan)new JValue(1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to TimeSpan.", () => { var i = (TimeSpan)new JValue(1.1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to TimeSpan.", () => { var i = (TimeSpan)new JValue(1.1m); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Null to TimeSpan.", () => { var i = (TimeSpan)new JValue((object)null); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to TimeSpan.", () => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Date to TimeSpan.", () => { var i = (TimeSpan)new JValue(DateTime.Now); }); #if !NET20 ExceptionAssert.Throws<ArgumentException>("Can not convert Date to TimeSpan.", () => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }); #endif ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to TimeSpan.", () => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to Guid.", () => { var i = (Guid)new JValue(true); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Integer to Guid.", () => { var i = (Guid)new JValue(1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Guid.", () => { var i = (Guid)new JValue(1.1); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Float to Guid.", () => { var i = (Guid)new JValue(1.1m); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Null to Guid.", () => { var i = (Guid)new JValue((object)null); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Guid.", () => { var i = (Guid)new JValue(DateTime.Now); }); #if !NET20 ExceptionAssert.Throws<ArgumentException>("Can not convert Date to Guid.", () => { var i = (Guid)new JValue(DateTimeOffset.Now); }); #endif ExceptionAssert.Throws<ArgumentException>("Can not convert TimeSpan to Guid.", () => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to Guid.", () => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }); #if !NET20 ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to DateTimeOffset.", () => { var i = (DateTimeOffset)new JValue(true); }); #endif ExceptionAssert.Throws<ArgumentException>("Can not convert Boolean to Uri.", () => { var i = (Uri)new JValue(true); }); #if !(NET20 || NET35 || PORTABLE || PORTABLE40) ExceptionAssert.Throws<ArgumentException>("Can not convert Uri to BigInteger.", () => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Null to BigInteger.", () => { var i = (new JValue((object)null)).ToObject<BigInteger>(); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to BigInteger.", () => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Guid to BigInteger.", () => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); }); #endif ExceptionAssert.Throws<ArgumentException>("Can not convert Date to SByte.", () => { var i = (sbyte?)new JValue(DateTime.Now); }); ExceptionAssert.Throws<ArgumentException>("Can not convert Date to SByte.", () => { var i = (sbyte)new JValue(DateTime.Now); }); } [Test] public void ToObject() { #if !(NET20 || NET35 || PORTABLE) Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger)))); Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?)))); Assert.AreEqual((BigInteger?)null, (new JValue((object)null).ToObject(typeof(BigInteger?)))); #endif Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort)))); Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort?)))); Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint)))); Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint?)))); Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong)))); Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong?)))); Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte)))); Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte?)))); Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte)))); Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte?)))); Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short)))); Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short?)))); Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int)))); Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int?)))); Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long)))); Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long?)))); Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float)))); Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float?)))); Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double)))); Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double?)))); Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal)))); Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal?)))); Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool)))); Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool?)))); Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char)))); Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char?)))); Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan)))); Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan?)))); Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime)))); Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime?)))); #if !NET20 Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset)))); Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset?)))); #endif Assert.AreEqual("b", (new JValue("b").ToObject(typeof(string)))); Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid)))); Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid?)))); Assert.AreEqual(new Uri("http://www.google.com/"), (new JValue(new Uri("http://www.google.com/")).ToObject(typeof(Uri)))); } [Test] public void ImplicitCastingTo() { Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20))); #if !NET20 Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero))); Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null)); #endif #if !(NET20 || NET35 || PORTABLE || PORTABLE40) // had to remove implicit casting to avoid user reference to System.Numerics.dll Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1)))); Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null))); #endif Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true)); Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true)); Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true)); Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10)); Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1)); Assert.IsTrue(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1)); Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f)); Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue)); Assert.IsTrue(JToken.DeepEquals(new JValue((object)null), (JValue)(double?)null)); Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null)); Assert.IsFalse(JToken.DeepEquals(new JValue((object)null), (JValue)(object)null)); byte[] emptyData = new byte[0]; Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData)); Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1])); Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi"))); Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1))); Assert.IsTrue(JToken.DeepEquals(new JValue((object)null), (JValue)(TimeSpan?)null)); Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1))); Assert.IsTrue(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue)new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))); Assert.IsTrue(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue)new Uri("http://www.google.com"))); Assert.IsTrue(JToken.DeepEquals(new JValue((object)null), (JValue)(Uri)null)); Assert.IsTrue(JToken.DeepEquals(new JValue((object)null), (JValue)(Guid?)null)); } [Test] public void Root() { JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); Assert.AreEqual(a, a.Root); Assert.AreEqual(a, a[0].Root); Assert.AreEqual(a, ((JArray)a[2])[0].Root); } [Test] public void Remove() { JToken t; JArray a = new JArray( 5, 6, new JArray(7, 8), new JArray(9, 10) ); a[0].Remove(); Assert.AreEqual(6, (int)a[0]); a[1].Remove(); Assert.AreEqual(6, (int)a[0]); Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1])); Assert.AreEqual(2, a.Count()); t = a[1]; t.Remove(); Assert.AreEqual(6, (int)a[0]); Assert.IsNull(t.Next); Assert.IsNull(t.Previous); Assert.IsNull(t.Parent); t = a[0]; t.Remove(); Assert.AreEqual(0, a.Count()); Assert.IsNull(t.Next); Assert.IsNull(t.Previous); Assert.IsNull(t.Parent); } [Test] public void AfterSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1]; List<JToken> afterTokens = t.AfterSelf().ToList(); Assert.AreEqual(2, afterTokens.Count); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2), afterTokens[0])); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1])); } [Test] public void BeforeSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[2]; List<JToken> beforeTokens = t.BeforeSelf().ToList(); Assert.AreEqual(2, beforeTokens.Count); Assert.IsTrue(JToken.DeepEquals(new JValue(5), beforeTokens[0])); Assert.IsTrue(JToken.DeepEquals(new JArray(1), beforeTokens[1])); } [Test] public void HasValues() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); Assert.IsTrue(a.HasValues); } [Test] public void Ancestors() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken t = a[1][0]; List<JToken> ancestors = t.Ancestors().ToList(); Assert.AreEqual(2, ancestors.Count()); Assert.AreEqual(a[1], ancestors[0]); Assert.AreEqual(a, ancestors[1]); } [Test] public void Descendants() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); List<JToken> descendants = a.Descendants().ToList(); Assert.AreEqual(10, descendants.Count()); Assert.AreEqual(5, (int)descendants[0]); Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4])); Assert.AreEqual(1, (int)descendants[descendants.Count - 3]); Assert.AreEqual(2, (int)descendants[descendants.Count - 2]); Assert.AreEqual(3, (int)descendants[descendants.Count - 1]); } [Test] public void CreateWriter() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JsonWriter writer = a.CreateWriter(); Assert.IsNotNull(writer); Assert.AreEqual(4, a.Count()); writer.WriteValue("String"); Assert.AreEqual(5, a.Count()); Assert.AreEqual("String", (string)a[4]); writer.WriteStartObject(); writer.WritePropertyName("Property"); writer.WriteValue("PropertyValue"); writer.WriteEnd(); Assert.AreEqual(6, a.Count()); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5])); } [Test] public void AddFirst() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a.AddFirst("First"); Assert.AreEqual("First", (string)a[0]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(5, a.Count()); a.AddFirst("NewFirst"); Assert.AreEqual("NewFirst", (string)a[0]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(6, a.Count()); Assert.AreEqual(a[0], a[0].Next.Previous); } [Test] public void RemoveAll() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); JToken first = a.First; Assert.AreEqual(5, (int)first); a.RemoveAll(); Assert.AreEqual(0, a.Count()); Assert.IsNull(first.Parent); Assert.IsNull(first.Next); } [Test] public void AddPropertyToArray() { ExceptionAssert.Throws<ArgumentException>("Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.", () => { JArray a = new JArray(); a.Add(new JProperty("PropertyName")); }); } [Test] public void AddValueToObject() { ExceptionAssert.Throws<ArgumentException>( "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", () => { JObject o = new JObject(); o.Add(5); }); } [Test] public void Replace() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[0].Replace(new JValue(int.MaxValue)); Assert.AreEqual(int.MaxValue, (int)a[0]); Assert.AreEqual(4, a.Count()); a[1][0].Replace(new JValue("Test")); Assert.AreEqual("Test", (string)a[1][0]); a[2].Replace(new JValue(int.MaxValue)); Assert.AreEqual(int.MaxValue, (int)a[2]); Assert.AreEqual(4, a.Count()); Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a)); } [Test] public void ToStringWithConverters() { JArray a = new JArray( new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)) ); string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter()); Assert.AreEqual(@"[ ""2009-02-15T00:00:00Z"" ]", json); json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter()); Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json); } [Test] public void ToStringWithNoIndenting() { JArray a = new JArray( new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc)) ); string json = a.ToString(Formatting.None, new IsoDateTimeConverter()); Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json); } [Test] public void AddAfterSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[1].AddAfterSelf("pie"); Assert.AreEqual(5, (int)a[0]); Assert.AreEqual(1, a[1].Count()); Assert.AreEqual("pie", (string)a[2]); Assert.AreEqual(5, a.Count()); a[4].AddAfterSelf("lastpie"); Assert.AreEqual("lastpie", (string)a[5]); Assert.AreEqual("lastpie", (string)a.Last); } [Test] public void AddBeforeSelf() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3) ); a[1].AddBeforeSelf("pie"); Assert.AreEqual(5, (int)a[0]); Assert.AreEqual("pie", (string)a[1]); Assert.AreEqual(a, a[1].Parent); Assert.AreEqual(a[2], a[1].Next); Assert.AreEqual(5, a.Count()); a[0].AddBeforeSelf("firstpie"); Assert.AreEqual("firstpie", (string)a[0]); Assert.AreEqual(5, (int)a[1]); Assert.AreEqual("pie", (string)a[2]); Assert.AreEqual(a, a[0].Parent); Assert.AreEqual(a[1], a[0].Next); Assert.AreEqual(6, a.Count()); a.Last.AddBeforeSelf("secondlastpie"); Assert.AreEqual("secondlastpie", (string)a[5]); Assert.AreEqual(7, a.Count()); } [Test] public void DeepClone() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3), new JObject( new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))), new JProperty("Second", 1), new JProperty("Third", null), new JProperty("Fourth", new JConstructor("Date", 12345)), new JProperty("Fifth", double.PositiveInfinity), new JProperty("Sixth", double.NaN) ) ); JArray a2 = (JArray)a.DeepClone(); Console.WriteLine(a2.ToString(Formatting.Indented)); Assert.IsTrue(a.DeepEquals(a2)); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void Clone() { JArray a = new JArray( 5, new JArray(1), new JArray(1, 2), new JArray(1, 2, 3), new JObject( new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))), new JProperty("Second", 1), new JProperty("Third", null), new JProperty("Fourth", new JConstructor("Date", 12345)), new JProperty("Fifth", double.PositiveInfinity), new JProperty("Sixth", double.NaN) ) ); ICloneable c = a; JArray a2 = (JArray)c.Clone(); Assert.IsTrue(a.DeepEquals(a2)); } #endif [Test] public void DoubleDeepEquals() { JArray a = new JArray( double.NaN, double.PositiveInfinity, double.NegativeInfinity ); JArray a2 = (JArray)a.DeepClone(); Assert.IsTrue(a.DeepEquals(a2)); double d = 1 + 0.1 + 0.1 + 0.1; JValue v1 = new JValue(d); JValue v2 = new JValue(1.3); Assert.IsTrue(v1.DeepEquals(v2)); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>("Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.", () => { string json = @"[ ""Small"", ""Medium"", ""Large"" ],"; JToken.Parse(json); }); } [Test] public void Path() { JObject o = new JObject( new JProperty("Test1", new JArray(1, 2, 3)), new JProperty("Test2", "Test2Value"), new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))), new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3))) ); JToken t = o.SelectToken("Test1[0]"); Assert.AreEqual("Test1[0]", t.Path); t = o.SelectToken("Test2"); Assert.AreEqual("Test2", t.Path); t = o.SelectToken(""); Assert.AreEqual("", t.Path); t = o.SelectToken("Test4[0][0]"); Assert.AreEqual("Test4[0][0]", t.Path); t = o.SelectToken("Test4[0]"); Assert.AreEqual("Test4[0]", t.Path); t = t.DeepClone(); Assert.AreEqual("", t.Path); t = o.SelectToken("Test3.Test1[1].Test1"); Assert.AreEqual("Test3.Test1[1].Test1", t.Path); JArray a = new JArray(1); Assert.AreEqual("", a.Path); Assert.AreEqual("[0]", a[0].Path); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using Palaso.Data; namespace Palaso.Tests.Data { public class PalasoChildTestItem { private PalasoChildTestItem _testItem; public PalasoChildTestItem() {} public PalasoChildTestItem(string s, int i, DateTime d) { StoredInt = i; StoredString = s; StoredDateTime = d; } public PalasoChildTestItem Child { get { return _testItem; } set { _testItem = value; } } public int Depth { get { int depth = 1; PalasoChildTestItem item = Child; while (item != null) { ++depth; item = item.Child; } return depth; } } public int StoredInt { get; set; } public string StoredString { get; set; } public DateTime StoredDateTime { get; set; } } public class PalasoTestItem: INotifyPropertyChanged { private int _storedInt; private string _storedString; private DateTime _storedDateTime; private PalasoChildTestItem _childTestItem; private List<string> _storedList; private List<PalasoChildTestItem> _childItemList; public List<PalasoChildTestItem> ChildItemList { get { return _childItemList; } set { _childItemList = value; OnPropertyChanged(new PropertyChangedEventArgs("Children")); } } public int OnActivateDepth { get; private set; } public PalasoChildTestItem Child { get { return _childTestItem; } set { _childTestItem = value; OnPropertyChanged(new PropertyChangedEventArgs("Child")); } } public int Depth { get { int depth = 1; PalasoChildTestItem item = Child; while (item != null) { ++depth; item = item.Child; } return depth; } } public PalasoTestItem() { _storedDateTime = PreciseDateTime.UtcNow; _childTestItem = new PalasoChildTestItem(); } public PalasoTestItem(string s, int i, DateTime d) { _storedString = s; _storedInt = i; _storedDateTime = d; } public override string ToString() { return StoredInt + ". " + StoredString + " " + StoredDateTime; } public override bool Equals(object obj) { if (obj == null) { return false; } var item = obj as PalasoTestItem; if (item == null) { return false; } return Equals(item); } public bool Equals(PalasoTestItem item) { if (item == null) { return false; } return (_storedInt == item._storedInt) && (_storedString == item._storedString) && (_storedDateTime == item._storedDateTime); } public int StoredInt { get { return _storedInt; } set { if (_storedInt != value) { _storedInt = value; OnPropertyChanged(new PropertyChangedEventArgs("StoredInt")); } } } public string StoredString { get { return _storedString; } set { if (_storedString != value) { _storedString = value; OnPropertyChanged(new PropertyChangedEventArgs("StoredString")); } } } public DateTime StoredDateTime { get { return _storedDateTime; } set { if (_storedDateTime != value) { _storedDateTime = value; OnPropertyChanged(new PropertyChangedEventArgs("StoredDateTime")); } } } public List<string> StoredList { get { return _storedList; } set { _storedList = value; OnPropertyChanged(new PropertyChangedEventArgs("StoredList")); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } #endregion } }
using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Document; using ICSharpCode.TextEditor.Util; using Lewis.SST.Controls; using Lewis.SST.DTSPackageClass; using Lewis.Xml; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Reflection; using System.Text; using System.Windows.Forms; using System.Xml; using WeifenLuo.WinFormsUI.Docking; namespace Lewis.SST.Gui { public partial class XMLDoc : Document { private object _isDTS; private object _isXMLSchema; private object _isXMLDiff; private bool _isSelected = false; private string xmlText; public event EventHandler<XMLDocEventArgs> SelectedForCompare; public event EventHandler<XMLDocEventArgs> UnSelectedForCompare; public event EventHandler<XMLDocEventArgs> SyncWithTree; public event EventHandler<XMLDocEventArgs> ReCreateDTS; public XMLDoc() { InitializeComponent(); SetTextEditorDefaultProperties(); XmlFormattingStrategy strategy = new XmlFormattingStrategy(); XmlFoldingStrategy folding = new XmlFoldingStrategy(); txtEditCtl.Document.FormattingStrategy = (IFormattingStrategy)strategy; txtEditCtl.Document.HighlightingStrategy = HighlightingManager.Manager.FindHighlighter("XML"); txtEditCtl.Document.FoldingManager.FoldingStrategy = (IFoldingStrategy)folding; WireEvents(); backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { txtEditCtl.Text = xmlText; ForceFoldingUpdate(m_fileName); SetupMenuIemSelectCompare(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { xmlText = XsltHelper.Transform(File.ReadAllText(m_fileName), XsltHelper.PRETTYXSLT); } private void OnUnSelectedForCompare(int index) { XMLDocEventArgs args = new XMLDocEventArgs(); args.selectedFileAndIndex = string.Format("{0},{1}", m_fileName, index).Split(','); EventHandler<XMLDocEventArgs> handler = UnSelectedForCompare; if (handler != null) { // raises the event. handler(this, args); } } private void OnSelectedForCompare(int index) { XMLDocEventArgs args = new XMLDocEventArgs(); args.selectedFileAndIndex = string.Format("{0},{1}", m_fileName, index).Split(','); EventHandler<XMLDocEventArgs> handler = SelectedForCompare; if (handler != null) { // raises the event. handler(this, args); } } private void OnSyncWithTree() { XMLDocEventArgs args = new XMLDocEventArgs(); args.selectedFileAndIndex = string.Format("{0},-1", m_fileName).Split(','); EventHandler<XMLDocEventArgs> handler = SyncWithTree; if (handler != null) { // raises the event. handler(this, args); } } private void OnReCreateDTS() { XMLDocEventArgs args = new XMLDocEventArgs(); args.selectedFileAndIndex = string.Format("{0},-1", m_fileName).Split(','); EventHandler<XMLDocEventArgs> handler = ReCreateDTS; if (handler != null) { // raises the event. handler(this, args); } } private void SetupMenuIemSelectCompare() { if (IsDatabaseSchema) { menuItem3.Name = "SelectCompare"; menuItem3.Checked = false; menuItem3.Text = "Select for Schema Compare"; menuItem3.Click += new EventHandler(SelectCompare_Click); } else if (IsDTSPackage) { menuItem3.Name = "createServerDTSPackage"; menuItem3.Text = "Recreate DTS Package From This"; menuItem3.Click += new EventHandler(createDTS_Click); } else { menuItem3.Visible = false; } menuItem4.Name = "SyncXMLTree"; menuItem4.Text = "Synchronize in XML Node Explorer"; menuItem4.Click += new EventHandler(SyncTree_Click); menuItem5.Name = "Close"; menuItem5.Text = "Close This"; menuItem5.Click += new EventHandler(closeThis_Click); } private void createDTS_Click(object sender, EventArgs e) { OnReCreateDTS(); } private void closeThis_Click(object sender, EventArgs e) { // Close doc Close(); } private void SyncTree_Click(object sender, EventArgs e) { // setup for xmlnodeexplorer synchronize // This will handle the fact that loading another explorer control or // resyncing when this window gets made active is a time expensive operation // TODO: check for doc changes to save first OnSyncWithTree(); } private void SelectCompare_Click(object sender, EventArgs e) { // setup for schemacompare menuItem3.Checked = !menuItem3.Checked; IsSelectedCompare = menuItem3.Checked; } public override bool Open(DockPanel dockPanel) { m_DialogTitle = "Open XML File..."; m_DialogTypeFilter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"; bool result = base.Open(dockPanel); FileName = m_fileName; if (result) { Show(dockPanel); } return result; } public override string FileName { get { return m_fileName; } set { if (value != null && value != string.Empty) { m_fileName = value; if (File.Exists(m_fileName)) { Cursor.Current = Cursors.WaitCursor; FileInfo fi = new FileInfo(m_fileName); this.TabText = fi.Name; this.Text = fi.Name; this.ToolTipText = fi.Name; backgroundWorker1.RunWorkerAsync(); Cursor.Current = Cursors.Default; } else { m_fileName = null; } } } } public override void Save(bool showDialog) { m_DialogTitle = "Save XML File As..."; m_DialogTypeFilter = "XML files (*.xml)|*.xml|All files (*.*)|*.*"; base.Save(showDialog); } public bool IsDatabaseSchema { get { // persist return value on the first time //if (_isXMLSchema == null) { _isXMLSchema = false; if (txtEditCtl.Text.Trim().Length > 0) { XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.LoadXml(txtEditCtl.Text); XmlNodeList xNodeList = xmlDoc.SelectNodes("/DataBase_Schema/Database"); _isXMLSchema = (xNodeList.Count > 0); xNodeList = null; } catch { } xmlDoc = null; } } return (bool)_isXMLSchema; } } public bool IsDatabaseDiff { get { // persist return value on the first time //if (_isXMLDiff == null) { _isXMLDiff = false; if (txtEditCtl.Text.Trim().Length > 0) { XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.LoadXml(txtEditCtl.Text); XmlNodeList xNodeList = xmlDoc.SelectNodes("/DataBase_Schema"); if (xNodeList.Count > 0) { _isXMLDiff = xNodeList[0].FirstChild.Value.ToLower().Trim().Replace("\n", "") == "diffdata" ? true : false; //expect in node "DiffData\n " } xNodeList = null; } catch { } xmlDoc = null; } } return (bool)_isXMLDiff; } } public bool IsDTSPackage { get { // persist return value on the first time //if (_isDTS == null) { _isDTS = false; if (txtEditCtl.Text.Trim().Length > 0) { XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.LoadXml(txtEditCtl.Text); XmlNodeList xNodeList = xmlDoc.SelectNodes("/DTS_File/Package"); _isDTS = (xNodeList.Count > 0); xNodeList = null; } catch { } xmlDoc = null; } } return (bool)_isDTS; } } public bool IsSelectedCompare { get { return _isSelected; } set { _isSelected = value; if (!_isSelected && IsDatabaseSchema) { if (menuItem3.Checked) menuItem3.Checked = false; if (!SelectedCompareDocs.ContainsKey(TabText)) return; int index = ((string)SelectedCompareDocs[TabText]).Equals("Source") ? 0 : 1; SelectedCompareDocs.Remove(TabText); index = index >= 0 ? index : Tag != null ? (int)Tag : -1; OnUnSelectedForCompare(index); txtEditCtl.Document.ReadOnly = false; Tag = null; } if (_isSelected && IsDatabaseSchema) { int count = SelectedCompareDocs.Count; if (count > 1) { _isSelected = false; if (menuItem3.Checked) menuItem3.Checked = false; MessageBox.Show("You can only select two XML Snapshots to compare!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (!menuItem3.Checked) menuItem3.Checked = true; if (count == 0 || !SelectedCompareDocs.ContainsKey(TabText)) { // TODO: check for databases already selected SelectedCompareDocs.Add(TabText, count == 0 ? "Source" : SelectedCompareDocs.ContainsValue("Target") ? "Source" : "Target"); } int index = ((string)SelectedCompareDocs[TabText]).Equals("Source") ? 0 : 1; Tag = index; txtEditCtl.Document.ReadOnly = true; // add eventhandler to this class to expose down in main window class OnSelectedForCompare(index); } } } public void ReHydrateDTS(string[] servers) { if (IsDTSPackage) { string PackageName = null; string Logfile = null; string PackageDescription = null; string _UID = null; string _PWD = null; string _SQLServer = null; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(txtEditCtl.Text); XmlNodeList xNodeList = xmlDoc.SelectNodes("/DTS_File/Package/Name"); PackageName = xNodeList.Count > 0 ? ((XmlNode)xNodeList.Item(0)).InnerText : ""; xNodeList = xmlDoc.SelectNodes("/DTS_File/Package/Description"); PackageDescription = xNodeList.Count > 0 ? ((XmlNode)xNodeList.Item(0)).InnerText : ""; xNodeList = xmlDoc.SelectNodes("/DTS_File/Package/LogFileName"); Logfile = xNodeList.Count > 0 ? ((XmlNode)xNodeList.Item(0)).InnerText : ""; xNodeList = null; xmlDoc = null; // create new DTS package object in memory DTSPackage2 oPackage = new DTSPackage2(PackageName, Logfile, PackageDescription); SQLSecuritySettings sss = new SQLSecuritySettings(servers); if (servers != null && servers.Length > 0) { sss.SetServerName(servers[0]); } DialogResult dr = sss.ShowDialog(this); if (dr == DialogResult.OK) { try { _UID = sss.User; _PWD = sss.PWD; _SQLServer = sss.SelectedSQLServer; // set up the DTS package authentication type if (sss.SecurityMode() == Lewis.SST.SQLMethods.SecurityType.Mixed) { oPackage.Authentication = DTSPackage2.authTypeFlags.Default; } else { oPackage.Authentication = DTSPackage2.authTypeFlags.Trusted; } // TODO: make this an async operation for larger dts files Cursor.Current = Cursors.WaitCursor; oPackage.Load(FileName); oPackage.Save(_SQLServer, _UID, _PWD, null); } catch (Exception ex) { Cursor.Current = Cursors.Default; MessageBox.Show(ex.Message); } finally { oPackage = null; Cursor.Current = Cursors.Default; } } } } } public class XMLDocEventArgs : EventArgs { public string [] selectedFileAndIndex; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.Net.Sockets { internal sealed partial class SafeCloseSocket : #if DEBUG DebugSafeHandleMinusOneIsInvalid #else SafeHandleMinusOneIsInvalid #endif { private ThreadPoolBoundHandle _iocpBoundHandle; private object _iocpBindingLock = new object(); public ThreadPoolBoundHandle IOCPBoundHandle { get { return _iocpBoundHandle; } } // Binds the Socket Win32 Handle to the ThreadPool's CompletionPort. public ThreadPoolBoundHandle GetOrAllocateThreadPoolBoundHandle() { if (_released) { // Keep the exception message pointing at the external type. throw new ObjectDisposedException(typeof(Socket).FullName); } // Check to see if the socket native _handle is already // bound to the ThreadPool's completion port. if (_iocpBoundHandle == null) { lock (_iocpBindingLock) { if (_iocpBoundHandle == null) { // Bind the socket native _handle to the ThreadPool. GlobalLog.Print("SafeCloseSocket#" + Logging.HashString(this) + "::BindToCompletionPort() calling ThreadPool.BindHandle()"); try { // The handle (this) may have been already released: // E.g.: The socket has been disposed in the main thread. A completion callback may // attempt starting another operation. _iocpBoundHandle = ThreadPoolBoundHandle.BindHandle(this); } catch (Exception exception) { if (ExceptionCheck.IsFatal(exception)) throw; CloseAsIs(); throw; } } } } return _iocpBoundHandle; } internal unsafe static SafeCloseSocket CreateWSASocket(byte* pinnedBuffer) { return CreateSocket(InnerSafeCloseSocket.CreateWSASocket(pinnedBuffer)); } internal static SafeCloseSocket CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return CreateSocket(InnerSafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType)); } internal static SafeCloseSocket Accept( SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize) { return CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize)); } private void InnerReleaseHandle() { // Keep m_IocpBoundHandle around after disposing it to allow freeing NativeOverlapped. // ThreadPoolBoundHandle allows FreeNativeOverlapped even after it has been disposed. if (_iocpBoundHandle != null) { _iocpBoundHandle.Dispose(); } } internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid { private SocketError InnerReleaseHandle() { SocketError errorCode; // If _blockable was set in BlockingRelease, it's safe to block here, which means // we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which // case we need to do some recovery. if (_blockable) { GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch."); errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket()#1:" + errorCode.ToString()); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return errorCode; } // The socket must be non-blocking with a linger timeout set. // We have to set the socket to blocking. int nonBlockCmd = 0; errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref nonBlockCmd); if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") ioctlsocket()#1:" + errorCode.ToString()); // This can fail if there's a pending WSAEventSelect. Try canceling it. if (errorCode == SocketError.InvalidArgument) { errorCode = Interop.Winsock.WSAEventSelect( handle, IntPtr.Zero, Interop.Winsock.AsyncEventBits.FdNone); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") WSAEventSelect():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString()); // Now retry the ioctl. errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref nonBlockCmd); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") ioctlsocket#2():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString()); } // If that succeeded, try again. if (errorCode == SocketError.Success) { errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket#2():" + errorCode.ToString()); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return errorCode; } } // It failed. Fall through to the regular abortive close. } // By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST). Interop.Winsock.Linger lingerStruct; lingerStruct.OnOff = 1; lingerStruct.Time = 0; errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lingerStruct, 4); #if DEBUG _closeSocketLinger = errorCode; #endif if (errorCode == SocketError.SocketError) errorCode = (SocketError)Marshal.GetLastWin32Error(); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString()); if (errorCode != SocketError.Success && errorCode != SocketError.InvalidArgument && errorCode != SocketError.ProtocolOption) { // Too dangerous to try closesocket() - it might block! return errorCode; } errorCode = Interop.Winsock.closesocket(handle); #if DEBUG _closeSocketHandle = handle; _closeSocketResult = errorCode; #endif GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket#3():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString()); return errorCode; } internal unsafe static InnerSafeCloseSocket CreateWSASocket(byte* pinnedBuffer) { // NOTE: -1 is the value for FROM_PROTOCOL_INFO. InnerSafeCloseSocket result = Interop.Winsock.WSASocketW((AddressFamily)(-1), (SocketType)(-1), (ProtocolType)(-1), pinnedBuffer, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } internal static InnerSafeCloseSocket CreateWSASocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { InnerSafeCloseSocket result = Interop.Winsock.WSASocketW(addressFamily, socketType, protocolType, IntPtr.Zero, 0, Interop.Winsock.SocketConstructorFlags.WSA_FLAG_OVERLAPPED); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } internal static InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize) { InnerSafeCloseSocket result = Interop.Winsock.accept(socketHandle.DangerousGetHandle(), socketAddress, ref socketAddressSize); if (result.IsInvalid) { result.SetHandleAsInvalid(); } return result; } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Text.RegularExpressions; using NAudio.Utils; using NAudio.Midi; namespace MarkHeath.MidiUtils { class MidiConverter { public event EventHandler<ProgressEventArgs> Progress; int filesConverted; int filesCopied; int directoriesCreated; int errors; DateTime startTime; Properties.Settings settings; Regex ezdFileName; NamingRules namingRules; public MidiConverter(NamingRules namingRules) { settings = Properties.Settings.Default; this.namingRules = namingRules; ezdFileName = new Regex(namingRules.FilenameRegex); } public void Start() { filesConverted = 0; filesCopied = 0; directoriesCreated = 0; errors = 0; startTime = DateTime.Now; LogInformation("{0} Beginning to Convert MIDI Files...", startTime); LogInformation("Processing using EZdrummer MIDI Converter v{0}", System.Windows.Forms.Application.ProductVersion); LogInformation("Output MIDI type {0}", settings.OutputMidiType); LogInformation("Output Channel Number {0}", settings.OutputChannelNumber == -1 ? "Unchanged" : settings.OutputChannelNumber.ToString()); // warn user if they are using hidden settings if (settings.RemoveSequencerSpecific) { LogWarning("Sequencer Specific Messages will be turned off"); } if (settings.RemoveEmptyTracks) { LogWarning("Empty type 1 tracks will be removed"); } if (!settings.RecreateEndTrackMarkers) { LogWarning("End track markers will be left where they are"); } if (settings.TrimTextEvents) { LogWarning("Text events will have whitespace trimmed"); } if (settings.AddNameMarker) { LogWarning("Name markers will be added"); } if (settings.RemoveExtraTempoEvents) { LogWarning("Extra tempo events will be removed"); } if (settings.RemoveExtraMarkers) { LogWarning("Extra markers will be removed"); } ProcessFolder(settings.InputFolder, settings.OutputFolder, new string[0]); TimeSpan timeTaken = DateTime.Now - startTime; LogInformation("Finished in {0}", timeTaken); LogInformation(Summary); } private string[] CreateNewContext(string[] oldContext, string newContextItem) { string[] newContext = new string[oldContext.Length + 1]; for (int n = 0; n < oldContext.Length; n++) { newContext[n] = oldContext[n]; } newContext[oldContext.Length] = newContextItem; return newContext; } private void ProcessFolder(string folder, string outputFolder, string[] context) { string[] midiFiles = Directory.GetFiles(folder); foreach (string midiFile in midiFiles) { try { ProcessFile(midiFile, outputFolder, context); } catch (Exception e) { LogError("Unexpected error processing file {0}", midiFile); LogError(e.ToString()); errors++; } } string[] subfolders = Directory.GetDirectories(folder); foreach (string subfolder in subfolders) { string folderName = Path.GetFileName(subfolder); string newOutputFolder = Path.Combine(outputFolder, folderName); string[] newContext = CreateNewContext(context, folderName); if (!Directory.Exists(newOutputFolder)) { if (settings.VerboseOutput) { LogTrace("Creating folder {0}", newOutputFolder); } Directory.CreateDirectory(newOutputFolder); directoriesCreated++; } ProcessFolder(subfolder, newOutputFolder, newContext); } } private void ProcessFile(string file, string outputFolder, string[] context) { bool copy = false; string fileName = Path.GetFileName(file); string target = Path.Combine(outputFolder, fileName); if (Path.GetExtension(file).ToLower() == ".mid") { MidiFile midiFile = new MidiFile(file); ConvertMidi(midiFile, target, CreateNewContext(context, Path.GetFileNameWithoutExtension(file))); filesConverted++; } else { copy = true; } if (copy) { if (settings.VerboseOutput) { LogTrace("Copying File {0} to {1}", fileName, target); } File.Copy(file, target); filesCopied++; } } private void ConvertMidi(MidiFile midiFile, string target, string[] context) { string fileNameWithoutExtension = context[context.Length - 1]; string name = null; long endTrackTime = -1; if (settings.UseFileName) { name = fileNameWithoutExtension; } if (settings.ApplyNamingRules) { if (ezdFileName.Match(fileNameWithoutExtension).Success) { name = CreateEzdName(context); } } int outputFileType = midiFile.FileFormat; int outputTrackCount; if (settings.OutputMidiType == OutputMidiType.Type0) { outputFileType = 0; } else if (settings.OutputMidiType == OutputMidiType.Type1) { outputFileType = 1; } if (outputFileType == 0) { outputTrackCount = 1; } else { if (midiFile.FileFormat == 0) outputTrackCount = 2; else outputTrackCount = midiFile.Tracks; } MidiEventCollection events = new MidiEventCollection(outputFileType, midiFile.DeltaTicksPerQuarterNote); for (int track = 0; track < outputTrackCount; track++) { events.AddTrack(); } if (name != null) { for (int track = 0; track < outputTrackCount; track++) { events[track].Add(new TextEvent(name, MetaEventType.SequenceTrackName, 0)); } if (settings.AddNameMarker) { events[0].Add(new TextEvent(name, MetaEventType.Marker, 0)); } } foreach (MidiEvent midiEvent in midiFile.Events[0]) { if (settings.OutputChannelNumber != -1) midiEvent.Channel = settings.OutputChannelNumber; MetaEvent metaEvent = midiEvent as MetaEvent; if (metaEvent != null) { bool exclude = false; switch (metaEvent.MetaEventType) { case MetaEventType.SequenceTrackName: if (name != null) { exclude = true; } break; case MetaEventType.SequencerSpecific: exclude = settings.RemoveSequencerSpecific; break; case MetaEventType.EndTrack: exclude = settings.RecreateEndTrackMarkers; endTrackTime = metaEvent.AbsoluteTime; break; case MetaEventType.SetTempo: if (metaEvent.AbsoluteTime != 0 && settings.RemoveExtraTempoEvents) { LogWarning("Removing a tempo event ({0}bpm) at {1} from {2}", ((TempoEvent)metaEvent).Tempo, metaEvent.AbsoluteTime, target); exclude = true; } break; case MetaEventType.TextEvent: if (settings.TrimTextEvents) { TextEvent textEvent = (TextEvent)midiEvent; textEvent.Text = textEvent.Text.Trim(); if (textEvent.Text.Length == 0) { exclude = true; } } break; case MetaEventType.Marker: if (settings.AddNameMarker && midiEvent.AbsoluteTime == 0) { exclude = true; } if (settings.RemoveExtraMarkers && midiEvent.AbsoluteTime > 0) { LogWarning("Removing a marker ({0}) at {1} from {2}", ((TextEvent)metaEvent).Text, metaEvent.AbsoluteTime, target); exclude = true; } break; } if (!exclude) { events[0].Add(midiEvent); } } else { if (outputFileType == 1) events[1].Add(midiEvent); else events[0].Add(midiEvent); } } // now do track 1 (Groove Monkee) for (int inputTrack = 1; inputTrack < midiFile.Tracks; inputTrack++) { int outputTrack; if(outputFileType == 1) outputTrack = inputTrack; else outputTrack = 0; foreach (MidiEvent midiEvent in midiFile.Events[inputTrack]) { if (settings.OutputChannelNumber != -1) midiEvent.Channel = settings.OutputChannelNumber; bool exclude = false; MetaEvent metaEvent = midiEvent as MetaEvent; if (metaEvent != null) { switch (metaEvent.MetaEventType) { case MetaEventType.SequenceTrackName: if (name != null) { exclude = true; } break; case MetaEventType.SequencerSpecific: exclude = settings.RemoveSequencerSpecific; break; case MetaEventType.EndTrack: exclude = settings.RecreateEndTrackMarkers; break; } } if (!exclude) { events[outputTrack].Add(midiEvent); } } if(outputFileType == 1 && settings.RecreateEndTrackMarkers) { AppendEndMarker(events[outputTrack]); } } if (settings.RecreateEndTrackMarkers) { if (outputFileType == 1) { // if we are converting type 0 to type 1 and recreating end markers, if (midiFile.FileFormat == 0) { AppendEndMarker(events[1]); } } // make sure that track zero has an end track marker AppendEndMarker(events[0]); } else { // if we are converting type 0 to type 1 without recreating end markers, // then we still need to add an end marker to track 1 if (midiFile.FileFormat == 0) { // use the time we got from track 0 as the end track time for track 1 if (endTrackTime == -1) { LogError("Error adding track 1 end marker"); // make it a valid MIDI file anyway AppendEndMarker(events[1]); } else { events[1].Add(new MetaEvent(MetaEventType.EndTrack, 0, endTrackTime)); } } } if (settings.VerboseOutput) { LogTrace("Processing {0}: {1}", name, target); } if (settings.RemoveEmptyTracks) { MidiEventCollection newList = new MidiEventCollection(events.MidiFileType, events.DeltaTicksPerQuarterNote); int removed = 0; for (int track = 0; track < events.Tracks; track++) { IList<MidiEvent> trackEvents = events[track]; if (track < 2) { newList.AddTrack(events[track]); } else { if(HasNotes(trackEvents)) { newList.AddTrack(trackEvents); } else { removed++; } } } if (removed > 0) { events = newList; LogWarning("Removed {0} empty tracks from {1} ({2} remain)", removed, target, events.Tracks); } } MidiFile.Export(target, events); } private bool HasNotes(IList<MidiEvent> midiEvents) { foreach (MidiEvent midiEvent in midiEvents) { if (midiEvent.CommandCode == MidiCommandCode.NoteOn) return true; } return false; } private void AppendEndMarker(IList<MidiEvent> eventList) { long absoluteTime = 0; if (eventList.Count > 0) absoluteTime = eventList[eventList.Count - 1].AbsoluteTime; eventList.Add(new MetaEvent(MetaEventType.EndTrack, 0, absoluteTime)); } private string CreateEzdName(string[] context) { StringBuilder name = new StringBuilder(); int contextLevels = Math.Min(namingRules.ContextDepth, context.Length); for (int n = 0; n < contextLevels; n++) { string filtered = ApplyNameFilters(context[context.Length - contextLevels + n]); if (filtered.Length > 0) { name.Append(filtered); if (n != contextLevels - 1) name.Append(namingRules.ContextSeparator); } } return name.ToString(); } private string ApplyNameFilters(string name) { foreach (NamingRule rule in namingRules.Rules) { name = Regex.Replace(name, rule.Regex, rule.Replacement); } return name; } private void LogTrace(string message, params object[] args) { OnProgress(this, new ProgressEventArgs(ProgressMessageType.Trace, message, args)); } private void LogInformation(string message, params object[] args) { OnProgress(this, new ProgressEventArgs(ProgressMessageType.Information, message, args)); } private void LogWarning(string message, params object[] args) { OnProgress(this, new ProgressEventArgs(ProgressMessageType.Warning, message, args)); } private void LogError(string message, params object[] args) { OnProgress(this, new ProgressEventArgs(ProgressMessageType.Error, message, args)); } protected void OnProgress(object sender, ProgressEventArgs args) { if (Progress != null) { Progress(sender, args); } } public string Summary { get { return String.Format("Files Converted {0}\r\nFiles Copied {1}\r\nFolders Created {2}\r\nErrors {3}", filesConverted, filesCopied, directoriesCreated, errors); } } } }
using System; using System.IO; using System.Linq; using Baseline; using Marten.Events; using Marten.Schema; using Marten.Schema.Identity.Sequences; using Marten.Testing.Documents; using Marten.Testing.Events; using Shouldly; using StructureMap; using Xunit; using Issue = Marten.Testing.Documents.Issue; namespace Marten.Testing.Schema { public class DocumentSchemaOnOtherSchemaTests : IntegratedFixture { private readonly string _binAllsql = AppContext.BaseDirectory.AppendPath("bin", "allsql"); private readonly string _binAllsql2 = AppContext.BaseDirectory.AppendPath("bin", "allsql2"); private IDocumentSchema theSchema => theStore.Schema; public DocumentSchemaOnOtherSchemaTests() { StoreOptions(_ => _.DatabaseSchemaName = "other"); } [Fact] public void generate_ddl() { theStore.Tenancy.Default.StorageFor(typeof(User)); theStore.Tenancy.Default.StorageFor(typeof(Issue)); theStore.Tenancy.Default.StorageFor(typeof(Company)); var sql = theSchema.ToDDL(); sql.ShouldContain("CREATE OR REPLACE FUNCTION other.mt_upsert_user"); sql.ShouldContain("CREATE OR REPLACE FUNCTION other.mt_upsert_issue"); sql.ShouldContain("CREATE OR REPLACE FUNCTION other.mt_upsert_company"); sql.ShouldContain("CREATE TABLE other.mt_doc_user"); sql.ShouldContain("CREATE TABLE other.mt_doc_issue"); sql.ShouldContain("CREATE TABLE other.mt_doc_company"); } [Fact] public void do_not_write_event_sql_if_the_event_graph_is_not_active() { theStore.Events.IsActive.ShouldBeFalse(); theSchema.ToDDL().ShouldNotContain("other.mt_streams"); } [Fact] public void do_write_the_event_sql_if_the_event_graph_is_active() { theStore.Events.AddEventType(typeof(MembersJoined)); theStore.Events.IsActive.ShouldBeTrue(); theSchema.ToDDL().ShouldContain("other.mt_streams"); } [Fact] public void builds_schema_objects_on_the_fly_as_needed() { theStore.Tenancy.Default.StorageFor(typeof(User)).ShouldNotBeNull(); theStore.Tenancy.Default.StorageFor(typeof(Issue)).ShouldNotBeNull(); theStore.Tenancy.Default.StorageFor(typeof(Company)).ShouldNotBeNull(); var tables = theSchema.DbObjects.SchemaTables(); tables.ShouldContain("other.mt_doc_user"); tables.ShouldContain("other.mt_doc_issue"); tables.ShouldContain("other.mt_doc_company"); var functions = theSchema.DbObjects.Functions(); functions.ShouldContain("other.mt_upsert_user"); functions.ShouldContain("other.mt_upsert_issue"); functions.ShouldContain("other.mt_upsert_company"); } [Fact] public void do_not_rebuild_a_table_that_already_exists() { using (var container1 = Container.For<DevelopmentModeRegistry>()) { using (var session = container1.GetInstance<IDocumentStore>().LightweightSession()) { session.Store(new User()); session.Store(new User()); session.Store(new User()); session.SaveChanges(); } } using (var container2 = Container.For<DevelopmentModeRegistry>()) { using (var session = container2.GetInstance<IDocumentStore>().LightweightSession()) { session.Query<User>().Count().ShouldBeGreaterThanOrEqualTo(3); } } } [Fact] public void throw_ambigous_alias_exception_when_you_have_duplicate_document_aliases() { using (var container = Container.For<DevelopmentModeRegistry>()) { var schema = container.GetInstance<IDocumentSchema>(); var storage = container.GetInstance<IDocumentStore>().As<DocumentStore>().Storage; storage.StorageFor(typeof(Examples.User)).ShouldNotBeNull(); Exception<AmbiguousDocumentTypeAliasesException>.ShouldBeThrownBy(() => { storage.StorageFor(typeof(User)); }); } } [Fact] public void can_write_ddl_by_type_with_schema_creation() { using (var store = DocumentStore.For(_ => { _.DatabaseSchemaName = "yet_another"; _.RegisterDocumentType<Company>(); _.Schema.For<User>().DatabaseSchemaName("other"); _.Events.DatabaseSchemaName = "event_store"; _.Events.EventMappingFor<MembersJoined>(); _.Connection(ConnectionSource.ConnectionString); })) { store.Schema.WriteDDLByType(_binAllsql); } string filename = _binAllsql.AppendPath("all.sql"); var fileSystem = new FileSystem(); fileSystem.FileExists(filename).ShouldBeTrue(); var contents = fileSystem.ReadStringFromFile(filename); contents.ShouldContain("CREATE SCHEMA event_store"); contents.ShouldContain("CREATE SCHEMA other"); contents.ShouldContain("CREATE SCHEMA yet_another"); } [Fact] public void write_ddl_by_type_generates_the_all_sql_script() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.DatabaseSchemaName = "yet_another"; _.Schema.For<User>().DatabaseSchemaName("other"); _.Events.AddEventType(typeof(MembersJoined)); _.Connection(ConnectionSource.ConnectionString); })) { store.Schema.WriteDDLByType(_binAllsql); } var filename = _binAllsql.AppendPath("all.sql"); var lines = new FileSystem().ReadStringFromFile(filename).ReadLines().Select(x => x.Trim()).ToArray(); // should create the schemas too lines.ShouldContain("EXECUTE 'CREATE SCHEMA yet_another';"); lines.ShouldContain("EXECUTE 'CREATE SCHEMA other';"); lines.ShouldContain("\\i user.sql"); lines.ShouldContain("\\i company.sql"); lines.ShouldContain("\\i issue.sql"); lines.ShouldContain("\\i eventstore.sql"); } [Fact] public void write_ddl_by_type_with_no_events() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.Connection(ConnectionSource.ConnectionString); })) { store.Events.IsActive.ShouldBeFalse(); store.Schema.WriteDDLByType(_binAllsql); } var fileSystem = new FileSystem(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow("*mt_streams.sql")) .Any().ShouldBeFalse(); } [Fact] public void write_ddl_by_type_with_events() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.Events.AddEventType(typeof(MembersJoined)); _.Connection(ConnectionSource.ConnectionString); })) { store.Events.IsActive.ShouldBeTrue(); store.Schema.WriteDDLByType(_binAllsql); } var fileSystem = new FileSystem(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow("eventstore.sql")) .Any().ShouldBeTrue(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow(".sql")) .Any().ShouldBeFalse(); } [Fact] public void fixing_bug_343_double_export_of_events() { using (var store = DocumentStore.For(_ => { _.RegisterDocumentType<User>(); _.RegisterDocumentType<Company>(); _.RegisterDocumentType<Issue>(); _.Events.AddEventType(typeof(MembersJoined)); _.Connection(ConnectionSource.ConnectionString); })) { store.Events.IsActive.ShouldBeTrue(); store.Schema.WriteDDLByType(_binAllsql); } var fileSystem = new FileSystem(); fileSystem.FindFiles(_binAllsql, FileSet.Shallow(".sql")) .Any().ShouldBeFalse(); } [Fact] public void resolve_a_document_mapping_for_an_event_type() { StoreOptions(_ => { _.Events.AddEventType(typeof(RaceStarted)); }); theStore.Tenancy.Default.MappingFor(typeof(RaceStarted)).ShouldBeOfType<EventMapping<RaceStarted>>() .DocumentType.ShouldBe(typeof(RaceStarted)); } [Fact] public void resolve_storage_for_event_type() { theStore.Events.AddEventType(typeof(RaceStarted)); theStore.Tenancy.Default.StorageFor(typeof(RaceStarted)).ShouldBeOfType<EventMapping<RaceStarted>>() .DocumentType.ShouldBe(typeof(RaceStarted)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MongoInClustorWithFailover.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Linq; using System.Text; using Eto.Drawing; using Eto.Forms; using swi = Windows.UI.Xaml.Input; using swm = Windows.UI.Xaml.Media; using wf = Windows.Foundation; using sw = Windows.UI.Xaml; //using sp = System.Printing; using swc = Windows.UI.Xaml.Controls; using swmi = Windows.UI.Xaml.Media.Imaging; using wu = Windows.UI; using wuc = Windows.UI.Core; using wut = Windows.UI.Text; using System.Text.RegularExpressions; using Eto.Direct2D.Drawing; //using Eto.WinRT.Drawing; namespace Eto.WinRT { /// <summary> /// Xaml conversions. /// </summary> /// <copyright>(c) 2014 by Vivek Jhaveri</copyright> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public static partial class Conversions { public const float WheelDelta = 120f; public static readonly wf.Size PositiveInfinitySize = new wf.Size(double.PositiveInfinity, double.PositiveInfinity); public static readonly wf.Size ZeroSize = new wf.Size(0, 0); public static wu.Color ToWpf(this Color value) { return wu.Color.FromArgb((byte)(value.A * byte.MaxValue), (byte)(value.R * byte.MaxValue), (byte)(value.G * byte.MaxValue), (byte)(value.B * byte.MaxValue)); } public static swm.Brush ToWpfBrush(this Color value, swm.Brush brush = null) { var solidBrush = brush as swm.SolidColorBrush; if (solidBrush == null #if TODO_XAML || solidBrush.IsSealed #endif ) { solidBrush = new swm.SolidColorBrush(); } solidBrush.Color = value.ToWpf(); return solidBrush; } public static Color ToEto(this wu.Color value) { return new Color { A = value.A / 255f, R = value.R / 255f, G = value.G / 255f, B = value.B / 255f }; } public static Color ToEtoColor(this swm.Brush brush) { var solidBrush = brush as swm.SolidColorBrush; if (solidBrush != null) return solidBrush.Color.ToEto(); return Colors.Transparent; } public static Padding ToEto(this sw.Thickness value) { return new Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom); } public static sw.Thickness ToWpf(this Padding value) { return new sw.Thickness(value.Left, value.Top, value.Right, value.Bottom); } public static Rectangle ToEto(this wf.Rect value) { return new Rectangle((int)value.X, (int)value.Y, (int)value.Width, (int)value.Height); } public static RectangleF ToEtoF(this wf.Rect value) { return new RectangleF((float)value.X, (float)value.Y, (float)value.Width, (float)value.Height); } public static wf.Rect ToWpf(this Rectangle value) { return new wf.Rect(value.X, value.Y, value.Width, value.Height); } #if TODO_XAML public static sw.Int32Rect ToWpfInt32(this Rectangle value) { return new sw.Int32Rect(value.X, value.Y, value.Width, value.Height); } #endif public static wf.Rect ToWpf(this RectangleF value) { return new wf.Rect(value.X, value.Y, value.Width, value.Height); } public static SizeF ToEto(this wf.Size value) { return new SizeF((float)value.Width, (float)value.Height); } public static Size ToEtoSize(this wf.Size value) { return new Size((int)(double.IsNaN(value.Width) ? -1 : value.Width), (int)(double.IsNaN(value.Height) ? -1 : value.Height)); } public static wf.Size ToWpf(this Size value) { return new wf.Size(value.Width == -1 ? double.NaN : value.Width, value.Height == -1 ? double.NaN : value.Height); } public static wf.Size ToWpf(this SizeF value) { return new wf.Size(value.Width, value.Height); } public static PointF ToEto(this wf.Point value) { return new PointF((float)value.X, (float)value.Y); } public static Point ToEtoPoint(this wf.Point value) { return new Point((int)value.X, (int)value.Y); } public static wf.Point ToWpf(this Point value) { return new wf.Point(value.X, value.Y); } public static wf.Point ToWpf(this PointF value) { return new wf.Point(value.X, value.Y); } public static string ToWpfMneumonic(this string value) { if (value == null) return string.Empty; value = value.Replace("_", "__"); var match = Regex.Match(value, @"(?<=([^&](?:[&]{2})*)|^)[&](?![&])"); if (match.Success) { var sb = new StringBuilder(value); sb[match.Index] = '_'; sb.Replace("&&", "&"); return sb.ToString(); } return value.Replace("&&", "&"); } public static string ToEtoMneumonic(this string value) { if (value == null) return null; var match = Regex.Match(value, @"(?<=([^_](?:[_]{2})*)|^)[_](?![_])"); if (match.Success) { var sb = new StringBuilder(value); sb[match.Index] = '&'; sb.Replace("__", "_"); return sb.ToString(); } value = value.Replace("__", "_"); return value; } #if TODO_XAML public static KeyEventArgs ToEto(this wuc.KeyEventArgs e, KeyEventType keyType) { var key = KeyMap.Convert(e.Key, swi.Keyboard.Modifiers); return new KeyEventArgs(key, keyType) { Handled = e.Handled }; } #endif #if TODO_XAML public static MouseEventArgs ToEto(this swi.MouseButtonEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.ChangedButton == swi.MouseButton.Left && e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.ChangedButton == swi.MouseButton.Right && e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.ChangedButton == swi.MouseButton.Middle && e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = Keys.None; var location = e.GetPosition(control).ToEto(); return new MouseEventArgs(buttons, modifiers, location); } public static MouseEventArgs ToEto(this swi.MouseEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = Keys.None; var location = e.GetPosition(control).ToEto(); return new MouseEventArgs(buttons, modifiers, location); } public static MouseEventArgs ToEto(this swi.MouseWheelEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = Keys.None; var location = e.GetPosition(control).ToEto(); var delta = new SizeF(0, (float)e.Delta / WheelDelta); return new MouseEventArgs(buttons, modifiers, location, delta); } #endif #if TODO_XAML public static swm.BitmapScalingMode ToWpf(this ImageInterpolation value) { switch (value) { case ImageInterpolation.Default: return swm.BitmapScalingMode.Unspecified; case ImageInterpolation.None: return swm.BitmapScalingMode.NearestNeighbor; case ImageInterpolation.Low: return swm.BitmapScalingMode.LowQuality; case ImageInterpolation.Medium: return swm.BitmapScalingMode.HighQuality; case ImageInterpolation.High: return swm.BitmapScalingMode.HighQuality; default: throw new NotSupportedException(); } } public static ImageInterpolation ToEto(this swm.BitmapScalingMode value) { switch (value) { case swm.BitmapScalingMode.HighQuality: return ImageInterpolation.High; case swm.BitmapScalingMode.LowQuality: return ImageInterpolation.Low; case swm.BitmapScalingMode.NearestNeighbor: return ImageInterpolation.None; case swm.BitmapScalingMode.Unspecified: return ImageInterpolation.Default; default: throw new NotSupportedException(); } } public static sp.PageOrientation ToSP(this PageOrientation value) { switch (value) { case PageOrientation.Portrait: return sp.PageOrientation.Portrait; case PageOrientation.Landscape: return sp.PageOrientation.Landscape; default: throw new NotSupportedException(); } } public static PageOrientation ToEto(this sp.PageOrientation? value) { if (value == null) return PageOrientation.Portrait; switch (value.Value) { case sp.PageOrientation.Landscape: return PageOrientation.Landscape; case sp.PageOrientation.Portrait: return PageOrientation.Portrait; default: throw new NotSupportedException(); } } public static swc.PageRange ToPageRange(this Range range) { return new swc.PageRange(range.Start, range.End); } public static Range ToEto(this swc.PageRange range) { return new Range(range.PageFrom, range.PageTo - range.PageFrom + 1); } public static swc.PageRangeSelection ToSWC(this PrintSelection value) { switch (value) { case PrintSelection.AllPages: return swc.PageRangeSelection.AllPages; case PrintSelection.SelectedPages: return swc.PageRangeSelection.UserPages; default: throw new NotSupportedException(); } } public static PrintSelection ToEto(this swc.PageRangeSelection value) { switch (value) { case swc.PageRangeSelection.AllPages: return PrintSelection.AllPages; case swc.PageRangeSelection.UserPages: return PrintSelection.SelectedPages; default: throw new NotSupportedException(); } } #endif public static Size GetSize(this sw.FrameworkElement element) { #if TODO_XAML if (element.IsVisible && (!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight))) return new Size((int)element.ActualWidth, (int)element.ActualHeight); return new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height)); #else if ((!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight))) return new Size((int)element.ActualWidth, (int)element.ActualHeight); return new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height)); #endif } public static void SetSize(this sw.FrameworkElement element, Size size) { element.Width = size.Width == -1 ? double.NaN : size.Width; element.Height = size.Height == -1 ? double.NaN : size.Height; } public static void SetSize(this sw.FrameworkElement element, wf.Size size) { element.Width = size.Width; element.Height = size.Height; } public static FontStyle Convert(wut.FontStyle fontStyle, wut.FontWeight fontWeight) { var style = FontStyle.None; if (fontStyle == wut.FontStyle.Italic) style |= FontStyle.Italic; if (fontStyle == wut.FontStyle.Oblique) style |= FontStyle.Italic; if (ReferenceEquals(fontWeight, wut.FontWeights.Bold)) style |= FontStyle.Bold; return style; } #if TODO_XAML public static FontDecoration Convert(sw.TextDecorationCollection decorations) { var decoration = FontDecoration.None; if (decorations != null) { if (sw.TextDecorations.Underline.All(decorations.Contains)) decoration |= FontDecoration.Underline; if (sw.TextDecorations.Strikethrough.All(decorations.Contains)) decoration |= FontDecoration.Strikethrough; } return decoration; } #endif public static swmi.BitmapSource ToWpf(this Image image, int? size = null) { #if TODO_XAML if (image == null) return null; var imageHandler = image.Handler as IWpfImage; if (imageHandler != null) return imageHandler.GetImageClosestToSize(size); return image.ControlObject as swmi.BitmapSource; #else return image.ControlObject as swmi.BitmapSource; #endif } public static swc.Image ToWpfImage(this Image image, int? size = null) { var source = image.ToWpf(size); if (source == null) return null; var swcImage = new swc.Image { Source = source }; if (size != null) { swcImage.MaxWidth = size.Value; swcImage.MaxHeight = size.Value; } return swcImage; } #if TODO_XAML public static swm.Pen ToWpf(this Pen pen, bool clone = false) { var p = (swm.Pen)pen.ControlObject; if (clone) p = p.Clone(); return p; } #endif public static swm.PenLineJoin ToWpf(this PenLineJoin value) { switch (value) { case PenLineJoin.Miter: return swm.PenLineJoin.Miter; case PenLineJoin.Bevel: return swm.PenLineJoin.Bevel; case PenLineJoin.Round: return swm.PenLineJoin.Round; default: throw new NotSupportedException(); } } public static PenLineJoin ToEto(this swm.PenLineJoin value) { switch (value) { case swm.PenLineJoin.Bevel: return PenLineJoin.Bevel; case swm.PenLineJoin.Miter: return PenLineJoin.Miter; case swm.PenLineJoin.Round: return PenLineJoin.Round; default: throw new NotSupportedException(); } } public static swm.PenLineCap ToWpf(this PenLineCap value) { switch (value) { case PenLineCap.Butt: return swm.PenLineCap.Flat; case PenLineCap.Round: return swm.PenLineCap.Round; case PenLineCap.Square: return swm.PenLineCap.Square; default: throw new NotSupportedException(); } } public static PenLineCap ToEto(this swm.PenLineCap value) { switch (value) { case swm.PenLineCap.Flat: return PenLineCap.Butt; case swm.PenLineCap.Round: return PenLineCap.Round; case swm.PenLineCap.Square: return PenLineCap.Square; default: throw new NotSupportedException(); } } public static swm.Brush ToWpf(this Brush brush, bool clone = false) { var b = (swm.Brush)brush.ControlObject; if (clone) { #if TODO_XAML b = b.Clone(); #else throw new NotImplementedException(); #endif } return b; } public static swm.Matrix ToWpf(this IMatrix matrix) { return (swm.Matrix)matrix.ControlObject; } public static swm.Transform ToWpfTransform(this IMatrix matrix) { return new swm.MatrixTransform { Matrix = matrix.ToWpf() }; } #if TODO_XAML public static IMatrix ToEtoMatrix(this swm.Transform transform) { return new MatrixHandler(transform.Value); } #endif public static swm.PathGeometry ToWpf(this IGraphicsPath path) { return (swm.PathGeometry)path.ControlObject; } public static swm.GradientSpreadMethod ToWpf(this GradientWrapMode wrap) { switch (wrap) { case GradientWrapMode.Reflect: return swm.GradientSpreadMethod.Reflect; case GradientWrapMode.Repeat: return swm.GradientSpreadMethod.Repeat; default: throw new NotSupportedException(); } } public static GradientWrapMode ToEto(this swm.GradientSpreadMethod spread) { switch (spread) { case swm.GradientSpreadMethod.Reflect: return GradientWrapMode.Reflect; case swm.GradientSpreadMethod.Repeat: return GradientWrapMode.Repeat; default: throw new NotSupportedException(); } } public static TextAlignment ToEto(this sw.TextAlignment align) { switch (align) { case sw.TextAlignment.Left: return TextAlignment.Left; case sw.TextAlignment.Right: return TextAlignment.Right; case sw.TextAlignment.Center: return TextAlignment.Center; default: throw new NotSupportedException(); } } public static sw.TextAlignment ToWpfTextAlignment(this TextAlignment align) { switch (align) { case TextAlignment.Center: return sw.TextAlignment.Center; case TextAlignment.Left: return sw.TextAlignment.Left; case TextAlignment.Right: return sw.TextAlignment.Right; default: throw new NotSupportedException(); } } #if TODO_XAML public static WindowStyle ToEto(this sw.WindowStyle style) { switch (style) { case sw.WindowStyle.None: return WindowStyle.None; case sw.WindowStyle.ThreeDBorderWindow: return WindowStyle.Default; default: throw new NotSupportedException(); } } public static sw.WindowStyle ToWpf(this WindowStyle style) { switch (style) { case WindowStyle.None: return sw.WindowStyle.None; case WindowStyle.Default: return sw.WindowStyle.ThreeDBorderWindow; default: throw new NotSupportedException(); } } #endif } }
namespace Trionic5Controls { partial class frmPartnumberLookup { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmPartnumberLookup)); this.buttonEdit1 = new DevExpress.XtraEditors.ButtonEdit(); this.groupControl1 = new DevExpress.XtraEditors.GroupControl(); this.lblStageIII = new DevExpress.XtraEditors.LabelControl(); this.lblStageII = new DevExpress.XtraEditors.LabelControl(); this.lblStageI = new DevExpress.XtraEditors.LabelControl(); this.lblTorque = new DevExpress.XtraEditors.LabelControl(); this.lblPower = new DevExpress.XtraEditors.LabelControl(); this.lblMaxBoostAUT = new DevExpress.XtraEditors.LabelControl(); this.lblMaxBoostManual = new DevExpress.XtraEditors.LabelControl(); this.lblBaseBoost = new DevExpress.XtraEditors.LabelControl(); this.lblEngineType = new DevExpress.XtraEditors.LabelControl(); this.lblCarModel = new DevExpress.XtraEditors.LabelControl(); this.labelControl11 = new DevExpress.XtraEditors.LabelControl(); this.labelControl10 = new DevExpress.XtraEditors.LabelControl(); this.labelControl9 = new DevExpress.XtraEditors.LabelControl(); this.labelControl8 = new DevExpress.XtraEditors.LabelControl(); this.labelControl7 = new DevExpress.XtraEditors.LabelControl(); this.labelControl6 = new DevExpress.XtraEditors.LabelControl(); this.labelControl5 = new DevExpress.XtraEditors.LabelControl(); this.labelControl4 = new DevExpress.XtraEditors.LabelControl(); this.checkEdit5 = new DevExpress.XtraEditors.CheckEdit(); this.labelControl3 = new DevExpress.XtraEditors.LabelControl(); this.labelControl2 = new DevExpress.XtraEditors.LabelControl(); this.checkEdit4 = new DevExpress.XtraEditors.CheckEdit(); this.checkEdit3 = new DevExpress.XtraEditors.CheckEdit(); this.checkEdit2 = new DevExpress.XtraEditors.CheckEdit(); this.checkEdit1 = new DevExpress.XtraEditors.CheckEdit(); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton2 = new DevExpress.XtraEditors.SimpleButton(); this.simpleButton3 = new DevExpress.XtraEditors.SimpleButton(); ((System.ComponentModel.ISupportInitialize)(this.buttonEdit1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).BeginInit(); this.groupControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit5.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit4.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit3.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit1.Properties)).BeginInit(); this.SuspendLayout(); // // buttonEdit1 // resources.ApplyResources(this.buttonEdit1, "buttonEdit1"); this.buttonEdit1.BackgroundImage = null; this.buttonEdit1.EditValue = null; this.buttonEdit1.Name = "buttonEdit1"; this.buttonEdit1.Properties.AccessibleDescription = null; this.buttonEdit1.Properties.AccessibleName = null; this.buttonEdit1.Properties.AutoHeight = ((bool)(resources.GetObject("buttonEdit1.Properties.AutoHeight"))); this.buttonEdit1.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("buttonEdit1.Properties.Buttons"))), ((System.Drawing.Image)(resources.GetObject("buttonEdit1.Properties.Buttons1"))), null)}); this.buttonEdit1.Properties.Mask.AutoComplete = ((DevExpress.XtraEditors.Mask.AutoCompleteType)(resources.GetObject("buttonEdit1.Properties.Mask.AutoComplete"))); this.buttonEdit1.Properties.Mask.BeepOnError = ((bool)(resources.GetObject("buttonEdit1.Properties.Mask.BeepOnError"))); this.buttonEdit1.Properties.Mask.EditMask = resources.GetString("buttonEdit1.Properties.Mask.EditMask"); this.buttonEdit1.Properties.Mask.IgnoreMaskBlank = ((bool)(resources.GetObject("buttonEdit1.Properties.Mask.IgnoreMaskBlank"))); this.buttonEdit1.Properties.Mask.MaskType = ((DevExpress.XtraEditors.Mask.MaskType)(resources.GetObject("buttonEdit1.Properties.Mask.MaskType"))); this.buttonEdit1.Properties.Mask.PlaceHolder = ((char)(resources.GetObject("buttonEdit1.Properties.Mask.PlaceHolder"))); this.buttonEdit1.Properties.Mask.SaveLiteral = ((bool)(resources.GetObject("buttonEdit1.Properties.Mask.SaveLiteral"))); this.buttonEdit1.Properties.Mask.ShowPlaceHolders = ((bool)(resources.GetObject("buttonEdit1.Properties.Mask.ShowPlaceHolders"))); this.buttonEdit1.Properties.Mask.UseMaskAsDisplayFormat = ((bool)(resources.GetObject("buttonEdit1.Properties.Mask.UseMaskAsDisplayFormat"))); this.buttonEdit1.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.buttonEdit1_ButtonClick); this.buttonEdit1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.buttonEdit1_KeyDown); // // groupControl1 // this.groupControl1.AccessibleDescription = null; this.groupControl1.AccessibleName = null; resources.ApplyResources(this.groupControl1, "groupControl1"); this.groupControl1.Controls.Add(this.lblStageIII); this.groupControl1.Controls.Add(this.lblStageII); this.groupControl1.Controls.Add(this.lblStageI); this.groupControl1.Controls.Add(this.lblTorque); this.groupControl1.Controls.Add(this.lblPower); this.groupControl1.Controls.Add(this.lblMaxBoostAUT); this.groupControl1.Controls.Add(this.lblMaxBoostManual); this.groupControl1.Controls.Add(this.lblBaseBoost); this.groupControl1.Controls.Add(this.lblEngineType); this.groupControl1.Controls.Add(this.lblCarModel); this.groupControl1.Controls.Add(this.labelControl11); this.groupControl1.Controls.Add(this.labelControl10); this.groupControl1.Controls.Add(this.labelControl9); this.groupControl1.Controls.Add(this.labelControl8); this.groupControl1.Controls.Add(this.labelControl7); this.groupControl1.Controls.Add(this.labelControl6); this.groupControl1.Controls.Add(this.labelControl5); this.groupControl1.Controls.Add(this.labelControl4); this.groupControl1.Controls.Add(this.checkEdit5); this.groupControl1.Controls.Add(this.labelControl3); this.groupControl1.Controls.Add(this.labelControl2); this.groupControl1.Controls.Add(this.checkEdit4); this.groupControl1.Controls.Add(this.checkEdit3); this.groupControl1.Controls.Add(this.checkEdit2); this.groupControl1.Controls.Add(this.checkEdit1); this.groupControl1.Name = "groupControl1"; // // lblStageIII // this.lblStageIII.AccessibleDescription = null; this.lblStageIII.AccessibleName = null; resources.ApplyResources(this.lblStageIII, "lblStageIII"); this.lblStageIII.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblStageIII.Appearance.Options.UseForeColor = true; this.lblStageIII.Name = "lblStageIII"; // // lblStageII // this.lblStageII.AccessibleDescription = null; this.lblStageII.AccessibleName = null; resources.ApplyResources(this.lblStageII, "lblStageII"); this.lblStageII.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblStageII.Appearance.Options.UseForeColor = true; this.lblStageII.Name = "lblStageII"; // // lblStageI // this.lblStageI.AccessibleDescription = null; this.lblStageI.AccessibleName = null; resources.ApplyResources(this.lblStageI, "lblStageI"); this.lblStageI.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblStageI.Appearance.Options.UseForeColor = true; this.lblStageI.Name = "lblStageI"; // // lblTorque // this.lblTorque.AccessibleDescription = null; this.lblTorque.AccessibleName = null; resources.ApplyResources(this.lblTorque, "lblTorque"); this.lblTorque.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblTorque.Appearance.Options.UseForeColor = true; this.lblTorque.Name = "lblTorque"; // // lblPower // this.lblPower.AccessibleDescription = null; this.lblPower.AccessibleName = null; resources.ApplyResources(this.lblPower, "lblPower"); this.lblPower.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblPower.Appearance.Options.UseForeColor = true; this.lblPower.Name = "lblPower"; // // lblMaxBoostAUT // this.lblMaxBoostAUT.AccessibleDescription = null; this.lblMaxBoostAUT.AccessibleName = null; resources.ApplyResources(this.lblMaxBoostAUT, "lblMaxBoostAUT"); this.lblMaxBoostAUT.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblMaxBoostAUT.Appearance.Options.UseForeColor = true; this.lblMaxBoostAUT.Name = "lblMaxBoostAUT"; // // lblMaxBoostManual // this.lblMaxBoostManual.AccessibleDescription = null; this.lblMaxBoostManual.AccessibleName = null; resources.ApplyResources(this.lblMaxBoostManual, "lblMaxBoostManual"); this.lblMaxBoostManual.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblMaxBoostManual.Appearance.Options.UseForeColor = true; this.lblMaxBoostManual.Name = "lblMaxBoostManual"; // // lblBaseBoost // this.lblBaseBoost.AccessibleDescription = null; this.lblBaseBoost.AccessibleName = null; resources.ApplyResources(this.lblBaseBoost, "lblBaseBoost"); this.lblBaseBoost.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblBaseBoost.Appearance.Options.UseForeColor = true; this.lblBaseBoost.Name = "lblBaseBoost"; // // lblEngineType // this.lblEngineType.AccessibleDescription = null; this.lblEngineType.AccessibleName = null; resources.ApplyResources(this.lblEngineType, "lblEngineType"); this.lblEngineType.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblEngineType.Appearance.Options.UseForeColor = true; this.lblEngineType.Name = "lblEngineType"; // // lblCarModel // this.lblCarModel.AccessibleDescription = null; this.lblCarModel.AccessibleName = null; resources.ApplyResources(this.lblCarModel, "lblCarModel"); this.lblCarModel.Appearance.ForeColor = System.Drawing.Color.Blue; this.lblCarModel.Appearance.Options.UseForeColor = true; this.lblCarModel.Name = "lblCarModel"; // // labelControl11 // this.labelControl11.AccessibleDescription = null; this.labelControl11.AccessibleName = null; resources.ApplyResources(this.labelControl11, "labelControl11"); this.labelControl11.Name = "labelControl11"; // // labelControl10 // this.labelControl10.AccessibleDescription = null; this.labelControl10.AccessibleName = null; resources.ApplyResources(this.labelControl10, "labelControl10"); this.labelControl10.Name = "labelControl10"; // // labelControl9 // this.labelControl9.AccessibleDescription = null; this.labelControl9.AccessibleName = null; resources.ApplyResources(this.labelControl9, "labelControl9"); this.labelControl9.Name = "labelControl9"; // // labelControl8 // this.labelControl8.AccessibleDescription = null; this.labelControl8.AccessibleName = null; resources.ApplyResources(this.labelControl8, "labelControl8"); this.labelControl8.Name = "labelControl8"; // // labelControl7 // this.labelControl7.AccessibleDescription = null; this.labelControl7.AccessibleName = null; resources.ApplyResources(this.labelControl7, "labelControl7"); this.labelControl7.Name = "labelControl7"; // // labelControl6 // this.labelControl6.AccessibleDescription = null; this.labelControl6.AccessibleName = null; resources.ApplyResources(this.labelControl6, "labelControl6"); this.labelControl6.Name = "labelControl6"; // // labelControl5 // this.labelControl5.AccessibleDescription = null; this.labelControl5.AccessibleName = null; resources.ApplyResources(this.labelControl5, "labelControl5"); this.labelControl5.Name = "labelControl5"; // // labelControl4 // this.labelControl4.AccessibleDescription = null; this.labelControl4.AccessibleName = null; resources.ApplyResources(this.labelControl4, "labelControl4"); this.labelControl4.Name = "labelControl4"; // // checkEdit5 // resources.ApplyResources(this.checkEdit5, "checkEdit5"); this.checkEdit5.BackgroundImage = null; this.checkEdit5.Name = "checkEdit5"; this.checkEdit5.Properties.AccessibleDescription = null; this.checkEdit5.Properties.AccessibleName = null; this.checkEdit5.Properties.AutoHeight = ((bool)(resources.GetObject("checkEdit5.Properties.AutoHeight"))); this.checkEdit5.Properties.Caption = resources.GetString("checkEdit5.Properties.Caption"); // // labelControl3 // this.labelControl3.AccessibleDescription = null; this.labelControl3.AccessibleName = null; resources.ApplyResources(this.labelControl3, "labelControl3"); this.labelControl3.Name = "labelControl3"; // // labelControl2 // this.labelControl2.AccessibleDescription = null; this.labelControl2.AccessibleName = null; resources.ApplyResources(this.labelControl2, "labelControl2"); this.labelControl2.Name = "labelControl2"; // // checkEdit4 // resources.ApplyResources(this.checkEdit4, "checkEdit4"); this.checkEdit4.BackgroundImage = null; this.checkEdit4.Name = "checkEdit4"; this.checkEdit4.Properties.AccessibleDescription = null; this.checkEdit4.Properties.AccessibleName = null; this.checkEdit4.Properties.AutoHeight = ((bool)(resources.GetObject("checkEdit4.Properties.AutoHeight"))); this.checkEdit4.Properties.Caption = resources.GetString("checkEdit4.Properties.Caption"); // // checkEdit3 // resources.ApplyResources(this.checkEdit3, "checkEdit3"); this.checkEdit3.BackgroundImage = null; this.checkEdit3.Name = "checkEdit3"; this.checkEdit3.Properties.AccessibleDescription = null; this.checkEdit3.Properties.AccessibleName = null; this.checkEdit3.Properties.AutoHeight = ((bool)(resources.GetObject("checkEdit3.Properties.AutoHeight"))); this.checkEdit3.Properties.Caption = resources.GetString("checkEdit3.Properties.Caption"); // // checkEdit2 // resources.ApplyResources(this.checkEdit2, "checkEdit2"); this.checkEdit2.BackgroundImage = null; this.checkEdit2.Name = "checkEdit2"; this.checkEdit2.Properties.AccessibleDescription = null; this.checkEdit2.Properties.AccessibleName = null; this.checkEdit2.Properties.AutoHeight = ((bool)(resources.GetObject("checkEdit2.Properties.AutoHeight"))); this.checkEdit2.Properties.Caption = resources.GetString("checkEdit2.Properties.Caption"); // // checkEdit1 // resources.ApplyResources(this.checkEdit1, "checkEdit1"); this.checkEdit1.BackgroundImage = null; this.checkEdit1.Name = "checkEdit1"; this.checkEdit1.Properties.AccessibleDescription = null; this.checkEdit1.Properties.AccessibleName = null; this.checkEdit1.Properties.AutoHeight = ((bool)(resources.GetObject("checkEdit1.Properties.AutoHeight"))); this.checkEdit1.Properties.Caption = resources.GetString("checkEdit1.Properties.Caption"); // // labelControl1 // this.labelControl1.AccessibleDescription = null; this.labelControl1.AccessibleName = null; resources.ApplyResources(this.labelControl1, "labelControl1"); this.labelControl1.Name = "labelControl1"; // // simpleButton1 // this.simpleButton1.AccessibleDescription = null; this.simpleButton1.AccessibleName = null; resources.ApplyResources(this.simpleButton1, "simpleButton1"); this.simpleButton1.BackgroundImage = null; this.simpleButton1.Name = "simpleButton1"; this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click); // // simpleButton2 // this.simpleButton2.AccessibleDescription = null; this.simpleButton2.AccessibleName = null; resources.ApplyResources(this.simpleButton2, "simpleButton2"); this.simpleButton2.BackgroundImage = null; this.simpleButton2.Name = "simpleButton2"; this.simpleButton2.Click += new System.EventHandler(this.simpleButton2_Click); // // simpleButton3 // this.simpleButton3.AccessibleDescription = null; this.simpleButton3.AccessibleName = null; resources.ApplyResources(this.simpleButton3, "simpleButton3"); this.simpleButton3.BackgroundImage = null; this.simpleButton3.Name = "simpleButton3"; this.simpleButton3.Click += new System.EventHandler(this.simpleButton3_Click); // // frmPartnumberLookup // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.simpleButton3); this.Controls.Add(this.simpleButton2); this.Controls.Add(this.simpleButton1); this.Controls.Add(this.labelControl1); this.Controls.Add(this.groupControl1); this.Controls.Add(this.buttonEdit1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmPartnumberLookup"; ((System.ComponentModel.ISupportInitialize)(this.buttonEdit1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.groupControl1)).EndInit(); this.groupControl1.ResumeLayout(false); this.groupControl1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit5.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit4.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit3.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.checkEdit1.Properties)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private DevExpress.XtraEditors.ButtonEdit buttonEdit1; private DevExpress.XtraEditors.GroupControl groupControl1; private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraEditors.CheckEdit checkEdit4; private DevExpress.XtraEditors.CheckEdit checkEdit3; private DevExpress.XtraEditors.CheckEdit checkEdit2; private DevExpress.XtraEditors.CheckEdit checkEdit1; private DevExpress.XtraEditors.LabelControl labelControl3; private DevExpress.XtraEditors.LabelControl labelControl2; private DevExpress.XtraEditors.LabelControl labelControl8; private DevExpress.XtraEditors.LabelControl labelControl7; private DevExpress.XtraEditors.LabelControl labelControl6; private DevExpress.XtraEditors.LabelControl labelControl5; private DevExpress.XtraEditors.LabelControl labelControl4; private DevExpress.XtraEditors.CheckEdit checkEdit5; private DevExpress.XtraEditors.LabelControl labelControl11; private DevExpress.XtraEditors.LabelControl labelControl10; private DevExpress.XtraEditors.LabelControl labelControl9; private DevExpress.XtraEditors.SimpleButton simpleButton1; private DevExpress.XtraEditors.LabelControl lblStageIII; private DevExpress.XtraEditors.LabelControl lblStageII; private DevExpress.XtraEditors.LabelControl lblStageI; private DevExpress.XtraEditors.LabelControl lblTorque; private DevExpress.XtraEditors.LabelControl lblPower; private DevExpress.XtraEditors.LabelControl lblMaxBoostAUT; private DevExpress.XtraEditors.LabelControl lblMaxBoostManual; private DevExpress.XtraEditors.LabelControl lblBaseBoost; private DevExpress.XtraEditors.LabelControl lblEngineType; private DevExpress.XtraEditors.LabelControl lblCarModel; private DevExpress.XtraEditors.SimpleButton simpleButton2; private DevExpress.XtraEditors.SimpleButton simpleButton3; } }
// ZipInputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // HISTORY // 2010-05-25 Z-1663 Fixed exception when testing local header compressed size of -1 using System; using System.IO; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// This is an InflaterInputStream that reads the files baseInputStream an zip archive /// one after another. It has a special method to get the zip entry of /// the next file. The zip entry contains information about the file name /// size, compressed size, Crc, etc. /// It includes support for Stored and Deflated entries. /// <br/> /// <br/>Author of the original java version : Jochen Hoenicke /// </summary> /// /// <example> This sample shows how to read a zip file /// <code lang="C#"> /// using System; /// using System.Text; /// using System.IO; /// /// using ICSharpCode.SharpZipLib.Zip; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) { /// /// ZipEntry theEntry; /// const int size = 2048; /// byte[] data = new byte[2048]; /// /// while ((theEntry = s.GetNextEntry()) != null) { /// if ( entry.IsFile ) { /// Console.Write("Show contents (y/n) ?"); /// if (Console.ReadLine() == "y") { /// while (true) { /// size = s.Read(data, 0, data.Length); /// if (size > 0) { /// Console.Write(new ASCIIEncoding().GetString(data, 0, size)); /// } else { /// break; /// } /// } /// } /// } /// } /// } /// } /// } /// </code> /// </example> public class ZipInputStream : InflaterInputStream { #region Instance Fields /// <summary> /// Delegate for reading bytes from a stream. /// </summary> delegate int ReadDataHandler(byte[] b, int offset, int length); /// <summary> /// The current reader this instance. /// </summary> ReadDataHandler internalReader; Crc32 crc = new Crc32(); ZipEntry entry; long size; int method; int flags; string password; #endregion #region Constructors /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true)) { internalReader = new ReadDataHandler(ReadingNotAvailable); } /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> /// <param name="bufferSize">Size of the buffer.</param> public ZipInputStream( Stream baseInputStream, int bufferSize ) : base(baseInputStream, new Inflater(true), bufferSize) { internalReader = new ReadDataHandler(ReadingNotAvailable); } #endregion /// <summary> /// Optional password used for encryption when non-null /// </summary> /// <value>A password for all encrypted <see cref="ZipEntry">entries </see> in this <see cref="ZipInputStream"/></value> public string Password { get { return password; } set { password = value; } } /// <summary> /// Gets a value indicating if there is a current entry and it can be decompressed /// </summary> /// <remarks> /// The entry can only be decompressed if the library supports the zip features required to extract it. /// See the <see cref="ZipEntry.Version">ZipEntry Version</see> property for more details. /// </remarks> public bool CanDecompressEntry { get { return (entry != null) && entry.CanDecompress; } } /// <summary> /// Advances to the next entry in the archive /// </summary> /// <returns> /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries. /// </returns> /// <remarks> /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called. /// </remarks> /// <exception cref="InvalidOperationException"> /// Input stream is closed /// </exception> /// <exception cref="ZipException"> /// Password is not set, password is invalid, compression method is invalid, /// version required to extract is not supported /// </exception> public ZipEntry GetNextEntry() { if (crc == null) { throw new InvalidOperationException("Closed."); } if (entry != null) { CloseEntry(); } int header = inputBuffer.ReadLeInt(); if (header == ZipConstants.CentralHeaderSignature || header == ZipConstants.EndOfCentralDirectorySignature || header == ZipConstants.CentralHeaderDigitalSignature || header == ZipConstants.ArchiveExtraDataSignature || header == ZipConstants.Zip64CentralFileHeaderSignature) { // No more individual entries exist Close(); return null; } // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found // Spanning signature is same as descriptor signature and is untested as yet. if ( (header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature) ) { header = inputBuffer.ReadLeInt(); } if (header != ZipConstants.LocalHeaderSignature) { throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); } short versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); flags = inputBuffer.ReadLeShort(); method = inputBuffer.ReadLeShort(); uint dostime = (uint)inputBuffer.ReadLeInt(); int crc2 = inputBuffer.ReadLeInt(); csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); int nameLen = inputBuffer.ReadLeShort(); int extraLen = inputBuffer.ReadLeShort(); bool isCrypted = (flags & 1) == 1; byte[] buffer = new byte[nameLen]; inputBuffer.ReadRawBuffer(buffer); string name = ZipConstants.ConvertToStringExt(flags, buffer); entry = new ZipEntry(name, versionRequiredToExtract); entry.Flags = flags; entry.CompressionMethod = (CompressionMethod)method; if ((flags & 8) == 0) { entry.Crc = crc2 & 0xFFFFFFFFL; entry.Size = size & 0xFFFFFFFFL; entry.CompressedSize = csize & 0xFFFFFFFFL; entry.CryptoCheckValue = (byte)((crc2 >> 24) & 0xff); } else { // This allows for GNU, WinZip and possibly other archives, the PKZIP spec // says these values are zero under these circumstances. if (crc2 != 0) { entry.Crc = crc2 & 0xFFFFFFFFL; } if (size != 0) { entry.Size = size & 0xFFFFFFFFL; } if (csize != 0) { entry.CompressedSize = csize & 0xFFFFFFFFL; } entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); } entry.DosTime = dostime; // If local header requires Zip64 is true then the extended header should contain // both values. // Handle extra data if present. This can set/alter some fields of the entry. if (extraLen > 0) { byte[] extra = new byte[extraLen]; inputBuffer.ReadRawBuffer(extra); entry.ExtraData = extra; } entry.ProcessExtraData(true); if ( entry.CompressedSize >= 0 ) { csize = entry.CompressedSize; } if ( entry.Size >= 0 ) { size = entry.Size; } if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) { throw new ZipException("Stored, but compressed != uncompressed"); } // Determine how to handle reading of data if this is attempted. if (entry.IsCompressionMethodSupported()) { internalReader = new ReadDataHandler(InitialRead); } else { internalReader = new ReadDataHandler(ReadingNotSupported); } return entry; } /// <summary> /// Read data descriptor at the end of compressed data. /// </summary> void ReadDataDescriptor() { if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); } entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL; if ( entry.LocalHeaderRequiresZip64 ) { csize = inputBuffer.ReadLeLong(); size = inputBuffer.ReadLeLong(); } else { csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); } entry.CompressedSize = csize; entry.Size = size; } /// <summary> /// Complete cleanup as the final part of closing. /// </summary> /// <param name="testCrc">True if the crc value should be tested</param> void CompleteCloseEntry(bool testCrc) { StopDecrypting(); if ((flags & 8) != 0) { ReadDataDescriptor(); } size = 0; if ( testCrc && ((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1)) { throw new ZipException("CRC mismatch"); } crc.Reset(); if (method == (int)CompressionMethod.Deflated) { inf.Reset(); } entry = null; } /// <summary> /// Closes the current zip entry and moves to the next one. /// </summary> /// <exception cref="InvalidOperationException"> /// The stream is closed /// </exception> /// <exception cref="ZipException"> /// The Zip stream ends early /// </exception> public void CloseEntry() { if (crc == null) { throw new InvalidOperationException("Closed"); } if (entry == null) { return; } if (method == (int)CompressionMethod.Deflated) { if ((flags & 8) != 0) { // We don't know how much we must skip, read until end. byte[] tmp = new byte[4096]; // Read will close this entry while (Read(tmp, 0, tmp.Length) > 0) { } return; } csize -= inf.TotalIn; inputBuffer.Available += inf.RemainingInput; } if ( (inputBuffer.Available > csize) && (csize >= 0) ) { inputBuffer.Available = (int)((long)inputBuffer.Available - csize); } else { csize -= inputBuffer.Available; inputBuffer.Available = 0; while (csize != 0) { long skipped = base.Skip(csize); if (skipped <= 0) { throw new ZipException("Zip archive ends early."); } csize -= skipped; } } CompleteCloseEntry(false); } /// <summary> /// Returns 1 if there is an entry available /// Otherwise returns 0. /// </summary> public override int Available { get { return entry != null ? 1 : 0; } } /// <summary> /// Returns the current size that can be read from the current entry if available /// </summary> /// <exception cref="ZipException">Thrown if the entry size is not known.</exception> /// <exception cref="InvalidOperationException">Thrown if no entry is currently available.</exception> public override long Length { get { if ( entry != null ) { if ( entry.Size >= 0 ) { return entry.Size; } else { throw new ZipException("Length not available for the current entry"); } } else { throw new InvalidOperationException("No current entry"); } } } /// <summary> /// Reads a byte from the current zip entry. /// </summary> /// <returns> /// The byte or -1 if end of stream is reached. /// </returns> public override int ReadByte() { byte[] b = new byte[1]; if (Read(b, 0, 1) <= 0) { return -1; } return b[0] & 0xff; } /// <summary> /// Handle attempts to read by throwing an <see cref="InvalidOperationException"/>. /// </summary> /// <param name="destination">The destination array to store data in.</param> /// <param name="offset">The offset at which data read should be stored.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> int ReadingNotAvailable(byte[] destination, int offset, int count) { throw new InvalidOperationException("Unable to read from this stream"); } /// <summary> /// Handle attempts to read from this entry by throwing an exception /// </summary> int ReadingNotSupported(byte[] destination, int offset, int count) { throw new ZipException("The compression method for this entry is not supported"); } /// <summary> /// Perform the initial read on an entry which may include /// reading encryption headers and setting up inflation. /// </summary> /// <param name="destination">The destination to fill with data read.</param> /// <param name="offset">The offset to start reading at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read.</returns> int InitialRead(byte[] destination, int offset, int count) { if ( !CanDecompressEntry ) { throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")"); } // Handle encryption if required. if (entry.IsCrypted) { throw new ZipException("Encryption not supported for Compact Framework 1.0"); } else { inputBuffer.CryptoTransform = null; } if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) { if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0)) { inputBuffer.SetInflaterInput(inf); } internalReader = new ReadDataHandler(BodyRead); return BodyRead(destination, offset, count); } else { internalReader = new ReadDataHandler(ReadingNotAvailable); return 0; } } /// <summary> /// Read a block of bytes from the stream. /// </summary> /// <param name="buffer">The destination for the bytes.</param> /// <param name="offset">The index to start storing data.</param> /// <param name="count">The number of bytes to attempt to read.</param> /// <returns>Returns the number of bytes read.</returns> /// <remarks>Zero bytes read means end of stream.</remarks> public override int Read(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if ( (buffer.Length - offset) < count ) { throw new ArgumentException("Invalid offset/count combination"); } return internalReader(buffer, offset, count); } /// <summary> /// Reads a block of bytes from the current zip entry. /// </summary> /// <returns> /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. /// </returns> /// <exception name="IOException"> /// An i/o error occured. /// </exception> /// <exception cref="ZipException"> /// The deflated stream is corrupted. /// </exception> /// <exception cref="InvalidOperationException"> /// The stream is not open. /// </exception> int BodyRead(byte[] buffer, int offset, int count) { if ( crc == null ) { throw new InvalidOperationException("Closed"); } if ( (entry == null) || (count <= 0) ) { return 0; } if ( offset + count > buffer.Length ) { throw new ArgumentException("Offset + count exceeds buffer size"); } bool finished = false; switch (method) { case (int)CompressionMethod.Deflated: count = base.Read(buffer, offset, count); if (count <= 0) { if (!inf.IsFinished) { throw new ZipException("Inflater not finished!"); } inputBuffer.Available = inf.RemainingInput; // A csize of -1 is from an unpatched local header if ((flags & 8) == 0 && (inf.TotalIn != csize && csize != 0xFFFFFFFF && csize != -1 || inf.TotalOut != size)) { throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut); } inf.Reset(); finished = true; } break; case (int)CompressionMethod.Stored: if ( (count > csize) && (csize >= 0) ) { count = (int)csize; } if ( count > 0 ) { count = inputBuffer.ReadClearTextBuffer(buffer, offset, count); if (count > 0) { csize -= count; size -= count; } } if (csize == 0) { finished = true; } else { if (count < 0) { throw new ZipException("EOF in stored block"); } } break; } if (count > 0) { crc.Update(buffer, offset, count); } if (finished) { CompleteCloseEntry(true); } return count; } /// <summary> /// Closes the zip input stream /// </summary> public override void Close() { internalReader = new ReadDataHandler(ReadingNotAvailable); crc = null; entry = null; base.Close(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for ProjectMetadata</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Xunit; namespace Microsoft.Build.UnitTests.OM.Definition { /// <summary> /// Tests for ProjectMetadata /// </summary> public class ProjectMetadata_Tests { /// <summary> /// Project getter /// </summary> [Fact] public void ProjectGetter() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; ProjectMetadata metadatum = item.SetMetadataValue("m", "m1"); Assert.Equal(true, Object.ReferenceEquals(project, metadatum.Project)); } /// <summary> /// Set a new metadata value via the evaluated ProjectMetadata object /// </summary> [Fact] public void SetUnevaluatedValue() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m1>v1</m1> <m2>v%253</m2> </i> </ItemGroup> </Project> "); ProjectRootElement projectXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Project project = new Project(projectXml); Assert.Equal(false, project.IsDirty); Helpers.GetFirst(project.GetItems("i")).SetMetadataValue("m1", "v2"); Helpers.GetFirst(project.GetItems("i")).SetMetadataValue("m2", "v%214"); Assert.Equal(true, project.IsDirty); StringWriter writer = new StringWriter(); projectXml.Save(writer); string expected = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m1>v2</m1> <m2>v%214</m2> </i> </ItemGroup> </Project> "); Helpers.CompareProjectXml(expected, writer.ToString()); Assert.Equal("v!4", Helpers.GetFirst(project.GetItems("i")).GetMetadataValue("m2")); } /// <summary> /// If the value doesn't change then the project shouldn't dirty /// </summary> [Fact] public void SetUnchangedValue() { Project project = new Project(); ProjectItem item = project.AddItem("i", "i1")[0]; item.SetMetadataValue("m", "m1"); project.ReevaluateIfNecessary(); item.SetMetadataValue("m", "m1"); Assert.Equal(false, project.IsDirty); item.GetMetadata("m").UnevaluatedValue = "m1"; Assert.Equal(false, project.IsDirty); } /// <summary> /// Properties should be expanded /// </summary> [Fact] public void SetValueWithPropertyExpression() { Project project = new Project(); project.SetProperty("p", "p0"); ProjectItem item = project.AddItem("i", "i1")[0]; ProjectMetadata metadatum = item.SetMetadataValue("m", "m1"); project.ReevaluateIfNecessary(); metadatum.UnevaluatedValue = "$(p)"; Assert.Equal("$(p)", metadatum.UnevaluatedValue); Assert.Equal("p0", metadatum.EvaluatedValue); } /// <summary> /// Items should be expanded /// </summary> [Fact] public void SetValueWithItemExpression() { Project project = new Project(); project.AddItem("i", "i1"); ProjectItem item = project.AddItem("j", "j1")[0]; ProjectMetadata metadatum = item.SetMetadataValue("m", "@(i)"); project.ReevaluateIfNecessary(); metadatum.UnevaluatedValue = "@(i)"; Assert.Equal("@(i)", metadatum.UnevaluatedValue); Assert.Equal("i1", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with a qualified metadata expression. /// Per 3.5, this expands to nothing. /// </summary> [Fact] public void SetValueWithQualifiedMetadataExpressionOtherItemType() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m1>v1</m1> </i> <j Include='j1'> <m1>v2</m1> </j> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("j")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(i.m1)"; Assert.Equal("%(i.m1)", metadatum.UnevaluatedValue); Assert.Equal(String.Empty, metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with a qualified metadata expression of the same item type /// </summary> [Fact] public void SetValueWithQualifiedMetadataExpressionSameItemType() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m0>v0</m0> <m1>v1</m1> </i> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("i")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(i.m0)"; Assert.Equal("%(i.m0)", metadatum.UnevaluatedValue); Assert.Equal("v0", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with a qualified metadata expression of the same item type /// </summary> [Fact] public void SetValueWithQualifiedMetadataExpressionSameMetadata() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m1>v1</m1> </i> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("i")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(i.m1)"; Assert.Equal("%(i.m1)", metadatum.UnevaluatedValue); Assert.Equal(String.Empty, metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with an unqualified metadata expression /// </summary> [Fact] public void SetValueWithUnqualifiedMetadataExpression() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <i Include='i1'> <m0>v0</m0> <m1>v1</m1> </i> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("i")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(m0)"; Assert.Equal("%(m0)", metadatum.UnevaluatedValue); Assert.Equal("v0", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with an unqualified metadata expression /// Value from an item definition /// </summary> [Fact] public void SetValueWithUnqualifiedMetadataExpressionFromItemDefinition() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemDefinitionGroup> <i> <m0>v0</m0> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <m1>v1</m1> </i> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("i")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(m0)"; Assert.Equal("%(m0)", metadatum.UnevaluatedValue); Assert.Equal("v0", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with a qualified metadata expression /// Value from an item definition /// </summary> [Fact] public void SetValueWithQualifiedMetadataExpressionFromItemDefinition() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemDefinitionGroup> <i> <m0>v0</m0> </i> </ItemDefinitionGroup> <ItemGroup> <i Include='i1'> <m1>v1</m1> </i> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("i")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(i.m0)"; Assert.Equal("%(i.m0)", metadatum.UnevaluatedValue); Assert.Equal("v0", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value with an qualified metadata expression /// of the wrong item type. /// Per 3.5, this evaluates to nothing. /// </summary> [Fact] public void SetValueWithQualifiedMetadataExpressionWrongItemType() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemGroup> <j Include='j1'> <m0>v0</m0> </j> <i Include='i1'> <m0>v0</m0> <m1>v1</m1> </i> </ItemGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectMetadata metadatum = Helpers.GetFirst(project.GetItems("i")).GetMetadata("m1"); metadatum.UnevaluatedValue = "%(j.m0)"; Assert.Equal("%(j.m0)", metadatum.UnevaluatedValue); Assert.Equal(String.Empty, metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value on an item definition with an unqualified metadata expression /// </summary> [Fact] public void SetValueOnItemDefinitionWithUnqualifiedMetadataExpression() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemDefinitionGroup> <i> <m0>v0</m0> </i> </ItemDefinitionGroup> <ItemDefinitionGroup> <i> <m1>v1</m1> </i> </ItemDefinitionGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItemDefinition itemDefinition; project.ItemDefinitions.TryGetValue("i", out itemDefinition); ProjectMetadata metadatum = itemDefinition.GetMetadata("m1"); metadatum.UnevaluatedValue = "%(m0)"; Assert.Equal("%(m0)", metadatum.UnevaluatedValue); Assert.Equal("v0", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value on an item definition with an qualified metadata expression /// </summary> [Fact] public void SetValueOnItemDefinitionWithQualifiedMetadataExpression() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemDefinitionGroup> <i> <m0>v0</m0> <m1>v1</m1> </i> </ItemDefinitionGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItemDefinition itemDefinition; project.ItemDefinitions.TryGetValue("i", out itemDefinition); ProjectMetadata metadatum = itemDefinition.GetMetadata("m1"); metadatum.UnevaluatedValue = "%(i.m0)"; Assert.Equal("%(i.m0)", metadatum.UnevaluatedValue); Assert.Equal("v0", metadatum.EvaluatedValue); } /// <summary> /// Set a new metadata value on an item definition with an qualified metadata expression /// of the wrong item type. /// Per 3.5, this evaluates to empty string. /// </summary> [Fact] public void SetValueOnItemDefinitionWithQualifiedMetadataExpressionWrongItemType() { string content = ObjectModelHelpers.CleanupFileContents(@" <Project xmlns='msbuildnamespace' > <ItemDefinitionGroup> <j> <m0>v0</m0> </j> <i> <m0>v0</m0> <m1>v1</m1> </i> </ItemDefinitionGroup> </Project> "); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectItemDefinition itemDefinition; project.ItemDefinitions.TryGetValue("i", out itemDefinition); ProjectMetadata metadatum = itemDefinition.GetMetadata("m1"); metadatum.UnevaluatedValue = "%(j.m0)"; Assert.Equal("%(j.m0)", metadatum.UnevaluatedValue); Assert.Equal(String.Empty, metadatum.EvaluatedValue); } /// <summary> /// IsImported = false /// </summary> [Fact] public void IsImportedFalse() { Project project = new Project(); ProjectMetadata metadata = project.AddItem("i", "i1")[0].SetMetadataValue("m", "m1"); Assert.Equal(false, metadata.IsImported); } /// <summary> /// Attempt to set metadata on imported item should fail /// </summary> [Fact] public void SetMetadataImported() { Assert.Throws<InvalidOperationException>(() => { ProjectRootElement import = ProjectRootElement.Create("import"); ProjectItemElement itemXml = import.AddItem("i", "i1"); itemXml.AddMetadata("m", "m0"); ProjectRootElement xml = ProjectRootElement.Create(); xml.AddImport("import"); Project project = new Project(xml); ProjectItem item = Helpers.GetFirst(project.GetItems("i")); ProjectMetadata metadata = item.GetMetadata("m"); Assert.Equal(true, metadata.IsImported); metadata.UnevaluatedValue = "m1"; } ); } /// <summary> /// Escaping in metadata values /// </summary> [Fact] public void SpecialCharactersInMetadataValueConstruction() { string projectString = ObjectModelHelpers.CleanupFileContents(@"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace""> <ItemGroup> <None Include='MetadataTests'> <EscapedSemicolon>%3B</EscapedSemicolon> <EscapedDollarSign>%24</EscapedDollarSign> </None> </ItemGroup> </Project>"); System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString)); Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project(reader); Microsoft.Build.Evaluation.ProjectItem item = project.GetItems("None").Single(); SpecialCharactersInMetadataValueTests(item); } /// <summary> /// Escaping in metadata values /// </summary> [Fact] public void SpecialCharactersInMetadataValueEvaluation() { Microsoft.Build.Evaluation.Project project = new Microsoft.Build.Evaluation.Project(); var metadata = new Dictionary<string, string> { { "EscapedSemicolon", "%3B" }, // Microsoft.Build.Internal.Utilities.Escape(";") { "EscapedDollarSign", "%24" }, // Microsoft.Build.Internal.Utilities.Escape("$") }; Microsoft.Build.Evaluation.ProjectItem item = project.AddItem( "None", "MetadataTests", metadata).Single(); SpecialCharactersInMetadataValueTests(item); project.ReevaluateIfNecessary(); SpecialCharactersInMetadataValueTests(item); } /// <summary> /// Helper for metadata escaping tests /// </summary> private void SpecialCharactersInMetadataValueTests(Microsoft.Build.Evaluation.ProjectItem item) { Assert.Equal("%3B", item.GetMetadata("EscapedSemicolon").UnevaluatedValue); Assert.Equal(";", item.GetMetadata("EscapedSemicolon").EvaluatedValue); Assert.Equal(";", item.GetMetadataValue("EscapedSemicolon")); Assert.Equal("%24", item.GetMetadata("EscapedDollarSign").UnevaluatedValue); Assert.Equal("$", item.GetMetadata("EscapedDollarSign").EvaluatedValue); Assert.Equal("$", item.GetMetadataValue("EscapedDollarSign")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Diagnostics; using System.Data.Common; using Res = System.SR; namespace System.Data.SqlTypes { public sealed class SqlChars : System.Data.SqlTypes.INullable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlChars has five possible states // 1) SqlChars is Null // - m_stream must be null, m_lCuLen must be x_lNull // 2) SqlChars contains a valid buffer, // - m_rgchBuf must not be null, and m_stream must be null // 3) SqlChars contains a valid pointer // - m_rgchBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlChars contains a SqlStreamChars // - m_stream must not be null // - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal char[] m_rgchBuf; // Data buffer private long _lCurLen; // Current data length internal SqlStreamChars m_stream; private SqlBytesCharsState _state; private char[] _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = (long)System.Int32.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlChars() { SetNull(); } // Create a SqlChars with an in-memory buffer public SqlChars(char[] buffer) { m_rgchBuf = buffer; m_stream = null; if (m_rgchBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = (long)m_rgchBuf.Length; } _rgchWorkBuf = null; AssertValid(); } // Create a SqlChars from a SqlString public SqlChars(SqlString value) : this(value.IsNull ? (char[])null : value.Value.ToCharArray()) { } // Create a SqlChars from a SqlStreamChars internal SqlChars(SqlStreamChars s) { m_rgchBuf = null; _lCurLen = x_lNull; m_stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. public char[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return m_rgchBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return m_stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlChars is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (m_rgchBuf == null) ? -1L : (long)m_rgchBuf.Length; } } } // Property: get a copy of the data in a new char[] array. public char[] Value { get { char[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (m_stream.Length > x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); buffer = new char[m_stream.Length]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(buffer, 0, checked((int)m_stream.Length)); break; default: buffer = new char[_lCurLen]; Array.Copy(m_rgchBuf, buffer, (int)_lCurLen); break; } return buffer; } } // class indexer public char this[long offset] { get { if (offset < 0 || offset >= this.Length) throw new ArgumentOutOfRangeException("offset"); if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } } internal SqlStreamChars Stream { get { return FStream() ? m_stream : new StreamOnSqlChars(this); } set { _lCurLen = x_lNull; m_stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; m_stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("value"); if (FStream()) { m_stream.SetLength(value); } else { // If there is a buffer, even the value of SqlChars is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == m_rgchBuf) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (value > (long)m_rgchBuf.Length) throw new ArgumentOutOfRangeException("value"); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, char[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException("buffer"); if (offset > this.Length || offset < 0) throw new ArgumentOutOfRangeException("offset"); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException("offsetInBuffer"); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException("count"); // Adjust count based on data length if (count > this.Length - offset) count = (int)(this.Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Read(buffer, offsetInBuffer, count); break; default: // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(m_rgchBuf, checked((int)offset), buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlChars from specified offset public void Write(long offset, char[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException("buffer"); if (m_rgchBuf == null) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (offset > m_rgchBuf.Length) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException("offsetInBuffer"); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException("count"); if (count > m_rgchBuf.Length - offset) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteNonZeroOffsetOnNullMessage)); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteOffsetLargerThanLenMessage)); } if (count != 0) { // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(buffer, offsetInBuffer, m_rgchBuf, checked((int)offset), count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlString ToSqlString() { return IsNull ? SqlString.Null : new String(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlString() public static explicit operator SqlString(SqlChars value) { return value.ToSqlString(); } // Alternative method: constructor SqlChars(SqlString) public static explicit operator SqlChars(SqlString value) { return new SqlChars(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [System.Diagnostics.Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (m_rgchBuf != null && _lCurLen <= m_rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } // Copy the data from the Stream to the array buffer. // If the SqlChars doesn't hold a buffer or the buffer // is not big enough, allocate new char array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = m_stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (m_rgchBuf == null || m_rgchBuf.Length < lStreamLen) m_rgchBuf = new char[lStreamLen]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(m_rgchBuf, 0, (int)lStreamLen); m_stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlChars is mutable, have to be property and create a new one each time. public static SqlChars Null { get { return new SqlChars((char[])null); } } } // class SqlChars // StreamOnSqlChars is a stream build on top of SqlChars, and // provides the Stream interface. The purpose is to help users // to read/write SqlChars object. internal sealed class StreamOnSqlChars : SqlStreamChars { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlChars _sqlchars; // the SqlChars object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal StreamOnSqlChars(SqlChars s) { _sqlchars = s; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- public override bool IsNull { get { return _sqlchars == null || _sqlchars.IsNull; } } // Always can read/write/seek, unless sb is null, // which means the stream has been closed. public override bool CanRead { get { return _sqlchars != null && !_sqlchars.IsNull; } } public override bool CanSeek { get { return _sqlchars != null; } } public override bool CanWrite { get { return _sqlchars != null && (!_sqlchars.IsNull || _sqlchars.m_rgchBuf != null); } } public override long Length { get { CheckIfStreamClosed("get_Length"); return _sqlchars.Length; } } public override long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sqlchars.Length) throw new ArgumentOutOfRangeException("value"); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed("Seek"); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange("offset"); _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange("offset"); ; } return _lPosition; } // The Read/Write/Readchar/Writechar simply delegates to SqlChars public override int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed("Read"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count); _lPosition += icharsRead; return icharsRead; } public override void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed("Write"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); _sqlchars.Write(_lPosition, buffer, offset, count); _lPosition += count; } public override int ReadChar() { CheckIfStreamClosed("ReadChar"); // If at the end of stream, return -1, rather than call SqlChars.Readchar, // which will throw exception. This is the behavior for Stream. // if (_lPosition >= _sqlchars.Length) return -1; int ret = _sqlchars[_lPosition]; _lPosition++; return ret; } public override void WriteChar(char value) { CheckIfStreamClosed("WriteChar"); _sqlchars[_lPosition] = value; _lPosition++; } public override void SetLength(long value) { CheckIfStreamClosed("SetLength"); _sqlchars.SetLength(value); if (_lPosition > value) _lPosition = value; } // Flush is a no-op if underlying SqlChars is not a stream on SqlChars public override void Flush() { if (_sqlchars.FStream()) _sqlchars.m_stream.Flush(); } protected override void Dispose(bool disposing) { // When m_sqlchars is null, it means the stream has been closed, and // any opearation in the future should fail. // This is the only case that m_sqlchars is null. _sqlchars = null; } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sqlchars == null; } private void CheckIfStreamClosed(string methodname) { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class StreamOnSqlChars } // namespace System.Data.SqlTypes
/* * 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 OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Groups { public class HGGroupsService : GroupsService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IOfflineIMService m_OfflineIM; private IUserAccountService m_UserAccounts; private string m_HomeURI; public HGGroupsService(IConfigSource config, IOfflineIMService im, IUserAccountService users, string homeURI) : base(config, string.Empty) { m_OfflineIM = im; m_UserAccounts = users; m_HomeURI = homeURI; if (!m_HomeURI.EndsWith("/")) m_HomeURI += "/"; } #region HG specific operations public bool CreateGroupProxy(string RequestingAgentID, string agentID, string accessToken, UUID groupID, string serviceLocation, string name, out string reason) { reason = string.Empty; Uri uri = null; try { uri = new Uri(serviceLocation); } catch (UriFormatException) { reason = "Bad location for group proxy"; return false; } // Check if it already exists GroupData grec = m_Database.RetrieveGroup(groupID); if (grec == null || (grec != null && grec.Data["Location"] != string.Empty && grec.Data["Location"].ToLower() != serviceLocation.ToLower())) { // Create the group grec = new GroupData(); grec.GroupID = groupID; grec.Data = new Dictionary<string, string>(); grec.Data["Name"] = name + " @ " + uri.Authority; grec.Data["Location"] = serviceLocation; grec.Data["Charter"] = string.Empty; grec.Data["InsigniaID"] = UUID.Zero.ToString(); grec.Data["FounderID"] = UUID.Zero.ToString(); grec.Data["MembershipFee"] = "0"; grec.Data["OpenEnrollment"] = "0"; grec.Data["ShowInList"] = "0"; grec.Data["AllowPublish"] = "0"; grec.Data["MaturePublish"] = "0"; grec.Data["OwnerRoleID"] = UUID.Zero.ToString(); if (!m_Database.StoreGroup(grec)) return false; } if (grec.Data["Location"] == string.Empty) { reason = "Cannot add proxy membership to non-proxy group"; return false; } UUID uid = UUID.Zero; string url = string.Empty, first = string.Empty, last = string.Empty, tmp = string.Empty; Util.ParseUniversalUserIdentifier(RequestingAgentID, out uid, out url, out first, out last, out tmp); string fromName = first + "." + last + "@" + url; // Invite to group again InviteToGroup(fromName, groupID, new UUID(agentID), grec.Data["Name"]); // Stick the proxy membership in the DB already // we'll delete it if the agent declines the invitation MembershipData membership = new MembershipData(); membership.PrincipalID = agentID; membership.GroupID = groupID; membership.Data = new Dictionary<string, string>(); membership.Data["SelectedRoleID"] = UUID.Zero.ToString(); membership.Data["Contribution"] = "0"; membership.Data["ListInProfile"] = "1"; membership.Data["AcceptNotices"] = "1"; membership.Data["AccessToken"] = accessToken; m_Database.StoreMember(membership); return true; } public bool RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID, string token) { // check the token MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID); if (membership != null) { if (token != string.Empty && token.Equals(membership.Data["AccessToken"])) { return RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID); } else { m_log.DebugFormat("[Groups.HGGroupsService]: access token {0} did not match stored one {1}", token, membership.Data["AccessToken"]); return false; } } else { m_log.DebugFormat("[Groups.HGGroupsService]: membership not found for {0}", AgentID); return false; } } public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string groupName, string token) { // check the token if (!VerifyToken(GroupID, RequestingAgentID, token)) return null; ExtendedGroupRecord grec; if (GroupID == UUID.Zero) grec = GetGroupRecord(RequestingAgentID, groupName); else grec = GetGroupRecord(RequestingAgentID, GroupID); if (grec != null) FillFounderUUI(grec); return grec; } public List<ExtendedGroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID, string token) { if (!VerifyToken(GroupID, RequestingAgentID, token)) return new List<ExtendedGroupMembersData>(); List<ExtendedGroupMembersData> members = GetGroupMembers(RequestingAgentID, GroupID); // convert UUIDs to UUIs members.ForEach(delegate (ExtendedGroupMembersData m) { if (m.AgentID.ToString().Length == 36) // UUID { UserAccount account = m_UserAccounts.GetUserAccount(UUID.Zero, new UUID(m.AgentID)); if (account != null) m.AgentID = Util.UniversalIdentifier(account.PrincipalID, account.FirstName, account.LastName, m_HomeURI); } }); return members; } public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID GroupID, string token) { if (!VerifyToken(GroupID, RequestingAgentID, token)) return new List<GroupRolesData>(); return GetGroupRoles(RequestingAgentID, GroupID); } public List<ExtendedGroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID GroupID, string token) { if (!VerifyToken(GroupID, RequestingAgentID, token)) return new List<ExtendedGroupRoleMembersData>(); List<ExtendedGroupRoleMembersData> rolemembers = GetGroupRoleMembers(RequestingAgentID, GroupID); // convert UUIDs to UUIs rolemembers.ForEach(delegate(ExtendedGroupRoleMembersData m) { if (m.MemberID.ToString().Length == 36) // UUID { UserAccount account = m_UserAccounts.GetUserAccount(UUID.Zero, new UUID(m.MemberID)); if (account != null) m.MemberID = Util.UniversalIdentifier(account.PrincipalID, account.FirstName, account.LastName, m_HomeURI); } }); return rolemembers; } public bool AddNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID) { // check that the group proxy exists ExtendedGroupRecord grec = GetGroupRecord(RequestingAgentID, groupID); if (grec == null) { m_log.DebugFormat("[Groups.HGGroupsService]: attempt at adding notice to non-existent group proxy"); return false; } // check that the group is remote if (grec.ServiceLocation == string.Empty) { m_log.DebugFormat("[Groups.HGGroupsService]: attempt at adding notice to local (non-proxy) group"); return false; } // check that there isn't already a notice with the same ID if (GetGroupNotice(RequestingAgentID, noticeID) != null) { m_log.DebugFormat("[Groups.HGGroupsService]: a notice with the same ID already exists", grec.ServiceLocation); return false; } // This has good intentions (security) but it will potentially DDS the origin... // We'll need to send a proof along with the message. Maybe encrypt the message // using key pairs // //// check that the notice actually exists in the origin //GroupsServiceHGConnector c = new GroupsServiceHGConnector(grec.ServiceLocation); //if (!c.VerifyNotice(noticeID, groupID)) //{ // m_log.DebugFormat("[Groups.HGGroupsService]: notice does not exist at origin {0}", grec.ServiceLocation); // return false; //} // ok, we're good! return _AddNotice(groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, attOwnerID); } public bool VerifyNotice(UUID noticeID, UUID groupID) { GroupNoticeInfo notice = GetGroupNotice(string.Empty, noticeID); if (notice == null) return false; if (notice.GroupID != groupID) return false; return true; } #endregion private void InviteToGroup(string fromName, UUID groupID, UUID invitedAgentID, string groupName) { // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); if (AddAgentToGroupInvite(InviteID, groupID, invitedAgentID.ToString())) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = agentID.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = fromName; msg.message = string.Format("Please confirm your acceptance to join group {0}.", groupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[20]; string reason = string.Empty; m_OfflineIM.StoreMessage(msg, out reason); } } private bool AddAgentToGroupInvite(UUID inviteID, UUID groupID, string agentID) { // Check whether the invitee is already a member of the group MembershipData m = m_Database.RetrieveMember(groupID, agentID); if (m != null) return false; // Check whether there are pending invitations and delete them InvitationData invite = m_Database.RetrieveInvitation(groupID, agentID); if (invite != null) m_Database.DeleteInvite(invite.InviteID); invite = new InvitationData(); invite.InviteID = inviteID; invite.PrincipalID = agentID; invite.GroupID = groupID; invite.RoleID = UUID.Zero; invite.Data = new Dictionary<string, string>(); return m_Database.StoreInvitation(invite); } private void FillFounderUUI(ExtendedGroupRecord grec) { UserAccount account = m_UserAccounts.GetUserAccount(UUID.Zero, grec.FounderID); if (account != null) grec.FounderUUI = Util.UniversalIdentifier(account.PrincipalID, account.FirstName, account.LastName, m_HomeURI); } private bool VerifyToken(UUID groupID, string agentID, string token) { // check the token MembershipData membership = m_Database.RetrieveMember(groupID, agentID); if (membership != null) { if (token != string.Empty && token.Equals(membership.Data["AccessToken"])) return true; else m_log.DebugFormat("[Groups.HGGroupsService]: access token {0} did not match stored one {1}", token, membership.Data["AccessToken"]); } else m_log.DebugFormat("[Groups.HGGroupsService]: membership not found for {0}", agentID); return false; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using pinch.Http.Request; using pinch.Http.Response; using unirest_net.http; using UniHttpRequest = unirest_net.request.HttpRequest; using UniHttpMethod = System.Net.Http.HttpMethod; namespace pinch.Http.Client { public class UnirestClient: IHttpClient { public static IHttpClient SharedClient { get; set; } static UnirestClient() { SharedClient = new UnirestClient(); } #region Execute methods public HttpResponse ExecuteAsString(HttpRequest request) { //raise the on before request event raiseOnBeforeHttpRequestEvent(request); UniHttpRequest uniRequest = ConvertRequest(request); HttpResponse response = ConvertResponse(uniRequest.asString()); //raise the on after response event raiseOnAfterHttpResponseEvent(response); return response; } public Task<HttpResponse> ExecuteAsStringAsync(HttpRequest request) { return Task.Factory.StartNew(() => ExecuteAsString(request)); } public HttpResponse ExecuteAsBinary(HttpRequest request) { //raise the on before request event raiseOnBeforeHttpRequestEvent(request); UniHttpRequest uniRequest = ConvertRequest(request); HttpResponse response = ConvertResponse(uniRequest.asBinary()); //raise the on after response event raiseOnAfterHttpResponseEvent(response); return response; } public Task<HttpResponse> ExecuteAsBinaryAsync(HttpRequest request) { return Task.Factory.StartNew(() => ExecuteAsString(request)); } #endregion #region Http request and response events public event OnBeforeHttpRequestEventHandler OnBeforeHttpRequestEvent; public event OnAfterHttpResponseEventHandler OnAfterHttpResponseEvent; private void raiseOnBeforeHttpRequestEvent(HttpRequest request) { if ((null != OnBeforeHttpRequestEvent) && (null != request)) OnBeforeHttpRequestEvent(this, request); } private void raiseOnAfterHttpResponseEvent(HttpResponse response) { if ((null != OnAfterHttpResponseEvent) && (null != response)) OnAfterHttpResponseEvent(this, response); } #endregion #region Http methods public HttpRequest Get(string queryUrl, Dictionary<string, string> headers, string username = null, string password = null) { return new HttpRequest(HttpMethod.GET, queryUrl, headers, username, password); } public HttpRequest Get(string queryUrl) { return new HttpRequest(HttpMethod.GET, queryUrl); } public HttpRequest Post(string queryUrl) { return new HttpRequest(HttpMethod.POST, queryUrl); } public HttpRequest Put(string queryUrl) { return new HttpRequest(HttpMethod.PUT, queryUrl); } public HttpRequest Delete(string queryUrl) { return new HttpRequest(HttpMethod.DELETE, queryUrl); } public HttpRequest Patch(string queryUrl) { return new HttpRequest(HttpMethod.PATCH, queryUrl); } public HttpRequest Post(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null, string password = null) { return new HttpRequest(HttpMethod.POST, queryUrl, headers, formParameters, username, password); } public HttpRequest PostBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null) { return new HttpRequest(HttpMethod.POST, queryUrl, headers, body, username, password); } public HttpRequest Put(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null, string password = null) { return new HttpRequest(HttpMethod.PUT, queryUrl, headers, formParameters, username, password); } public HttpRequest PutBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null) { return new HttpRequest(HttpMethod.PUT, queryUrl, headers, body, username, password); } public HttpRequest Patch(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null, string password = null) { return new HttpRequest(HttpMethod.PATCH, queryUrl, headers, formParameters, username, password); } public HttpRequest PatchBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null) { return new HttpRequest(HttpMethod.PATCH, queryUrl, headers, body, username, password); } public HttpRequest Delete(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null, string password = null) { return new HttpRequest(HttpMethod.DELETE, queryUrl, headers, formParameters, username, password); } public HttpRequest DeleteBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null) { return new HttpRequest(HttpMethod.DELETE, queryUrl, headers, body, username, password); } #endregion #region Helper methods private static UniHttpMethod ConvertHttpMethod(HttpMethod method) { switch (method) { case HttpMethod.GET: case HttpMethod.POST: case HttpMethod.PUT: case HttpMethod.PATCH: case HttpMethod.DELETE: return new UniHttpMethod(method.ToString().ToUpperInvariant()); default: throw new ArgumentOutOfRangeException("Unkown method" + method.ToString()); } } private static UniHttpRequest ConvertRequest(HttpRequest request) { var uniMethod = ConvertHttpMethod(request.HttpMethod); var queryUrl = request.QueryUrl; //instantiate unirest request object UniHttpRequest uniRequest = new UniHttpRequest(uniMethod,queryUrl); //set request payload if (request.Body != null) { uniRequest.body(request.Body); } else if (request.FormParameters != null) { if (request.FormParameters.Any(p => p.Value is Stream || p.Value is FileStreamInfo)) { //multipart foreach (var kvp in request.FormParameters) { if (kvp.Value is FileStreamInfo){ var fileInfo = (FileStreamInfo) kvp.Value; uniRequest.field(kvp.Key,fileInfo.FileStream); continue; } uniRequest.field(kvp.Key,kvp.Value); } } else { //URL Encode params var paramsString = string.Join("&", request.FormParameters.Select(kvp => string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value.ToString())))); uniRequest.body(paramsString); uniRequest.header("Content-Type", "application/x-www-form-urlencoded"); } } //set request headers Dictionary<string, Object> headers = request.Headers.ToDictionary(item=> item.Key,item=> (Object) item.Value); uniRequest.headers(headers); //Set basic auth credentials if any if (!string.IsNullOrWhiteSpace(request.Username)) { uniRequest.basicAuth(request.Username, request.Password); } return uniRequest; } private static HttpResponse ConvertResponse(HttpResponse<Stream> binaryResponse) { return new HttpResponse { Headers = binaryResponse.Headers, RawBody = binaryResponse.Body, StatusCode = binaryResponse.Code }; } private static HttpResponse ConvertResponse(HttpResponse<string> stringResponse) { return new HttpStringResponse { Headers = stringResponse.Headers, RawBody = stringResponse.Raw, Body = stringResponse.Body, StatusCode = stringResponse.Code }; } #endregion } }
//--------------------------------------------------------------------------- // // File: InkCanvasSelection.cs // // Description: // Element that represents InkCanvas selection // // History: // 9/01/2004 samgeo: Created // // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using MS.Utility; using MS.Internal; using MS.Internal.Controls; using MS.Internal.Ink; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.ComponentModel; using System.ComponentModel.Design; using System.Windows; using System.Windows.Media; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Controls; using System.Windows.Markup; using System.Windows.Threading; namespace MS.Internal.Ink { /// <summary> /// InkCanvasSelection /// </summary> internal sealed class InkCanvasSelection { //------------------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------------------- #region Constructors /// <summary> /// InkCanvasSelection has an internal constructor to prevent direct instantiation /// </summary> /// <param name="inkCanvas">inkCanvas</param> internal InkCanvasSelection(InkCanvas inkCanvas) { //validate if (inkCanvas == null) { throw new ArgumentNullException("inkCanvas"); } _inkCanvas = inkCanvas; _inkCanvas.FeedbackAdorner.UpdateBounds(Rect.Empty); } #endregion Constructors //------------------------------------------------------------------------------- // // Internal Properties // //------------------------------------------------------------------------------- #region Internal Properties /// <summary> /// Returns the collection of selected strokes /// </summary> internal StrokeCollection SelectedStrokes { get { if ( _selectedStrokes == null ) { _selectedStrokes = new StrokeCollection(); _areStrokesChanged = true; } return _selectedStrokes; } } /// <summary> /// Returns the collection of selected elements /// </summary> internal ReadOnlyCollection<UIElement> SelectedElements { get { if ( _selectedElements == null ) { _selectedElements = new List<UIElement>(); } return new ReadOnlyCollection<UIElement>(_selectedElements); } } /// <summary> /// Indicates whether there is a selection in the current InkCanvas. /// </summary> internal bool HasSelection { get { return SelectedStrokes.Count != 0 || SelectedElements.Count != 0; } } /// <summary> /// Returns the selection bounds /// </summary> internal Rect SelectionBounds { get { return Rect.Union(GetStrokesBounds(), GetElementsUnionBounds()); } } #endregion Internal Properties //------------------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------------------- #region Internal Methods /// <summary> /// Start a feedback rubberband. /// This method is called from SelectionEditingBehavior.OnActivated /// </summary> /// <param name="feedbackRect"></param> /// <param name="activeSelectionHitResult"></param> internal void StartFeedbackAdorner(Rect feedbackRect, InkCanvasSelectionHitResult activeSelectionHitResult) { Debug.Assert( _inkCanvas.EditingCoordinator.UserIsEditing == true ); Debug.Assert(activeSelectionHitResult != InkCanvasSelectionHitResult.None, "activeSelectionHitResult cannot be InkCanvasSelectionHitResult.None."); _activeSelectionHitResult = activeSelectionHitResult; AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(_inkCanvas.InnerCanvas); // Until the next start, we are going to use this adorner regardless user will change feedback adorner or not during the editing. InkCanvasFeedbackAdorner feedbackAdorner = _inkCanvas.FeedbackAdorner; // The feedback adorner shouldn't have been connected to the adorner layer yet. Debug.Assert(VisualTreeHelper.GetParent(feedbackAdorner) == null, "feedbackAdorner shouldn't be added to tree."); // Now, attach the feedback adorner to the adorner layer. Then update its bounds adornerLayer.Add(feedbackAdorner); feedbackAdorner.UpdateBounds(feedbackRect); } /// <summary> /// This method updates the feedback rubberband. /// This method is called from SelectionEditingBehavior.OnMouseMove. /// </summary> /// <param name="feedbackRect"></param> internal void UpdateFeedbackAdorner(Rect feedbackRect) { Debug.Assert(VisualTreeHelper.GetParent(_inkCanvas.FeedbackAdorner) == AdornerLayer.GetAdornerLayer(_inkCanvas.InnerCanvas), "feedbackAdorner should have been added to tree."); // Update the feedback bounds _inkCanvas.FeedbackAdorner.UpdateBounds(feedbackRect); } /// <summary> /// Ends a feedback rubberband /// This method is called from SelectionEditingBehavior.OnMoveUp /// </summary> /// <param name="finalRectangle"></param> internal void EndFeedbackAdorner(Rect finalRectangle) { AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(_inkCanvas.InnerCanvas); InkCanvasFeedbackAdorner feedbackAdorner = _inkCanvas.FeedbackAdorner; Debug.Assert(VisualTreeHelper.GetParent(feedbackAdorner) == adornerLayer, "feedbackAdorner should have been added to tree."); // Reset the feedback bounds and detach it from the adorner layer. feedbackAdorner.UpdateBounds(Rect.Empty); adornerLayer.Remove(feedbackAdorner); // Commit the new rectange of the selection. CommitChanges(finalRectangle, true); _activeSelectionHitResult = null; } /// <summary> /// Set the new selection to this helper class. /// </summary> /// <param name="strokes"></param> /// <param name="elements"></param> /// <param name="raiseSelectionChanged"></param> internal void Select(StrokeCollection strokes, IList<UIElement> elements, bool raiseSelectionChanged) { // Can't be null. Debug.Assert(strokes != null && elements != null); // // check to see if we're different. If not, there is no need to raise the changed event // bool strokesAreDifferent; bool elementsAreDifferent; int count = 0; SelectionIsDifferentThanCurrent(strokes, out strokesAreDifferent, elements, out elementsAreDifferent); // Besides the differences of both the stroks and the elements, there is a chance that the selected strokes and elements // have been removed from the InkCanvas. Meanwhile, we may still hold the reference of _inkCanvasSelection which is empty. // So, we should make sure to remove _inkCanvasSelection in this case. if ( strokesAreDifferent || elementsAreDifferent ) { if ( strokesAreDifferent && SelectedStrokes.Count != 0 ) { // PERF-2006/05/02-WAYNEZEN, // Unsubscribe the event fisrt so that reseting IsSelected won't call into our handler. // // quit listening to changes // QuitListeningToStrokeChanges(); count = SelectedStrokes.Count; for ( int i = 0; i < count; i++ ) { SelectedStrokes[i].IsSelected = false; } } _selectedStrokes = strokes; _areStrokesChanged = true; _selectedElements = new List<UIElement>(elements); // PERF-2006/05/02-WAYNEZEN, // Update IsSelected property before adding the event handlers. // NTRAID#WINDOWS-1191424-2005/07/07-WAYNEZNE, // We don't have to render hollow strokes if the current mode isn't Select mode if ( _inkCanvas.ActiveEditingMode == InkCanvasEditingMode.Select ) { // NTRAID#T2-26511-2004/10/18-waynezen, // Updating the visuals of the hitted strokes. count = strokes.Count; for ( int i = 0; i < count; i++ ) { strokes[i].IsSelected = true; } } // Add a LayoutUpdated handler if it's necessary. UpdateCanvasLayoutUpdatedHandler(); // Update our selection adorner manually UpdateSelectionAdorner(); ListenToStrokeChanges(); // // And finally... raise the SelectionChanged event // if ( raiseSelectionChanged ) { _inkCanvas.RaiseSelectionChanged(EventArgs.Empty); } } } /// <summary> /// Our internal method to commit the current editing. /// Called by EndFeedbackAdorner or InkCanvas.PasteFromDataObject /// </summary> internal void CommitChanges(Rect finalRectangle, bool raiseEvent) { // The follow moving or resizing raises SelectionMove or SelectionResize event // The out-side code could throw exception in the their handlers. We use try/finally block to protect our status. Rect selectionBounds = SelectionBounds; // NTRAID:WINDOWS#1464216-2006/01/27-WAYNEZEN // If the selection is cleared programmatically somehow during user interaction, we will get an empty source rect. // We should check if the source still valid here. If not, no selection needs to be changed. if ( selectionBounds.IsEmpty ) { return; } try { QuitListeningToStrokeChanges( ); if ( raiseEvent ) { // // see if we resized // if ( !DoubleUtil.AreClose(finalRectangle.Height, selectionBounds.Height) || !DoubleUtil.AreClose(finalRectangle.Width, selectionBounds.Width) ) { // // we resized // CommitResizeChange(finalRectangle); } else if ( !DoubleUtil.AreClose(finalRectangle.Top, selectionBounds.Top) || !DoubleUtil.AreClose(finalRectangle.Left, selectionBounds.Left) ) { // // we moved // CommitMoveChange(finalRectangle); } } else { // // Just perform the move without raising any events. // MoveSelection(selectionBounds, finalRectangle); } } finally { ListenToStrokeChanges( ); } } /// <summary> /// Try to remove an element from the selected elements list. /// Called by: /// OnCanvasLayoutUpdated /// </summary> /// <param name="removedElement"></param> internal void RemoveElement(UIElement removedElement) { // No selected element. Bail out if ( _selectedElements == null || _selectedElements.Count == 0 ) { return; } if ( _selectedElements.Remove(removedElement) ) { // The element existed and was removed successfully. // Now if there is no selected element, we should remove our LayoutUpdated handler. if ( _selectedElements.Count == 0 ) { UpdateCanvasLayoutUpdatedHandler(); UpdateSelectionAdorner(); } } } /// <summary> /// UpdateElementBounds: /// Called by InkCanvasSelection.MoveSelection /// </summary> /// <param name="element"></param> /// <param name="transform"></param> internal void UpdateElementBounds(UIElement element, Matrix transform) { UpdateElementBounds(element, element, transform); } /// <summary> /// UpdateElementBounds: /// Called by InkCanvasSelection.UpdateElementBounds /// ClipboardProcessor.CopySelectionInXAML /// </summary> /// <param name="originalElement"></param> /// <param name="updatedElement"></param> /// <param name="transform"></param> internal void UpdateElementBounds(UIElement originalElement, UIElement updatedElement, Matrix transform) { if ( originalElement.DependencyObjectType.Id == updatedElement.DependencyObjectType.Id ) { // Get the transform from element to Canvas GeneralTransform elementToCanvas = originalElement.TransformToAncestor(_inkCanvas.InnerCanvas); //cast to a FrameworkElement, nothing inherits from UIElement besides it right now FrameworkElement frameworkElement = originalElement as FrameworkElement; Size size; Thickness thickness = new Thickness(); if ( frameworkElement == null ) { // Get the element's render size. size = originalElement.RenderSize; } else { size = new Size(frameworkElement.ActualWidth, frameworkElement.ActualHeight); thickness = frameworkElement.Margin; } Rect elementBounds = new Rect(0, 0, size.Width, size.Height); // Rect in element space elementBounds = elementToCanvas.TransformBounds(elementBounds); // Rect in Canvas space // Now apply the matrix to the element bounds Rect newBounds = Rect.Transform(elementBounds, transform); if ( !DoubleUtil.AreClose(elementBounds.Width, newBounds.Width) ) { if ( frameworkElement == null ) { Size newSize = originalElement.RenderSize; newSize.Width = newBounds.Width; updatedElement.RenderSize = newSize; } else { ((FrameworkElement)updatedElement).Width = newBounds.Width; } } if ( !DoubleUtil.AreClose(elementBounds.Height, newBounds.Height) ) { if ( frameworkElement == null ) { Size newSize = originalElement.RenderSize; newSize.Height = newBounds.Height; updatedElement.RenderSize = newSize; } else { ( (FrameworkElement)updatedElement ).Height = newBounds.Height; } } double left = InkCanvas.GetLeft(originalElement); double top = InkCanvas.GetTop(originalElement); double right = InkCanvas.GetRight(originalElement); double bottom = InkCanvas.GetBottom(originalElement); Point originalPosition = new Point(); // Default as (0, 0) if ( !double.IsNaN(left) ) { originalPosition.X = left; } else if ( !double.IsNaN(right) ) { originalPosition.X = right; } if ( !double.IsNaN(top) ) { originalPosition.Y = top; } else if ( !double.IsNaN(bottom) ) { originalPosition.Y = bottom; } Point newPosition = originalPosition * transform; if ( !double.IsNaN(left) ) { InkCanvas.SetLeft(updatedElement, newPosition.X - thickness.Left); // Left wasn't auto } else if ( !double.IsNaN(right) ) { // NOTICE-2005/05/05-WAYNEZEN // Canvas.RightProperty means the distance between element right side and its parent Canvas // right side. The same definition is applied to Canvas.BottomProperty InkCanvas.SetRight(updatedElement, ( right - ( newPosition.X - originalPosition.X ) )); // Right wasn't not auto } else { InkCanvas.SetLeft(updatedElement, newPosition.X - thickness.Left); // Both Left and Right were aut. Modify Left by default. } if ( !double.IsNaN(top) ) { InkCanvas.SetTop(updatedElement, newPosition.Y - thickness.Top); // Top wasn't auto } else if ( !double.IsNaN(bottom) ) { InkCanvas.SetBottom(updatedElement, ( bottom - ( newPosition.Y - originalPosition.Y ) )); // Bottom wasn't not auto } else { InkCanvas.SetTop(updatedElement, newPosition.Y - thickness.Top); // Both Top and Bottom were aut. Modify Left by default. } } else { Debug.Assert(false, "The updatedElement has to be the same type as the originalElement."); } } internal void TransformStrokes(StrokeCollection strokes, Matrix matrix) { strokes.Transform(matrix, false /*Don't apply the transform to StylusTip*/); } internal InkCanvasSelectionHitResult HitTestSelection(Point pointOnInkCanvas) { // If Selection is moving or resizing now, we should returns the active hit result. if ( _activeSelectionHitResult.HasValue ) { return _activeSelectionHitResult.Value; } // No selection at all. Just return None. if ( !HasSelection ) { return InkCanvasSelectionHitResult.None; } // Get the transform from InkCanvas to SelectionAdorner GeneralTransform inkCanvasToSelectionAdorner = _inkCanvas.TransformToDescendant(_inkCanvas.SelectionAdorner); Point pointOnSelectionAdorner = inkCanvasToSelectionAdorner.Transform(pointOnInkCanvas); InkCanvasSelectionHitResult hitResult = _inkCanvas.SelectionAdorner.SelectionHandleHitTest(pointOnSelectionAdorner); // If the hit test returns Selection and there is one and only one element is selected. // We have to check whether we hit on inside the element. if ( hitResult == InkCanvasSelectionHitResult.Selection && SelectedElements.Count == 1 && SelectedStrokes.Count == 0 ) { GeneralTransform transformToInnerCanvas = _inkCanvas.TransformToDescendant(_inkCanvas.InnerCanvas); Point pointOnInnerCanvas = transformToInnerCanvas.Transform(pointOnInkCanvas); // Try to find out whether we hit the single selement. If so, just return None. if ( HasHitSingleSelectedElement(pointOnInnerCanvas) ) { hitResult = InkCanvasSelectionHitResult.None; } } return hitResult; } /// <summary> /// Private helper to used to determine if the current selection /// is different than the selection passed /// </summary> /// <param name="strokes">strokes</param> /// <param name="strokesAreDifferent">strokesAreDifferent</param> /// <param name="elements">elements</param> /// <param name="elementsAreDifferent">elementsAreDifferent</param> internal void SelectionIsDifferentThanCurrent(StrokeCollection strokes, out bool strokesAreDifferent, IList<UIElement> elements, out bool elementsAreDifferent) { strokesAreDifferent = false; elementsAreDifferent = false; if ( SelectedStrokes.Count == 0 ) { if ( strokes.Count > 0 ) { strokesAreDifferent = true; } } else if ( !InkCanvasSelection.StrokesAreEqual(SelectedStrokes, strokes) ) { strokesAreDifferent = true; } if ( SelectedElements.Count == 0 ) { if ( elements.Count > 0 ) { elementsAreDifferent = true; } } else if ( !InkCanvasSelection.FrameworkElementArraysAreEqual(elements, SelectedElements) ) { elementsAreDifferent = true; } } #endregion Internal Methods //------------------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------------------- #region Private Methods /// <summary> /// HasHitSingleSelectedElement /// This method hits test against the current selection. If the point is inside the single selected element, /// it will return true. Otherwise, return false. /// </summary> /// <param name="pointOnInnerCanvas"></param> /// <returns></returns> private bool HasHitSingleSelectedElement(Point pointOnInnerCanvas) { bool hasHit = false; if ( SelectedElements.Count == 1 ) { IEnumerator<Rect> enumerator = SelectedElementsBoundsEnumerator.GetEnumerator(); if ( enumerator.MoveNext() ) { Rect elementRect = enumerator.Current; hasHit = elementRect.Contains(pointOnInnerCanvas); } else { Debug.Assert(false, "An unexpected single selected Element"); } } return hasHit; } /// <summary> /// Private helper to stop listening to stroke changes /// </summary> private void QuitListeningToStrokeChanges() { if ( _inkCanvas.Strokes != null ) { _inkCanvas.Strokes.StrokesChanged -= new StrokeCollectionChangedEventHandler(this.OnStrokeCollectionChanged); } foreach ( Stroke s in SelectedStrokes ) { s.Invalidated -= new EventHandler(this.OnStrokeInvalidated); } } /// <summary> /// Private helper to listen to stroke changes /// </summary> private void ListenToStrokeChanges() { if ( _inkCanvas.Strokes != null ) { _inkCanvas.Strokes.StrokesChanged += new StrokeCollectionChangedEventHandler(this.OnStrokeCollectionChanged); } foreach ( Stroke s in SelectedStrokes ) { s.Invalidated += new EventHandler(this.OnStrokeInvalidated); } } /// <summary> /// Helper method that take a finalRectangle and raised the appropriate /// events on the InkCanvas. Handles cancellation /// </summary> private void CommitMoveChange(Rect finalRectangle) { Rect selectionBounds = SelectionBounds; // //*** MOVED *** // InkCanvasSelectionEditingEventArgs args = new InkCanvasSelectionEditingEventArgs(selectionBounds, finalRectangle); _inkCanvas.RaiseSelectionMoving(args); if ( !args.Cancel ) { if ( finalRectangle != args.NewRectangle ) { finalRectangle = args.NewRectangle; } // // perform the move // MoveSelection(selectionBounds, finalRectangle); // // raise the 'changed' event // _inkCanvas.RaiseSelectionMoved(EventArgs.Empty); } } /// <summary> /// Helper method that take a finalRectangle and raised the appropriate /// events on the InkCanvas. Handles cancellation /// </summary> private void CommitResizeChange(Rect finalRectangle) { Rect selectionBounds = SelectionBounds; // // *** RESIZED *** // InkCanvasSelectionEditingEventArgs args = new InkCanvasSelectionEditingEventArgs(selectionBounds, finalRectangle); _inkCanvas.RaiseSelectionResizing(args); if ( !args.Cancel ) { if ( finalRectangle != args.NewRectangle ) { finalRectangle = args.NewRectangle; } // // perform the move // MoveSelection(selectionBounds, finalRectangle); // // raise the 'changed' event // _inkCanvas.RaiseSelectionResized(EventArgs.Empty); } } /// <summary> /// Private helper that moves all selected elements from the previous location /// to the new one /// </summary> /// <param name="previousRect"></param> /// <param name="newRect"></param> private void MoveSelection(Rect previousRect, Rect newRect) { // // compute our transform, but first remove our artificial border // Matrix matrix = InkCanvasSelection.MapRectToRect(newRect, previousRect); // // transform the elements // int count = SelectedElements.Count; IList<UIElement> elements = SelectedElements; for ( int i = 0; i < count ; i++ ) { UpdateElementBounds(elements[i], matrix); } // // transform the strokes // if ( SelectedStrokes.Count > 0 ) { TransformStrokes(SelectedStrokes, matrix); // Flag the change _areStrokesChanged = true; } if ( SelectedElements.Count == 0 ) { // If there is no element in the current selection, the inner canvas won't have layout changes. // So there is no LayoutUpdated event. We have to manually update the selection bounds. UpdateSelectionAdorner(); } // NTRAID:WINDOWSOS#1565058-2006/03/20-WAYNEZEN, // Always bring the new selection rectangle into the current view when the InkCanvas is hosted inside a ScrollViewer. _inkCanvas.BringIntoView(newRect); } /// <summary> /// A handler which receives LayoutUpdated from the layout manager. Since the selected elements can be animated, /// moved, resized or even removed programmatically from the InkCanvas, we have to monitor /// the any layout changes caused by those actions. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnCanvasLayoutUpdated(object sender, EventArgs e) { Debug.Assert( SelectedElements.Count != 0, "The handler only can be hooked up when there are elements being selected" ); // Update the selection adorner when receive the layout changed UpdateSelectionAdorner(); } /// <summary> /// Our own internal listener for packet changes /// </summary> private void OnStrokeInvalidated(object sender, EventArgs e) { OnStrokeCollectionChanged(sender, new StrokeCollectionChangedEventArgs(new StrokeCollection(), new StrokeCollection())); } /// <summary> /// Our own internal listener for strokes changed. /// This is used so that if someone deletes or modifies a stroke /// we are currently displaying for selection, we can update our size /// </summary> private void OnStrokeCollectionChanged(object target, StrokeCollectionChangedEventArgs e) { // If the strokes only get added to the InkCanvas, we don't have to update our internal selected strokes. if ( e.Added.Count != 0 && e.Removed.Count == 0 ) { return; } foreach (Stroke s in e.Removed) { if ( SelectedStrokes.Contains(s) ) { s.Invalidated -= new EventHandler(this.OnStrokeInvalidated); s.IsSelected = false; // Now remove the stroke from our private collection. SelectedStrokes.Remove(s); } } // Mark the strokes change _areStrokesChanged = true; UpdateSelectionAdorner(); } /// <summary> /// Get the cached bounding boxes to be updated. /// </summary> private Rect GetStrokesBounds() { // Update the strokes bounds if they are changed. if ( _areStrokesChanged ) { _cachedStrokesBounds = SelectedStrokes.Count != 0 ? SelectedStrokes.GetBounds( ) : Rect.Empty; _areStrokesChanged = false; } return _cachedStrokesBounds; } /// <summary> /// Get the bounding boxes of the selected elements. /// </summary> /// <returns></returns> private List<Rect> GetElementsBounds() { List<Rect> rects = new List<Rect>(); if ( SelectedElements.Count != 0 ) { // The private SelectedElementsBounds property will ensure the size is got after rendering's done. foreach ( Rect elementRect in SelectedElementsBoundsEnumerator ) { rects.Add(elementRect); } } return rects; } /// <summary> /// Get the union box of the selected elements. /// </summary> /// <returns></returns> private Rect GetElementsUnionBounds() { if ( SelectedElements.Count == 0 ) { return Rect.Empty; } Rect elementsBounds = Rect.Empty; // The private SelectedElementsBounds property will ensure the size is got after rendering's done. foreach ( Rect elementRect in SelectedElementsBoundsEnumerator ) { elementsBounds.Union(elementRect); } return elementsBounds; } /// <summary> /// Update the selection adorners state. /// The method is called by: /// MoveSelection /// OnCanvasLayoutUpdated /// OnStrokeCollectionChanged /// RemoveElement /// Select /// </summary> private void UpdateSelectionAdorner() { // The Selection Adorner will be visible all the time unless the ActiveEditingMode is None. if ( _inkCanvas.ActiveEditingMode != InkCanvasEditingMode.None ) { Debug.Assert(_inkCanvas.SelectionAdorner.Visibility == Visibility.Visible, "SelectionAdorner should be always visible except under the None ActiveEditingMode"); _inkCanvas.SelectionAdorner.UpdateSelectionWireFrame(GetStrokesBounds(), GetElementsBounds()); } else { Debug.Assert(_inkCanvas.SelectionAdorner.Visibility == Visibility.Collapsed, "SelectionAdorner should be collapsed except if the ActiveEditingMode is None"); } } /// <summary> /// Ensure the rendering is valid. /// Called by: /// SelectedElementsBounds /// </summary> private void EnusreElementsBounds() { InkCanvasInnerCanvas innerCanvas = _inkCanvas.InnerCanvas; // Make sure the arrange is valid. If not, we invoke UpdateLayout now. if ( !innerCanvas.IsMeasureValid || !innerCanvas.IsArrangeValid ) { innerCanvas.UpdateLayout(); } } /// <summary> /// Utility for computing a transformation that maps one rect to another /// </summary> /// <param name="target">Destination Rectangle</param> /// <param name="source">Source Rectangle</param> /// <returns>Transform that maps source rectangle to destination rectangle</returns> private static Matrix MapRectToRect(Rect target, Rect source) { if(source.IsEmpty) throw new ArgumentOutOfRangeException("source", SR.Get(SRID.InvalidDiameter)); /* In the horizontal direction: M11*source.left + Dx = target.left M11*source.right + Dx = target.right Subtracting the equations yields: M11*(source.right - source.left) = target.right - target.left hence: M11 = (target.right - target.left) / (source.right - source.left) Having computed M11, solve the first equation for Dx: Dx = target.left - M11*source.left */ double m11 = target.Width / source.Width; double dx = target.Left - m11 * source.Left; // Now do the same thing in the vertical direction double m22 = target.Height / source.Height; double dy = target.Top - m22 * source.Top; /* We are looking for the transformation that takes one upright rectangle to another. This involves neither rotation nor shear, so: */ return new Matrix(m11, 0, 0, m22, dx, dy); } /// <summary> /// Adds/Removes the LayoutUpdated handler according to whether there is selected elements or not. /// </summary> private void UpdateCanvasLayoutUpdatedHandler() { // If there are selected elements, we should create a LayoutUpdated handler in order to monitor their arrange changes. // Otherwise, we don't have to listen the LayoutUpdated if there is no selected element at all. if ( SelectedElements.Count != 0 ) { // Make sure we hook up the event handler. if ( _layoutUpdatedHandler == null ) { _layoutUpdatedHandler = new EventHandler(OnCanvasLayoutUpdated); _inkCanvas.InnerCanvas.LayoutUpdated += _layoutUpdatedHandler; } } else { // Remove the handler if there is one. if ( _layoutUpdatedHandler != null ) { _inkCanvas.InnerCanvas.LayoutUpdated -= _layoutUpdatedHandler; _layoutUpdatedHandler = null; } } } /// <summary> /// Private helper method used to determine if two stroke collection either /// 1) are both null /// or /// 2) both refer to the identical set of strokes /// </summary> private static bool StrokesAreEqual(StrokeCollection strokes1, StrokeCollection strokes2) { if ( strokes1 == null && strokes2 == null ) { return true; } // // we know that one of the stroke collections is // not null. If the other one is, they're not // equal // if ( strokes1 == null || strokes2 == null ) { return false; } if ( strokes1.Count != strokes2.Count ) { return false; } foreach ( Stroke s in strokes1 ) { if ( !strokes2.Contains(s) ) { return false; } } return true; } /// <summary> /// Private helper method used to determine if two collection either /// 1) are both null /// or /// 2) both refer to the identical set of elements /// </summary> private static bool FrameworkElementArraysAreEqual(IList<UIElement> elements1, IList<UIElement> elements2) { if ( elements1 == null && elements2 == null ) { return true; } // // we know that one of the stroke collections is // not null. If the other one is, they're not // equal // if ( elements1 == null || elements2 == null ) { return false; } if ( elements1.Count != elements2.Count ) { return false; } foreach ( UIElement e in elements1 ) { if ( !elements2.Contains(e) ) { return false; } } return true; } #endregion Private Methods //------------------------------------------------------------------------------- // // Private Properties // //------------------------------------------------------------------------------- #region Private Properties /// <summary> /// Iterates the bounding boxes of the selected elements relevent to their parent (InnerCanvas) /// </summary> private IEnumerable<Rect> SelectedElementsBoundsEnumerator { get { // Ensure the elements have been rendered completely. EnusreElementsBounds(); InkCanvasInnerCanvas innerCanvas = _inkCanvas.InnerCanvas; foreach ( UIElement element in SelectedElements ) { // Get the transform from element to Canvas GeneralTransform elementToCanvas = element.TransformToAncestor(innerCanvas); // Get the element's render size. Size size = element.RenderSize; Rect rect = new Rect(0, 0, size.Width, size.Height); // Rect in element space rect = elementToCanvas.TransformBounds(rect); // Rect in Canvas space yield return rect; } } } #endregion Private Properties //------------------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------------------- #region Private Fields /// <summary> /// Our logical parent. /// </summary> private InkCanvas _inkCanvas; /// <summary> /// The collection of strokes this selectedinkelement represents /// </summary> private StrokeCollection _selectedStrokes; /// <summary> /// The last known rectangle before the current edit. used to revert /// when events are cancelled and expose the value to the InkCanvas.GetSelectionBounds /// </summary> private Rect _cachedStrokesBounds; private bool _areStrokesChanged; /// <summary> /// The collection of elements this selectedinkelement represents /// </summary> private List<UIElement> _selectedElements; private EventHandler _layoutUpdatedHandler; private Nullable<InkCanvasSelectionHitResult> _activeSelectionHitResult; #endregion Private Fields } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// ThrowsConstraint is used to test the exception thrown by /// a delegate by applying a constraint to it. /// </summary> public class ThrowsConstraint : PrefixConstraint { private Exception caughtException; /// <summary> /// Initializes a new instance of the <see cref="ThrowsConstraint"/> class, /// using a constraint to be applied to the exception. /// </summary> /// <param name="baseConstraint">A constraint to apply to the caught exception.</param> public ThrowsConstraint(IConstraint baseConstraint) : base(baseConstraint) { } /// <summary> /// Get the actual exception thrown - used by Assert.Throws. /// </summary> public Exception ActualException { get { return caughtException; } } #region Constraint Overrides /// <summary> /// Gets text describing a constraint /// </summary> public override string Description { get { return baseConstraint.Description; } } /// <summary> /// Executes the code of the delegate and captures any exception. /// If a non-null base constraint was provided, it applies that /// constraint to the exception. /// </summary> /// <param name="actual">A delegate representing the code to be tested</param> /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns> public override ConstraintResult ApplyTo<TActual>(TActual actual) { //TestDelegate code = actual as TestDelegate; //if (code == null) // throw new ArgumentException( // string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual"); //caughtException = null; //try //{ // code(); //} //catch (Exception ex) //{ // caughtException = ex; //} caughtException = ExceptionInterceptor.Intercept(actual); return new ThrowsConstraintResult( this, caughtException, caughtException != null ? baseConstraint.ApplyTo(caughtException) : null); } /// <summary> /// Converts an ActualValueDelegate to a TestDelegate /// before calling the primary overload. /// </summary> /// <param name="del"></param> /// <returns></returns> public override ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del) { //TestDelegate testDelegate = new TestDelegate(delegate { del(); }); //return ApplyTo((object)testDelegate); return ApplyTo(new GenericInvocationDescriptor<TActual>(del)); } #endregion #region Nested Result Class private class ThrowsConstraintResult : ConstraintResult { private readonly ConstraintResult baseResult; public ThrowsConstraintResult(ThrowsConstraint constraint, Exception caughtException, ConstraintResult baseResult) : base(constraint, caughtException) { if (caughtException != null && baseResult.IsSuccess) Status = ConstraintStatus.Success; else Status = ConstraintStatus.Failure; this.baseResult = baseResult; } /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. This override only handles the special message /// used when an exception is expected but none is thrown. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { if (ActualValue == null) writer.Write("no exception thrown"); else baseResult.WriteActualValueTo(writer); } } #endregion #region ExceptionInterceptor internal class ExceptionInterceptor { private ExceptionInterceptor() { } internal static Exception Intercept(object invocation) { var invocationDescriptor = GetInvocationDescriptor(invocation); #if NET_4_0 || NET_4_5 || PORTABLE if (AsyncInvocationRegion.IsAsyncOperation(invocationDescriptor.Delegate)) { using (var region = AsyncInvocationRegion.Create(invocationDescriptor.Delegate)) { object result = invocationDescriptor.Invoke(); try { region.WaitForPendingOperationsToComplete(result); return null; } catch (Exception ex) { return ex; } } } else #endif { try { invocationDescriptor.Invoke(); return null; } catch (Exception ex) { return ex; } } } private static IInvocationDescriptor GetInvocationDescriptor(object actual) { var invocationDescriptor = actual as IInvocationDescriptor; if (invocationDescriptor == null) { var testDelegate = actual as TestDelegate; if (testDelegate == null) throw new ArgumentException( String.Format("The actual value must be a TestDelegate or ActualValueDelegate but was {0}", actual.GetType().Name), "actual"); invocationDescriptor = new VoidInvocationDescriptor(testDelegate); } return invocationDescriptor; } } #endregion #region InvocationDescriptor internal class GenericInvocationDescriptor<T> : IInvocationDescriptor { private readonly ActualValueDelegate<T> _del; public GenericInvocationDescriptor(ActualValueDelegate<T> del) { _del = del; } public object Invoke() { return _del(); } public Delegate Delegate { get { return _del; } } } private interface IInvocationDescriptor { Delegate Delegate { get; } object Invoke(); } private class VoidInvocationDescriptor : IInvocationDescriptor { private readonly TestDelegate _del; public VoidInvocationDescriptor(TestDelegate del) { _del = del; } public object Invoke() { _del(); return null; } public Delegate Delegate { get { return _del; } } } #endregion } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NUnit.TestUtilities.Collections; using NUnit.TestUtilities.Comparers; namespace NUnit.Framework.Assertions { /// <summary> /// Test Library for the NUnit CollectionAssert class. /// </summary> [TestFixture()] public class CollectionAssertTest { #region AllItemsAreInstancesOfType [Test()] public void ItemsOfType() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string)); } [Test] public void ItemsOfTypeFailure() { var collection = new SimpleObjectCollection("x", "y", new object()); var expectedMessage = " Expected: all items instance of <System.String>" + Environment.NewLine + " But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine + " First non-matching item at index [2]: <System.Object>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection, typeof(string))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region AllItemsAreNotNull [Test()] public void ItemsNotNull() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AllItemsAreNotNull(collection); } [Test] public void ItemsNotNullFailure() { var collection = new SimpleObjectCollection("x", null, "z"); var expectedMessage = " Expected: all items not null" + Environment.NewLine + " But was: < \"x\", null, \"z\" >" + Environment.NewLine + " First non-matching item at index [1]: null" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region AllItemsAreUnique [Test] public void Unique_WithObjects() { CollectionAssert.AllItemsAreUnique( new SimpleObjectCollection(new object(), new object(), new object())); } [Test] public void Unique_WithStrings() { CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z")); } [Test] public void Unique_WithNull() { CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z")); } [Test] public void UniqueFailure() { var expectedMessage = " Expected: all items unique" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine + " Not unique items: < \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x"))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void UniqueFailure_WithTwoNulls() { var expectedMessage = " Expected: all items unique" + Environment.NewLine + " But was: < \"x\", null, \"y\", null, \"z\" >" + Environment.NewLine + " Not unique items: < null >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>( () => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z"))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void UniqueFailure_WithMultipleNonUniques() { var collection = new SimpleObjectCollection("x", "y", "x", "x", "z", "y"); var expectedMessage = " Expected: all items unique" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\", \"x\", \"z\", \"y\" >" + Environment.NewLine + " Not unique items: < \"x\", \"y\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void UniqueFailure_ElementTypeIsObject_NUnitEqualityIsUsed() { var collection = new List<object> { 42, null, 42f }; Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection)); } [Test] public void UniqueFailure_ElementTypeIsInterface_NUnitEqualityIsUsed() { var collection = new List<IConvertible> { 42, null, 42f }; Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection)); } [Test] public void UniqueFailure_ElementTypeIsStruct_ImplicitCastAndNewAlgorithmIsUsed() { var collection = new List<float> { 42, 42f }; Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection)); } [Test] public void UniqueFailure_ElementTypeIsNotSealed_NUnitEqualityIsUsed() { var collection = new List<ValueType> { 42, 42f }; Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection)); } static readonly IEnumerable<int> RANGE = Enumerable.Range(0, 10_000); static readonly IEnumerable[] PerformanceData = { RANGE, new List<int>(RANGE), new List<double>(RANGE.Select(v => (double)v)), new List<string>(RANGE.Select(v => v.ToString())) }; [TestCaseSource(nameof(PerformanceData))] public void PerformanceTests(IEnumerable values) { Warn.Unless(() => CollectionAssert.AllItemsAreUnique(values), HelperConstraints.HasMaxTime(100)); } #endregion #region AreEqual [Test] public void AreEqual() { var set1 = new SimpleEnumerable("x", "y", "z"); var set2 = new SimpleEnumerable("x", "y", "z"); CollectionAssert.AreEqual(set1,set2); CollectionAssert.AreEqual(set1,set2,new TestComparer()); Assert.AreEqual(set1,set2); } [Test] public void AreEqualFailCount() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("x", "y", "z", "a"); var expectedMessage = " Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine + " Values differ at index [3]" + Environment.NewLine + " Extra: < \"a\" >"; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEqualFail() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("x", "y", "a"); var expectedMessage = " Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine + " Values differ at index [2]" + Environment.NewLine + " String lengths are both 1. Strings differ at index 0." + Environment.NewLine + " Expected: \"z\"" + Environment.NewLine + " But was: \"a\"" + Environment.NewLine + " -----------^" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEqual_HandlesNull() { object[] set1 = new object[3]; object[] set2 = new object[3]; CollectionAssert.AreEqual(set1,set2); CollectionAssert.AreEqual(set1,set2,new TestComparer()); } [Test] public void EnsureComparerIsUsed() { // Create two collections int[] array1 = new int[2]; int[] array2 = new int[2]; array1[0] = 4; array1[1] = 5; array2[0] = 99; array2[1] = -99; CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer()); } [Test] public void AreEqual_UsingIterator() { int[] array = new int[] { 1, 2, 3 }; CollectionAssert.AreEqual(array, CountToThree()); } [Test] public void AreEqualFails_ObjsUsingIEquatable() { IEnumerable set1 = new SimpleEnumerableWithIEquatable("x", "y", "z"); IEnumerable set2 = new SimpleEnumerableWithIEquatable("x", "z", "z"); CollectionAssert.AreNotEqual(set1, set2); Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2)); } [Test] public void IEnumerablesAreEqualWithCollectionsObjectsImplemetingIEquatable() { IEnumerable set1 = new SimpleEnumerable(new SimpleIEquatableObj()); IEnumerable set2 = new SimpleEnumerable(new SimpleIEquatableObj()); CollectionAssert.AreEqual(set1, set2); } [Test] public void ArraysAreEqualWithCollectionsObjectsImplementingIEquatable() { SimpleIEquatableObj[] set1 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() }; SimpleIEquatableObj[] set2 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() }; CollectionAssert.AreEqual(set1, set2); } IEnumerable CountToThree() { yield return 1; yield return 2; yield return 3; } [Test] public void AreEqual_UsingIterator_Fails() { int[] array = new int[] { 1, 3, 5 }; AssertionException ex = Assert.Throws<AssertionException>( delegate { CollectionAssert.AreEqual(array, CountToThree()); } ); Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And. Contains("Expected: 3").And. Contains("But was: 2")); } [Test] public void AreEqual_UsingLinqQuery() { int[] array = new int[] { 1, 2, 3 }; CollectionAssert.AreEqual(array, array.Select((item) => item)); } [Test] public void AreEqual_UsingLinqQuery_Fails() { int[] array = new int[] { 1, 2, 3 }; AssertionException ex = Assert.Throws<AssertionException>( delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } ); Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And. Contains("Expected: 1").And. Contains("But was: 2")); } [Test] public void AreEqual_IEquatableImplementationIsIgnored() { var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42); var y = new Constraints.EnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 15); // They are not equal using Assert Assert.AreNotEqual(x, y, "Assert 1"); Assert.AreNotEqual(y, x, "Assert 2"); // Using CollectionAssert they are equal CollectionAssert.AreEqual(x, y, "CollectionAssert 1"); CollectionAssert.AreEqual(y, x, "CollectionAssert 2"); } #endregion #region AreEquivalent [Test] public void Equivalent() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("z", "y", "x"); CollectionAssert.AreEquivalent(set1,set2); } [Test] public void EquivalentFailOne() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("x", "y", "x"); var expectedMessage = " Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine + " Missing (1): < \"z\" >" + Environment.NewLine + " Extra (1): < \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void EquivalentFailTwo() { ICollection set1 = new SimpleObjectCollection("x", "y", "x"); ICollection set2 = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine + " Missing (1): < \"x\" >" + Environment.NewLine + " Extra (1): < \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEquivalentHandlesNull() { ICollection set1 = new SimpleObjectCollection(null, "x", null, "z"); ICollection set2 = new SimpleObjectCollection("z", null, "x", null); CollectionAssert.AreEquivalent(set1,set2); } #endregion #region AreNotEqual [Test] public void AreNotEqual() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "x"); CollectionAssert.AreNotEqual(set1,set2); CollectionAssert.AreNotEqual(set1,set2,new TestComparer()); CollectionAssert.AreNotEqual(set1,set2,"test"); CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test"); CollectionAssert.AreNotEqual(set1,set2,"test {0}","1"); CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1"); } [Test] public void AreNotEqual_Fails() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreNotEqual_HandlesNull() { object[] set1 = new object[3]; var set2 = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AreNotEqual(set1,set2); CollectionAssert.AreNotEqual(set1,set2,new TestComparer()); } [Test] public void AreNotEqual_IEquatableImplementationIsIgnored() { var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42); var y = new Constraints.EnumerableObject<int>(new[] { 5, 4, 3, 2, 1 }, 42); // Equal using Assert Assert.AreEqual(x, y, "Assert 1"); Assert.AreEqual(y, x, "Assert 2"); // Not equal using CollectionAssert CollectionAssert.AreNotEqual(x, y, "CollectionAssert 1"); CollectionAssert.AreNotEqual(y, x, "CollectionAssert 2"); } #endregion #region AreNotEquivalent [Test] public void NotEquivalent() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "x"); CollectionAssert.AreNotEquivalent(set1,set2); } [Test] public void NotEquivalent_Fails() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "z", "y"); var expectedMessage = " Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NotEquivalentHandlesNull() { var set1 = new SimpleObjectCollection("x", null, "z"); var set2 = new SimpleObjectCollection("x", null, "x"); CollectionAssert.AreNotEquivalent(set1,set2); } #endregion #region Contains [Test] public void Contains_IList() { var list = new SimpleObjectList("x", "y", "z"); CollectionAssert.Contains(list, "x"); } [Test] public void Contains_ICollection() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.Contains(collection,"x"); } [Test] public void ContainsFails_ILIst() { var list = new SimpleObjectList("x", "y", "z"); var expectedMessage = " Expected: some item equal to \"a\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_ICollection() { var collection = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: some item equal to \"a\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_EmptyIList() { var list = new SimpleObjectList(); var expectedMessage = " Expected: some item equal to \"x\"" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_EmptyICollection() { var ca = new SimpleObjectCollection(new object[0]); var expectedMessage = " Expected: some item equal to \"x\"" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsNull_IList() { Object[] oa = new object[] { 1, 2, 3, null, 4, 5 }; CollectionAssert.Contains( oa, null ); } [Test] public void ContainsNull_ICollection() { var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 }); CollectionAssert.Contains( ca, null ); } #endregion #region DoesNotContain [Test] public void DoesNotContain() { var list = new SimpleObjectList(); CollectionAssert.DoesNotContain(list,"a"); } [Test] public void DoesNotContain_Empty() { var list = new SimpleObjectList(); CollectionAssert.DoesNotContain(list,"x"); } [Test] public void DoesNotContain_Fails() { var list = new SimpleObjectList("x", "y", "z"); var expectedMessage = " Expected: not some item equal to \"y\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region IsSubsetOf [Test] public void IsSubsetOf() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z"); CollectionAssert.IsSubsetOf(set2,set1); Assert.That(set2, Is.SubsetOf(set1)); } [Test] public void IsSubsetOf_Fails() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z", "a"); var expectedMessage = " Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine + " Extra items: < \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsSubsetOfHandlesNull() { var set1 = new SimpleObjectList("x", null, "z"); var set2 = new SimpleObjectList(null, "z"); CollectionAssert.IsSubsetOf(set2,set1); Assert.That(set2, Is.SubsetOf(set1)); } #endregion #region IsNotSubsetOf [Test] public void IsNotSubsetOf() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z", "a"); CollectionAssert.IsNotSubsetOf(set1,set2); Assert.That(set1, Is.Not.SubsetOf(set2)); } [Test] public void IsNotSubsetOf_Fails() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z"); var expectedMessage = " Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotSubsetOfHandlesNull() { var set1 = new SimpleObjectList("x", null, "z"); var set2 = new SimpleObjectList(null, "z", "a"); CollectionAssert.IsNotSubsetOf(set1,set2); } #endregion #region IsOrdered [Test] public void IsOrdered() { var list = new SimpleObjectList("x", "y", "z"); CollectionAssert.IsOrdered(list); } [Test] public void IsOrdered_Fails() { var list = new SimpleObjectList("x", "z", "y"); var expectedMessage = " Expected: collection ordered" + Environment.NewLine + " But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine + " Ordering breaks at index [2]: \"y\"" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsOrdered_Allows_adjacent_equal_values() { var list = new SimpleObjectList("x", "x", "z"); CollectionAssert.IsOrdered(list); } [Test] public void IsOrdered_Handles_null() { var list = new SimpleObjectList(null, "x", "z"); Assert.That(list, Is.Ordered); } [Test] public void IsOrdered_ContainedTypesMustBeCompatible() { var list = new SimpleObjectList(1, "x"); Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list)); } [Test] public void IsOrdered_TypesMustImplementIComparable() { var list = new SimpleObjectList(new object(), new object()); Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list)); } [Test] public void IsOrdered_Handles_custom_comparison() { var list = new SimpleObjectList(new object(), new object()); CollectionAssert.IsOrdered(list, new AlwaysEqualComparer()); } [Test] public void IsOrdered_Handles_custom_comparison2() { var list = new SimpleObjectList(2, 1); CollectionAssert.IsOrdered(list, new TestComparer()); } #endregion #region Equals [Test] public void EqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used.")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used.")); } #endregion #region ValueTuple [Test] public void ValueTupleAreEqual() { var set1 = new SimpleEnumerable((1, 2, 3), (1, 2, 3), (1, 2, 3)); var set2 = new SimpleEnumerable((1, 2, 3), (1, 2, 3), (1, 2, 3)); CollectionAssert.AreEqual(set1, set2); CollectionAssert.AreEqual(set1, set2, new TestComparer()); Assert.AreEqual(set1, set2); } [Test] public void ValueTupleAreEqualFail() { var set1 = new SimpleEnumerable((1, 2, 3), (1, 2, 3), (1, 2, 3)); var set2 = new SimpleEnumerable((1, 2, 3), (1, 2, 3), (1, 2, 4)); var expectedMessage = " Expected and actual are both <NUnit.TestUtilities.Collections.SimpleEnumerable>" + Environment.NewLine + " Values differ at index [2]" + Environment.NewLine + " Expected: (1, 2, 3)" + Environment.NewLine + " But was: (1, 2, 4)" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ElementsWithinTuplesAreComparedUsingNUnitEqualityComparer() { var a = new Dictionary<string, (string, Dictionary<string, string>)>() { { "key", ("name", new Dictionary<string, string>())} }; var b = new Dictionary<string, (string, Dictionary<string, string>)>() { { "key", ("name", new Dictionary<string, string>())} }; CollectionAssert.AreEquivalent(a, b); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IO; using System.Net; using System.Net.Security; using System.Runtime; using System.Security.Authentication; using System.Security.Principal; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal class WindowsStreamSecurityUpgradeProvider : StreamSecurityUpgradeProvider { private bool _extractGroupsForWindowsAccounts; private EndpointIdentity _identity; private SecurityTokenManager _securityTokenManager; private bool _isClient; private Uri _listenUri; public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement, BindingContext context, bool isClient) : base(context.Binding) { Contract.Assert(isClient, ".NET Core and .NET Native does not support server side"); _extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts; ProtectionLevel = bindingElement.ProtectionLevel; Scheme = context.Binding.Scheme; _isClient = isClient; _listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress); SecurityCredentialsManager credentialProvider = context.BindingParameters.Find<SecurityCredentialsManager>(); if (credentialProvider == null) { credentialProvider = ClientCredentials.CreateDefaultCredentials(); } _securityTokenManager = credentialProvider.CreateSecurityTokenManager(); } public string Scheme { get; } internal bool ExtractGroupsForWindowsAccounts { get { return _extractGroupsForWindowsAccounts; } } public override EndpointIdentity Identity { get { // If the server credential is null, then we have not been opened yet and have no identity to expose. if (ServerCredential != null) { if (_identity == null) { lock (ThisLock) { if (_identity == null) { _identity = SecurityUtils.CreateWindowsIdentity(ServerCredential); } } } } return _identity; } } internal IdentityVerifier IdentityVerifier { get; private set; } public ProtectionLevel ProtectionLevel { get; } private NetworkCredential ServerCredential { get; set; } public override StreamUpgradeInitiator CreateUpgradeInitiator(EndpointAddress remoteAddress, Uri via) { ThrowIfDisposedOrNotOpen(); return new WindowsStreamSecurityUpgradeInitiator(this, remoteAddress, via); } protected override void OnAbort() { } protected override void OnClose(TimeSpan timeout) { } protected internal override Task OnCloseAsync(TimeSpan timeout) { return TaskHelpers.CompletedTask(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return OnCloseAsync(timeout).ToApm(callback, state); } protected override void OnEndClose(IAsyncResult result) { result.ToApmEnd(); } protected override void OnOpen(TimeSpan timeout) { if (!_isClient) { SecurityTokenRequirement sspiTokenRequirement = TransportSecurityHelpers.CreateSspiTokenRequirement(Scheme, _listenUri); ServerCredential = TransportSecurityHelpers.GetSspiCredential(_securityTokenManager, sspiTokenRequirement, timeout, out _extractGroupsForWindowsAccounts); } } protected internal override Task OnOpenAsync(TimeSpan timeout) { OnOpen(timeout); return TaskHelpers.CompletedTask(); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return OnOpenAsync(timeout).ToApm(callback, state); } protected override void OnEndOpen(IAsyncResult result) { result.ToApmEnd(); } protected override void OnOpened() { base.OnOpened(); if (IdentityVerifier == null) { IdentityVerifier = IdentityVerifier.CreateDefault(); } if (ServerCredential == null) { ServerCredential = CredentialCache.DefaultNetworkCredentials; } } private class WindowsStreamSecurityUpgradeInitiator : StreamSecurityUpgradeInitiatorBase { private WindowsStreamSecurityUpgradeProvider _parent; private IdentityVerifier _identityVerifier; private NetworkCredential _credential; private TokenImpersonationLevel _impersonationLevel; private SspiSecurityTokenProvider _clientTokenProvider; private bool _allowNtlm; public WindowsStreamSecurityUpgradeInitiator( WindowsStreamSecurityUpgradeProvider parent, EndpointAddress remoteAddress, Uri via) : base(FramingUpgradeString.Negotiate, remoteAddress, via) { _parent = parent; _clientTokenProvider = TransportSecurityHelpers.GetSspiTokenProvider( parent._securityTokenManager, remoteAddress, via, parent.Scheme, out _identityVerifier); } internal override async Task OpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Open(timeoutHelper.RemainingTime()); OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>(); OutWrapper<bool> allowNtlmWrapper = new OutWrapper<bool>(); SecurityUtils.OpenTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime()); _credential = await TransportSecurityHelpers.GetSspiCredentialAsync( _clientTokenProvider, impersonationLevelWrapper, allowNtlmWrapper, timeoutHelper.RemainingTime()); _impersonationLevel = impersonationLevelWrapper.Value; _allowNtlm = allowNtlmWrapper; return; } internal override void Open(TimeSpan timeout) { OpenAsync(timeout).GetAwaiter(); } internal override void Close(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Close(timeoutHelper.RemainingTime()); SecurityUtils.CloseTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime()); } private static SecurityMessageProperty CreateServerSecurity(NegotiateStream negotiateStream) { GenericIdentity remoteIdentity = (GenericIdentity)negotiateStream.RemoteIdentity; string principalName = remoteIdentity.Name; if ((principalName != null) && (principalName.Length > 0)) { ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(principalName); SecurityMessageProperty result = new SecurityMessageProperty(); result.TransportToken = new SecurityTokenSpecification(null, authorizationPolicies); result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return result; } else { return null; } } protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity) { OutWrapper<SecurityMessageProperty> remoteSecurityOut = new OutWrapper<SecurityMessageProperty>(); var retVal = OnInitiateUpgradeAsync(stream, remoteSecurityOut).GetAwaiter().GetResult(); remoteSecurity = remoteSecurityOut.Value; return retVal; } protected override async Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity) { NegotiateStream negotiateStream; string targetName; EndpointIdentity identity; if (WcfEventSource.Instance.WindowsStreamSecurityOnInitiateUpgradeIsEnabled()) { WcfEventSource.Instance.WindowsStreamSecurityOnInitiateUpgrade(); } // prepare InitiateUpgradePrepare(stream, out negotiateStream, out targetName, out identity); // authenticate try { await negotiateStream.AuthenticateAsClientAsync(_credential, targetName, _parent.ProtectionLevel, _impersonationLevel); } catch (AuthenticationException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } remoteSecurity.Value = CreateServerSecurity(negotiateStream); ValidateMutualAuth(identity, negotiateStream, remoteSecurity.Value, _allowNtlm); return negotiateStream; } private void InitiateUpgradePrepare( Stream stream, out NegotiateStream negotiateStream, out string targetName, out EndpointIdentity identity) { negotiateStream = new NegotiateStream(stream); targetName = string.Empty; identity = null; if (_parent.IdentityVerifier.TryGetIdentity(RemoteAddress, Via, out identity)) { targetName = SecurityUtils.GetSpnFromIdentity(identity, RemoteAddress); } else { targetName = SecurityUtils.GetSpnFromTarget(RemoteAddress); } } private void ValidateMutualAuth(EndpointIdentity expectedIdentity, NegotiateStream negotiateStream, SecurityMessageProperty remoteSecurity, bool allowNtlm) { if (negotiateStream.IsMutuallyAuthenticated) { if (expectedIdentity != null) { if (!_parent.IdentityVerifier.CheckAccess(expectedIdentity, remoteSecurity.ServiceSecurityContext.AuthorizationContext)) { string primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(remoteSecurity.ServiceSecurityContext.AuthorizationContext); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format( SR.RemoteIdentityFailedVerification, primaryIdentity))); } } } else if (!allowNtlm) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.StreamMutualAuthNotSatisfied))); } } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Controls; using Avalonia.Controls.Shapes; using Avalonia.Layout; using Avalonia.Media; using Xunit; #if AVALONIA_SKIA namespace Avalonia.Skia.RenderTests #else namespace Avalonia.Direct2D1.RenderTests.Shapes #endif { using System.Threading.Tasks; using Avalonia.Collections; public class PathTests : TestBase { public PathTests() : base(@"Shapes\Path") { } [Fact] public async Task Line_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 10,190 L 190,10 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Line_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M10,190 l190,-190 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task HorizontalLine_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 H10 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task HorizontalLine_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 h-180 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task VerticalLine_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M100,190 V10 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task VerticalLine_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M100,190 V-180 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task CubicBezier_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,0 C10,10 190,190 10,190 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task CubicBezier_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,0 c-180,10 0,190 -180,190 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Arc_Absolute() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 A90,90 0 1,0 10,100 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Arc_Relative() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 1, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M190,100 a90,90 0 1,0 -180,0 M0,0M200,200"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_100px_Triangle_Centered() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 2, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 0,100 L 100,100 50,0 Z"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_Tick_Scaled() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 2, Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 1145.607177734375,430 C1145.607177734375,430 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1138,434.5538330078125 1138,434.5538330078125 1138,434.5538330078125 1141.482177734375,438 1141.482177734375,438 1141.482177734375,438 1141.96875,437.9375 1141.96875,437.9375 1141.96875,437.9375 1147,431.34619140625 1147,431.34619140625 1147,431.34619140625 1145.607177734375,430 1145.607177734375,430 z"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_Tick_Scaled_Stroke_8px() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Fill = Brushes.Gray, Stroke = Brushes.Red, StrokeThickness = 8, Stretch = Stretch.Uniform, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Data = StreamGeometry.Parse("M 1145.607177734375,430 C1145.607177734375,430 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1141.449951171875,435.0772705078125 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1139.232177734375,433.0999755859375 1138,434.5538330078125 1138,434.5538330078125 1138,434.5538330078125 1141.482177734375,438 1141.482177734375,438 1141.482177734375,438 1141.96875,437.9375 1141.96875,437.9375 1141.96875,437.9375 1147,431.34619140625 1147,431.34619140625 1147,431.34619140625 1145.607177734375,430 1145.607177734375,430 z"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_Expander_With_Border() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Border { BorderBrush = Brushes.Red, BorderThickness = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Child = new Path { Fill = Brushes.Black, Stroke = Brushes.Black, StrokeThickness = 1, Stretch = Stretch.Uniform, Data = StreamGeometry.Parse("M 0 2 L 4 6 L 0 10 Z"), } } }; await RenderToFile(target); CompareImages(); } #if AVALONIA_SKIA_SKIP_FAIL [Fact(Skip = "FIXME")] #else [Fact] #endif public async Task Path_With_PenLineCap() { Decorator target = new Decorator { Width = 200, Height = 200, Child = new Path { Stroke = Brushes.Black, StrokeThickness = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, StrokeDashCap = PenLineCap.Triangle, StrokeDashArray = new AvaloniaList<double>(3, 1), StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Square, Data = StreamGeometry.Parse("M 20,20 L 180,180"), } }; await RenderToFile(target); CompareImages(); } [Fact] public async Task Path_With_Rotated_Geometry() { var target = new Border { Width = 200, Height = 200, Background = Brushes.White, Child = new Path { Fill = Brushes.Red, Data = new RectangleGeometry { Rect = new Rect(50, 50, 100, 100), Transform = new RotateTransform(45), } } }; await RenderToFile(target); CompareImages(); } } }
#region License /* * HttpListenerRequest.cs * * This code is derived from HttpListenerRequest.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2015 sta.blockhead * * 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 #region Authors /* * Authors: * - Gonzalo Paniagua Javier <[email protected]> */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Provides the access to a request to the <see cref="HttpListener"/>. /// </summary> /// <remarks> /// The HttpListenerRequest class cannot be inherited. /// </remarks> public sealed class HttpListenerRequest { #region Private Fields private static readonly byte[] _100continue; private string[] _acceptTypes; private bool _chunked; private Encoding _contentEncoding; private long _contentLength; private bool _contentLengthWasSet; private HttpListenerContext _context; private CookieCollection _cookies; private WebHeaderCollection _headers; private Guid _identifier; private Stream _inputStream; private bool _keepAlive; private bool _keepAliveWasSet; private string _method; private NameValueCollection _queryString; private Uri _referer; private string _uri; private Uri _url; private string[] _userLanguages; private Version _version; private bool _websocketRequest; private bool _websocketRequestWasSet; #endregion #region Static Constructor static HttpListenerRequest () { _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n"); } #endregion #region Internal Constructors internal HttpListenerRequest (HttpListenerContext context) { _context = context; _contentLength = -1; _headers = new WebHeaderCollection (); _identifier = Guid.NewGuid (); } #endregion #region Public Properties /// <summary> /// Gets the media types which are acceptable for the response. /// </summary> /// <value> /// An array of <see cref="string"/> that contains the media type names in the Accept /// request-header, or <see langword="null"/> if the request didn't include an Accept header. /// </value> public string[] AcceptTypes { get { return _acceptTypes; } } /// <summary> /// Gets an error code that identifies a problem with the client's certificate. /// </summary> /// <value> /// Always returns <c>0</c>. /// </value> public int ClientCertificateError { get { return 0; // TODO: Always returns 0. } } /// <summary> /// Gets the encoding for the entity body data included in the request. /// </summary> /// <value> /// A <see cref="Encoding"/> that represents the encoding for the entity body data, /// or <see cref="Encoding.Default"/> if the request didn't include the information /// about the encoding. /// </value> public Encoding ContentEncoding { get { return _contentEncoding ?? (_contentEncoding = Encoding.Default); } } /// <summary> /// Gets the size of the entity body data included in the request. /// </summary> /// <value> /// A <see cref="long"/> that represents the value of the Content-Length entity-header. The /// value is a number of bytes in the entity body data. <c>-1</c> if the size isn't known. /// </value> public long ContentLength64 { get { return _contentLength; } } /// <summary> /// Gets the media type of the entity body included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Content-Type entity-header. /// </value> public string ContentType { get { return _headers["Content-Type"]; } } /// <summary> /// Gets the cookies included in the request. /// </summary> /// <value> /// A <see cref="CookieCollection"/> that contains the cookies included in the request. /// </value> public CookieCollection Cookies { get { return _cookies ?? (_cookies = _headers.GetCookies (false)); } } /// <summary> /// Gets a value indicating whether the request has the entity body. /// </summary> /// <value> /// <c>true</c> if the request has the entity body; otherwise, <c>false</c>. /// </value> public bool HasEntityBody { get { return _contentLength > 0 || _chunked; } } /// <summary> /// Gets the HTTP headers used in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the HTTP headers used in the request. /// </value> public NameValueCollection Headers { get { return _headers; } } /// <summary> /// Gets the HTTP method used in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the HTTP method used in the request. /// </value> public string HttpMethod { get { return _method; } } /// <summary> /// Gets a <see cref="Stream"/> that contains the entity body data included in the request. /// </summary> /// <value> /// A <see cref="Stream"/> that contains the entity body data included in the request. /// </value> public Stream InputStream { get { return _inputStream ?? (_inputStream = HasEntityBody ? _context.Connection.GetRequestStream (_contentLength, _chunked) : Stream.Null); } } /// <summary> /// Gets a value indicating whether the client that sent the request is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public bool IsAuthenticated { get { return _context.User != null; } } /// <summary> /// Gets a value indicating whether the request is sent from the local computer. /// </summary> /// <value> /// <c>true</c> if the request is sent from the local computer; otherwise, <c>false</c>. /// </value> public bool IsLocal { get { return RemoteEndPoint.Address.IsLocal (); } } /// <summary> /// Gets a value indicating whether the HTTP connection is secured using the SSL protocol. /// </summary> /// <value> /// <c>true</c> if the HTTP connection is secured; otherwise, <c>false</c>. /// </value> public bool IsSecureConnection { get { return _context.Connection.IsSecure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket connection request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>. /// </value> public bool IsWebSocketRequest { get { if (!_websocketRequestWasSet) { _websocketRequest = _method == "GET" && _version > HttpVersion.Version10 && _headers.Contains ("Upgrade", "websocket") && _headers.Contains ("Connection", "Upgrade"); _websocketRequestWasSet = true; } return _websocketRequest; } } /// <summary> /// Gets a value indicating whether the client requests a persistent connection. /// </summary> /// <value> /// <c>true</c> if the client requests a persistent connection; otherwise, <c>false</c>. /// </value> public bool KeepAlive { get { if (!_keepAliveWasSet) { string keepAlive; _keepAlive = _version > HttpVersion.Version10 || _headers.Contains ("Connection", "keep-alive") || ((keepAlive = _headers["Keep-Alive"]) != null && keepAlive != "closed"); _keepAliveWasSet = true; } return _keepAlive; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint. /// </value> public System.Net.IPEndPoint LocalEndPoint { get { return _context.Connection.LocalEndPoint; } } /// <summary> /// Gets the HTTP version used in the request. /// </summary> /// <value> /// A <see cref="Version"/> that represents the HTTP version used in the request. /// </value> public Version ProtocolVersion { get { return _version; } } /// <summary> /// Gets the query string included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the query string parameters. /// </value> public NameValueCollection QueryString { get { return _queryString ?? (_queryString = HttpUtility.InternalParseQueryString (_url.Query, Encoding.UTF8)); } } /// <summary> /// Gets the raw URL (without the scheme, host, and port) requested by the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the raw URL requested by the client. /// </value> public string RawUrl { get { return _url.PathAndQuery; // TODO: Should decode? } } /// <summary> /// Gets the client endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint. /// </value> public System.Net.IPEndPoint RemoteEndPoint { get { return _context.Connection.RemoteEndPoint; } } /// <summary> /// Gets the request identifier of a incoming HTTP request. /// </summary> /// <value> /// A <see cref="Guid"/> that represents the identifier of a request. /// </value> public Guid RequestTraceIdentifier { get { return _identifier; } } /// <summary> /// Gets the URL requested by the client. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the URL requested by the client. /// </value> public Uri Url { get { return _url; } } /// <summary> /// Gets the URL of the resource from which the requested URL was obtained. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the value of the Referer request-header, /// or <see langword="null"/> if the request didn't include an Referer header. /// </value> public Uri UrlReferrer { get { return _referer; } } /// <summary> /// Gets the information about the user agent originating the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the User-Agent request-header. /// </value> public string UserAgent { get { return _headers["User-Agent"]; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="string"/> that represents the server endpoint. /// </value> public string UserHostAddress { get { return LocalEndPoint.ToString (); } } /// <summary> /// Gets the internet host name and port number (if present) specified by the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Host request-header. /// </value> public string UserHostName { get { return _headers["Host"]; } } /// <summary> /// Gets the natural languages which are preferred for the response. /// </summary> /// <value> /// An array of <see cref="string"/> that contains the natural language names in /// the Accept-Language request-header, or <see langword="null"/> if the request /// didn't include an Accept-Language header. /// </value> public string[] UserLanguages { get { return _userLanguages; } } #endregion #region Private Methods private static bool tryCreateVersion (string version, out Version result) { try { result = new Version (version); return true; } catch { result = null; return false; } } #endregion #region Internal Methods internal void AddHeader (string header) { var colon = header.IndexOf (':'); if (colon == -1) { _context.ErrorMessage = "Invalid header"; return; } var name = header.Substring (0, colon).Trim (); var val = header.Substring (colon + 1).Trim (); _headers.InternalSet (name, val, false); var lower = name.ToLower (CultureInfo.InvariantCulture); if (lower == "accept") { _acceptTypes = new List<string> (val.SplitHeaderValue (',')).ToArray (); return; } if (lower == "accept-language") { _userLanguages = val.Split (','); return; } if (lower == "content-length") { long len; if (Int64.TryParse (val, out len) && len >= 0) { _contentLength = len; _contentLengthWasSet = true; } else { _context.ErrorMessage = "Invalid Content-Length header"; } return; } if (lower == "content-type") { try { _contentEncoding = HttpUtility.GetEncoding (val); } catch { _context.ErrorMessage = "Invalid Content-Type header"; } return; } if (lower == "referer") _referer = val.ToUri (); } internal void FinishInitialization () { var host = _headers["Host"]; var nohost = host == null || host.Length == 0; if (_version > HttpVersion.Version10 && nohost) { _context.ErrorMessage = "Invalid Host header"; return; } if (nohost) host = UserHostAddress; _url = HttpUtility.CreateRequestUrl (_uri, host, IsWebSocketRequest, IsSecureConnection); if (_url == null) { _context.ErrorMessage = "Invalid request url"; return; } var enc = Headers["Transfer-Encoding"]; if (_version > HttpVersion.Version10 && enc != null && enc.Length > 0) { _chunked = enc.ToLower () == "chunked"; if (!_chunked) { _context.ErrorMessage = String.Empty; _context.ErrorStatus = 501; return; } } if (!_chunked && !_contentLengthWasSet) { var method = _method.ToLower (); if (method == "post" || method == "put") { _context.ErrorMessage = String.Empty; _context.ErrorStatus = 411; return; } } var expect = Headers["Expect"]; if (expect != null && expect.Length > 0 && expect.ToLower () == "100-continue") { var output = _context.Connection.GetResponseStream (); output.WriteInternally (_100continue, 0, _100continue.Length); } } // Returns true is the stream could be reused. internal bool FlushInput () { if (!HasEntityBody) return true; var len = 2048; if (_contentLength > 0) len = (int) Math.Min (_contentLength, (long) len); var buff = new byte[len]; while (true) { // TODO: Test if MS has a timeout when doing this. try { var ares = InputStream.BeginRead (buff, 0, len, null, null); if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100)) return false; if (InputStream.EndRead (ares) <= 0) return true; } catch { return false; } } } internal void SetRequestLine (string requestLine) { var parts = requestLine.Split (new[] { ' ' }, 3); if (parts.Length != 3) { _context.ErrorMessage = "Invalid request line (parts)"; return; } _method = parts[0]; if (!_method.IsToken ()) { _context.ErrorMessage = "Invalid request line (method)"; return; } _uri = parts[1]; var ver = parts[2]; if (ver.Length != 8 || !ver.StartsWith ("HTTP/") || !tryCreateVersion (ver.Substring (5), out _version) || _version.Major < 1) _context.ErrorMessage = "Invalid request line (version)"; } #endregion #region Public Methods /// <summary> /// Begins getting the client's X.509 v.3 certificate asynchronously. /// </summary> /// <remarks> /// This asynchronous operation must be completed by calling the /// <see cref="EndGetClientCertificate"/> method. Typically, that method is invoked by the /// <paramref name="requestCallback"/> delegate. /// </remarks> /// <returns> /// An <see cref="IAsyncResult"/> that contains the status of the asynchronous operation. /// </returns> /// <param name="requestCallback"> /// An <see cref="AsyncCallback"/> delegate that references the method(s) called when the /// asynchronous operation completes. /// </param> /// <param name="state"> /// An <see cref="object"/> that contains a user defined object to pass to the /// <paramref name="requestCallback"/> delegate. /// </param> /// <exception cref="NotImplementedException"> /// This method isn't implemented. /// </exception> public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state) { // TODO: Not Implemented. throw new NotImplementedException (); } /// <summary> /// Ends an asynchronous operation to get the client's X.509 v.3 certificate. /// </summary> /// <remarks> /// This method completes an asynchronous operation started by calling the /// <see cref="BeginGetClientCertificate"/> method. /// </remarks> /// <returns> /// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate. /// </returns> /// <param name="asyncResult"> /// An <see cref="IAsyncResult"/> obtained by calling the /// <see cref="BeginGetClientCertificate"/> method. /// </param> /// <exception cref="NotImplementedException"> /// This method isn't implemented. /// </exception> public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult) { // TODO: Not Implemented. throw new NotImplementedException (); } /// <summary> /// Gets the client's X.509 v.3 certificate. /// </summary> /// <returns> /// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate. /// </returns> /// <exception cref="NotImplementedException"> /// This method isn't implemented. /// </exception> public X509Certificate2 GetClientCertificate () { // TODO: Not Implemented. throw new NotImplementedException (); } /// <summary> /// Returns a <see cref="string"/> that represents the current /// <see cref="HttpListenerRequest"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents the current <see cref="HttpListenerRequest"/>. /// </returns> public override string ToString () { var output = new StringBuilder (64); output.AppendFormat ("{0} {1} HTTP/{2}\r\n", _method, _uri, _version); output.Append (_headers.ToString ()); return output.ToString (); } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security; using NuGet; namespace NuGet.Common { public class Console : IConsole { public Console() { // setup CancelKeyPress handler so that the console colors are // restored to their original values when nuget.exe is interrupted // by Ctrl-C. var originalForegroundColor = System.Console.ForegroundColor; var originalBackgroundColor = System.Console.BackgroundColor; System.Console.CancelKeyPress += (sender, e) => { System.Console.ForegroundColor = originalForegroundColor; System.Console.BackgroundColor = originalBackgroundColor; }; } public int CursorLeft { get { try { return System.Console.CursorLeft; } catch (IOException) { return 0; } } set { System.Console.CursorLeft = value; } } public int WindowWidth { get { try { var width = System.Console.WindowWidth; if (width > 0) { return width; } else { return int.MaxValue; } } catch (IOException) { // probably means redirected to file return int.MaxValue; } } set { System.Console.WindowWidth = value; } } public Verbosity Verbosity { get; set; } public bool IsNonInteractive { get; set; } private TextWriter Out { get { return Verbosity == Verbosity.Quiet ? TextWriter.Null : System.Console.Out; } } public void Log(MessageLevel level, string message, params object[] args) { switch (level) { case MessageLevel.Info: WriteLine(message, args); break; case MessageLevel.Warning: WriteWarning(message, args); break; case MessageLevel.Debug: WriteColor(Out, ConsoleColor.Gray, message, args); break; } } public void Write(object value) { Out.Write(value); } public void Write(string value) { Out.Write(value); } public void Write(string format, params object[] args) { if (args == null || !args.Any()) { // Don't try to format strings that do not have arguments. We end up throwing if the original string was not meant to be a format token // and contained braces (for instance html) Out.Write(format); } else { Out.Write(format, args); } } public void WriteLine() { Out.WriteLine(); } public void WriteLine(object value) { Out.WriteLine(value); } public void WriteLine(string value) { Out.WriteLine(value); } public void WriteLine(string format, params object[] args) { Out.WriteLine(format, args); } public void WriteError(object value) { WriteError(value.ToString()); } public void WriteError(string value) { WriteError(value, new object[0]); } public void WriteError(string format, params object[] args) { WriteColor(System.Console.Error, ConsoleColor.Red, format, args); } public void WriteWarning(string value) { WriteWarning(prependWarningText: true, value: value, args: new object[0]); } public void WriteWarning(bool prependWarningText, string value) { WriteWarning(prependWarningText, value, new object[0]); } public void WriteWarning(string value, params object[] args) { WriteWarning(prependWarningText: true, value: value, args: args); } public void WriteWarning(bool prependWarningText, string value, params object[] args) { string message = prependWarningText ? String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("CommandLine_Warning"), value) : value; WriteColor(Out, ConsoleColor.Yellow, message, args); } public void WriteLine(ConsoleColor color, string value, params object[] args) { WriteColor(Out, color, value, args); } private static void WriteColor(TextWriter writer, ConsoleColor color, string value, params object[] args) { var currentColor = System.Console.ForegroundColor; try { currentColor = System.Console.ForegroundColor; System.Console.ForegroundColor = color; if (args == null || !args.Any()) { // If it doesn't look like something that needs to be formatted, don't format it. writer.WriteLine(value); } else { writer.WriteLine(value, args); } } finally { System.Console.ForegroundColor = currentColor; } } public void PrintJustified(int startIndex, string text) { PrintJustified(startIndex, text, WindowWidth); } public void PrintJustified(int startIndex, string text, int maxWidth) { if (maxWidth > startIndex) { maxWidth = maxWidth - startIndex - 1; } while (text.Length > 0) { // Trim whitespace at the beginning text = text.TrimStart(); // Calculate the number of chars to print based on the width of the System.Console int length = Math.Min(text.Length, maxWidth); string content; // Text we can print without overflowing the System.Console, excluding new line characters. int newLineIndex = text.IndexOf(Environment.NewLine, 0, length, StringComparison.OrdinalIgnoreCase); if (newLineIndex > -1) { content = text.Substring(0, newLineIndex); } else { content = text.Substring(0, length); } int leftPadding = startIndex + content.Length - CursorLeft; // Print it with the correct padding Out.WriteLine((leftPadding > 0) ? content.PadLeft(leftPadding) : content); // Get the next substring to be printed text = text.Substring(content.Length); } } public bool Confirm(string description) { if (IsNonInteractive) { return true; } var currentColor = ConsoleColor.Gray; try { currentColor = System.Console.ForegroundColor; System.Console.ForegroundColor = ConsoleColor.Yellow; System.Console.Write(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("ConsoleConfirmMessage"), description)); var result = System.Console.ReadLine(); return result.StartsWith(LocalizedResourceManager.GetString("ConsoleConfirmMessageAccept"), StringComparison.OrdinalIgnoreCase); } finally { System.Console.ForegroundColor = currentColor; } } public ConsoleKeyInfo ReadKey() { EnsureInteractive(); return System.Console.ReadKey(intercept: true); } public string ReadLine() { EnsureInteractive(); return System.Console.ReadLine(); } public void ReadSecureString(SecureString secureString) { EnsureInteractive(); try { ReadSecureStringFromConsole(secureString); } catch (InvalidOperationException) { // This can happen when you redirect nuget.exe input, either from the shell with "<" or // from code with ProcessStartInfo. // In this case, just read data from Console.ReadLine() foreach (var c in ReadLine()) { secureString.AppendChar(c); } } secureString.MakeReadOnly(); } private static void ReadSecureStringFromConsole(SecureString secureString) { ConsoleKeyInfo keyInfo; while ((keyInfo = System.Console.ReadKey(intercept: true)).Key != ConsoleKey.Enter) { if (keyInfo.Key == ConsoleKey.Backspace) { if (secureString.Length < 1) { continue; } System.Console.SetCursorPosition(System.Console.CursorLeft - 1, System.Console.CursorTop); System.Console.Write(' '); System.Console.SetCursorPosition(System.Console.CursorLeft - 1, System.Console.CursorTop); secureString.RemoveAt(secureString.Length - 1); } else { secureString.AppendChar(keyInfo.KeyChar); System.Console.Write('*'); } } System.Console.WriteLine(); } private void EnsureInteractive() { if (IsNonInteractive) { throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_CannotPromptForInput")); } } public FileConflictResolution ResolveFileConflict(string message) { // make the question stand out from previous text WriteLine(); WriteLine(ConsoleColor.Yellow, "File Conflict."); WriteLine(message); // Yes - Yes To All - No - No To All var acceptedAnswers = new List<string> { "Y", "A", "N", "L" }; var choices = new[] { FileConflictResolution.Overwrite, FileConflictResolution.OverwriteAll, FileConflictResolution.Ignore, FileConflictResolution.IgnoreAll }; while (true) { Write(LocalizedResourceManager.GetString("FileConflictChoiceText")); string answer = ReadLine(); if (!String.IsNullOrEmpty(answer)) { int index = acceptedAnswers.FindIndex(a => a.Equals(answer, StringComparison.OrdinalIgnoreCase)); if (index > -1) { return choices[index]; } } } } } }
using System; using System.Linq; namespace PluralizeSample { class MainClass { public static EnglishPluralizer Pluralizer { get; set; } public static int FailCount = 0; public static void Assert(string toPluralize, string expected) { var plural = Pluralizer.GetPluralForm(toPluralize); if(expected != plural.Value) { var oldBg = Console.BackgroundColor; var oldFg = Console.ForegroundColor; Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("{0} -> {1}, expected {2}", toPluralize, plural.Value, expected); Console.WriteLine(String.Join("\n", plural.Description.Split('\n').Select(d => "\t" + d))); Console.BackgroundColor = oldBg; Console.ForegroundColor = oldFg; FailCount++; } } public static void Main (string[] args) { Pluralizer = new EnglishPluralizer(); Assert("cheese", "cheeses"); Assert("chinese", "chinese"); Assert("codex", "codices"); Assert("stigma", "stigmata"); Assert("church", "churches"); Assert("class", "classes"); Assert("life", "lives"); Assert("wolf", "wolves"); Assert("knife", "knives"); Assert("scarf", "scarves"); Assert("leaf", "leaves"); Assert("deaf", "deaf"); Assert("roof", "roofs"); Assert("safe", "safes"); Assert("protozoon", "protozoa"); Assert("protozoan", "protozoa"); Assert("inferno", "infernos"); Assert("sex", "sexes"); Assert("cortex", "cortices"); Assert("schema", "schemata"); Assert("canto", "cantos"); Assert("solo", "solos"); Assert("phenomenon", "phenomena"); Assert("memorandum", "memoranda"); Assert("ovum", "ova"); Assert("radius", "radii"); Assert("impetus", "impetuses"); Assert("cherub", "cherubim"); Assert("sphinx", "sphinxes"); Assert("buzz", "buzzes"); Assert("campus", "campuses"); Assert("werewolf", "werewolves"); Assert("cow", "cows"); Assert("suffix", "suffixes"); Assert("bucktooth", "buckteeth"); Assert("flora", "florae"); // floras Assert("vacuum", "vacuums"); // vacua Assert("corf", "corves"); Assert("greave", "greaves"); Assert("oaf", "oafs"); Assert("meatloaf", "meatloaves"); Assert("rebus", "rebuses"); Assert("paradox", "paradoxes"); Assert("cox", "coxes"); Assert("coxswain", "coxswains"); Assert("goof", "goofs"); Assert("proof", "proofs"); Assert("reef", "reefs"); Assert("neckerchief", "neckerchiefs"); Assert("magma", "magmas"); Assert("drama", "dramas"); // dramata Assert("ranch", "ranches"); // From humanizer Assert("atlas", "atlases"); Assert("cod", "cod"); Assert("domino", "dominoes"); Assert("echo", "echoes"); Assert("hero", "heroes"); Assert("hoof", "hooves"); Assert("iris", "irises"); Assert("leaf", "leaves"); Assert("loaf", "loaves"); Assert("motto", "mottoes"); Assert("reflex", "reflexes"); Assert("sheaf", "sheaves"); Assert("syllabus", "syllabi"); Assert("thief", "thieves"); Assert("waltz", "waltzes"); Assert("gas", "gases"); Assert("focus", "foci"); // /focuses Assert("nucleus", "nuclei"); Assert("radius", "radii"); Assert("stimulus", "stimuli"); Assert("appendix", "appendices"); Assert("beau", "beaux"); Assert("corpus", "corpora"); Assert("criterion", "criteria"); Assert("curriculum", "curricula"); Assert("genus", "genera"); Assert("memorandum", "memoranda"); Assert("offspring", "offspring"); Assert("foot", "feet"); Assert("tooth", "teeth"); Assert("nebula", "nebulae"); Assert("vertebra", "vertebrae"); Assert("search", "searches"); Assert("switch", "switches"); Assert("fix", "fixes"); Assert("box", "boxes"); Assert("process", "processes"); Assert("address", "addresses"); Assert("case", "cases"); Assert("stack", "stacks"); Assert("wish", "wishes"); Assert("fish", "fish"); Assert("category", "categories"); Assert("query", "queries"); Assert("ability", "abilities"); Assert("agency", "agencies"); Assert("movie", "movies"); Assert("archive", "archives"); Assert("index", "indices"); Assert("wife", "wives"); Assert("half", "halves"); Assert("move", "moves"); Assert("salesperson", "salespeople"); Assert("person", "people"); Assert("spokesman", "spokesmen"); Assert("man", "men"); Assert("woman", "women"); Assert("basis", "bases"); Assert("diagnosis", "diagnoses"); Assert("datum", "data"); Assert("medium", "media"); Assert("analysis", "analyses"); Assert("node_child", "node_children"); Assert("child", "children"); Assert("experience", "experiences"); Assert("day", "days"); Assert("comment", "comments"); Assert("foobar", "foobars"); Assert("newsletter", "newsletters"); Assert("old_news", "old_news"); Assert("news", "news"); Assert("series", "series"); Assert("species", "species"); Assert("quiz", "quizzes"); Assert("perspective", "perspectives"); Assert("ox", "oxen"); Assert("photo", "photos"); Assert("buffalo", "buffaloes"); Assert("tomato", "tomatoes"); Assert("dwarf", "dwarves"); Assert("elf", "elves"); Assert("information", "information"); Assert("equipment", "equipment"); Assert("bus", "buses"); Assert("status", "statuses"); Assert("status_code", "status_codes"); Assert("mouse", "mice"); Assert("louse", "lice"); Assert("house", "houses"); Assert("octopus", "octopodes"); Assert("alias", "aliases"); Assert("portfolio", "portfolios"); Assert("vertex", "vertices"); Assert("matrix", "matrices"); Assert("axis", "axes"); Assert("testis", "testes"); Assert("crisis", "crises"); Assert("rice", "rice"); Assert("shoe", "shoes"); Assert("horse", "horses"); Assert("prize", "prizes"); Assert("edge", "edges"); Assert("goose", "geese"); Assert("deer", "deer"); Assert("sheep", "sheep"); Assert("wolf", "wolves"); Assert("volcano", "volcanoes"); Assert("aircraft", "aircraft"); Assert("alumna", "alumnae"); Assert("alumnus", "alumni"); Assert("fungus", "fungi"); Assert("virus", "viruses"); Assert("cactus", "cacti"); //Assert("safe", "saves"); Console.WriteLine(FailCount + " failed."); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Lens.Compiler; using Lens.Resolver; using NUnit.Framework; namespace Lens.Test.Internals { [TestFixture] public class TypeExtensionsTest { [Test] public void SelfEquality() { TestDistanceFrom<int, int>(0); TestDistanceFrom<object, object>(0); TestDistanceFrom<List<int>, List<int>>(0); } [Test] public void ParentTest() { TestDistanceFrom<ParentClass, DerivedClass>(1); TestDistanceFrom<DerivedClass, ParentClass>(int.MaxValue); } [Test] public void BoxTest() { TestDistanceFrom<object, int>(1); TestDistanceFrom<object, Struct>(1); } [Test] public void InterfaceTest() { TestDistanceFrom<IInterface, InterfaceImplementer>(1); TestDistanceFrom<IInterface, InterfaceDerivedImplementer>(1); TestDistanceFrom<IInterface, DerivedInterfaceImplementer>(1); } [Test] public void ContravarianceTest() { TestDistanceFrom<Action<DerivedClass>, Action<ParentClass>>(1); TestDistanceFrom<Action<int>, Action<object>>(int.MaxValue); } [Test] public void CovarianceTest() { TestDistanceFrom<IEnumerable<ParentClass>, IEnumerable<DerivedClass>>(1); TestDistanceFrom<IEnumerable<object>, IEnumerable<bool>>(int.MaxValue); } [Test] public void MultiArgumentGeneric() { TestDistanceFrom<Action<DerivedClass, DerivedClass>, Action<ParentClass, ParentClass>>(2); TestDistanceFrom<Func<DerivedClass, ParentClass>, Func<ParentClass, DerivedClass>>(2); } [Test] public void IntegralTypeConversion() { TestDistanceFrom<long, sbyte>(3); } [Test] public void FloatingPointTypeConversion() { TestDistanceFrom<double, float>(1); TestDistanceFrom<decimal, float>(2); TestDistanceFrom<decimal, double>(1); } [Test] public void CrossDomainNumberConversion() { TestDistanceFrom<float, int>(1); TestDistanceFrom<double, long>(1); TestDistanceFrom<double, short>(3); TestDistanceFrom<decimal, sbyte>(4); TestDistanceFrom<decimal, ulong>(1); } [Test] public void UnsignedToSignedConversion() { TestDistanceFrom<long, uint>(1); TestDistanceFrom<uint, int>(int.MaxValue); } [Test] public void UnsignedToFloatConversion() { TestDistanceFrom<float, ushort>(2); TestDistanceFrom<double, uint>(2); } [Test] public void IllegalConversionsTest() { TestDistanceFrom<sbyte, short>(int.MaxValue); TestDistanceFrom<sbyte, int>(int.MaxValue); TestDistanceFrom<sbyte, long>(int.MaxValue); TestDistanceFrom<sbyte, decimal>(int.MaxValue); TestDistanceFrom<sbyte, float>(int.MaxValue); TestDistanceFrom<sbyte, double>(int.MaxValue); TestDistanceFrom<sbyte, byte>(int.MaxValue); TestDistanceFrom<sbyte, ushort>(int.MaxValue); TestDistanceFrom<sbyte, uint>(int.MaxValue); TestDistanceFrom<sbyte, ulong>(int.MaxValue); TestDistanceFrom<short, int>(int.MaxValue); TestDistanceFrom<short, long>(int.MaxValue); TestDistanceFrom<short, decimal>(int.MaxValue); TestDistanceFrom<short, float>(int.MaxValue); TestDistanceFrom<short, double>(int.MaxValue); TestDistanceFrom<short, ushort>(int.MaxValue); TestDistanceFrom<short, uint>(int.MaxValue); TestDistanceFrom<short, ulong>(int.MaxValue); TestDistanceFrom<int, long>(int.MaxValue); TestDistanceFrom<int, decimal>(int.MaxValue); TestDistanceFrom<int, float>(int.MaxValue); TestDistanceFrom<int, double>(int.MaxValue); TestDistanceFrom<int, uint>(int.MaxValue); TestDistanceFrom<int, ulong>(int.MaxValue); TestDistanceFrom<long, ulong>(int.MaxValue); TestDistanceFrom<long, float>(int.MaxValue); TestDistanceFrom<long, double>(int.MaxValue); TestDistanceFrom<long, decimal>(int.MaxValue); TestDistanceFrom<double, ulong>(int.MaxValue); } [Test] public void ArrayAsObjectDistance() { // int[] -> Array -> object TestDistanceFrom<object, int[]>(2); } [Test] public void ArrayCovariance() { TestDistanceFrom<object[], string[]>(1); } [Test] public void Nullable() { TestDistanceFrom<int?, int>(1); } [Test] public void NumericOperationTypes() { AssertNumericOperationType<int, int, int>(); AssertNumericOperationType<long, long, long>(); AssertNumericOperationType<float, float, float>(); AssertNumericOperationType<double, double, double>(); AssertNumericOperationType<byte, byte, int>(); AssertNumericOperationType<short, short, int>(); AssertNumericOperationType<float, int, float>(); AssertNumericOperationType<float, long, double>(); AssertNumericOperationNotPermitted<int, uint>(); AssertNumericOperationNotPermitted<int, ulong>(); } [Test] public void ArrayInterface() { TestDistanceFrom<IEnumerable<int>, int[]>(1); } [Test] public void GenericParameter() { var from = typeof(bool[]); var to = typeof(IEnumerable<>); Assert.AreEqual(2, to.DistanceFrom(from)); } [Test] public void Generic() { TestDistanceFrom<List<float>, List<int>>(int.MaxValue); TestDistanceFrom<List<ParentClass>, List<DerivedClass>>(int.MaxValue); TestDistanceFrom<IEnumerable<float>, IEnumerable<int>>(int.MaxValue); TestDistanceFrom<IEnumerable<ParentClass>, IEnumerable<DerivedClass>>(1); } [Test] public void GenericParameter2() { var from1 = typeof(int[]); var from2 = typeof(Predicate<int>); var to = typeof(Array).GetMethod("FindAll").GetParameters().Select(p => p.ParameterType).ToArray(); Assert.AreEqual(2, to[0].DistanceFrom(from1)); Assert.AreEqual(2, to[1].DistanceFrom(from2)); } [Test] public void RefArguments() { var types = new[] {typeof(object), typeof(float), typeof(int), typeof(string)}; foreach (var type in types) Assert.AreEqual(0, type.MakeByRefType().DistanceFrom(type)); Assert.AreEqual(int.MaxValue, typeof(int).MakeByRefType().DistanceFrom(typeof(float))); Assert.AreEqual(int.MaxValue, typeof(float).MakeByRefType().DistanceFrom(typeof(int))); } [Test] public void Interface() { TestDistanceFrom<object, IEnumerable<int>>(1); TestDistanceFrom<object, IEnumerable<DerivedClass>>(1); } [Test] public void InterfaceImplementation() { TestDistanceFrom<IEnumerable<KeyValuePair<int, string>>, IDictionary<int, string>>(1); } [Test] public void CommonNumericTypes() { TestCommonType<int>(typeof(int), typeof(int), typeof(int)); TestCommonType<float>(typeof(float), typeof(int), typeof(int)); TestCommonType<long>(typeof(int), typeof(int), typeof(int), typeof(long)); TestCommonType<double>(typeof(float), typeof(int), typeof(long)); TestCommonType<double>(typeof(float), typeof(int), typeof(double)); } [Test] public void CommonTypes() { TestCommonType<ParentClass>(typeof(ParentClass), typeof(ParentClass)); TestCommonType<ParentClass>(typeof(DerivedClass), typeof(ParentClass)); TestCommonType<ParentClass>(typeof(DerivedClass), typeof(DerivedClass2)); TestCommonType<ParentClass>(typeof(SubDerivedClass), typeof(DerivedClass2)); } [Test] public void CommonArrayTypes() { TestCommonType<int[]>(typeof(int[]), typeof(int[])); TestCommonType<IList>(typeof(float[]), typeof(int[])); TestCommonType<ParentClass[]>(typeof(ParentClass[]), typeof(DerivedClass[])); TestCommonType<ParentClass[]>(typeof(DerivedClass[]), typeof(DerivedClass2[])); } [Test] public void CommonInterfaces() { TestCommonType<IList>(typeof(float[]), typeof(List<int>)); TestCommonType<IList<int>>(typeof(int[]), typeof(List<int>)); TestCommonType<IEnumerable<int>>(typeof(int[]), typeof(IEnumerable<int>)); TestCommonType<IEnumerable<int>>(typeof(List<int>), typeof(IEnumerable<int>)); } [Test] public void CommonObjectOnly() { TestCommonType<object>(typeof(ParentClass), typeof(DerivedClass2), typeof(IEnumerable<int>)); TestCommonType<object>(typeof(object), typeof(int)); TestCommonType<object>(typeof(int), typeof(float), typeof(double), typeof(Decimal)); TestCommonType<object>(typeof(IEnumerable<int>), typeof(IEnumerable<float>)); } [Test] public void CommonNullables() { TestCommonType<int?>(typeof(int), typeof(NullType)); TestCommonType<int?>(typeof(int), typeof(int?)); TestCommonType<double?>(typeof(NullType), typeof(double)); TestCommonType<double?>(typeof(double?), typeof(double)); TestCommonType<object>(typeof(int), typeof(double?)); TestCommonType<object>(typeof(int), typeof(double), typeof(NullType)); } [Test] public void TestInterfaceInheritance() { var from = typeof(IOrderedEnumerable<int>); var to = typeof(IEnumerable<>); Assert.IsTrue(to.DistanceFrom(from) < int.MaxValue); } /// <summary> /// Checks if the <see cref="expected"/> value are equal to the <see cref="TypeExtensions.DistanceFrom"/> call result. /// </summary> /// <typeparam name="T1">First type.</typeparam> /// <typeparam name="T2">Second type.</typeparam> /// <param name="expected">Expected distance between types.</param> private static void TestDistanceFrom<T1, T2>(int expected) { var result = typeof(T1).DistanceFrom(typeof(T2)); Assert.AreEqual(expected, result); } private static void AssertNumericOperationType<T1, T2, TResult>() { Assert.AreEqual(typeof(TResult), TypeExtensions.GetNumericOperationType(typeof(T1), typeof(T2))); } private static void AssertNumericOperationNotPermitted<T1, T2>() { Assert.IsNull(TypeExtensions.GetNumericOperationType(typeof(T1), typeof(T2))); } private static void TestCommonType<T>(params Type[] types) { Assert.AreEqual(typeof(T), types.GetMostCommonType()); } } }
//--------------------------------------------------------------------- // <copyright file="DefaultExpressionVisitor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Common.CommandTrees { using System; using System.Collections.Generic; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using CqtBuilder = System.Data.Common.CommandTrees.ExpressionBuilder.DbExpressionBuilder; /// <summary> /// Visits each element of an expression tree from a given root expression. If any element changes, the tree is /// rebuilt back to the root and the new root expression is returned; otherwise the original root expression is returned. /// </summary> public class DefaultExpressionVisitor : DbExpressionVisitor<DbExpression> { private readonly Dictionary<DbVariableReferenceExpression, DbVariableReferenceExpression> varMappings = new Dictionary<DbVariableReferenceExpression, DbVariableReferenceExpression>(); protected DefaultExpressionVisitor() { } protected virtual void OnExpressionReplaced(DbExpression oldExpression, DbExpression newExpression) { } protected virtual void OnVariableRebound(DbVariableReferenceExpression fromVarRef, DbVariableReferenceExpression toVarRef) { } protected virtual void OnEnterScope(IEnumerable<DbVariableReferenceExpression> scopeVariables) { } protected virtual void OnExitScope() { } protected virtual DbExpression VisitExpression(DbExpression expression) { DbExpression newValue = null; if (expression != null) { newValue = expression.Accept<DbExpression>(this); } return newValue; } protected virtual IList<DbExpression> VisitExpressionList(IList<DbExpression> list) { return VisitList(list, this.VisitExpression); } protected virtual DbExpressionBinding VisitExpressionBinding(DbExpressionBinding binding) { DbExpressionBinding result = binding; if (binding != null) { DbExpression newInput = this.VisitExpression(binding.Expression); if (!object.ReferenceEquals(binding.Expression, newInput)) { result = CqtBuilder.BindAs(newInput, binding.VariableName); this.RebindVariable(binding.Variable, result.Variable); } } return result; } protected virtual IList<DbExpressionBinding> VisitExpressionBindingList(IList<DbExpressionBinding> list) { return this.VisitList(list, this.VisitExpressionBinding); } protected virtual DbGroupExpressionBinding VisitGroupExpressionBinding(DbGroupExpressionBinding binding) { DbGroupExpressionBinding result = binding; if (binding != null) { DbExpression newInput = this.VisitExpression(binding.Expression); if (!object.ReferenceEquals(binding.Expression, newInput)) { result = CqtBuilder.GroupBindAs(newInput, binding.VariableName, binding.GroupVariableName); this.RebindVariable(binding.Variable, result.Variable); this.RebindVariable(binding.GroupVariable, result.GroupVariable); } } return result; } protected virtual DbSortClause VisitSortClause(DbSortClause clause) { DbSortClause result = clause; if (clause != null) { DbExpression newExpression = this.VisitExpression(clause.Expression); if (!object.ReferenceEquals(clause.Expression, newExpression)) { if (!string.IsNullOrEmpty(clause.Collation)) { result = (clause.Ascending ? CqtBuilder.ToSortClause(newExpression, clause.Collation) : CqtBuilder.ToSortClauseDescending(newExpression, clause.Collation)); } else { result = (clause.Ascending ? CqtBuilder.ToSortClause(newExpression) : CqtBuilder.ToSortClauseDescending(newExpression)); } } } return result; } protected virtual IList<DbSortClause> VisitSortOrder(IList<DbSortClause> sortOrder) { return VisitList(sortOrder, this.VisitSortClause); } protected virtual DbAggregate VisitAggregate(DbAggregate aggregate) { // Currently only function or group aggregate are possible DbFunctionAggregate functionAggregate = aggregate as DbFunctionAggregate; if (functionAggregate != null) { return VisitFunctionAggregate(functionAggregate); } DbGroupAggregate groupAggregate = (DbGroupAggregate)aggregate; return VisitGroupAggregate(groupAggregate); } protected virtual DbFunctionAggregate VisitFunctionAggregate(DbFunctionAggregate aggregate) { DbFunctionAggregate result = aggregate; if (aggregate != null) { EdmFunction newFunction = this.VisitFunction(aggregate.Function); IList<DbExpression> newArguments = this.VisitExpressionList(aggregate.Arguments); Debug.Assert(newArguments.Count == 1, "Function aggregate had more than one argument?"); if (!object.ReferenceEquals(aggregate.Function, newFunction) || !object.ReferenceEquals(aggregate.Arguments, newArguments)) { if (aggregate.Distinct) { result = CqtBuilder.AggregateDistinct(newFunction, newArguments[0]); } else { result = CqtBuilder.Aggregate(newFunction, newArguments[0]); } } } return result; } protected virtual DbGroupAggregate VisitGroupAggregate(DbGroupAggregate aggregate) { DbGroupAggregate result = aggregate; if (aggregate != null) { IList<DbExpression> newArguments = this.VisitExpressionList(aggregate.Arguments); Debug.Assert(newArguments.Count == 1, "Group aggregate had more than one argument?"); if (!object.ReferenceEquals(aggregate.Arguments, newArguments)) { result = CqtBuilder.GroupAggregate(newArguments[0]); } } return result; } protected virtual DbLambda VisitLambda(DbLambda lambda) { EntityUtil.CheckArgumentNull(lambda, "lambda"); DbLambda result = lambda; IList<DbVariableReferenceExpression> newFormals = this.VisitList(lambda.Variables, varRef => { TypeUsage newVarType = this.VisitTypeUsage(varRef.ResultType); if (!object.ReferenceEquals(varRef.ResultType, newVarType)) { return CqtBuilder.Variable(newVarType, varRef.VariableName); } else { return varRef; } } ); this.EnterScope(newFormals.ToArray()); // ToArray: Don't pass the List instance directly to OnEnterScope DbExpression newBody = this.VisitExpression(lambda.Body); this.ExitScope(); if (!object.ReferenceEquals(lambda.Variables, newFormals) || !object.ReferenceEquals(lambda.Body, newBody)) { result = CqtBuilder.Lambda(newBody, newFormals); } return result; } // Metadata 'Visitor' methods protected virtual EdmType VisitType(EdmType type) { return type; } protected virtual TypeUsage VisitTypeUsage(TypeUsage type) { return type; } protected virtual EntitySetBase VisitEntitySet(EntitySetBase entitySet) { return entitySet; } protected virtual EdmFunction VisitFunction(EdmFunction functionMetadata) { return functionMetadata; } #region Private Implementation private void NotifyIfChanged(DbExpression originalExpression, DbExpression newExpression) { if (!object.ReferenceEquals(originalExpression, newExpression)) { this.OnExpressionReplaced(originalExpression, newExpression); } } private IList<TElement> VisitList<TElement>(IList<TElement> list, Func<TElement, TElement> map) { IList<TElement> result = list; if(list != null) { List<TElement> newList = null; for (int idx = 0; idx < list.Count; idx++) { TElement newElement = map(list[idx]); if (newList == null && !object.ReferenceEquals(list[idx], newElement)) { newList = new List<TElement>(list); result = newList; } if (newList != null) { newList[idx] = newElement; } } } return result; } private DbExpression VisitUnary(DbUnaryExpression expression, Func<DbExpression, DbExpression> callback) { DbExpression result = expression; DbExpression newArgument = this.VisitExpression(expression.Argument); if (!object.ReferenceEquals(expression.Argument, newArgument)) { result = callback(newArgument); } NotifyIfChanged(expression, result); return result; } private DbExpression VisitTypeUnary(DbUnaryExpression expression, TypeUsage type, Func<DbExpression, TypeUsage, DbExpression> callback) { DbExpression result = expression; DbExpression newArgument = this.VisitExpression(expression.Argument); TypeUsage newType = this.VisitTypeUsage(type); if (!object.ReferenceEquals(expression.Argument, newArgument) || !object.ReferenceEquals(type, newType)) { result = callback(newArgument, newType); } NotifyIfChanged(expression, result); return result; } private DbExpression VisitBinary(DbBinaryExpression expression, Func<DbExpression, DbExpression, DbExpression> callback) { DbExpression result = expression; DbExpression newLeft = this.VisitExpression(expression.Left); DbExpression newRight = this.VisitExpression(expression.Right); if (!object.ReferenceEquals(expression.Left, newLeft) || !object.ReferenceEquals(expression.Right, newRight)) { result = callback(newLeft, newRight); } NotifyIfChanged(expression, result); return result; } private DbRelatedEntityRef VisitRelatedEntityRef(DbRelatedEntityRef entityRef) { RelationshipEndMember newSource; RelationshipEndMember newTarget; VisitRelationshipEnds(entityRef.SourceEnd, entityRef.TargetEnd, out newSource, out newTarget); DbExpression newTargetRef = this.VisitExpression(entityRef.TargetEntityReference); if (!object.ReferenceEquals(entityRef.SourceEnd, newSource) || !object.ReferenceEquals(entityRef.TargetEnd, newTarget) || !object.ReferenceEquals(entityRef.TargetEntityReference, newTargetRef)) { return CqtBuilder.CreateRelatedEntityRef(newSource, newTarget, newTargetRef); } else { return entityRef; } } private void VisitRelationshipEnds(RelationshipEndMember source, RelationshipEndMember target, out RelationshipEndMember newSource, out RelationshipEndMember newTarget) { // Debug.Assert(source.DeclaringType.EdmEquals(target.DeclaringType), "Relationship ends not declared by same relationship type?"); RelationshipType mappedType = (RelationshipType)this.VisitType(target.DeclaringType); newSource = mappedType.RelationshipEndMembers[source.Name]; newTarget = mappedType.RelationshipEndMembers[target.Name]; } private DbExpression VisitTerminal(DbExpression expression, Func<TypeUsage, DbExpression> reconstructor) { DbExpression result = expression; TypeUsage newType = this.VisitTypeUsage(expression.ResultType); if (!object.ReferenceEquals(expression.ResultType, newType)) { result = reconstructor(newType); } NotifyIfChanged(expression, result); return result; } private void RebindVariable(DbVariableReferenceExpression from, DbVariableReferenceExpression to) { // // The variable is only considered rebound if the name and/or type is different. // Otherwise, the original variable reference and the new variable reference are // equivalent, and no rebinding of references to the old variable is necessary. // // When considering the new/old result types, the TypeUsage instance may be equal // or equivalent, but the EdmType must be the same instance, so that expressions // such as a DbPropertyExpression with the DbVariableReferenceExpression as the Instance // continue to be valid. // if (!from.VariableName.Equals(to.VariableName, StringComparison.Ordinal) || !object.ReferenceEquals(from.ResultType.EdmType, to.ResultType.EdmType) || !from.ResultType.EdmEquals(to.ResultType)) { this.varMappings[from] = to; this.OnVariableRebound(from, to); } } private DbExpressionBinding VisitExpressionBindingEnterScope(DbExpressionBinding binding) { DbExpressionBinding result = this.VisitExpressionBinding(binding); this.OnEnterScope(new[] { result.Variable }); return result; } private void EnterScope(params DbVariableReferenceExpression[] scopeVars) { this.OnEnterScope(scopeVars); } private void ExitScope() { this.OnExitScope(); } #endregion #region DbExpressionVisitor<DbExpression> Members public override DbExpression Visit(DbExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); throw EntityUtil.NotSupported(System.Data.Entity.Strings.Cqt_General_UnsupportedExpression(expression.GetType().FullName)); } public override DbExpression Visit(DbConstantExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); // Note that it is only safe to call DbConstantExpression.GetValue because the call to // DbExpressionBuilder.Constant must clone immutable values (byte[]). return VisitTerminal(expression, newType => CqtBuilder.Constant(newType, expression.GetValue())); } public override DbExpression Visit(DbNullExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitTerminal(expression, CqtBuilder.Null); } public override DbExpression Visit(DbVariableReferenceExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbVariableReferenceExpression newRef; if (this.varMappings.TryGetValue(expression, out newRef)) { result = newRef; } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbParameterReferenceExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitTerminal(expression, newType => CqtBuilder.Parameter(newType, expression.ParameterName)); } public override DbExpression Visit(DbFunctionExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; IList<DbExpression> newArguments = this.VisitExpressionList(expression.Arguments); EdmFunction newFunction = this.VisitFunction(expression.Function); if (!object.ReferenceEquals(expression.Arguments, newArguments) || !object.ReferenceEquals(expression.Function, newFunction)) { result = CqtBuilder.Invoke(newFunction, newArguments); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbLambdaExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; IList<DbExpression> newArguments = this.VisitExpressionList(expression.Arguments); DbLambda newLambda = this.VisitLambda(expression.Lambda); if (!object.ReferenceEquals(expression.Arguments, newArguments) || !object.ReferenceEquals(expression.Lambda, newLambda)) { result = CqtBuilder.Invoke(newLambda, newArguments); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbPropertyExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpression newInstance = this.VisitExpression(expression.Instance); if (!object.ReferenceEquals(expression.Instance, newInstance)) { result = CqtBuilder.Property(newInstance, expression.Property.Name); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbComparisonExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); switch(expression.ExpressionKind) { case DbExpressionKind.Equals: return this.VisitBinary(expression, CqtBuilder.Equal); case DbExpressionKind.NotEquals: return this.VisitBinary(expression, CqtBuilder.NotEqual); case DbExpressionKind.GreaterThan: return this.VisitBinary(expression, CqtBuilder.GreaterThan); case DbExpressionKind.GreaterThanOrEquals: return this.VisitBinary(expression, CqtBuilder.GreaterThanOrEqual); case DbExpressionKind.LessThan: return this.VisitBinary(expression, CqtBuilder.LessThan); case DbExpressionKind.LessThanOrEquals: return this.VisitBinary(expression, CqtBuilder.LessThanOrEqual); default: throw EntityUtil.NotSupported(); } } public override DbExpression Visit(DbLikeExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpression newArgument = this.VisitExpression(expression.Argument); DbExpression newPattern = this.VisitExpression(expression.Pattern); DbExpression newEscape = this.VisitExpression(expression.Escape); if (!object.ReferenceEquals(expression.Argument, newArgument) || !object.ReferenceEquals(expression.Pattern, newPattern) || !object.ReferenceEquals(expression.Escape, newEscape)) { result = CqtBuilder.Like(newArgument, newPattern, newEscape); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbLimitExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpression newArgument = this.VisitExpression(expression.Argument); DbExpression newLimit = this.VisitExpression(expression.Limit); if (!object.ReferenceEquals(expression.Argument, newArgument) || !object.ReferenceEquals(expression.Limit, newLimit)) { Debug.Assert(!expression.WithTies, "Limit.WithTies == true?"); result = CqtBuilder.Limit(newArgument, newLimit); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbIsNullExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitUnary(expression, exp => { if(TypeSemantics.IsRowType(exp.ResultType)) { // return CqtBuilder.CreateIsNullExpressionAllowingRowTypeArgument(exp); } else { return CqtBuilder.IsNull(exp); } } ); } public override DbExpression Visit(DbArithmeticExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; IList<DbExpression> newArguments = this.VisitExpressionList(expression.Arguments); if (!object.ReferenceEquals(expression.Arguments, newArguments)) { switch(expression.ExpressionKind) { case DbExpressionKind.Divide: result = CqtBuilder.Divide(newArguments[0], newArguments[1]); break; case DbExpressionKind.Minus: result = CqtBuilder.Minus(newArguments[0], newArguments[1]); break; case DbExpressionKind.Modulo: result = CqtBuilder.Modulo(newArguments[0], newArguments[1]); break; case DbExpressionKind.Multiply: result = CqtBuilder.Multiply(newArguments[0], newArguments[1]); break; case DbExpressionKind.Plus: result = CqtBuilder.Plus(newArguments[0], newArguments[1]); break; case DbExpressionKind.UnaryMinus: result = CqtBuilder.UnaryMinus(newArguments[0]); break; default: throw EntityUtil.NotSupported(); } } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbAndExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitBinary(expression, CqtBuilder.And); } public override DbExpression Visit(DbOrExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitBinary(expression, CqtBuilder.Or); } public override DbExpression Visit(DbNotExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitUnary(expression, CqtBuilder.Not); } public override DbExpression Visit(DbDistinctExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitUnary(expression, CqtBuilder.Distinct); } public override DbExpression Visit(DbElementExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); Func<DbExpression, DbExpression> resultConstructor; if (expression.IsSinglePropertyUnwrapped) { // resultConstructor = CqtBuilder.CreateElementExpressionUnwrapSingleProperty; } else { resultConstructor = CqtBuilder.Element; } return VisitUnary(expression, resultConstructor); } public override DbExpression Visit(DbIsEmptyExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitUnary(expression, CqtBuilder.IsEmpty); } public override DbExpression Visit(DbUnionAllExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitBinary(expression, CqtBuilder.UnionAll); } public override DbExpression Visit(DbIntersectExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitBinary(expression, CqtBuilder.Intersect); } public override DbExpression Visit(DbExceptExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return VisitBinary(expression, CqtBuilder.Except); } public override DbExpression Visit(DbTreatExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return this.VisitTypeUnary(expression, expression.ResultType, CqtBuilder.TreatAs); } public override DbExpression Visit(DbIsOfExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); if (expression.ExpressionKind == DbExpressionKind.IsOfOnly) { return this.VisitTypeUnary(expression, expression.OfType, CqtBuilder.IsOfOnly); } else { return this.VisitTypeUnary(expression, expression.OfType, CqtBuilder.IsOf); } } public override DbExpression Visit(DbCastExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return this.VisitTypeUnary(expression, expression.ResultType, CqtBuilder.CastTo); } public override DbExpression Visit(DbCaseExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; IList<DbExpression> newWhens = this.VisitExpressionList(expression.When); IList<DbExpression> newThens = this.VisitExpressionList(expression.Then); DbExpression newElse = this.VisitExpression(expression.Else); if (!object.ReferenceEquals(expression.When, newWhens) || !object.ReferenceEquals(expression.Then, newThens) || !object.ReferenceEquals(expression.Else, newElse)) { result = CqtBuilder.Case(newWhens, newThens, newElse); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbOfTypeExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); if (expression.ExpressionKind == DbExpressionKind.OfTypeOnly) { return this.VisitTypeUnary(expression, expression.OfType, CqtBuilder.OfTypeOnly); } else { return this.VisitTypeUnary(expression, expression.OfType, CqtBuilder.OfType); } } public override DbExpression Visit(DbNewInstanceExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; TypeUsage newType = this.VisitTypeUsage(expression.ResultType); IList<DbExpression> newArguments = this.VisitExpressionList(expression.Arguments); bool unchanged = (object.ReferenceEquals(expression.ResultType, newType) && object.ReferenceEquals(expression.Arguments, newArguments)); if (expression.HasRelatedEntityReferences) { IList<DbRelatedEntityRef> newRefs = this.VisitList(expression.RelatedEntityReferences, this.VisitRelatedEntityRef); if (!unchanged || !object.ReferenceEquals(expression.RelatedEntityReferences, newRefs)) { result = CqtBuilder.CreateNewEntityWithRelationshipsExpression((EntityType)newType.EdmType, newArguments, newRefs); } } else { if (!unchanged) { result = CqtBuilder.New(newType, System.Linq.Enumerable.ToArray(newArguments)); } } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbRefExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; EntityType targetType = (EntityType)TypeHelpers.GetEdmType<RefType>(expression.ResultType).ElementType; DbExpression newArgument = this.VisitExpression(expression.Argument); EntityType newType = (EntityType)this.VisitType(targetType); EntitySet newSet = (EntitySet)this.VisitEntitySet(expression.EntitySet); if (!object.ReferenceEquals(expression.Argument, newArgument) || !object.ReferenceEquals(targetType, newType) || !object.ReferenceEquals(expression.EntitySet, newSet)) { result = CqtBuilder.RefFromKey(newSet, newArgument, newType); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbRelationshipNavigationExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; RelationshipEndMember newFrom; RelationshipEndMember newTo; VisitRelationshipEnds(expression.NavigateFrom, expression.NavigateTo, out newFrom, out newTo); DbExpression newNavSource = this.VisitExpression(expression.NavigationSource); if (!object.ReferenceEquals(expression.NavigateFrom, newFrom) || !object.ReferenceEquals(expression.NavigateTo, newTo) || !object.ReferenceEquals(expression.NavigationSource, newNavSource)) { result = CqtBuilder.Navigate(newNavSource, newFrom, newTo); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbDerefExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return this.VisitUnary(expression, CqtBuilder.Deref); } public override DbExpression Visit(DbRefKeyExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return this.VisitUnary(expression, CqtBuilder.GetRefKey); } public override DbExpression Visit(DbEntityRefExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); return this.VisitUnary(expression, CqtBuilder.GetEntityRef); } public override DbExpression Visit(DbScanExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; EntitySetBase newSet = this.VisitEntitySet(expression.Target); if (!object.ReferenceEquals(expression.Target, newSet)) { result = CqtBuilder.Scan(newSet); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbFilterExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding input = this.VisitExpressionBindingEnterScope(expression.Input); DbExpression predicate = this.VisitExpression(expression.Predicate); this.ExitScope(); if (!object.ReferenceEquals(expression.Input, input) || !object.ReferenceEquals(expression.Predicate, predicate)) { result = CqtBuilder.Filter(input, predicate); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbProjectExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding input = this.VisitExpressionBindingEnterScope(expression.Input); DbExpression projection = this.VisitExpression(expression.Projection); this.ExitScope(); if (!object.ReferenceEquals(expression.Input, input) || !object.ReferenceEquals(expression.Projection, projection)) { result = CqtBuilder.Project(input, projection); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbCrossJoinExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; IList<DbExpressionBinding> newInputs = this.VisitExpressionBindingList(expression.Inputs); if (!object.ReferenceEquals(expression.Inputs, newInputs)) { result = CqtBuilder.CrossJoin(newInputs); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbJoinExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding newLeft = this.VisitExpressionBinding(expression.Left); DbExpressionBinding newRight = this.VisitExpressionBinding(expression.Right); this.EnterScope(newLeft.Variable, newRight.Variable); DbExpression newCondition = this.VisitExpression(expression.JoinCondition); this.ExitScope(); if (!object.ReferenceEquals(expression.Left, newLeft) || !object.ReferenceEquals(expression.Right, newRight) || !object.ReferenceEquals(expression.JoinCondition, newCondition)) { if (DbExpressionKind.InnerJoin == expression.ExpressionKind) { result = CqtBuilder.InnerJoin(newLeft, newRight, newCondition); } else if (DbExpressionKind.LeftOuterJoin == expression.ExpressionKind) { result = CqtBuilder.LeftOuterJoin(newLeft, newRight, newCondition); } else { Debug.Assert(expression.ExpressionKind == DbExpressionKind.FullOuterJoin, "DbJoinExpression had ExpressionKind other than InnerJoin, LeftOuterJoin or FullOuterJoin?"); result = CqtBuilder.FullOuterJoin(newLeft, newRight, newCondition); } } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbApplyExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding newInput = this.VisitExpressionBindingEnterScope(expression.Input); DbExpressionBinding newApply = this.VisitExpressionBinding(expression.Apply); this.ExitScope(); if (!object.ReferenceEquals(expression.Input, newInput) || !object.ReferenceEquals(expression.Apply, newApply)) { if (DbExpressionKind.CrossApply == expression.ExpressionKind) { result = CqtBuilder.CrossApply(newInput, newApply); } else { Debug.Assert(expression.ExpressionKind == DbExpressionKind.OuterApply, "DbApplyExpression had ExpressionKind other than CrossApply or OuterApply?"); result = CqtBuilder.OuterApply(newInput, newApply); } } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbGroupByExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbGroupExpressionBinding newInput = this.VisitGroupExpressionBinding(expression.Input); this.EnterScope(newInput.Variable); IList<DbExpression> newKeys = this.VisitExpressionList(expression.Keys); this.ExitScope(); this.EnterScope(newInput.GroupVariable); IList<DbAggregate> newAggs = this.VisitList<DbAggregate>(expression.Aggregates, this.VisitAggregate); this.ExitScope(); if (!object.ReferenceEquals(expression.Input, newInput) || !object.ReferenceEquals(expression.Keys, newKeys) || !object.ReferenceEquals(expression.Aggregates, newAggs)) { RowType groupOutput = TypeHelpers.GetEdmType<RowType>(TypeHelpers.GetEdmType<CollectionType>(expression.ResultType).TypeUsage); var boundKeys = groupOutput.Properties.Take(newKeys.Count).Select(p => p.Name).Zip(newKeys).ToList(); var boundAggs = groupOutput.Properties.Skip(newKeys.Count).Select(p => p.Name).Zip(newAggs).ToList(); result = CqtBuilder.GroupBy(newInput, boundKeys, boundAggs); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbSkipExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding newInput = this.VisitExpressionBindingEnterScope(expression.Input); IList<DbSortClause> newSortOrder = this.VisitSortOrder(expression.SortOrder); this.ExitScope(); DbExpression newCount = this.VisitExpression(expression.Count); if (!object.ReferenceEquals(expression.Input, newInput) || !object.ReferenceEquals(expression.SortOrder, newSortOrder) || !object.ReferenceEquals(expression.Count, newCount)) { result = CqtBuilder.Skip(newInput, newSortOrder, newCount); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbSortExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding newInput = this.VisitExpressionBindingEnterScope(expression.Input); IList<DbSortClause> newSortOrder = this.VisitSortOrder(expression.SortOrder); this.ExitScope(); if (!object.ReferenceEquals(expression.Input, newInput) || !object.ReferenceEquals(expression.SortOrder, newSortOrder)) { result = CqtBuilder.Sort(newInput, newSortOrder); } NotifyIfChanged(expression, result); return result; } public override DbExpression Visit(DbQuantifierExpression expression) { EntityUtil.CheckArgumentNull(expression, "expression"); DbExpression result = expression; DbExpressionBinding input = this.VisitExpressionBindingEnterScope(expression.Input); DbExpression predicate = this.VisitExpression(expression.Predicate); this.ExitScope(); if (!object.ReferenceEquals(expression.Input, input) || !object.ReferenceEquals(expression.Predicate, predicate)) { if (DbExpressionKind.All == expression.ExpressionKind) { result = CqtBuilder.All(input, predicate); } else { Debug.Assert(expression.ExpressionKind == DbExpressionKind.Any, "DbQuantifierExpression had ExpressionKind other than All or Any?"); result = CqtBuilder.Any(input, predicate); } } NotifyIfChanged(expression, result); return result; } #endregion } }
// // Copyright (C) DataStax 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.ProtocolEvents; using Cassandra.Responses; using Cassandra.Serialization; using Cassandra.SessionManagement; using Cassandra.Tasks; namespace Cassandra.Connections.Control { internal class ControlConnection : IControlConnection { private const int StateRunning = 0; private const int StateDisposed = 1; private readonly IInternalCluster _cluster; private readonly Metadata _metadata; private volatile Host _host; private volatile IConnectionEndPoint _currentConnectionEndPoint; private volatile IConnection _connection; internal static readonly Logger Logger = new Logger(typeof(ControlConnection)); private readonly Configuration _config; private readonly IReconnectionPolicy _reconnectionPolicy; private IReconnectionSchedule _reconnectionSchedule; private readonly Timer _reconnectionTimer; private int _refreshFlag; private Task<bool> _reconnectTask; private readonly ISerializerManager _serializer; private readonly IProtocolEventDebouncer _eventDebouncer; private readonly IEnumerable<IContactPoint> _contactPoints; private readonly ITopologyRefresher _topologyRefresher; private readonly ISupportedOptionsInitializer _supportedOptionsInitializer; private long _state = ControlConnection.StateRunning; private bool IsShutdown => Interlocked.Read(ref _state) == ControlConnection.StateDisposed; /// <summary> /// Gets the binary protocol version to be used for this cluster. /// </summary> public ProtocolVersion ProtocolVersion => _serializer.CurrentProtocolVersion; /// <inheritdoc /> public Host Host { get => _host; internal set => _host = value; } public IConnectionEndPoint EndPoint => _connection?.EndPoint; public IPEndPoint LocalAddress => _connection?.LocalAddress; public ISerializerManager Serializer => _serializer; internal ControlConnection( IInternalCluster cluster, IProtocolEventDebouncer eventDebouncer, ProtocolVersion initialProtocolVersion, Configuration config, Metadata metadata, IEnumerable<IContactPoint> contactPoints) { _cluster = cluster; _metadata = metadata; _reconnectionPolicy = config.Policies.ReconnectionPolicy; _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); _reconnectionTimer = new Timer(ReconnectEventHandler, null, Timeout.Infinite, Timeout.Infinite); _config = config; _serializer = new SerializerManager(initialProtocolVersion, config.TypeSerializers); _eventDebouncer = eventDebouncer; _contactPoints = contactPoints; _topologyRefresher = config.TopologyRefresherFactory.Create(metadata, config); _supportedOptionsInitializer = config.SupportedOptionsInitializerFactory.Create(metadata); if (!_config.KeepContactPointsUnresolved) { TaskHelper.WaitToComplete(InitialContactPointResolutionAsync()); } } public void Dispose() { Shutdown(); } /// <inheritdoc /> public async Task InitAsync() { ControlConnection.Logger.Info("Trying to connect the ControlConnection"); await Connect(true).ConfigureAwait(false); } /// <summary> /// Resolves the contact points to a read only list of <see cref="IConnectionEndPoint"/> which will be used /// during initialization. Also sets <see cref="Metadata.SetResolvedContactPoints"/>. /// </summary> private async Task InitialContactPointResolutionAsync() { var tasksDictionary = _contactPoints.ToDictionary(c => c, c => c.GetConnectionEndPointsAsync(true)); await Task.WhenAll(tasksDictionary.Values).ConfigureAwait(false); var resolvedContactPoints = tasksDictionary.ToDictionary(t => t.Key, t => t.Value.Result); _metadata.SetResolvedContactPoints(resolvedContactPoints); if (!resolvedContactPoints.Any(kvp => kvp.Value.Any())) { var hostNames = tasksDictionary.Where(kvp => kvp.Key.CanBeResolved).Select(kvp => kvp.Key.StringRepresentation); throw new NoHostAvailableException($"No host name could be resolved, attempted: {string.Join(", ", hostNames)}"); } } private bool TotalConnectivityLoss() { var currentHosts = _metadata.AllHosts(); return currentHosts.Count(h => h.IsUp) == 0 || currentHosts.All(h => !_cluster.AnyOpenConnections(h)); } private async Task<IEnumerable<IConnectionEndPoint>> ResolveContactPoint(IContactPoint contactPoint, bool refresh) { try { var endpoints = await contactPoint.GetConnectionEndPointsAsync(refresh).ConfigureAwait(false); return _metadata.UpdateResolvedContactPoint(contactPoint, endpoints); } catch (Exception ex) { ControlConnection.Logger.Warning( "Failed to resolve contact point {0}. Exception: {1}", contactPoint.StringRepresentation, ex.ToString()); return Enumerable.Empty<IConnectionEndPoint>(); } } private async Task<IEnumerable<IConnectionEndPoint>> ResolveHostContactPointOrConnectionEndpointAsync( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, Host host, bool refreshContactPoints, bool refreshEndpoints) { if (host.ContactPoint != null && attemptedContactPoints.TryAdd(host.ContactPoint, null)) { return await ResolveContactPoint(host.ContactPoint, refreshContactPoints).ConfigureAwait(false); } var endpoint = await _config .EndPointResolver .GetConnectionEndPointAsync(host, refreshEndpoints) .ConfigureAwait(false); return new List<IConnectionEndPoint> { endpoint }; } private IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> ContactPointResolutionTasksEnumerable( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, bool refresh) { foreach (var contactPoint in _contactPoints) { if (attemptedContactPoints.TryAdd(contactPoint, null)) { yield return ResolveContactPoint(contactPoint, refresh); } } } private IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> AllHostsEndPointResolutionTasksEnumerable( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, ConcurrentDictionary<Host, object> attemptedHosts, bool isInitializing, bool refreshContactPoints, bool refreshEndpoints) { foreach (var host in GetHostEnumerable()) { if (attemptedHosts.TryAdd(host, null)) { if (!IsHostValid(host, isInitializing)) { continue; } yield return ResolveHostContactPointOrConnectionEndpointAsync( attemptedContactPoints, host, refreshContactPoints, refreshEndpoints); } } } private IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> DefaultLbpHostsEnumerable( ConcurrentDictionary<IContactPoint, object> attemptedContactPoints, ConcurrentDictionary<Host, object> attemptedHosts, bool isInitializing, bool refreshContactPoints, bool refreshEndpoints) { foreach (var host in _config.DefaultRequestOptions.LoadBalancingPolicy.NewQueryPlan(null, null)) { if (attemptedHosts.TryAdd(host, null)) { if (!IsHostValid(host, isInitializing)) { continue; } yield return ResolveHostContactPointOrConnectionEndpointAsync(attemptedContactPoints, host, refreshContactPoints, refreshEndpoints); } } } private bool IsHostValid(Host host, bool initializing) { if (initializing) { return true; } if (_cluster.RetrieveAndSetDistance(host) == HostDistance.Ignored) { ControlConnection.Logger.Verbose("Skipping {0} because it is ignored.", host.Address.ToString()); return false; } if (!host.IsUp) { ControlConnection.Logger.Verbose("Skipping {0} because it is not UP.", host.Address.ToString()); return false; } return true; } /// <summary> /// Iterates through the query plan or hosts and tries to create a connection. /// Once a connection is made, topology metadata is refreshed and the ControlConnection is subscribed to Host /// and Connection events. /// </summary> /// <param name="isInitializing"> /// Determines whether the ControlConnection is connecting for the first time as part of the initialization. /// </param> /// <exception cref="NoHostAvailableException" /> /// <exception cref="DriverInternalError" /> private async Task Connect(bool isInitializing) { if (isInitializing) { ControlConnection.Logger.Verbose("Control Connection {0} connecting.", GetHashCode()); } else { ControlConnection.Logger.Verbose("Control Connection {0} reconnecting.", GetHashCode()); } // lazy iterator of endpoints to try for the control connection IEnumerable<Task<IEnumerable<IConnectionEndPoint>>> endPointResolutionTasksLazyIterator = Enumerable.Empty<Task<IEnumerable<IConnectionEndPoint>>>(); var attemptedContactPoints = new ConcurrentDictionary<IContactPoint, object>(); var attemptedHosts = new ConcurrentDictionary<Host, object>(); // start with contact points if it is initializing or there is a total connectivity loss var totalConnectivityLoss = TotalConnectivityLoss(); var addedContactPoints = false; if (isInitializing || totalConnectivityLoss) { var refresh = true; if (isInitializing) { // refresh already happened in the ctor refresh = _config.KeepContactPointsUnresolved; } addedContactPoints = true; if (totalConnectivityLoss && !isInitializing) { ControlConnection.Logger.Warning( "Total connectivity loss detected due to the fact that there are no open connections, " + "re-resolving the contact points."); } endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( ContactPointResolutionTasksEnumerable(attemptedContactPoints, refresh)); } // add endpoints from the default LBP if it is already initialized if (!isInitializing) { endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( DefaultLbpHostsEnumerable(attemptedContactPoints, attemptedHosts, false, _config.KeepContactPointsUnresolved, true)); } // add contact points next if they haven't been added yet (without re-resolving them) if (!addedContactPoints) { addedContactPoints = true; endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( ContactPointResolutionTasksEnumerable(attemptedContactPoints, _config.KeepContactPointsUnresolved)); } // add all hosts iterator, this will contain already tried hosts but we will check for it with the concurrent dictionary if (isInitializing) { endPointResolutionTasksLazyIterator = endPointResolutionTasksLazyIterator.Concat( AllHostsEndPointResolutionTasksEnumerable(attemptedContactPoints, attemptedHosts, true, _config.KeepContactPointsUnresolved, true)); } var oldConnection = _connection; var oldHost = _host; var oldEndpoint = _currentConnectionEndPoint; var triedHosts = new Dictionary<IPEndPoint, Exception>(); foreach (var endPointResolutionTask in endPointResolutionTasksLazyIterator) { var endPoints = await endPointResolutionTask.ConfigureAwait(false); foreach (var endPoint in endPoints) { ControlConnection.Logger.Verbose("Attempting to connect to {0}.", endPoint.EndpointFriendlyName); var connection = _config.ConnectionFactory.CreateUnobserved(_serializer.GetCurrentSerializer(), endPoint, _config); Host currentHost = null; try { var version = _serializer.CurrentProtocolVersion; try { await connection.Open().ConfigureAwait(false); } catch (UnsupportedProtocolVersionException ex) { if (!isInitializing) { // The version of the protocol is not supported on this host // Most likely, we are using a higher protocol version than the host supports ControlConnection.Logger.Warning("Host {0} does not support protocol version {1}. You should use a fixed protocol " + "version during rolling upgrades of the cluster. " + "Skipping this host on the current attempt to open the control connection.", endPoint.EndpointFriendlyName, ex.ProtocolVersion); throw; } connection = await _config.ProtocolVersionNegotiator.ChangeProtocolVersion( _config, _serializer, ex.ResponseProtocolVersion, connection, ex, version) .ConfigureAwait(false); } if (isInitializing) { await _supportedOptionsInitializer.ApplySupportedOptionsAsync(connection).ConfigureAwait(false); } currentHost = await _topologyRefresher.RefreshNodeListAsync( endPoint, connection, _serializer.GetCurrentSerializer()).ConfigureAwait(false); if (isInitializing) { connection = await _config.ProtocolVersionNegotiator.NegotiateVersionAsync( _config, _metadata, connection, _serializer).ConfigureAwait(false); } if (!SetCurrentConnection(connection, currentHost, endPoint)) { ControlConnection.Logger.Info( "Connection established to {0} successfully but the Control Connection was being disposed, " + "closing the connection.", connection.EndPoint.EndpointFriendlyName); throw new ObjectDisposedException("Connection established successfully but the Control Connection was being disposed."); } Subscribe(currentHost, connection); ControlConnection.Logger.Info( "Connection established to {0} using protocol version {1}. Building token map...", connection.EndPoint.EndpointFriendlyName, _serializer.CurrentProtocolVersion.ToString("D")); await _config.ServerEventsSubscriber.SubscribeToServerEvents(connection, OnConnectionCassandraEvent).ConfigureAwait(false); await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false); return; } catch (Exception ex) { connection.Dispose(); SetCurrentConnection(oldConnection, oldHost, oldEndpoint); if (ex is ObjectDisposedException) { throw; } if (IsShutdown) { throw new ObjectDisposedException("Control Connection has been disposed.", ex); } ControlConnection.Logger.Info( "Failed to connect to {0}. Exception: {1}", endPoint.EndpointFriendlyName, ex.ToString()); // There was a socket or authentication exception or an unexpected error triedHosts[endPoint.GetHostIpEndPointWithFallback()] = ex; } } } throw new NoHostAvailableException(triedHosts); } private void ReconnectEventHandler(object state) { ReconnectFireAndForget(); } internal void OnConnectionClosing(IConnection connection) { connection.Closing -= OnConnectionClosing; connection.Dispose(); if (IsShutdown) { return; } ControlConnection.Logger.Warning( "Connection {0} used by the ControlConnection {1} is closing.", connection.EndPoint.EndpointFriendlyName, GetHashCode()); ReconnectFireAndForget(); } /// <summary> /// Handler that gets invoked when if there is a socket exception when making a heartbeat/idle request /// </summary> private void OnIdleRequestException(IConnection c, Exception ex) { if (c.IsDisposed) { ControlConnection.Logger.Info("Idle timeout exception, connection to {0} used in control connection is disposed, " + "triggering a reconnection. Exception: {1}", c.EndPoint.EndpointFriendlyName, ex); } else { ControlConnection.Logger.Warning("Connection to {0} used in control connection considered as unhealthy after " + "idle timeout exception, triggering reconnection: {1}", c.EndPoint.EndpointFriendlyName, ex); c.Close(); } } private async void ReconnectFireAndForget() { try { await Reconnect().ConfigureAwait(false); } catch (Exception ex) { ControlConnection.Logger.Error("An exception was thrown when reconnecting the control connection.", ex); } } internal async Task<bool> Reconnect() { var tcs = new TaskCompletionSource<bool>(); var currentTask = Interlocked.CompareExchange(ref _reconnectTask, tcs.Task, null); if (currentTask != null) { // If there is another thread reconnecting, use the same task return await currentTask.ConfigureAwait(false); } var oldConnection = _connection; var oldHost = _host; Unsubscribe(oldHost, oldConnection); try { ControlConnection.Logger.Info("Trying to reconnect the ControlConnection"); await Connect(false).ConfigureAwait(false); } catch (Exception ex) { // It failed to reconnect, schedule the timer for next reconnection and let go. var _ = Interlocked.Exchange(ref _reconnectTask, null); tcs.TrySetException(ex); var delay = _reconnectionSchedule.NextDelayMs(); ControlConnection.Logger.Error("ControlConnection was not able to reconnect: " + ex); try { _reconnectionTimer.Change((int)delay, Timeout.Infinite); } catch (ObjectDisposedException) { //Control connection is being disposed } // It will throw the same exception that it was set in the TCS throw; } finally { if (_connection != oldConnection) { oldConnection?.Dispose(); } } if (IsShutdown) { tcs.TrySetResult(false); return false; } try { _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); tcs.TrySetResult(true); var _ = Interlocked.Exchange(ref _reconnectTask, null); ControlConnection.Logger.Info("ControlConnection reconnected to host {0}", _host.Address); } catch (Exception ex) { var _ = Interlocked.Exchange(ref _reconnectTask, null); ControlConnection.Logger.Error("There was an error when trying to refresh the ControlConnection", ex); tcs.TrySetException(ex); try { _reconnectionTimer.Change((int)_reconnectionSchedule.NextDelayMs(), Timeout.Infinite); } catch (ObjectDisposedException) { //Control connection is being disposed } } return await tcs.Task.ConfigureAwait(false); } private async Task Refresh() { if (Interlocked.CompareExchange(ref _refreshFlag, 1, 0) != 0) { // Only one refresh at a time return; } var reconnect = false; try { var currentEndPoint = _currentConnectionEndPoint; var currentHost = await _topologyRefresher.RefreshNodeListAsync( currentEndPoint, _connection, _serializer.GetCurrentSerializer()).ConfigureAwait(false); SetCurrentConnectionEndpoint(currentHost, currentEndPoint); await _metadata.RebuildTokenMapAsync(false, _config.MetadataSyncOptions.MetadataSyncEnabled).ConfigureAwait(false); _reconnectionSchedule = _reconnectionPolicy.NewSchedule(); } catch (SocketException ex) { ControlConnection.Logger.Error("There was a SocketException when trying to refresh the ControlConnection", ex); reconnect = true; } catch (Exception ex) { ControlConnection.Logger.Error("There was an error when trying to refresh the ControlConnection", ex); reconnect = true; } finally { Interlocked.Exchange(ref _refreshFlag, 0); } if (reconnect) { await Reconnect().ConfigureAwait(false); } } public void Shutdown() { var oldState = Interlocked.Exchange(ref _state, ControlConnection.StateDisposed); if (oldState == ControlConnection.StateDisposed) { return; } var c = _connection; if (c != null) { ControlConnection.Logger.Info("Shutting down control connection to {0}", c.EndPoint.EndpointFriendlyName); c.Dispose(); } _reconnectionTimer.Change(Timeout.Infinite, Timeout.Infinite); _reconnectionTimer.Dispose(); } /// <summary> /// Unsubscribe from the current host 'Down' event and the connection 'Closing' event. /// </summary> private void Unsubscribe(Host h, IConnection c) { if (h != null) { h.Down -= OnHostDown; } if (c != null) { c.Closing -= OnConnectionClosing; } } /// <summary> /// Subscribe the current host 'Down' event and the connection 'Closing' event. /// </summary> private void Subscribe(Host h, IConnection c) { if (h == null || c == null) { return; } h.Down += OnHostDown; c.Closing += OnConnectionClosing; c.OnIdleRequestException += ex => OnIdleRequestException(c, ex); } private void OnHostDown(Host h) { h.Down -= OnHostDown; ControlConnection.Logger.Warning("Host {0} used by the ControlConnection DOWN", h.Address); // Queue reconnection to occur in the background ReconnectFireAndForget(); } private async void OnConnectionCassandraEvent(object sender, CassandraEventArgs e) { try { //This event is invoked from a worker thread (not a IO thread) if (e is TopologyChangeEventArgs tce) { if (tce.What == TopologyChangeEventArgs.Reason.NewNode || tce.What == TopologyChangeEventArgs.Reason.RemovedNode) { // Start refresh await ScheduleHostsRefreshAsync().ConfigureAwait(false); return; } } if (e is StatusChangeEventArgs args) { HandleStatusChangeEvent(args); return; } if (e is SchemaChangeEventArgs ssc) { await HandleSchemaChangeEvent(ssc, false).ConfigureAwait(false); } } catch (Exception ex) { ControlConnection.Logger.Error("Exception thrown while handling cassandra event.", ex); } } /// <inheritdoc /> public Task HandleSchemaChangeEvent(SchemaChangeEventArgs ssc, bool processNow) { if (!_config.MetadataSyncOptions.MetadataSyncEnabled) { return TaskHelper.Completed; } Func<Task> handler; if (!string.IsNullOrEmpty(ssc.Table)) { handler = () => { //Can be either a table or a view _metadata.ClearTable(ssc.Keyspace, ssc.Table); _metadata.ClearView(ssc.Keyspace, ssc.Table); return TaskHelper.Completed; }; } else if (ssc.FunctionName != null) { handler = TaskHelper.ActionToAsync(() => _metadata.ClearFunction(ssc.Keyspace, ssc.FunctionName, ssc.Signature)); } else if (ssc.AggregateName != null) { handler = TaskHelper.ActionToAsync(() => _metadata.ClearAggregate(ssc.Keyspace, ssc.AggregateName, ssc.Signature)); } else if (ssc.Type != null) { return TaskHelper.Completed; } else if (ssc.What == SchemaChangeEventArgs.Reason.Dropped) { handler = TaskHelper.ActionToAsync(() => _metadata.RemoveKeyspace(ssc.Keyspace)); } else { return ScheduleKeyspaceRefreshAsync(ssc.Keyspace, processNow); } return ScheduleObjectRefreshAsync(ssc.Keyspace, processNow, handler); } private void HandleStatusChangeEvent(StatusChangeEventArgs e) { //The address in the Cassandra event message needs to be translated var address = TranslateAddress(e.Address); ControlConnection.Logger.Info("Received Node status change event: host {0} is {1}", address, e.What.ToString().ToUpperInvariant()); if (!_metadata.Hosts.TryGet(address, out var host)) { ControlConnection.Logger.Info("Received status change event for host {0} but it was not found", address); return; } var distance = _cluster.RetrieveAndSetDistance(host); if (distance != HostDistance.Ignored) { // We should not consider events for status changes // We should trust the pools. return; } if (e.What == StatusChangeEventArgs.Reason.Up) { host.BringUpIfDown(); return; } host.SetDown(); } private IPEndPoint TranslateAddress(IPEndPoint value) { return _config.AddressTranslator.Translate(value); } private void SetCurrentConnectionEndpoint(Host host, IConnectionEndPoint endPoint) { _host = host; _currentConnectionEndPoint = endPoint; _metadata.SetCassandraVersion(host.CassandraVersion); } private bool SetCurrentConnection( IConnection connection, Host host, IConnectionEndPoint endPoint) { if (host != null) { _host = host; _metadata.SetCassandraVersion(host.CassandraVersion); } if (endPoint != null) { _currentConnectionEndPoint = endPoint; } if (connection != null) { _connection = connection; } var oldState = Interlocked.CompareExchange(ref _state, ControlConnection.StateRunning, ControlConnection.StateRunning); return oldState != ControlConnection.StateDisposed; } /// <summary> /// Uses the active connection to execute a query /// </summary> public IEnumerable<IRow> Query(string cqlQuery, bool retry = false) { return TaskHelper.WaitToComplete(QueryAsync(cqlQuery, retry), _config.SocketOptions.MetadataAbortTimeout); } public async Task<IEnumerable<IRow>> QueryAsync(string cqlQuery, bool retry = false) { return _config.MetadataRequestHandler.GetRowSet( await SendQueryRequestAsync(cqlQuery, retry, QueryProtocolOptions.Default).ConfigureAwait(false)); } public async Task<Response> SendQueryRequestAsync(string cqlQuery, bool retry, QueryProtocolOptions queryProtocolOptions) { Response response; try { response = await _config.MetadataRequestHandler.SendMetadataRequestAsync( _connection, _serializer.GetCurrentSerializer(), cqlQuery, queryProtocolOptions).ConfigureAwait(false); } catch (SocketException) { if (!retry) { throw; } // Try reconnect await Reconnect().ConfigureAwait(false); // Query with retry set to false return await SendQueryRequestAsync(cqlQuery, false, queryProtocolOptions).ConfigureAwait(false); } return response; } /// <inheritdoc /> public Task<Response> UnsafeSendQueryRequestAsync(string cqlQuery, QueryProtocolOptions queryProtocolOptions) { return _config.MetadataRequestHandler.UnsafeSendQueryRequestAsync( _connection, _serializer.GetCurrentSerializer(), cqlQuery, queryProtocolOptions); } /// <summary> /// An iterator designed for the underlying collection to change /// </summary> private IEnumerable<Host> GetHostEnumerable() { var index = 0; var hosts = _metadata.Hosts.ToArray(); while (index < hosts.Length) { yield return hosts[index++]; // Check that the collection changed var newHosts = _metadata.Hosts.ToCollection(); if (newHosts.Count != hosts.Length) { index = 0; hosts = newHosts.ToArray(); } } } /// <inheritdoc /> public async Task HandleKeyspaceRefreshLaterAsync(string keyspace) { var @event = new KeyspaceProtocolEvent(true, keyspace, async () => { await _metadata.RefreshSingleKeyspace(keyspace).ConfigureAwait(false); }); await _eventDebouncer.HandleEventAsync(@event, false).ConfigureAwait(false); } /// <inheritdoc /> public Task ScheduleKeyspaceRefreshAsync(string keyspace, bool processNow) { var @event = new KeyspaceProtocolEvent(true, keyspace, () => _metadata.RefreshSingleKeyspace(keyspace)); return processNow ? _eventDebouncer.HandleEventAsync(@event, true) : _eventDebouncer.ScheduleEventAsync(@event, false); } private Task ScheduleObjectRefreshAsync(string keyspace, bool processNow, Func<Task> handler) { var @event = new KeyspaceProtocolEvent(false, keyspace, handler); return processNow ? _eventDebouncer.HandleEventAsync(@event, true) : _eventDebouncer.ScheduleEventAsync(@event, false); } private Task ScheduleHostsRefreshAsync() { return _eventDebouncer.ScheduleEventAsync(new ProtocolEvent(Refresh), false); } /// <inheritdoc /> public Task ScheduleAllKeyspacesRefreshAsync(bool processNow) { var @event = new ProtocolEvent(() => _metadata.RebuildTokenMapAsync(false, true)); return processNow ? _eventDebouncer.HandleEventAsync(@event, true) : _eventDebouncer.ScheduleEventAsync(@event, false); } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Security.Auth.cs // // 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. #pragma warning disable 1717 namespace Javax.Security.Auth { /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/PrivateCredentialPermission /// </java-name> [Dot42.DexImport("javax/security/auth/PrivateCredentialPermission", AccessFlags = 49)] public sealed partial class PrivateCredentialPermission : global::Java.Security.Permission /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public PrivateCredentialPermission(string name, string action) /* MethodBuilder.Create */ { } /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)] public string[][] GetPrincipals() /* MethodBuilder.Create */ { return default(string[][]); } /// <java-name> /// getCredentialClass /// </java-name> [Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)] public string GetCredentialClass() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getActions /// </java-name> [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetActions() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// implies /// </java-name> [Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)] public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PrivateCredentialPermission() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getPrincipals /// </java-name> public string[][] Principals { [Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)] get{ return GetPrincipals(); } } /// <java-name> /// getCredentialClass /// </java-name> public string CredentialClass { [Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetCredentialClass(); } } /// <java-name> /// getActions /// </java-name> public string Actions { [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetActions(); } } } /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/SubjectDomainCombiner /// </java-name> [Dot42.DexImport("javax/security/auth/SubjectDomainCombiner", AccessFlags = 33)] public partial class SubjectDomainCombiner : global::Java.Security.IDomainCombiner /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljavax/security/auth/Subject;)V", AccessFlags = 1)] public SubjectDomainCombiner(global::Javax.Security.Auth.Subject subject) /* MethodBuilder.Create */ { } /// <java-name> /// getSubject /// </java-name> [Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)] public virtual global::Javax.Security.Auth.Subject GetSubject() /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Subject); } /// <summary> /// <para>Returns a combination of the two provided <c> ProtectionDomain </c> arrays. Implementers can simply merge the two arrays into one, remove duplicates and perform other optimizations.</para><para></para> /// </summary> /// <returns> /// <para>a single <c> ProtectionDomain </c> array computed from the two provided arrays. </para> /// </returns> /// <java-name> /// combine /// </java-name> [Dot42.DexImport("combine", "([Ljava/security/ProtectionDomain;[Ljava/security/ProtectionDomain;)[Ljava/securi" + "ty/ProtectionDomain;", AccessFlags = 1)] public virtual global::Java.Security.ProtectionDomain[] Combine(global::Java.Security.ProtectionDomain[] current, global::Java.Security.ProtectionDomain[] assigned) /* MethodBuilder.Create */ { return default(global::Java.Security.ProtectionDomain[]); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal SubjectDomainCombiner() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getSubject /// </java-name> public global::Javax.Security.Auth.Subject Subject { [Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)] get{ return GetSubject(); } } } /// <summary> /// <para>Allows for special treatment of sensitive information, when it comes to destroying or clearing of the data. </para> /// </summary> /// <java-name> /// javax/security/auth/Destroyable /// </java-name> [Dot42.DexImport("javax/security/auth/Destroyable", AccessFlags = 1537)] public partial interface IDestroyable /* scope: __dot42__ */ { /// <summary> /// <para>Erases the sensitive information. Once an object is destroyed any calls to its methods will throw an <c> IllegalStateException </c> . If it does not succeed a DestroyFailedException is thrown.</para><para></para> /// </summary> /// <java-name> /// destroy /// </java-name> [Dot42.DexImport("destroy", "()V", AccessFlags = 1025)] void Destroy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns <c> true </c> once an object has been safely destroyed.</para><para></para> /// </summary> /// <returns> /// <para>whether the object has been safely destroyed. </para> /// </returns> /// <java-name> /// isDestroyed /// </java-name> [Dot42.DexImport("isDestroyed", "()Z", AccessFlags = 1025)] bool IsDestroyed() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/AuthPermission /// </java-name> [Dot42.DexImport("javax/security/auth/AuthPermission", AccessFlags = 49)] public sealed partial class AuthPermission : global::Java.Security.BasicPermission /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public AuthPermission(string name) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public AuthPermission(string name, string actions) /* MethodBuilder.Create */ { } /// <java-name> /// getActions /// </java-name> [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetActions() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// implies /// </java-name> [Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)] public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AuthPermission() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getActions /// </java-name> public string Actions { [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetActions(); } } } /// <summary> /// <para>The central class of the <c> javax.security.auth </c> package representing an authenticated user or entity (both referred to as "subject"). IT defines also the static methods that allow code to be run, and do modifications according to the subject's permissions. </para><para>A subject has the following features: <ul><li><para>A set of <c> Principal </c> objects specifying the identities bound to a <c> Subject </c> that distinguish it. </para></li><li><para>Credentials (public and private) such as certificates, keys, or authentication proofs such as tickets </para></li></ul></para> /// </summary> /// <java-name> /// javax/security/auth/Subject /// </java-name> [Dot42.DexImport("javax/security/auth/Subject", AccessFlags = 49)] public sealed partial class Subject : global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>The default constructor initializing the sets of public and private credentials and principals with the empty set. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Subject() /* MethodBuilder.Create */ { } /// <summary> /// <para>The constructor for the subject, setting its public and private credentials and principals according to the arguments.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 1, Signature = "(ZLjava/util/Set<+Ljava/security/Principal;>;Ljava/util/Set<*>;Ljava/util/Set<*>;" + ")V")] public Subject(bool readOnly, global::Java.Util.ISet<global::Java.Security.IPrincipal> subjPrincipals, global::Java.Util.ISet<object> pubCredentials, global::Java.Util.ISet<object> privCredentials) /* MethodBuilder.Create */ { } /// <java-name> /// doAs /// </java-name> [Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;" + "", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" + "on<TT;>;)TT;")] public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAsPrivileged /// </java-name> [Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;Ljava/security/Acce" + "ssControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" + "on<TT;>;Ljava/security/AccessControlContext;)TT;")] public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAs /// </java-name> [Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;)Ljava/lan" + "g/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" + "ptionAction<TT;>;)TT;")] public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAsPrivileged /// </java-name> [Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;Ljava/secu" + "rity/AccessControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" + "ptionAction<TT;>;Ljava/security/AccessControlContext;)TT;")] public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */ { return default(T); } /// <summary> /// <para>Checks two Subjects for equality. More specifically if the principals, public and private credentials are equal, equality for two <c> Subjects </c> is implied.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if the specified <c> Subject </c> is equal to this one. </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")] public global::Java.Util.ISet<global::Java.Security.IPrincipal> GetPrincipals() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<global::Java.Security.IPrincipal>); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal which is a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. Modifications to the returned set of <c> Principal </c> s do not affect this <c> Subject </c> 's set. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T::Ljava/security/Principal;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPrincipals<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> [Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] public global::Java.Util.ISet<object> GetPrivateCredentials() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<object>); } /// <summary> /// <para>Returns this <c> Subject </c> 's private credentials which are a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's private credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> [Dot42.DexImport("getPrivateCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPrivateCredentials<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> [Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] public global::Java.Util.ISet<object> GetPublicCredentials() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<object>); } /// <summary> /// <para>Returns this <c> Subject </c> 's public credentials which are a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's public credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> [Dot42.DexImport("getPublicCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPublicCredentials<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns a hash code of this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>a hash code of this <c> Subject </c> . </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Prevents from modifications being done to the credentials and Principal sets. After setting it to read-only this <c> Subject </c> can not be made writable again. The destroy method on the credentials still works though. </para> /// </summary> /// <java-name> /// setReadOnly /// </java-name> [Dot42.DexImport("setReadOnly", "()V", AccessFlags = 1)] public void SetReadOnly() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether this <c> Subject </c> is read-only or not.</para><para></para> /// </summary> /// <returns> /// <para>whether this <c> Subject </c> is read-only or not. </para> /// </returns> /// <java-name> /// isReadOnly /// </java-name> [Dot42.DexImport("isReadOnly", "()Z", AccessFlags = 1)] public bool IsReadOnly() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns a <c> String </c> representation of this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>a <c> String </c> representation of this <c> Subject </c> . </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the <c> Subject </c> that was last associated with the <c> context </c> provided as argument.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Subject </c> that was last associated with the <c> context </c> provided as argument. </para> /// </returns> /// <java-name> /// getSubject /// </java-name> [Dot42.DexImport("getSubject", "(Ljava/security/AccessControlContext;)Ljavax/security/auth/Subject;", AccessFlags = 9)] public static global::Javax.Security.Auth.Subject GetSubject(global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Subject); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> public global::Java.Util.ISet<global::Java.Security.IPrincipal> Principals { [Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")] get{ return GetPrincipals(); } } /// <summary> /// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> public global::Java.Util.ISet<object> PrivateCredentials { [Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] get{ return GetPrivateCredentials(); } } /// <summary> /// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> public global::Java.Util.ISet<object> PublicCredentials { [Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] get{ return GetPublicCredentials(); } } } /// <summary> /// <para>Signals that the Destroyable#destroy() method failed. </para> /// </summary> /// <java-name> /// javax/security/auth/DestroyFailedException /// </java-name> [Dot42.DexImport("javax/security/auth/DestroyFailedException", AccessFlags = 33)] public partial class DestroyFailedException : global::System.Exception /* scope: __dot42__ */ { /// <summary> /// <para>Creates an exception of type <c> DestroyFailedException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public DestroyFailedException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates an exception of type <c> DestroyFailedException </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public DestroyFailedException(string message) /* MethodBuilder.Create */ { } } }
using System; using System.Text; using System.Collections.Generic; using SimpleJson; using Pomelo.Protobuf; namespace Pomelo.DotNetClient { public class MessageProtocol { private Dictionary<string, ushort> dict = new Dictionary<string, ushort>(); private Dictionary<ushort, string> abbrs = new Dictionary<ushort, string>(); private JsonObject encodeProtos = new JsonObject(); private JsonObject decodeProtos = new JsonObject(); private Dictionary<uint, string> reqMap; private Protobuf.Protobuf protobuf; public const int MSG_Route_Limit = 255; public const int MSG_Route_Mask = 0x01; public const int MSG_Type_Mask = 0x07; public MessageProtocol(JsonObject dict, JsonObject serverProtos, JsonObject clientProtos) { ICollection<string> keys = dict.Keys; foreach (string key in keys) { ushort value = Convert.ToUInt16(dict[key]); this.dict[key] = value; this.abbrs[value] = key; } protobuf = new Protobuf.Protobuf(clientProtos, serverProtos); this.encodeProtos = clientProtos; this.decodeProtos = serverProtos; this.reqMap = new Dictionary<uint, string>(); } public byte[] encode(string route, JsonObject msg) { return encode(route, 0, msg); } public byte[] encode(string route, uint id, JsonObject msg) { int routeLength = byteLength(route); if (routeLength > MSG_Route_Limit) { throw new Exception("Route is too long!"); } //Encode head //The maximus length of head is 1 byte flag + 4 bytes message id + route string length + 1byte byte[] head = new byte[routeLength + 6]; int offset = 1; byte flag = 0; if (id > 0) { byte[] bytes = Protobuf.Encoder.encodeUInt32(id); writeBytes(bytes, offset, head); flag |= ((byte)MessageType.MSG_REQUEST) << 1; offset += bytes.Length; } else { flag |= ((byte)MessageType.MSG_NOTIFY) << 1; } //Compress head if (dict.ContainsKey(route)) { ushort cmpRoute = dict[route]; writeShort(offset, cmpRoute, head); flag |= MSG_Route_Mask; offset += 2; } else { //Write route length head[offset++] = (byte)routeLength; //Write route writeBytes(Encoding.UTF8.GetBytes(route), offset, head); offset += routeLength; } head[0] = flag; //Encode body byte[] body; if (encodeProtos.ContainsKey(route)) { body = protobuf.encode(route, msg); } else { body = Encoding.UTF8.GetBytes(msg.ToString()); } //Construct the result byte[] result = new byte[offset + body.Length]; for (int i = 0; i < offset; i++) { result[i] = head[i]; } for (int i = 0; i < body.Length; i++) { result[offset + i] = body[i]; } //Add id to route map if (id > 0) reqMap.Add(id, route); return result; } public Message decode(byte[] buffer) { //Decode head //Get flag byte flag = buffer[0]; //Set offset to 1, for the 1st byte will always be the flag int offset = 1; //Get type from flag; MessageType type = (MessageType)((flag >> 1) & MSG_Type_Mask); uint id = 0; string route; if (type == MessageType.MSG_RESPONSE) { int length; id = (uint)Protobuf.Decoder.decodeUInt32(offset, buffer, out length); if (id <= 0 || !reqMap.ContainsKey(id)) { return null; } else { route = reqMap[id]; reqMap.Remove(id); } offset += length; } else if (type == MessageType.MSG_PUSH) { //Get route if ((flag & 0x01) == 1) { ushort routeId = readShort(offset, buffer); route = abbrs[routeId]; offset += 2; } else { byte length = buffer[offset]; offset += 1; route = Encoding.UTF8.GetString(buffer, offset, length); offset += length; } } else { return null; } //Decode body byte[] body = new byte[buffer.Length - offset]; for (int i = 0; i < body.Length; i++) { body[i] = buffer[i + offset]; } JsonObject msg; if (decodeProtos.ContainsKey(route)) { msg = protobuf.decode(route, body); } else { msg = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(body)); } //Construct the message return new Message(type, id, route, msg); } private void writeInt(int offset, uint value, byte[] bytes) { bytes[offset] = (byte)(value >> 24 & 0xff); bytes[offset + 1] = (byte)(value >> 16 & 0xff); bytes[offset + 2] = (byte)(value >> 8 & 0xff); bytes[offset + 3] = (byte)(value & 0xff); } private void writeShort(int offset, ushort value, byte[] bytes) { bytes[offset] = (byte)(value >> 8 & 0xff); bytes[offset + 1] = (byte)(value & 0xff); } private ushort readShort(int offset, byte[] bytes) { ushort result = 0; result += (ushort)(bytes[offset] << 8); result += (ushort)(bytes[offset + 1]); return result; } private int byteLength(string msg) { return Encoding.UTF8.GetBytes(msg).Length; } private void writeBytes(byte[] source, int offset, byte[] target) { for (int i = 0; i < source.Length; i++) { target[offset + i] = source[i]; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace RestBench.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// ----------------------------------------------------------------------- // <copyright file="JsonParser.cs" company=""> // fastJSON - http://fastjson.codeplex.com/ // </copyright> // ----------------------------------------------------------------------- namespace MeshExplorer.IO { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> internal class JsonParser { enum Token { None = -1, // Used to denote no Lookahead available Curly_Open, Curly_Close, Squared_Open, Squared_Close, Colon, Comma, String, Number, True, False, Null } readonly char[] json; readonly StringBuilder s = new StringBuilder(); Token lookAheadToken = Token.None; int index; public JsonParser(string json) { this.json = json.ToCharArray(); } public object Decode() { return ParseValue(); } private Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); ConsumeToken(); // { while (true) { switch (LookAhead()) { case Token.Comma: ConsumeToken(); break; case Token.Curly_Close: ConsumeToken(); return table; default: { // name string name = ParseString(); // : if (NextToken() != Token.Colon) { throw new Exception("Expected colon at index " + index); } // value object value = ParseValue(); table[name] = value; } break; } } } private ArrayList ParseArray() { ArrayList array = new ArrayList(); ConsumeToken(); // [ while (true) { switch (LookAhead()) { case Token.Comma: ConsumeToken(); break; case Token.Squared_Close: ConsumeToken(); return array; default: { array.Add(ParseValue()); } break; } } } private object ParseValue() { switch (LookAhead()) { case Token.Number: return ParseNumber(); case Token.String: return ParseString(); case Token.Curly_Open: return ParseObject(); case Token.Squared_Open: return ParseArray(); case Token.True: ConsumeToken(); return true; case Token.False: ConsumeToken(); return false; case Token.Null: ConsumeToken(); return null; } throw new Exception("Unrecognized token at index" + index); } private string ParseString() { ConsumeToken(); // " s.Length = 0; int runIndex = -1; while (index < json.Length) { var c = json[index++]; if (c == '"') { if (runIndex != -1) { if (s.Length == 0) return new string(json, runIndex, index - runIndex - 1); s.Append(json, runIndex, index - runIndex - 1); } return s.ToString(); } if (c != '\\') { if (runIndex == -1) runIndex = index - 1; continue; } if (index == json.Length) break; if (runIndex != -1) { s.Append(json, runIndex, index - runIndex - 1); runIndex = -1; } switch (json[index++]) { case '"': s.Append('"'); break; case '\\': s.Append('\\'); break; case '/': s.Append('/'); break; case 'b': s.Append('\b'); break; case 'f': s.Append('\f'); break; case 'n': s.Append('\n'); break; case 'r': s.Append('\r'); break; case 't': s.Append('\t'); break; case 'u': { int remainingLength = json.Length - index; if (remainingLength < 4) break; // parse the 32 bit hex into an integer codepoint uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]); s.Append((char)codePoint); // skip 4 chars index += 4; } break; } } throw new Exception("Unexpectedly reached end of string"); } private uint ParseSingleChar(char c1, uint multipliyer) { uint p1 = 0; if (c1 >= '0' && c1 <= '9') p1 = (uint)(c1 - '0') * multipliyer; else if (c1 >= 'A' && c1 <= 'F') p1 = (uint)((c1 - 'A') + 10) * multipliyer; else if (c1 >= 'a' && c1 <= 'f') p1 = (uint)((c1 - 'a') + 10) * multipliyer; return p1; } private uint ParseUnicode(char c1, char c2, char c3, char c4) { uint p1 = ParseSingleChar(c1, 0x1000); uint p2 = ParseSingleChar(c2, 0x100); uint p3 = ParseSingleChar(c3, 0x10); uint p4 = ParseSingleChar(c4, 1); return p1 + p2 + p3 + p4; } private string ParseNumber() { ConsumeToken(); // Need to start back one place because the first digit is also a token and would have been consumed var startIndex = index - 1; do { var c = json[index]; if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E') { if (++index == json.Length) throw new Exception("Unexpected end of string whilst parsing number"); continue; } break; } while (true); return new string(json, startIndex, index - startIndex); } private Token LookAhead() { if (lookAheadToken != Token.None) return lookAheadToken; return lookAheadToken = NextTokenCore(); } private void ConsumeToken() { lookAheadToken = Token.None; } private Token NextToken() { var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore(); lookAheadToken = Token.None; return result; } private Token NextTokenCore() { char c; // Skip past whitespace do { c = json[index]; if (c > ' ') break; if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break; } while (++index < json.Length); if (index == json.Length) { throw new Exception("Reached end of string unexpectedly"); } c = json[index]; index++; //if (c >= '0' && c <= '9') // return Token.Number; switch (c) { case '{': return Token.Curly_Open; case '}': return Token.Curly_Close; case '[': return Token.Squared_Open; case ']': return Token.Squared_Close; case ',': return Token.Comma; case '"': return Token.String; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': case '+': case '.': return Token.Number; case ':': return Token.Colon; case 'f': if (json.Length - index >= 4 && json[index + 0] == 'a' && json[index + 1] == 'l' && json[index + 2] == 's' && json[index + 3] == 'e') { index += 4; return Token.False; } break; case 't': if (json.Length - index >= 3 && json[index + 0] == 'r' && json[index + 1] == 'u' && json[index + 2] == 'e') { index += 3; return Token.True; } break; case 'n': if (json.Length - index >= 3 && json[index + 0] == 'u' && json[index + 1] == 'l' && json[index + 2] == 'l') { index += 3; return Token.Null; } break; } throw new Exception("Could not find token at index " + --index); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Runtime.Serialization; using System.IO; using DDay.iCal.Serialization.iCalendar; namespace DDay.iCal { /// <summary> /// An iCalendar representation of the <c>RRULE</c> property. /// </summary> #if !SILVERLIGHT [Serializable] #endif public partial class RecurrencePattern : EncodableDataType, IRecurrencePattern { #region Private Fields #if !SILVERLIGHT [NonSerialized] #endif private FrequencyType _Frequency; private DateTime _Until = DateTime.MinValue; private int _Count = int.MinValue; private int _Interval = int.MinValue; private IList<int> _BySecond = new List<int>(); private IList<int> _ByMinute = new List<int>(); private IList<int> _ByHour = new List<int>(); private IList<IWeekDay> _ByDay = new List<IWeekDay>(); private IList<int> _ByMonthDay = new List<int>(); private IList<int> _ByYearDay = new List<int>(); private IList<int> _ByWeekNo = new List<int>(); private IList<int> _ByMonth = new List<int>(); private IList<int> _BySetPosition = new List<int>(); private DayOfWeek _FirstDayOfWeek = DayOfWeek.Monday; private RecurrenceRestrictionType? _RestrictionType = null; private RecurrenceEvaluationModeType? _EvaluationMode = null; #endregion #region IRecurrencePattern Members public FrequencyType Frequency { get { return _Frequency; } set { _Frequency = value; } } public DateTime Until { get { return _Until; } set { _Until = value; } } public int Count { get { return _Count; } set { _Count = value; } } public int Interval { get { if (_Interval == int.MinValue) return 1; return _Interval; } set { _Interval = value; } } public IList<int> BySecond { get { return _BySecond; } set { _BySecond = value; } } public IList<int> ByMinute { get { return _ByMinute; } set { _ByMinute = value; } } public IList<int> ByHour { get { return _ByHour; } set { _ByHour = value; } } public IList<IWeekDay> ByDay { get { return _ByDay; } set { _ByDay = value; } } public IList<int> ByMonthDay { get { return _ByMonthDay; } set { _ByMonthDay = value; } } public IList<int> ByYearDay { get { return _ByYearDay; } set { _ByYearDay = value; } } public IList<int> ByWeekNo { get { return _ByWeekNo; } set { _ByWeekNo = value; } } public IList<int> ByMonth { get { return _ByMonth; } set { _ByMonth = value; } } public IList<int> BySetPosition { get { return _BySetPosition; } set { _BySetPosition = value; } } public DayOfWeek FirstDayOfWeek { get { return _FirstDayOfWeek; } set { _FirstDayOfWeek = value; } } public RecurrenceRestrictionType RestrictionType { get { // NOTE: Fixes bug #1924358 - Cannot evaluate Secondly patterns if (_RestrictionType != null && _RestrictionType.HasValue) return _RestrictionType.Value; else if (Calendar != null) return Calendar.RecurrenceRestriction; else return RecurrenceRestrictionType.Default; } set { _RestrictionType = value; } } public RecurrenceEvaluationModeType EvaluationMode { get { // NOTE: Fixes bug #1924358 - Cannot evaluate Secondly patterns if (_EvaluationMode != null && _EvaluationMode.HasValue) return _EvaluationMode.Value; else if (Calendar != null) return Calendar.RecurrenceEvaluationMode; else return RecurrenceEvaluationModeType.Default; } set { _EvaluationMode = value; } } /// <summary> /// Returns the next occurrence of the pattern, /// given a valid previous occurrence, <paramref name="lastOccurrence"/>. /// As long as the recurrence pattern is valid, and /// <paramref name="lastOccurrence"/> is a valid previous /// occurrence within the pattern, this will return the /// next occurrence. NOTE: This will not give accurate results /// when COUNT or BYSETVAL are used. /// </summary> virtual public IPeriod GetNextOccurrence(IDateTime lastOccurrence) { RecurrencePatternEvaluator evaluator = GetService<RecurrencePatternEvaluator>(); if (evaluator != null) return evaluator.GetNext(lastOccurrence); return null; } #endregion #region Constructors public RecurrencePattern() { Initialize(); } public RecurrencePattern(FrequencyType frequency) : this(frequency, 1) { } public RecurrencePattern(FrequencyType frequency, int interval) : this() { Frequency = frequency; Interval = interval; } public RecurrencePattern(string value) : this() { if (value != null) { DDay.iCal.Serialization.iCalendar.RecurrencePatternSerializer serializer = new DDay.iCal.Serialization.iCalendar.RecurrencePatternSerializer(); CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable); } } void Initialize() { SetService(new RecurrencePatternEvaluator(this)); } #endregion #region Overrides protected override void OnDeserializing(StreamingContext context) { base.OnDeserializing(context); Initialize(); } public override bool Equals(object obj) { if (obj is RecurrencePattern) { RecurrencePattern r = (RecurrencePattern)obj; if (!CollectionEquals(r.ByDay, ByDay) || !CollectionEquals(r.ByHour, ByHour) || !CollectionEquals(r.ByMinute, ByMinute) || !CollectionEquals(r.ByMonth, ByMonth) || !CollectionEquals(r.ByMonthDay, ByMonthDay) || !CollectionEquals(r.BySecond, BySecond) || !CollectionEquals(r.BySetPosition, BySetPosition) || !CollectionEquals(r.ByWeekNo, ByWeekNo) || !CollectionEquals(r.ByYearDay, ByYearDay)) return false; if (r.Count != Count) return false; if (r.Frequency != Frequency) return false; if (r.Interval != Interval) return false; if (r.Until != DateTime.MinValue) { if (!r.Until.Equals(Until)) return false; } else if (Until != DateTime.MinValue) return false; if (r.FirstDayOfWeek != FirstDayOfWeek) return false; return true; } return base.Equals(obj); } public override string ToString() { RecurrencePatternSerializer serializer = new RecurrencePatternSerializer(); return serializer.SerializeToString(this); } public override int GetHashCode() { int hashCode = ByDay.GetHashCode() ^ ByHour.GetHashCode() ^ ByMinute.GetHashCode() ^ ByMonth.GetHashCode() ^ ByMonthDay.GetHashCode() ^ BySecond.GetHashCode() ^ BySetPosition.GetHashCode() ^ ByWeekNo.GetHashCode() ^ ByYearDay.GetHashCode() ^ Count.GetHashCode() ^ Frequency.GetHashCode(); if (Interval.Equals(1)) hashCode ^= 0x1; else hashCode ^= Interval.GetHashCode(); hashCode ^= Until.GetHashCode(); hashCode ^= FirstDayOfWeek.GetHashCode(); return hashCode; } public override void CopyFrom(ICopyable obj) { base.CopyFrom(obj); if (obj is IRecurrencePattern) { IRecurrencePattern r = (IRecurrencePattern)obj; Frequency = r.Frequency; Until = r.Until; Count = r.Count; Interval = r.Interval; BySecond = new List<int>(r.BySecond); ByMinute = new List<int>(r.ByMinute); ByHour = new List<int>(r.ByHour); ByDay = new List<IWeekDay>(r.ByDay); ByMonthDay = new List<int>(r.ByMonthDay); ByYearDay = new List<int>(r.ByYearDay); ByWeekNo = new List<int>(r.ByWeekNo); ByMonth = new List<int>(r.ByMonth); BySetPosition = new List<int>(r.BySetPosition); FirstDayOfWeek = r.FirstDayOfWeek; RestrictionType = r.RestrictionType; EvaluationMode = r.EvaluationMode; } } private bool CollectionEquals<T>(IList<T> c1, IList<T> c2) { // NOTE: fixes a bug where collections weren't properly compared if (c1 == null || c2 == null) { if (c1 == c2) return true; else return false; } if (!c1.Count.Equals(c2.Count)) return false; IEnumerator e1 = c1.GetEnumerator(); IEnumerator e2 = c2.GetEnumerator(); while (e1.MoveNext() && e2.MoveNext()) { if (!object.Equals(e1.Current, e2.Current)) return false; } return true; } #endregion #region Protected Methods #endregion } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at [email protected] // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.UI.WebControls; using log4net; using Subtext.Framework.Logging; using Subtext.Web.Properties; namespace Subtext.Web.Controls.Captcha { /// <summary> /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Captcha")] public abstract class CaptchaBase : BaseValidator { static readonly SymmetricAlgorithm EncryptionAlgorithm = InitializeEncryptionAlgorithm(); private readonly static ILog Log = new Log(); /// <summary> /// Gets the name of the hidden form field in which the encrypted answer /// is located. The answer is sent encrypted to the browser, which must /// send the answer back. /// </summary> /// <value>The name of the hidden encrypted answer field.</value> protected string HiddenEncryptedAnswerFieldName { get { return ClientID + "_encrypted"; } } /// <summary> /// The input field (possibly hidden) in which the client /// will specify the answer. /// </summary> protected string AnswerFormFieldName { get { return ClientID + "_answer"; } } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Captcha")] [DefaultValue(0)] [Description("Number of seconds this CAPTCHA is valid after it is generated. Zero means valid forever.")] [Category("Captcha")] public int CaptchaTimeout { get; set; } static SymmetricAlgorithm InitializeEncryptionAlgorithm() { SymmetricAlgorithm rijaendel = Rijndael.Create(); //TODO: We should set these values in the db the very first time this code is called and load them from the db every other time. rijaendel.GenerateKey(); rijaendel.GenerateIV(); return rijaendel; } /// <summary> /// Encrypts the string and returns a base64 encoded encrypted string. /// </summary> /// <param name="clearText">The clear text.</param> /// <returns></returns> public static string EncryptString(string clearText) { byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText); byte[] encrypted = EncryptionAlgorithm.CreateEncryptor().TransformFinalBlock(clearTextBytes, 0, clearTextBytes.Length); return Convert.ToBase64String(encrypted); } /// <summary> /// Decrypts the base64 encrypted string and returns the cleartext. /// </summary> /// <param name="encryptedEncodedText">The clear text.</param> /// <exception type="System.Security.Cryptography.CryptographicException">Thrown the string to be decrypted /// was encrypted using a different encryptor (for example, if we recompile and /// receive an old string).</exception> /// <returns></returns> public static string DecryptString(string encryptedEncodedText) { try { byte[] encryptedBytes = Convert.FromBase64String(encryptedEncodedText); byte[] decryptedBytes = EncryptionAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); return Encoding.UTF8.GetString(decryptedBytes); } catch (FormatException fe) { throw new CaptchaExpiredException( String.Format(CultureInfo.InvariantCulture, Resources.CaptchaExpired_EncryptedTextNotValid, encryptedEncodedText), fe); } catch (CryptographicException e) { throw new CaptchaExpiredException(Resources.CaptchaExpired_KeyOutOfSynch, e); } } /// <summary>Checks the properties of the control for valid values.</summary> /// <returns>true if the control properties are valid; otherwise, false.</returns> protected override bool ControlPropertiesValid() { if (!String.IsNullOrEmpty(ControlToValidate)) { CheckControlValidationProperty(ControlToValidate, "ControlToValidate"); } return true; } /// <summary> /// Encrypts the answer along with the current datetime. /// </summary> /// <param name="answer">The answer.</param> /// <returns></returns> protected virtual string EncryptAnswer(string answer) { return EncryptString(answer + "|" + DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture)); } ///<summary> ///When overridden in a derived class, this method contains the code to determine whether the value in the input control is valid. ///</summary> ///<returns> ///true if the value in the input control is valid; otherwise, false. ///</returns> /// protected override bool EvaluateIsValid() { try { return ValidateCaptcha(); } catch (CaptchaExpiredException e) { if (e.InnerException != null) { string warning = Resources.Warning_CaptchaExpired; if (HttpContext.Current != null && HttpContext.Current.Request != null) { warning += " User Agent: " + HttpContext.Current.Request.UserAgent; } Log.Warn(warning, e.InnerException); } ErrorMessage = Resources.Message_FormExpired; return false; } } private bool ValidateCaptcha() { string answer = GetClientSpecifiedAnswer(); AnswerAndDate answerAndDate = GetEncryptedAnswerFromForm(); string expectedAnswer = answerAndDate.Answer; bool isValid = !String.IsNullOrEmpty(answer) && String.Equals(answer, expectedAnswer, StringComparison.OrdinalIgnoreCase); return isValid; } // Gets the answer from the client, whether entered by // javascript or by the user. protected virtual string GetClientSpecifiedAnswer() { return Page.Request.Form[AnswerFormFieldName]; } /// <summary> /// Gets the encrypted answer from form. /// </summary> /// <returns></returns> /// <exception type="CaptchaExpiredException">Thrown when the user takes too long to submit a captcha answer.</exception> protected virtual AnswerAndDate GetEncryptedAnswerFromForm() { string formValue = Page.Request.Form[HiddenEncryptedAnswerFieldName]; AnswerAndDate answerAndDate = AnswerAndDate.ParseAnswerAndDate(formValue, CaptchaTimeout); if (answerAndDate.Expired) { throw new CaptchaExpiredException(Resources.CaptchaExpired_WaitedTooLong); } return answerAndDate; } } /// <summary> /// Represents the answer and date returned by the /// client. /// </summary> public struct AnswerAndDate { public string Answer { get { return _answer; } } string _answer; public DateTime Date { get { return _date; } } DateTime _date; public bool Expired { get { return _expired; } } bool _expired; public static AnswerAndDate ParseAnswerAndDate(string encryptedAnswer, int timeoutInSeconds) { AnswerAndDate answerAndDate; answerAndDate._expired = false; answerAndDate._answer = string.Empty; answerAndDate._date = DateTime.MinValue; if (String.IsNullOrEmpty(encryptedAnswer)) { return answerAndDate; } string decryptedAnswer = CaptchaBase.DecryptString(encryptedAnswer); string[] answerParts = decryptedAnswer.Split('|'); if (answerParts.Length < 2) { return answerAndDate; } answerAndDate._answer = answerParts[0]; answerAndDate._date = DateTime.ParseExact(answerParts[1], "yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture); if (timeoutInSeconds != 0 && (DateTime.UtcNow - answerAndDate._date).TotalSeconds >= timeoutInSeconds) { throw new CaptchaExpiredException(Resources.CaptchaExpired_WaitedTooLong); } return answerAndDate; } } }
/* Copyright 2008 The 'A Concurrent Hashtable' development team (http://www.codeplex.com/CH/People/ProjectPeople.aspx) This library is licensed under the GNU Library General Public License (LGPL). You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at http://www.codeplex.com/CH/license. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Runtime.Serialization; using System.Security; namespace Orvid.Concurrent.Collections { #if !SILVERLIGHT [Serializable] #endif public class WeakKeyDictionary<TWeakKey1, TStrongKey, TValue> : DictionaryBase<Tuple<TWeakKey1, TStrongKey>, TValue> #if !SILVERLIGHT , ISerializable #endif where TWeakKey1 : class { sealed class InternalWeakKeyDictionary : InternalWeakDictionaryStrongValueBase< Key<TWeakKey1, TStrongKey>, Tuple<TWeakKey1, TStrongKey>, TValue, Stacktype<TWeakKey1, TStrongKey> > { public InternalWeakKeyDictionary(int concurrencyLevel, int capacity, KeyComparer<TWeakKey1, TStrongKey> keyComparer) : base(concurrencyLevel, capacity, keyComparer) { _comparer = keyComparer; MaintenanceWorker.Register(this); } public InternalWeakKeyDictionary(KeyComparer<TWeakKey1, TStrongKey> keyComparer) : base(keyComparer) { _comparer = keyComparer; MaintenanceWorker.Register(this); } public KeyComparer<TWeakKey1, TStrongKey> _comparer; protected override Key<TWeakKey1, TStrongKey> FromExternalKeyToSearchKey(Tuple<TWeakKey1, TStrongKey> externalKey) { return new SearchKey<TWeakKey1, TStrongKey>().Set(externalKey, _comparer); } protected override Key<TWeakKey1, TStrongKey> FromExternalKeyToStorageKey(Tuple<TWeakKey1, TStrongKey> externalKey) { return new StorageKey<TWeakKey1, TStrongKey>().Set(externalKey, _comparer); } protected override Key<TWeakKey1, TStrongKey> FromStackKeyToSearchKey(Stacktype<TWeakKey1, TStrongKey> externalKey) { return new SearchKey<TWeakKey1, TStrongKey>().Set(externalKey, _comparer); } protected override Key<TWeakKey1, TStrongKey> FromStackKeyToStorageKey(Stacktype<TWeakKey1, TStrongKey> externalKey) { return new StorageKey<TWeakKey1, TStrongKey>().Set(externalKey, _comparer); } protected override bool FromInternalKeyToExternalKey(Key<TWeakKey1, TStrongKey> internalKey, out Tuple<TWeakKey1, TStrongKey> externalKey) { return internalKey.Get(out externalKey); } protected override bool FromInternalKeyToStackKey(Key<TWeakKey1, TStrongKey> internalKey, out Stacktype<TWeakKey1, TStrongKey> externalKey) { return internalKey.Get(out externalKey); } } readonly InternalWeakKeyDictionary _internalDictionary; protected override IDictionary<Tuple<TWeakKey1, TStrongKey>, TValue> InternalDictionary { get { return _internalDictionary; } } #if !SILVERLIGHT WeakKeyDictionary(SerializationInfo serializationInfo, StreamingContext streamingContext) { var comparer = (KeyComparer<TWeakKey1, TStrongKey>)serializationInfo.GetValue("Comparer", typeof(KeyComparer<TWeakKey1, TStrongKey>)); var items = (List<KeyValuePair<Tuple<TWeakKey1, TStrongKey>, TValue>>)serializationInfo.GetValue("Items", typeof(List<KeyValuePair<Tuple<TWeakKey1, TStrongKey>, TValue>>)); _internalDictionary = new InternalWeakKeyDictionary(comparer); _internalDictionary.InsertContents(items); } #region ISerializable Members [SecurityCritical] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Comparer", _internalDictionary._comparer); info.AddValue("Items", _internalDictionary.GetContents()); } #endregion #endif public WeakKeyDictionary() : this(EqualityComparer<TWeakKey1>.Default, EqualityComparer<TStrongKey>.Default) {} public WeakKeyDictionary(IEqualityComparer<TWeakKey1> weakKeyComparer, IEqualityComparer<TStrongKey> strongKeyComparer) : this(Enumerable.Empty<KeyValuePair<Tuple<TWeakKey1,TStrongKey>,TValue>>(), weakKeyComparer, strongKeyComparer) {} public WeakKeyDictionary(IEnumerable<KeyValuePair<Tuple<TWeakKey1,TStrongKey>,TValue>> collection) : this(collection, EqualityComparer<TWeakKey1>.Default, EqualityComparer<TStrongKey>.Default) {} public WeakKeyDictionary(IEnumerable<KeyValuePair<Tuple<TWeakKey1, TStrongKey>, TValue>> collection, IEqualityComparer<TWeakKey1> weakKeyComparer, IEqualityComparer<TStrongKey> strongKeyComparer) { _internalDictionary = new InternalWeakKeyDictionary( new KeyComparer<TWeakKey1, TStrongKey>(weakKeyComparer, strongKeyComparer) ) ; _internalDictionary.InsertContents(collection); } public WeakKeyDictionary(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, EqualityComparer<TWeakKey1>.Default, EqualityComparer<TStrongKey>.Default) {} public WeakKeyDictionary(int concurrencyLevel, IEnumerable<KeyValuePair<Tuple<TWeakKey1, TStrongKey>, TValue>> collection, IEqualityComparer<TWeakKey1> weakKeyComparer, IEqualityComparer<TStrongKey> strongKeyComparer) { var contentsList = collection.ToList(); _internalDictionary = new InternalWeakKeyDictionary( concurrencyLevel, contentsList.Count, new KeyComparer<TWeakKey1, TStrongKey>(weakKeyComparer, strongKeyComparer) ) ; _internalDictionary.InsertContents(contentsList); } public WeakKeyDictionary(int concurrencyLevel, int capacity, IEqualityComparer<TWeakKey1> weakKeyComparer, IEqualityComparer<TStrongKey> strongKeyComparer) { _internalDictionary = new InternalWeakKeyDictionary( concurrencyLevel, capacity, new KeyComparer<TWeakKey1, TStrongKey>(weakKeyComparer, strongKeyComparer) ) ; } public bool ContainsKey(TWeakKey1 weakKey, TStrongKey strongKey) { return _internalDictionary.ContainsKey(Stacktype.Create(weakKey, strongKey)); } public bool TryGetValue(TWeakKey1 weakKey, TStrongKey strongKey, out TValue value) { return _internalDictionary.TryGetValue(Stacktype.Create(weakKey, strongKey), out value); } public TValue this[TWeakKey1 weakKey, TStrongKey strongKey] { get { return _internalDictionary.GetItem(Stacktype.Create(weakKey, strongKey)); } set { _internalDictionary.SetItem(Stacktype.Create(weakKey, strongKey), value); } } public bool IsEmpty { get { return _internalDictionary.IsEmpty; } } public TValue AddOrUpdate(TWeakKey1 weakKey, TStrongKey strongKey, Func<TWeakKey1, TStrongKey, TValue> addValueFactory, Func<TWeakKey1, TStrongKey, TValue, TValue> updateValueFactory) { if (null == addValueFactory) throw new ArgumentNullException("addValueFactory"); if (null == updateValueFactory) throw new ArgumentNullException("updateValueFactory"); return _internalDictionary.AddOrUpdate( Stacktype.Create(weakKey, strongKey), hr => addValueFactory(hr.Item1, hr.Item2), (hr, v) => updateValueFactory(hr.Item1, hr.Item2, v) ) ; } public TValue AddOrUpdate(TWeakKey1 weakKey, TStrongKey strongKey, TValue addValue, Func<TWeakKey1, TStrongKey, TValue, TValue> updateValueFactory) { if (null == updateValueFactory) throw new ArgumentNullException("updateValueFactory"); return _internalDictionary.AddOrUpdate( Stacktype.Create(weakKey, strongKey), addValue, (hr, v) => updateValueFactory(hr.Item1, hr.Item2, v) ) ; } public TValue GetOrAdd(TWeakKey1 weakKey, TStrongKey strongKey, TValue value) { return _internalDictionary.GetOrAdd(Stacktype.Create(weakKey, strongKey), value); } public TValue GetOrAdd(TWeakKey1 weakKey, TStrongKey strongKey, Func<TWeakKey1, TStrongKey, TValue> valueFactory) { if (null == valueFactory) throw new ArgumentNullException("valueFactory"); return _internalDictionary.GetOrAdd(Stacktype.Create(weakKey, strongKey), hr => valueFactory(hr.Item1, hr.Item2)); } public KeyValuePair<Tuple<TWeakKey1, TStrongKey>, TValue>[] ToArray() { return _internalDictionary.ToArray(); } public bool TryAdd(TWeakKey1 weakKey, TStrongKey strongKey, TValue value) { return _internalDictionary.TryAdd(Stacktype.Create(weakKey, strongKey), value); } public bool TryRemove(TWeakKey1 weakKey, TStrongKey strongKey, out TValue value) { return _internalDictionary.TryRemove(Stacktype.Create(weakKey, strongKey), out value); } public bool TryUpdate(TWeakKey1 weakKey, TStrongKey strongKey, TValue newValue, TValue comparisonValue) { return _internalDictionary.TryUpdate(Stacktype.Create(weakKey, strongKey), newValue, comparisonValue ); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Diagnostics.Application; #if USE_REFEMIT public class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #else internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #endif { protected IDataContractSurrogate dataContractSurrogate; SerializationMode mode; SerializationBinder binder; ISurrogateSelector surrogateSelector; StreamingContext streamingContext; Hashtable surrogateDataContracts; internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.mode = SerializationMode.SharedContract; this.preserveObjectReferences = serializer.PreserveObjectReferences; this.dataContractSurrogate = serializer.DataContractSurrogate; } internal XmlObjectSerializerWriteContextComplex(NetDataContractSerializer serializer, Hashtable surrogateDataContracts) : base(serializer) { this.mode = SerializationMode.SharedType; this.preserveObjectReferences = true; this.streamingContext = serializer.Context; this.binder = serializer.Binder; this.surrogateSelector = serializer.SurrogateSelector; this.surrogateDataContracts = surrogateDataContracts; } internal XmlObjectSerializerWriteContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override SerializationMode Mode { get { return mode; } } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, streamingContext, typeHandle, type, ref surrogateDataContracts); } if (dataContract != null) { if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(typeHandle, type); } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, streamingContext, typeHandle, null /*type*/, ref surrogateDataContracts); } if (dataContract != null) { if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContract(id, typeHandle); } internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = null; if (mode == SerializationMode.SharedType && surrogateSelector != null) { dataContract = NetDataContractSerializer.GetDataContractFromSurrogateSelector(surrogateSelector, streamingContext, typeHandle, null /*type*/, ref surrogateDataContracts); } if (dataContract != null) { if (this.IsGetOnlyCollection && dataContract is SurrogateDataContract) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } return dataContract; } return base.GetDataContractSkipValidation(typeId, typeHandle, type); } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { if (mode == SerializationMode.SharedType) { NetDataContractSerializer.WriteClrTypeInfo(xmlWriter, dataContract, binder); return true; } return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { if (mode == SerializationMode.SharedType) { NetDataContractSerializer.WriteClrTypeInfo(xmlWriter, dataContractType, binder, clrTypeName, clrAssemblyName); return true; } return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo) { if (mode == SerializationMode.SharedType) { NetDataContractSerializer.WriteClrTypeInfo(xmlWriter, dataContractType, binder, serInfo); return true; } return false; } public override void WriteAnyType(XmlWriterDelegator xmlWriter, object value) { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteAnyType(value); } public override void WriteString(XmlWriterDelegator xmlWriter, string value) { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteString(value); } public override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteBase64(value); } public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteUri(value); } public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteQName(value); } public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } public override void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (dataContractSurrogate == null) { base.InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } else { InternalSerializeWithSurrogate(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } } internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !this.IsGetOnlyCollection) { bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); if (isNew) xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, objectId); else { xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, objectId); xmlWriter.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true); } return !isNew; } return base.OnHandleReference(xmlWriter, obj, canContainCyclicReference); } internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !this.IsGetOnlyCollection) return; base.OnEndHandleReference(xmlWriter, obj, canContainCyclicReference); } [Fx.Tag.SecurityNote(Critical = "Calls the critical methods of ISurrogateSelector", Safe = "Demands for FullTrust")] [SecuritySafeCritical] [PermissionSet(SecurityAction.Demand, Unrestricted = true)] [MethodImpl(MethodImplOptions.NoInlining)] bool CheckIfTypeSerializableForSharedTypeMode(Type memberType) { Fx.Assert(surrogateSelector != null, "Method should not be called when surrogateSelector is null."); ISurrogateSelector surrogateSelectorNotUsed; return (surrogateSelector.GetSurrogate(memberType, streamingContext, out surrogateSelectorNotUsed) != null); } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (mode == SerializationMode.SharedType && surrogateSelector != null && CheckIfTypeSerializableForSharedTypeMode(memberType)) { return; } else { if (dataContractSurrogate != null) { while (memberType.IsArray) memberType = memberType.GetElementType(); memberType = DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, memberType); if (!DataContract.IsTypeSerializable(memberType)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.TypeNotSerializable, memberType))); return; } } base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } internal override Type GetSurrogatedType(Type type) { if (dataContractSurrogate == null) { return base.GetSurrogatedType(type); } else { type = DataContract.UnwrapNullableType(type); Type surrogateType = DataContractSerializer.GetSurrogatedType(dataContractSurrogate, type); if (this.IsGetOnlyCollection && surrogateType != type) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.GetString(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(type)))); } else { return surrogateType; } } } void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { RuntimeTypeHandle objTypeHandle = isDeclaredType ? declaredTypeHandle : Type.GetTypeHandle(obj); object oldObj = obj; int objOldId = 0; Type objType = Type.GetTypeFromHandle(objTypeHandle); Type declaredType = GetSurrogatedType(Type.GetTypeFromHandle(declaredTypeHandle)); if (TD.DCSerializeWithSurrogateStartIsEnabled()) { TD.DCSerializeWithSurrogateStart(declaredType.FullName); } declaredTypeHandle = declaredType.TypeHandle; obj = DataContractSerializer.SurrogateToDataContractType(dataContractSurrogate, obj, declaredType, ref objType); objTypeHandle = objType.TypeHandle; if (oldObj != obj) objOldId = SerializedObjects.ReassignId(0, oldObj, obj); if (writeXsiType) { declaredType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, objTypeHandle, objType, -1, declaredType.TypeHandle, declaredType); } else if (declaredTypeHandle.Equals(objTypeHandle)) { DataContract contract = GetDataContract(objTypeHandle, objType); SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, objTypeHandle, objType, -1, declaredTypeHandle, declaredType); } if (oldObj != obj) SerializedObjects.ReassignId(objOldId, obj, oldObj); if (TD.DCSerializeWithSurrogateStopIsEnabled()) { TD.DCSerializeWithSurrogateStop(); } } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { if (preserveObjectReferences && size > -1) xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.ArraySizeLocalName, DictionaryGlobals.SerializationNamespace, size); } } }
/// Dedicated to the public domain by Christopher Diggins /// http://creativecommons.org/licenses/publicdomain/ using System; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.ComponentModel; using System.Text.RegularExpressions; namespace Cat { public interface INameLookup { Function Lookup(string s); Function ThrowingLookup(string s); } public class Executor : INameLookup { private Dictionary<string, Function> dictionary = new Dictionary<string, Function>(); INameLookup otherNames; List<Object> stack = new List<Object>(); public int testCount = 0; public bool bTrace = false; public Executor() { RegisterType(typeof(MetaCommands)); RegisterType(typeof(Primitives)); } public Executor(INameLookup other) { otherNames = other; } public Object Peek() { if (stack.Count == 0) throw new Exception("stack underflow occured"); return stack[stack.Count - 1]; } public void Push(Object o) { stack.Add(o); } public Object Pop() { Object o = Peek(); stack.RemoveAt(stack.Count - 1); return o; } public Object PeekBelow(int n) { if (stack.Count <= n) throw new Exception("stack underflow occured"); return stack[stack.Count - 1 - n]; } public int Count() { return stack.Count; } public Object[] GetStackAsArray() { return stack.ToArray(); } public void Dup() { if (Peek() is CatList) Push((Peek() as CatList).Clone()); else Push(Peek()); } public void Swap() { if (stack.Count < 2) throw new Exception("stack underflow occured"); Object tmp = stack[stack.Count - 2]; stack[stack.Count - 2] = stack[stack.Count - 1]; stack[stack.Count - 1] = tmp; } public bool IsEmpty() { return Count() == 0; } public void Clear() { stack.Clear(); } public string StackToString() { if (IsEmpty()) return "_empty_"; string s = ""; int nMax = 5; if (Count() > nMax) s = "..."; if (Count() < nMax) nMax = Count(); for (int i = nMax - 1; i >= 0; --i) { Object o = PeekBelow(i); s += Output.ObjectToString(o) + " "; } return s; } public T TypedPop<T>() { T result = TypedPeek<T>(); Pop(); return result; } public T TypedPeek<T>() { Object o = Peek(); if (!(o is T)) throw new Exception("Expected type " + typeof(T).Name + " but instead found " + o.GetType().Name); return (T)o; } public void PushInt(int n) { Push(n); } public void PushBool(bool x) { Push(x); } public void PushString(string x) { Push(x); } public void PushFxn(Function x) { Push(x); } public int PopInt() { return TypedPop<int>(); } public bool PopBool() { return TypedPop<bool>(); } public QuotedFunction PopFxn() { return TypedPop<QuotedFunction>(); } public String PopString() { return TypedPop<String>(); } public CatList PopList() { return TypedPop<CatList>(); } public Function PeekFxn() { return TypedPeek<Function>(); } public String PeekString() { return TypedPeek<String>(); } public int PeekInt() { return TypedPeek<int>(); } public bool PeekBool() { return TypedPeek<bool>(); } public CatList PeekList() { return TypedPeek<CatList>(); } public void Import() { LoadModule(PopString()); } public void LoadModule(string s) { bool b1 = Config.gbVerboseInference; bool b2 = Config.gbShowInferredType; Config.gbVerboseInference = Config.gbVerboseInferenceOnLoad; Config.gbShowInferredType = false; try { Execute(Util.FileToString(s)); } catch (Exception e) { Output.WriteLine("Failed to load \"" + s + "\" with message: " + e.Message); } Config.gbVerboseInference = b1; Config.gbShowInferredType = b2; } public void Execute(string s) { List<CatAstNode> nodes = CatParser.Parse(s + "\n"); Execute(nodes); } public void OutputStack() { Output.WriteLine("stack: " + StackToString()); } public Function LiteralToFunction(string name, AstLiteral literal) { switch (literal.GetLabel()) { case AstLabel.Int: { AstInt tmp = literal as AstInt; return new PushInt(tmp.GetValue()); } case AstLabel.Bin: { AstBin tmp = literal as AstBin; return new PushInt(tmp.GetValue()); } case AstLabel.Char: { AstChar tmp = literal as AstChar; return new PushValue<char>(tmp.GetValue()); } case AstLabel.String: { AstString tmp = literal as AstString; return new PushValue<string>(tmp.GetValue()); } case AstLabel.Float: { AstFloat tmp = literal as AstFloat; return new PushValue<double>(tmp.GetValue()); } case AstLabel.Hex: { AstHex tmp = literal as AstHex; return new PushInt(tmp.GetValue()); } case AstLabel.Quote: { AstQuote tmp = literal as AstQuote; CatExpr fxns = NodesToFxns(name, tmp.GetTerms()); if (Config.gbOptimizeQuotations) MetaCat.ApplyMacros(this, fxns); return new PushFunction(fxns); } case AstLabel.Lambda: { AstLambda tmp = literal as AstLambda; CatLambdaConverter.Convert(tmp); CatExpr fxns = NodesToFxns(name, tmp.GetTerms()); if (Config.gbOptimizeLambdas) MetaCat.ApplyMacros(this, fxns); return new PushFunction(fxns); } default: throw new Exception("unhandled literal " + literal.ToString()); } } void Trace(string s) { if (bTrace) Output.WriteLine("trace: " + s); } /// <summary> /// This function is optimized to handle tail-calls with increasing the stack size. /// </summary> /// <param name="fxns"></param> public void Execute(CatExpr fxns) { int i = 0; while (i < fxns.Count) { //DM+ Added ability to cancel execution by cancellation request CatEnvironment.CheckCancellationPending(); //DM- Function f = fxns[i]; // Check if this is a tail call // if so then we are going to avoid creating a new stack frame if (i == fxns.Count - 1 && f.GetSubFxns() != null) { Trace("tail-call of '" + f.GetName() + "' function"); fxns = f.GetSubFxns(); i = 0; } else if (i == fxns.Count - 1 && f is Primitives.If) { Trace("tail-call of 'if' function"); QuotedFunction onfalse = PopFxn(); QuotedFunction ontrue = PopFxn(); if (PopBool()) fxns = ontrue.GetSubFxns(); else fxns = onfalse.GetSubFxns(); i = 0; } else if (i == fxns.Count - 1 && f is Primitives.ApplyFxn) { Trace("tail-call of 'apply' function"); QuotedFunction q = PopFxn(); fxns = q.GetSubFxns(); i = 0; } else { Trace(f.ToString()); f.Eval(this); ++i; } } } public CatExpr NodesToFxns(string name, List<CatAstNode> nodes) { CatExpr result = new CatExpr(); for (int i = 0; i < nodes.Count; ++i) { CatAstNode node = nodes[i]; if (node.GetLabel().Equals(AstLabel.Name)) { string s = node.ToString(); if (s.Equals(name)) result.Add(new SelfFunction(name)); else result.Add(ThrowingLookup(s)); } else if (node is AstLiteral) { result.Add(LiteralToFunction(name, node as AstLiteral)); } else if (node is AstDef) { MakeFunction(node as AstDef); } else if (node is AstMacro) { MetaCat.AddMacro(node as AstMacro); } else { throw new Exception("unable to convert node to function: " + node.ToString()); } } return result; } public void Execute(List<CatAstNode> nodes) { Execute(NodesToFxns("self", nodes)); } public void ClearTo(int n) { while (Count() > n) Pop(); } public CatList GetStackAsList() { return new CatList(stack); } #region dictionary management public void RegisterType(Type t) { foreach (Type memberType in t.GetNestedTypes()) { // Is is it a function object if (typeof(Function).IsAssignableFrom(memberType)) { ConstructorInfo ci = memberType.GetConstructor(new Type[] { }); Object o = ci.Invoke(null); if (!(o is Function)) throw new Exception("Expected only function objects in " + t.ToString()); Function f = o as Function; AddFunction(f); } else { RegisterType(memberType); } } foreach (MemberInfo mi in t.GetMembers()) { if (mi is MethodInfo) { MethodInfo meth = mi as MethodInfo; if (meth.IsStatic) { Function f = AddMethod(null, meth); if (f != null) f.msTags = "level2"; } } } } /// <summary> /// Creates an ObjectBoundMethod for each public function in the object /// </summary> /// <param name="o"></param> public void RegisterObject(Object o) { foreach (MemberInfo mi in o.GetType().GetMembers()) { if (mi is MethodInfo) { MethodInfo meth = mi as MethodInfo; AddMethod(o, meth); } } } #region INameLookup implementation public Function Lookup(string s) { if (s.Length < 1) throw new Exception("trying to lookup a function with no name"); if (dictionary.ContainsKey(s)) return dictionary[s]; if (otherNames != null) return otherNames.Lookup(s); return null; } public Function ThrowingLookup(string s) { Function f = Lookup(s); if (f == null) throw new Exception("could not find function " + s); return f; } #endregion /// <summary> /// Methods allow overloading of function definitions. /// </summary> public Function AddMethod(Object o, MethodInfo mi) { // Does not add public methods. if (!mi.IsPublic) return null; if (mi.IsStatic) o = null; Method f = new Method(o, mi); AddFunction(f); return f; } public List<Function> GetAllFunctions() { List<Function> fxns = new List<Function>(dictionary.Values); fxns.Sort(delegate(Function x, Function y) { return x.GetName().CompareTo(y.GetName()); }); return fxns; } public Dictionary<string, List<Function>> GetFunctionsByTag() { Dictionary<string, List<Function> > ret = new Dictionary<string, List<Function>>(); foreach (Function f in GetAllFunctions()) { foreach (string s in f.GetTags()) { string s2 = s.Trim(); if (s.Length > 0) { if (!ret.ContainsKey(s2)) ret.Add(s2, new List<Function>()); ret[s2].Add(f); } } } return ret; } public bool TestFunction(Function f) { bool bRet = true; testCount += 1; CatMetaDataBlock md = f.GetMetaData(); if (md != null) { List<CatMetaData> tests = md.FindAll("test"); foreach (CatMetaData test in tests) { CatMetaData input = test.Find("in"); CatMetaData output = test.Find("out"); if (input == null || output == null) { Output.WriteLine("ill-formed test in " + f.GetName()); return false; } try { Executor aux = new Executor(this); aux.Execute(input.GetContent()); CatList listInput = aux.GetStackAsList(); aux.Clear(); aux.Execute(output.GetContent()); CatList listOutput = aux.GetStackAsList(); aux.Clear(); if (!listInput.Equals(listOutput)) { Output.WriteLine("failed test for instruction " + f.GetName()); Output.WriteLine("test input program = " + input.GetContent()); Output.WriteLine("test output program = " + output.GetContent()); Output.WriteLine("input program result = " + listInput.ToString()); Output.WriteLine("output program result = " + listOutput.ToString()); bRet = false; } } catch (Exception e) { Output.WriteLine("failed test for instruction " + f.GetName()); Output.WriteLine("exception occured: " + e.Message); bRet = false; } } } return bRet; } public Function MakeFunction(AstDef def) { bool bLambda = def.mParams.Count > 0; if (bLambda) CatLambdaConverter.Convert(def); CatExpr fxns = NodesToFxns(def.mName, def.mTerms); Function ret = new DefinedFunction(def.mName, fxns); if (def.mpMetaData != null) { ret.SetMetaData(new CatMetaDataBlock(def.mpMetaData)); } if (bLambda && Config.gbOptimizeLambdas) MetaCat.ApplyMacros(this, fxns); AddFunction(ret); return ret; } public Function AddFunction(Function f) { string s = f.GetName(); if (dictionary.ContainsKey(s)) { if (!Config.gbAllowRedefines) throw new Exception("can not overload functions " + s); dictionary[s] = f; } else { dictionary.Add(s, f); } return f; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Specialized.Tests { public static class StringCollectionTests { private const string ElementNotPresent = "element-not-present"; /// <summary> /// Data used for testing with Insert. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. data to insert (ElementNotPresent or null) /// 4. location to insert (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> Insert_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); foreach (string element in new[] { ElementNotPresent, null }) { foreach (int location in new[] { 0, d.Length / 2, d.Length }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, element, location }; } } } }/// <summary> /// Data used for testing with RemoveAt. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. location to remove (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> RemoveAt_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); if (d.Length > 0) { foreach (int location in new[] { 0, d.Length / 2, d.Length - 1 }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, location }; } } } } /// <summary> /// Data used for testing with a set of collections. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Data() { yield return ConstructRow(new string[] { /* empty */ }); yield return ConstructRow(new string[] { null }); yield return ConstructRow(new string[] { "single" }); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x.ToString()).ToArray()); for (int index = 0; index < 100; index += 25) { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x == index ? null : x.ToString()).ToArray()); } } /// <summary> /// Data used for testing with a set of collections, where the data has duplicates. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Duplicates_Data() { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (string)null).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x % 10 == 0 ? null : (x % 10).ToString()).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (x % 10).ToString()).ToArray()); } private static object[] ConstructRow(string[] data) { if (data.Contains(ElementNotPresent)) throw new ArgumentException("Do not include \"" + ElementNotPresent + "\" in data."); StringCollection col = new StringCollection(); col.AddRange(data); return new object[] { col, data }; } [Fact] public static void Constructor_DefaultTest() { StringCollection sc = new StringCollection(); Assert.Equal(0, sc.Count); Assert.False(sc.Contains(null)); Assert.False(sc.Contains("")); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data) { IList added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddRangeTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); added.AddRange(data); Assert.Equal(collection, added); added.AddRange(new string[] { /*empty*/}); Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddRange_NullTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>("value", () => collection.AddRange(null)); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void ClearTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyToTest(StringCollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyTo_ExplicitInterface_Test(ICollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[data.Length - 1], 0)); } // As explicit interface implementation Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0)); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CountTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); collection.Add("one"); Assert.Equal(1, collection.Count); collection.AddRange(data); Assert.Equal(1 + data.Length, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void ContainsTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.True(collection.Contains(element))); Assert.All(data, element => Assert.True(((IList)collection).Contains(element))); Assert.False(collection.Contains(ElementNotPresent)); Assert.False(((IList)collection).Contains(ElementNotPresent)); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetEnumeratorTest(StringCollection collection, string[] data) { bool repeat = true; StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); while (repeat) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); foreach (string element in data) { Assert.True(enumerator.MoveNext()); Assert.Equal(element, enumerator.Current); Assert.Equal(element, enumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator.Reset(); enumerator.Reset(); repeat = false; } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data) { StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); if (data.Length > 0) { Assert.True(enumerator.MoveNext()); string current = enumerator.Current; Assert.Equal(data[0], current); collection.RemoveAt(0); if (data.Length > 1 && data[0] != data[1]) { Assert.NotEqual(current, collection[0]); } Assert.Equal(current, enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { collection.Add("newValue"); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSetTest(StringCollection collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { string temp = collection[i]; collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSet_ExplicitInterface_Test(IList collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { object temp = collection[i]; if (temp != null) { Assert.IsType<string>(temp); } collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSet_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length]); // As explicitly implementing the interface Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length]); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void IndexOfTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void IndexOf_DuplicateTest(StringCollection collection, string[] data) { // Only the index of the first element will be returned. data = data.Distinct().ToArray(); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData(nameof(Insert_Data))] public static void InsertTest(StringCollection collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData(nameof(Insert_Data))] public static void Insert_ExplicitInterface_Test(IList collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Insert_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(data.Length + 1, ElementNotPresent)); // And as explicit interface implementation Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(data.Length + 1, ElementNotPresent)); } [Fact] public static void IsFixedSizeTest() { Assert.False(((IList)new StringCollection()).IsFixedSize); } [Fact] public static void IsReadOnlyTest() { Assert.False(new StringCollection().IsReadOnly); Assert.False(((IList)new StringCollection()).IsReadOnly); } [Fact] public static void IsSynchronizedTest() { Assert.False(new StringCollection().IsSynchronized); Assert.False(((IList)new StringCollection()).IsSynchronized); } [Theory] [MemberData(nameof(StringCollection_Data))] public static void RemoveTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] public static void Remove_IListTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_NotPresentTest(StringCollection collection, string[] data) { collection.Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); ((IList)collection).Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_DuplicateTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(RemoveAt_Data))] public static void RemoveAtTest(StringCollection collection, string[] data, int location) { collection.RemoveAt(location); Assert.Equal(data.Length - 1, collection.Count); for (int i = 0; i < data.Length - 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i >= location) { Assert.Equal(data[i + 1], collection[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void RemoveAt_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(data.Length)); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void SyncRootTest(StringCollection collection, string[] data) { object syncRoot = collection.SyncRoot; Assert.NotNull(syncRoot); Assert.IsType<object>(syncRoot); Assert.Same(syncRoot, collection.SyncRoot); Assert.NotSame(syncRoot, new StringCollection().SyncRoot); StringCollection other = new StringCollection(); other.AddRange(data); Assert.NotSame(syncRoot, other.SyncRoot); } } }
// // 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.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql { /// <summary> /// Contains operations for getting Azure SQL Databases that can be /// recovered. /// </summary> internal partial class RecoverableDatabaseOperations : IServiceOperations<SqlManagementClient>, Microsoft.WindowsAzure.Management.Sql.IRecoverableDatabaseOperations { /// <summary> /// Initializes a new instance of the RecoverableDatabaseOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RecoverableDatabaseOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Returns information about a recoverable Azure SQL Database. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database was hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the recoverable Azure SQL Database to be /// obtained. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response to the Get Recoverable Database request. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.RecoverableDatabaseGetResponse> GetAsync(string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/recoverabledatabases/" + databaseName.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result RecoverableDatabaseGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RecoverableDatabaseGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourceElement = responseDoc.Element(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure")); if (serviceResourceElement != null) { RecoverableDatabase serviceResourceInstance = new RecoverableDatabase(); result.Database = serviceResourceInstance; XElement entityIdElement = serviceResourceElement.Element(XName.Get("EntityId", "http://schemas.microsoft.com/windowsazure")); if (entityIdElement != null) { string entityIdInstance = entityIdElement.Value; serviceResourceInstance.EntityId = entityIdInstance; } XElement serverNameElement = serviceResourceElement.Element(XName.Get("ServerName", "http://schemas.microsoft.com/windowsazure")); if (serverNameElement != null) { string serverNameInstance = serverNameElement.Value; serviceResourceInstance.ServerName = serverNameInstance; } XElement editionElement = serviceResourceElement.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure")); if (editionElement != null) { string editionInstance = editionElement.Value; serviceResourceInstance.Edition = editionInstance; } XElement lastAvailableBackupDateElement = serviceResourceElement.Element(XName.Get("LastAvailableBackupDate", "http://schemas.microsoft.com/windowsazure")); if (lastAvailableBackupDateElement != null) { DateTime lastAvailableBackupDateInstance = DateTime.Parse(lastAvailableBackupDateElement.Value, CultureInfo.InvariantCulture); serviceResourceInstance.LastAvailableBackupDate = lastAvailableBackupDateInstance; } XElement nameElement = serviceResourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourceElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns a collection of databases that can be recovered from a /// specified server. /// </summary> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// databases were hosted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Contains the response to the List Recoverable Databases request. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Sql.Models.RecoverableDatabaseListResponse> ListAsync(string serverName, CancellationToken cancellationToken) { // Validate if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serverName", serverName); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/sqlservers/servers/" + serverName.Trim() + "/recoverabledatabases?contentview=generic"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2012-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result RecoverableDatabaseListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RecoverableDatabaseListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement serviceResourcesSequenceElement = responseDoc.Element(XName.Get("ServiceResources", "http://schemas.microsoft.com/windowsazure")); if (serviceResourcesSequenceElement != null) { foreach (XElement serviceResourcesElement in serviceResourcesSequenceElement.Elements(XName.Get("ServiceResource", "http://schemas.microsoft.com/windowsazure"))) { RecoverableDatabase serviceResourceInstance = new RecoverableDatabase(); result.Databases.Add(serviceResourceInstance); XElement entityIdElement = serviceResourcesElement.Element(XName.Get("EntityId", "http://schemas.microsoft.com/windowsazure")); if (entityIdElement != null) { string entityIdInstance = entityIdElement.Value; serviceResourceInstance.EntityId = entityIdInstance; } XElement serverNameElement = serviceResourcesElement.Element(XName.Get("ServerName", "http://schemas.microsoft.com/windowsazure")); if (serverNameElement != null) { string serverNameInstance = serverNameElement.Value; serviceResourceInstance.ServerName = serverNameInstance; } XElement editionElement = serviceResourcesElement.Element(XName.Get("Edition", "http://schemas.microsoft.com/windowsazure")); if (editionElement != null) { string editionInstance = editionElement.Value; serviceResourceInstance.Edition = editionInstance; } XElement lastAvailableBackupDateElement = serviceResourcesElement.Element(XName.Get("LastAvailableBackupDate", "http://schemas.microsoft.com/windowsazure")); if (lastAvailableBackupDateElement != null) { DateTime lastAvailableBackupDateInstance = DateTime.Parse(lastAvailableBackupDateElement.Value, CultureInfo.InvariantCulture); serviceResourceInstance.LastAvailableBackupDate = lastAvailableBackupDateInstance; } XElement nameElement = serviceResourcesElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; serviceResourceInstance.Name = nameInstance; } XElement typeElement = serviceResourcesElement.Element(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); if (typeElement != null) { string typeInstance = typeElement.Value; serviceResourceInstance.Type = typeInstance; } XElement stateElement = serviceResourcesElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; serviceResourceInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Runtime.InteropServices; using VsChromium.Commands; using VsChromium.Core.Files; using VsChromium.Core.Ipc; using VsChromium.Core.Ipc.TypedMessages; using VsChromium.Core.Logging; using VsChromium.Core.Utility; using VsChromium.Features.IndexServerInfo; using VsChromium.Package; using VsChromium.Package.CommandHandler; using VsChromium.ServerProxy; using VsChromium.Settings; using VsChromium.Threads; using VsChromium.Views; namespace VsChromium.Features.SourceExplorerHierarchy { public class SourceExplorerHierarchyController : ISourceExplorerHierarchyController { private readonly ISynchronizationContextProvider _synchronizationContextProvider; private readonly IFileSystemTreeSource _fileSystemTreeSource; private readonly IVisualStudioPackageProvider _visualStudioPackageProvider; private readonly IImageSourceFactory _imageSourceFactory; private readonly IOpenDocumentHelper _openDocumentHelper; private readonly IFileSystem _fileSystem; private readonly IClipboard _clipboard; private readonly IWindowsExplorer _windowsExplorer; private readonly IDispatchThreadServerRequestExecutor _dispatchThreadServerRequestExecutor; private readonly IDispatchThreadEventBus _eventBus; private readonly IGlobalSettingsProvider _globalSettingsProvider; private readonly IDelayedOperationExecutor _delayedOperationExecutor; private readonly IShowServerInfoService _showServerInfoService; private readonly VsHierarchyAggregate _hierarchy; private readonly NodeTemplateFactory _nodeTemplateFactory; private readonly NodeViewModelLoader _nodeViewModelLoader; /// <summary> /// Keeps track of the latest file system tree version received from the /// server, so that we can ensure only the latest update wins in case of /// concurrent updates. /// </summary> private int _latestFileSystemTreeVersion; public SourceExplorerHierarchyController( ISynchronizationContextProvider synchronizationContextProvider, IFileSystemTreeSource fileSystemTreeSource, IVisualStudioPackageProvider visualStudioPackageProvider, IVsGlyphService vsGlyphService, IImageSourceFactory imageSourceFactory, IOpenDocumentHelper openDocumentHelper, IFileSystem fileSystem, IClipboard clipboard, IWindowsExplorer windowsExplorer, IDispatchThreadServerRequestExecutor dispatchThreadServerRequestExecutor, ITypedRequestProcessProxy typedRequestProcessProxy, IDispatchThreadEventBus eventBus, IGlobalSettingsProvider globalSettingsProvider, IDelayedOperationExecutor delayedOperationExecutor, IDispatchThread dispatchThread, IShowServerInfoService showServerInfoService) { _synchronizationContextProvider = synchronizationContextProvider; _fileSystemTreeSource = fileSystemTreeSource; _visualStudioPackageProvider = visualStudioPackageProvider; _imageSourceFactory = imageSourceFactory; _openDocumentHelper = openDocumentHelper; _fileSystem = fileSystem; _clipboard = clipboard; _windowsExplorer = windowsExplorer; _dispatchThreadServerRequestExecutor = dispatchThreadServerRequestExecutor; _eventBus = eventBus; _globalSettingsProvider = globalSettingsProvider; _delayedOperationExecutor = delayedOperationExecutor; _showServerInfoService = showServerInfoService; _nodeTemplateFactory = new NodeTemplateFactory(vsGlyphService, imageSourceFactory); _nodeViewModelLoader = new NodeViewModelLoader(typedRequestProcessProxy); _hierarchy = new VsHierarchyAggregate( visualStudioPackageProvider.Package.ServiceProvider, vsGlyphService, _imageSourceFactory, _nodeTemplateFactory, _nodeViewModelLoader, dispatchThread); } public void Activate() { IVsSolutionEventsHandler vsSolutionEvents = new VsSolutionEventsHandler(_visualStudioPackageProvider); vsSolutionEvents.AfterOpenSolution += AfterOpenSolutionHandler; vsSolutionEvents.BeforeCloseSolution += BeforeCloseSolutionHandler; _fileSystemTreeSource.TreeReceived += OnTreeReceived; _fileSystemTreeSource.ErrorReceived += OnErrorReceived; var mcs = _visualStudioPackageProvider.Package.OleMenuCommandService; if (mcs != null) { var cmd = new SimplePackageCommandHandler( new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidSyncWithActiveDocument), enabled: () => !_hierarchy.IsEmpty, visible: () => _globalSettingsProvider.GlobalSettings.EnableSourceExplorerHierarchy && !_hierarchy.IsEmpty, execute: (s, e) => SyncToActiveDocument()); mcs.AddCommand(cmd.ToOleMenuCommand()); } RegisterHierarchyCommands(_hierarchy); _nodeTemplateFactory.Activate(); _eventBus.RegisterHandler(EventNames.SolutionExplorer.ShowFile, ShowInSolutionExplorerHandler); _globalSettingsProvider.GlobalSettings.PropertyChanged += GlobalSettingsOnPropertyChanged; SynchronizeHierarchy(); } private void RegisterHierarchyCommands(IVsHierarchyImpl hierarchy) { hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(VSConstants.GUID_VsUIHierarchyWindowCmds, (int)VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_DoubleClick), IsEnabled = node => node is FileNodeViewModel, Execute = args => OpenDocument(args.Hierarchy, args.Node) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(VSConstants.GUID_VsUIHierarchyWindowCmds, (int)VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_EnterKey), IsEnabled = node => node is FileNodeViewModel, Execute = args => OpenDocument(args.Hierarchy, args.Node) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(VSConstants.GUID_VsUIHierarchyWindowCmds, (int)VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_RightClick), IsEnabled = node => true, Execute = args => ShowContextMenu(args.Node, args.VariantIn) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.Open), IsEnabled = node => node is FileNodeViewModel, Execute = args => OpenDocument(args.Hierarchy, args.Node) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.OpenWith), IsEnabled = node => node is FileNodeViewModel, Execute = args => OpenDocument(args.Hierarchy, args.Node, openWith: true) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(VSConstants.VSStd2K, (int)VSConstants.VSStd2KCmdID.SLNREFRESH), IsEnabled = node => true, Execute = args => RefreshFileSystemTree() }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyFullPath), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => _clipboard.SetText(args.Node.FullPathString) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyFullPathPosix), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => _clipboard.SetText(PathHelpers.ToPosix(args.Node.FullPathString)) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyRelativePath), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => _clipboard.SetText(args.Node.RelativePath) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyRelativePathPosix), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => _clipboard.SetText(PathHelpers.ToPosix(args.Node.RelativePath)) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidOpenFolderInExplorer), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => _windowsExplorer.OpenFolder(args.Node.FullPathString) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidShowProjectIndexDetails), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => ShowProjectIndexDetails(args.Node.FullPathString) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidShowDirectoryIndexDetails), IsEnabled = node => node is DirectoryNodeViewModel, Execute = args => ShowDirectoryIndexDetails(args.Node.FullPathString) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyFileFullPath), IsEnabled = node => node is FileNodeViewModel, Execute = args => _clipboard.SetText(args.Node.FullPathString) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyFileFullPathPosix), IsEnabled = node => node is FileNodeViewModel, Execute = args => _clipboard.SetText(PathHelpers.ToPosix(args.Node.FullPathString)) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyFileRelativePath), IsEnabled = node => node is FileNodeViewModel, Execute = args => _clipboard.SetText(args.Node.RelativePath) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidCopyFileRelativePathPosix), IsEnabled = node => node is FileNodeViewModel, Execute = args => _clipboard.SetText(PathHelpers.ToPosix(args.Node.RelativePath)) }); hierarchy.AddCommandHandler(new VsHierarchyCommandHandler { CommandId = new CommandID(GuidList.GuidVsChromiumCmdSet, (int)PkgCmdIdList.CmdidOpenContainingFolder), IsEnabled = node => node is FileNodeViewModel, Execute = args => _windowsExplorer.OpenContainingFolder(args.Node.FullPathString) }); } private void GlobalSettingsOnPropertyChanged(object sender, PropertyChangedEventArgs args) { var name = args.PropertyName; var model = (GlobalSettings)sender; if (name == ReflectionUtils.GetPropertyName(model, x => x.EnableSourceExplorerHierarchy)) { SynchronizeHierarchy(); } } private void SynchronizeHierarchy() { // Force getting the tree and refreshing the ui hierarchy. if (_globalSettingsProvider.GlobalSettings.EnableSourceExplorerHierarchy) { _fileSystemTreeSource.Fetch(); } else { _hierarchy.Disable(); } } private void ShowInSolutionExplorerHandler(object sender, EventArgs eventArgs) { ShowInSolutionExplorer(((FilePathEventArgs)eventArgs).FilePath); } private void RefreshFileSystemTree() { var uiRequest = new DispatchThreadServerRequest { Request = new RefreshFileSystemTreeRequest(), Id = "RefreshFileSystemTreeRequest", Delay = TimeSpan.FromSeconds(0.0), }; _dispatchThreadServerRequestExecutor.Post(uiRequest); } private void ShowProjectIndexDetails(string path) { _showServerInfoService.ShowProjectIndexDetailsDialog(path); } private void ShowDirectoryIndexDetails(string path) { _showServerInfoService.ShowDirectoryIndexDetailsDialog(path); } private void ShowContextMenu(NodeViewModel node, IntPtr variantIn) { // See https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.vsconstants.vsuihierarchywindowcmdids.aspx // // The UIHWCMDID_RightClick command is what tells the interface // IVsUIHierarchy in a IVsUIHierarchyWindow to display the context menu. // Since the mouse position may change between the mouse down and the // mouse up events and the right click command might even originate from // the keyboard Visual Studio provides the proper menu position into // pvaIn by performing a memory copy operation on a POINTS structure // into the VT_UI4 part of the pvaIn variant. // // To show the menu use the derived POINTS as the coordinates to show // the context menu, calling ShowContextMenu. To ensure proper command // handling you should pass a NULL command target into ShowContextMenu // menu so that the IVsUIHierarchyWindow will have the first chance to // handle commands like delete. object variant = Marshal.GetObjectForNativeVariant(variantIn); var pointsAsUint = (UInt32)variant; var x = (short)(pointsAsUint & 0xffff); var y = (short)(pointsAsUint >> 16); var points = new POINTS(); points.x = x; points.y = y; var shell = _visualStudioPackageProvider.Package.ServiceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell; if (shell == null) { Logger.LogError("Error accessing IVsUIShell service."); return; } var pointsIn = new POINTS[1]; pointsIn[0].x = points.x; pointsIn[0].y = points.y; var groupGuid = VsMenus.guidSHLMainMenu; var menuId = (node.IsRoot) ? VsMenus.IDM_VS_CTXT_PROJNODE : (node is DirectoryNodeViewModel) ? VsMenus.IDM_VS_CTXT_FOLDERNODE : VsMenus.IDM_VS_CTXT_ITEMNODE; int hresult = shell.ShowContextMenu(0, ref groupGuid, menuId, pointsIn, null); if (!ErrorHandler.Succeeded(hresult)) { Logger.LogHResult(hresult, "Error showing context menu."); } } private void OpenDocument(VsHierarchy hierarchy, NodeViewModel node, bool openWith = false) { Logger.WrapActionInvocation( () => { if (!_fileSystem.FileExists(new FullPath(node.FullPathString))) return; if (openWith) _openDocumentHelper.OpenDocumentWith(node.FullPathString, hierarchy, node.ItemId, view => null); else _openDocumentHelper.OpenDocument(node.FullPathString, view => null); }); } private void SyncToActiveDocument() { Logger.WrapActionInvocation( () => { var dte = _visualStudioPackageProvider.Package.DTE; var document = dte.ActiveDocument; if (document == null) return; ShowInSolutionExplorer(document.FullName); }); } private void ShowInSolutionExplorer(string path) { if (!PathHelpers.IsAbsolutePath(path)) return; if (!PathHelpers.IsValidBclPath(path)) return; _hierarchy.SelectNodeByFilePath(path); } /// <summary> /// Note: This is executed on the UI thread. /// </summary> private void AfterOpenSolutionHandler() { _hierarchy.Reconnect(); } /// <summary> /// Note: This is executed on the UI thread. /// </summary> private void BeforeCloseSolutionHandler() { _hierarchy.Disconnect(); } /// <summary> /// Note: This is executed on a background thred. /// </summary> private void OnTreeReceived(FileSystemTree fileSystemTree) { if (!_globalSettingsProvider.GlobalSettings.EnableSourceExplorerHierarchy) return; _latestFileSystemTreeVersion = fileSystemTree.Version; PostApplyFileSystemTreeToVsHierarchy(fileSystemTree); } private void PostApplyFileSystemTreeToVsHierarchy(FileSystemTree fileSystemTree) { _delayedOperationExecutor.Post( new DelayedOperation { Id = "ApplyFileSystemTreeToVsHierarchy", Action = () => ApplyFileSystemTreeToVsHierarchy(fileSystemTree), Delay = TimeSpan.FromSeconds(0.1), }); } private void ApplyFileSystemTreeToVsHierarchy(FileSystemTree fileSystemTree) { var builder = CreateIncrementalBuilder(fileSystemTree); var applyChanges = builder.ComputeChangeApplier(); _synchronizationContextProvider.DispatchThreadContext.Post(() => { var result = applyChanges(_latestFileSystemTreeVersion); if (result == ApplyChangesResult.Retry) { PostApplyFileSystemTreeToVsHierarchy(fileSystemTree); } }); } private IIncrementalHierarchyBuilder CreateIncrementalBuilder(FileSystemTree fileSystemTree) { return new IncrementalHierarchyBuilderAggregate( _nodeTemplateFactory, _hierarchy, fileSystemTree, _nodeViewModelLoader, _imageSourceFactory); } private void OnErrorReceived(ErrorResponse errorResponse) { // TODO(rpaquay) } } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Security; using NUnit.Options; namespace NUnit.Common { /// <summary> /// CommandLineOptions is the base class the specific option classes /// used for nunit3-console and nunitlite. It encapsulates all common /// settings and features of both. This is done to ensure that common /// features remain common and for the convenience of having the code /// in a common location. The class inherits from the Mono /// Options OptionSet class and provides a central location /// for defining and parsing options. /// </summary> public class CommandLineOptions : OptionSet { private static readonly string DEFAULT_WORK_DIRECTORY = GetDefaultWorkDirectory(); private bool validated; #if !PORTABLE private bool noresult; #endif #region Constructor internal CommandLineOptions(IDefaultOptionsProvider defaultOptionsProvider, params string[] args) { // Apply default options if (defaultOptionsProvider == null) throw new ArgumentNullException("defaultOptionsProvider"); TeamCity = defaultOptionsProvider.TeamCity; ConfigureOptions(); if (args != null) Parse(args); } public CommandLineOptions(params string[] args) { ConfigureOptions(); if (args != null) Parse(args); } private static string GetDefaultWorkDirectory() { try { return GetDefaultWorkDirectoryCore(); } catch ( SecurityException ) { // For restricted Silverlight environment. return null; } } [MethodImpl(MethodImplOptions.NoInlining)] private static string GetDefaultWorkDirectoryCore() { #if NETCF || PORTABLE return @"\My Documents"; #elif SILVERLIGHT return Environment.GetFolderPath(Environment.SpecialFolder.Personal); #else return Environment.CurrentDirectory; #endif } #endregion #region Properties // Action to Perform public bool Explore { get; private set; } public bool ShowHelp { get; private set; } public bool ShowVersion { get; private set; } // Select tests private List<string> inputFiles = new List<string>(); public IList<string> InputFiles { get { return inputFiles; } } private List<string> testList = new List<string>(); public IList<string> TestList { get { return testList; } } public string TestParameters { get; private set; } public string WhereClause { get; private set; } public bool WhereClauseSpecified { get { return WhereClause != null; } } private int defaultTimeout = -1; public int DefaultTimeout { get { return defaultTimeout; } } public bool DefaultTimeoutSpecified { get { return defaultTimeout >= 0; } } private int randomSeed = -1; public int RandomSeed { get { return randomSeed; } } public bool RandomSeedSpecified { get { return randomSeed >= 0; } } public string DefaultTestNamePattern { get; private set; } private int numWorkers = -1; public int NumberOfTestWorkers { get { return numWorkers; } } public bool NumberOfTestWorkersSpecified { get { return numWorkers >= 0; } } public bool StopOnError { get; private set; } public bool WaitBeforeExit { get; private set; } // Output Control public bool NoHeader { get; private set; } public bool NoColor { get; private set; } public bool Verbose { get; private set; } public bool TeamCity { get; private set; } public string OutFile { get; private set; } public bool OutFileSpecified { get { return OutFile != null; } } public string ErrFile { get; private set; } public bool ErrFileSpecified { get { return ErrFile != null; } } public string DisplayTestLabels { get; private set; } #if !PORTABLE private string workDirectory = null; public string WorkDirectory { get { return workDirectory ?? DEFAULT_WORK_DIRECTORY; } } public bool WorkDirectorySpecified { get { return workDirectory != null; } } #endif public string InternalTraceLevel { get; private set; } public bool InternalTraceLevelSpecified { get { return InternalTraceLevel != null; } } /// <summary>Indicates whether a full report should be displayed.</summary> public bool Full { get; private set; } #if !PORTABLE private List<OutputSpecification> resultOutputSpecifications = new List<OutputSpecification>(); public IList<OutputSpecification> ResultOutputSpecifications { get { if (noresult) return new OutputSpecification[0]; if (resultOutputSpecifications.Count == 0) resultOutputSpecifications.Add(new OutputSpecification("TestResult.xml")); return resultOutputSpecifications; } } private List<OutputSpecification> exploreOutputSpecifications = new List<OutputSpecification>(); public IList<OutputSpecification> ExploreOutputSpecifications { get { return exploreOutputSpecifications; } } #endif // Error Processing public List<string> errorMessages = new List<string>(); public IList<string> ErrorMessages { get { return errorMessages; } } #endregion #region Public Methods public bool Validate() { if (!validated) { CheckOptionCombinations(); validated = true; } return ErrorMessages.Count == 0; } #endregion #region Helper Methods protected virtual void CheckOptionCombinations() { } /// <summary> /// Case is ignored when val is compared to validValues. When a match is found, the /// returned value will be in the canonical case from validValues. /// </summary> protected string RequiredValue(string val, string option, params string[] validValues) { if (string.IsNullOrEmpty(val)) ErrorMessages.Add("Missing required value for option '" + option + "'."); bool isValid = true; if (validValues != null && validValues.Length > 0) { isValid = false; foreach (string valid in validValues) if (string.Compare(valid, val, StringComparison.OrdinalIgnoreCase) == 0) return valid; } if (!isValid) ErrorMessages.Add(string.Format("The value '{0}' is not valid for option '{1}'.", val, option)); return val; } protected int RequiredInt(string val, string option) { // We have to return something even though the value will // be ignored if an error is reported. The -1 value seems // like a safe bet in case it isn't ignored due to a bug. int result = -1; if (string.IsNullOrEmpty(val)) ErrorMessages.Add("Missing required value for option '" + option + "'."); else { // NOTE: Don't replace this with TryParse or you'll break the CF build! try { result = int.Parse(val); } catch (Exception) { ErrorMessages.Add("An int value was expected for option '{0}' but a value of '{1}' was used"); } } return result; } private string ExpandToFullPath(string path) { if (path == null) return null; #if NETCF || PORTABLE return Path.Combine(DEFAULT_WORK_DIRECTORY , path); #else return Path.GetFullPath(path); #endif } protected virtual void ConfigureOptions() { // NOTE: The order in which patterns are added // determines the display order for the help. // Select Tests this.Add("test=", "Comma-separated list of {NAMES} of tests to run or explore. This option may be repeated.", v => ((List<string>)TestList).AddRange(TestNameParser.Parse(RequiredValue(v, "--test")))); #if !PORTABLE this.Add("testlist=", "File {PATH} containing a list of tests to run, one per line. This option may be repeated.", v => { string testListFile = RequiredValue(v, "--testlist"); var fullTestListPath = ExpandToFullPath(testListFile); if (!File.Exists(fullTestListPath)) ErrorMessages.Add("Unable to locate file: " + testListFile); else { try { using (var rdr = new StreamReader(fullTestListPath)) { while (!rdr.EndOfStream) { var line = rdr.ReadLine().Trim(); if (!string.IsNullOrEmpty(line) && line[0] != '#') ((List<string>)TestList).Add(line); } } } catch (IOException) { ErrorMessages.Add("Unable to read file: " + testListFile); } } }); #endif this.Add("where=", "Test selection {EXPRESSION} indicating what tests will be run. See description below.", v => WhereClause = RequiredValue(v, "--where")); this.Add("params|p=", "Define a test parameter.", v => { string parameters = RequiredValue( v, "--params"); foreach (string param in parameters.Split(new[] { ';' })) { if (!param.Contains("=")) ErrorMessages.Add("Invalid format for test parameter. Use NAME=VALUE."); } if (TestParameters == null) TestParameters = parameters; else TestParameters += ";" + parameters; }); this.Add("timeout=", "Set timeout for each test case in {MILLISECONDS}.", v => defaultTimeout = RequiredInt(v, "--timeout")); this.Add("seed=", "Set the random {SEED} used to generate test cases.", v => randomSeed = RequiredInt(v, "--seed")); #if !PORTABLE this.Add("workers=", "Specify the {NUMBER} of worker threads to be used in running tests. If not specified, defaults to 2 or the number of processors, whichever is greater.", v => numWorkers = RequiredInt(v, "--workers")); #endif this.Add("stoponerror", "Stop run immediately upon any test failure or error.", v => StopOnError = v != null); this.Add("wait", "Wait for input before closing console window.", v => WaitBeforeExit = v != null); #if !PORTABLE // Output Control this.Add("work=", "{PATH} of the directory to use for output files. If not specified, defaults to the current directory.", v => workDirectory = RequiredValue(v, "--work")); this.Add("output|out=", "File {PATH} to contain text output from the tests.", v => OutFile = RequiredValue(v, "--output")); this.Add("err=", "File {PATH} to contain error output from the tests.", v => ErrFile = RequiredValue(v, "--err")); this.Add("full", "Prints full report of all test results.", v => Full = v != null); this.Add("result=", "An output {SPEC} for saving the test results.\nThis option may be repeated.", v => resultOutputSpecifications.Add(new OutputSpecification(RequiredValue(v, "--resultxml")))); this.Add("explore:", "Display or save test info rather than running tests. Optionally provide an output {SPEC} for saving the test info. This option may be repeated.", v => { Explore = true; if (v != null) ExploreOutputSpecifications.Add(new OutputSpecification(v)); }); this.Add("noresult", "Don't save any test results.", v => noresult = v != null); #endif this.Add("labels=", "Specify whether to write test case names to the output. Values: Off, On, All", v => DisplayTestLabels = RequiredValue(v, "--labels", "Off", "On", "All")); this.Add("test-name-format=", "Non-standard naming pattern to use in generating test names.", v => DefaultTestNamePattern = RequiredValue(v, "--test-name-format")); #if !NETCF this.Add("teamcity", "Turns on use of TeamCity service messages.", v => TeamCity = v != null); #endif #if !PORTABLE this.Add("trace=", "Set internal trace {LEVEL}.\nValues: Off, Error, Warning, Info, Verbose (Debug)", v => InternalTraceLevel = RequiredValue(v, "--trace", "Off", "Error", "Warning", "Info", "Verbose", "Debug")); this.Add("noheader|noh", "Suppress display of program information at start of run.", v => NoHeader = v != null); this.Add("nocolor|noc", "Displays console output without color.", v => NoColor = v != null); #endif this.Add("verbose|v", "Display additional information as the test runs.", v => Verbose = v != null); this.Add("help|h", "Display this message and exit.", v => ShowHelp = v != null); this.Add("version|V", "Display the header and exit.", v => ShowVersion = v != null); // Default this.Add("<>", v => { #if PORTABLE if (v.StartsWith("-") || v.StartsWith("/") && Environment.NewLine == "\r\n") #else if (v.StartsWith("-") || v.StartsWith("/") && Path.DirectorySeparatorChar != '/') #endif ErrorMessages.Add("Invalid argument: " + v); else InputFiles.Add(v); }); } #endregion } }
#region Imported Types using DeviceSQL.Device.ROC.Data; using DeviceSQL.Devices.Device.ROC.Data; using Microsoft.SqlServer.Server; using System; using System.Data.SqlTypes; using System.IO; using System.Linq; #endregion namespace DeviceSQL.SQLTypes.ROCMaster { [Serializable()] [SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 29)] public struct ROCMaster_AuditLogRecord : INullable, IBinarySerialize { #region Fields private byte[] data; #endregion #region Properties public bool IsNull { get; internal set; } public static ROCMaster_AuditLogRecord Null { get { return new ROCMaster_AuditLogRecord() { IsNull = true }; } } public byte[] Data { get { if (data == null) { data = new byte[24]; } return data; } internal set { data = value; } } public SqlDateTime DateTimeStamp { get { var dateTimeStamp = new AuditLogRecord(Convert.ToUInt16(Index), Data).DateTimeStamp; return dateTimeStamp.HasValue ? dateTimeStamp.Value : SqlDateTime.Null; } } public int Index { get; internal set; } public SqlByte FstNumber { get { var fstNumber = new AuditLogRecord(Convert.ToUInt16(Index), Data).FstNumber; return fstNumber.HasValue ? fstNumber.Value : SqlByte.Null; } } public SqlByte PointType { get { var pointType = new AuditLogRecord(Convert.ToUInt16(Index), Data).PointType; return pointType.HasValue ? pointType.Value : SqlByte.Null; } } public SqlByte LogicalNumber { get { var logicalNumber = new AuditLogRecord(Convert.ToUInt16(Index), Data).LogicalNumber; return logicalNumber.HasValue ? logicalNumber.Value : SqlByte.Null; } } public SqlByte ParameterNumber { get { var parameterNumber = new AuditLogRecord(Convert.ToUInt16(Index), Data).ParameterNumber; return parameterNumber.HasValue ? parameterNumber.Value : SqlByte.Null; } } public SqlInt32 Tag { get { var tag = new AuditLogRecord(Convert.ToUInt16(Index), Data).Tag; return tag.HasValue ? tag.Value : SqlInt32.Null; } } public SqlDateTime PowerRemovedDateTime { get { var powerRemovedDateTime = new AuditLogRecord(Convert.ToUInt16(Index), Data).PowerRemovedDateTime; return powerRemovedDateTime.HasValue ? powerRemovedDateTime.Value : SqlDateTime.Null; } } public SqlString CalibrationPointType { get { var calibrationPointType = new AuditLogRecord(Convert.ToUInt16(Index), Data).CalibrationPointType; return calibrationPointType.HasValue ? calibrationPointType.Value.ToString() : SqlString.Null; } } public SqlString CalibrationMultivariableSensorInput { get { var calibrationMultivariableSensorInput = new AuditLogRecord(Convert.ToUInt16(Index), Data).CalibrationMultivariableSensorInput; return calibrationMultivariableSensorInput.HasValue ? calibrationMultivariableSensorInput.Value.ToString() : SqlString.Null; } } public SqlString CalibrationType { get { var calibrationType = new AuditLogRecord(Convert.ToUInt16(Index), Data).CalibrationType; return calibrationType.HasValue ? calibrationType.Value.ToString() : SqlString.Null; } } public SqlString EventCode { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).EventCode.ToString(); } } public SqlString OperatorId { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).OperatorId; } } public SqlString EventText { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).EventText; } } public SqlBinary OldValue { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).OldValue; } } public SqlSingle FstFloatValue { get { var fstFloatValue = new AuditLogRecord(Convert.ToUInt16(Index), Data).FstFloatValue; return fstFloatValue.HasValue ? fstFloatValue.Value : SqlSingle.Null; } } public SqlBinary NewValue { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).NewValue; } } public ROCMaster_Parameter OldParameterValue { get { if (!PointType.IsNull && !ParameterNumber.IsNull) { var pointType = PointType.Value; var parameterNumber = ParameterNumber.Value; var parameterDefinition = Device.ROC.Message.ParameterDatabase.ParameterDefinitions.Where(pd => pd.PointType == pointType && pd.Parameter == parameterNumber).FirstOrDefault(); switch (parameterDefinition.DataType) { case "AC": switch (parameterDefinition.Length) { case 3: return new ROCMaster_Parameter() { RawType = ParameterType.AC3, RawValue = OldValue.Value.Take(3).ToArray() }; default: return ROCMaster_Parameter.Null; } case "BIN": return new ROCMaster_Parameter() { RawType = ParameterType.BIN, RawValue = OldValue.Value.Take(1).ToArray() }; case "FL": return new ROCMaster_Parameter() { RawType = ParameterType.FL, RawValue = OldValue.Value }; case "INT16": return new ROCMaster_Parameter() { RawType = ParameterType.INT16, RawValue = OldValue.Value.Take(2).ToArray() }; case "INT32": return new ROCMaster_Parameter() { RawType = ParameterType.INT32, RawValue = OldValue.Value }; case "INT8": return new ROCMaster_Parameter() { RawType = ParameterType.INT8, RawValue = OldValue.Value.Take(1).ToArray() }; case "TLP": return new ROCMaster_Parameter() { RawType = ParameterType.TLP, RawValue = OldValue.Value.Take(3).ToArray() }; case "UINT16": return new ROCMaster_Parameter() { RawType = ParameterType.UINT16, RawValue = OldValue.Value.Take(2).ToArray() }; case "UINT32": return new ROCMaster_Parameter() { RawType = ParameterType.UINT32, RawValue = OldValue.Value }; case "TIME": return new ROCMaster_Parameter() { RawType = ParameterType.TIME, RawValue = OldValue.Value }; case "UINT8": return new ROCMaster_Parameter() { RawType = ParameterType.UINT8, RawValue = OldValue.Value.Take(1).ToArray() }; default: return ROCMaster_Parameter.Null; } } else { return ROCMaster_Parameter.Null; } } } public ROCMaster_Parameter NewParameterValue { get { if (!PointType.IsNull && !ParameterNumber.IsNull) { var pointType = PointType.Value; var parameterNumber = ParameterNumber.Value; var parameterDefinition = Device.ROC.Message.ParameterDatabase.ParameterDefinitions.Where(pd => pd.PointType == pointType && pd.Parameter == parameterNumber).FirstOrDefault(); switch (parameterDefinition.DataType) { case "AC": switch (parameterDefinition.Length) { case 3: return new ROCMaster_Parameter() { RawType = ParameterType.AC3, RawValue = NewValue.Value.Take(3).ToArray() }; case 7: return new ROCMaster_Parameter() { RawType = ParameterType.AC7, RawValue = NewValue.Value.Union(new byte[3]).ToArray() }; case 10: return new ROCMaster_Parameter() { RawType = ParameterType.AC10, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).ToArray() }; case 12: return new ROCMaster_Parameter() { RawType = ParameterType.AC12, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[2]).ToArray() }; case 20: return new ROCMaster_Parameter() { RawType = ParameterType.AC20, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[10]).ToArray() }; case 30: return new ROCMaster_Parameter() { RawType = ParameterType.AC30, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[20]).ToArray() }; case 40: return new ROCMaster_Parameter() { RawType = ParameterType.AC40, RawValue = OldValue.Value.Union(NewValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Tag.Value))).Union(new byte[30]).ToArray() }; default: return ROCMaster_Parameter.Null; } case "BIN": return new ROCMaster_Parameter() { RawType = ParameterType.BIN, RawValue = NewValue.Value.Take(1).ToArray() }; case "FL": return new ROCMaster_Parameter() { RawType = ParameterType.FL, RawValue = NewValue.Value }; case "INT16": return new ROCMaster_Parameter() { RawType = ParameterType.INT16, RawValue = NewValue.Value.Take(2).ToArray() }; case "INT32": return new ROCMaster_Parameter() { RawType = ParameterType.INT32, RawValue = NewValue.Value }; case "INT8": return new ROCMaster_Parameter() { RawType = ParameterType.INT8, RawValue = NewValue.Value.Take(1).ToArray() }; case "TLP": return new ROCMaster_Parameter() { RawType = ParameterType.TLP, RawValue = NewValue.Value.Take(3).ToArray() }; case "UINT16": return new ROCMaster_Parameter() { RawType = ParameterType.UINT16, RawValue = NewValue.Value.Take(2).ToArray() }; case "UINT32": return new ROCMaster_Parameter() { RawType = ParameterType.UINT32, RawValue = NewValue.Value }; case "TIME": return new ROCMaster_Parameter() { RawType = ParameterType.TIME, RawValue = NewValue.Value }; case "UINT8": return new ROCMaster_Parameter() { RawType = ParameterType.UINT8, RawValue = NewValue.Value.Take(1).ToArray() }; default: return ROCMaster_Parameter.Null; } } else { return ROCMaster_Parameter.Null; } } } public SqlInt32 SequenceNumber { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).SequenceNumber; } } public SqlBoolean EventNotSaved { get { return new AuditLogRecord(Convert.ToUInt16(Index), Data).EventNotSaved; } } #endregion #region Helper Methods public static ROCMaster_AuditLogRecord Parse(SqlString stringToParse) { var parsedAuditLogRecord = stringToParse.Value.Split(",".ToCharArray()); var base64Bytes = Convert.FromBase64String(parsedAuditLogRecord[1]); if (base64Bytes.Length == 24) { return new ROCMaster_AuditLogRecord() { Index = ushort.Parse(parsedAuditLogRecord[0]), Data = base64Bytes }; } else { throw new ArgumentException("Input must be exactly 24 bytes"); } } public override string ToString() { return string.Format("{0},{1}", Index, Convert.ToBase64String(Data)); } #endregion #region Serialization Methods public void Read(BinaryReader binaryReader) { IsNull = binaryReader.ReadBoolean(); Index = binaryReader.ReadInt32(); if (!IsNull) { Data = binaryReader.ReadBytes(24); } } public void Write(BinaryWriter binaryWriter) { binaryWriter.Write(IsNull); binaryWriter.Write(Index); if (!IsNull) { binaryWriter.Write(Data, 0, 24); } } #endregion } }
/* Copyright 2010 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.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using Google.Apis.Discovery; using Google.Apis.Logging; using Google.Apis.Testing; using Google.Apis.Tools.CodeGen.Decorator; using Google.Apis.Tools.CodeGen.Decorator.ResourceContainerDecorator; using Google.Apis.Tools.CodeGen.Decorator.ResourceDecorator; using Google.Apis.Tools.CodeGen.Decorator.ResourceDecorator.RequestDecorator; using Google.Apis.Tools.CodeGen.Decorator.ServiceDecorator; using Google.Apis.Tools.CodeGen.Generator; using Google.Apis.Util; namespace Google.Apis.Tools.CodeGen { /// <summary> /// The main entry for generating code to access google services. /// For a default generation try calling /// <example> /// <code> /// GoogleServiceGenerator.GenerateService("buzz", "v1", "Com.Example.Namespace", "CSharp", "c:\example\"); /// </code> /// </example> /// </summary> public class GoogleServiceGenerator : BaseGenerator { /// <summary> /// Defines the URL used to discover Google APIs /// {0}: Service name /// {1}: Version /// </summary> public const string GoogleDiscoveryURL = "https://www.googleapis.com/discovery/v1/apis/{0}/{1}/rest"; /// <summary> /// The nested namespace where data classes are generated. /// </summary> private const string DataNamespaceExtension = ".Data"; private static readonly ILogger logger = ApplicationContext.Logger.ForType<GoogleServiceGenerator>(); /// <summary> /// List of all request class decorators /// </summary> public static IList<IRequestDecorator> GetSchemaAwareCommonRequestDecorators( string schemaNamespace, IService service) { var typeProvider = new DefaultObjectTypeProvider(schemaNamespace); return (new List<IRequestDecorator> { new CommonParameterRequestDecorator(service.Parameters), new ParameterPropertyDecorator(), }).AsReadOnly(); } /// <summary> /// List of all request class decorators /// </summary> public static IList<IRequestDecorator> GetSchemaAwareRequestDecorators( string schemaNamespace, IService service) { var typeProvider = new DefaultObjectTypeProvider(schemaNamespace); return (new List<IRequestDecorator>() { new ServiceRequestInheritanceDecorator(typeProvider), new BodyPropertyDecorator(typeProvider), new RequestConstructorDecorator(typeProvider) { CreateOptionalConstructor = false }, new ServiceRequestFieldDecorator(), new InitRequestParametersDecorator(), new MediaDownloaderDecorator(), }).AsReadOnly(); } /// <summary> /// List of all upload class decorators /// </summary> public static IList<IRequestDecorator> GetSchemaAwareUploadDecorators( string schemaNamespace, IService service) { var typeProvider = new DefaultObjectTypeProvider(schemaNamespace); return (new List<IRequestDecorator> { new ResumableUploadInheritanceDecorator(typeProvider), new UploadConstructorDecorator(typeProvider), }).AsReadOnly(); } /// <summary> /// List of all schema aware service decorators /// </summary> public static readonly IList<IServiceDecorator> SchemaAwareServiceDecorators = (new List<IServiceDecorator> { new StandardConstructServiceDecorator(), new EasyConstructServiceDecorator(), new VersionInformationServiceDecorator(), new BaseClientServiceAbstractPropertiesDecorator(), new ScopeEnumDecorator(), new InitServiceParametersDecorator(), }).AsReadOnly(); /// <summary> /// List of all resource container decorators /// </summary> public static readonly IList<IResourceContainerDecorator> StandardResourceContainerDecorator = (new List<IResourceContainerDecorator> { new StandardResourcePropertyServiceDecorator() }).AsReadOnly(); private readonly string codeClientNamespace; private readonly IEnumerable<IResourceContainerDecorator> resourceContainerDecorators; private readonly IEnumerable<IResourceDecorator> resourceDecorators; private readonly GoogleSchemaGenerator schemaGenerator; private readonly IService service; private readonly IEnumerable<IServiceDecorator> serviceDecorators; /// <summary> /// Generates a new instance of the service generator for a specific service /// </summary> public GoogleServiceGenerator(IService service, string clientNamespace, IEnumerable<IResourceDecorator> resourceDecorators, IEnumerable<IServiceDecorator> serviceDecorators, IEnumerable<IResourceContainerDecorator> resourceContainerDecorators, GoogleSchemaGenerator schemaGenerator) { service.ThrowIfNull("service"); clientNamespace.ThrowIfNull("clientNamespace"); resourceDecorators.ThrowIfNull("resourceDecorators"); serviceDecorators.ThrowIfNull("serviceDecorators"); resourceContainerDecorators.ThrowIfNull("resourceContainerDecorators"); codeClientNamespace = clientNamespace; this.service = service; // Defensive copy and readonly this.resourceDecorators = new List<IResourceDecorator>(resourceDecorators).AsReadOnly(); this.serviceDecorators = new List<IServiceDecorator>(serviceDecorators).AsReadOnly(); this.resourceContainerDecorators = new List<IResourceContainerDecorator>(resourceContainerDecorators).AsReadOnly(); this.schemaGenerator = schemaGenerator; } /// <summary> /// Generates a new service generator for a specific service /// </summary> public GoogleServiceGenerator(IService service, string clientNamespace) : this( service, clientNamespace, GetSchemaAwareResourceDecorators(DataNamespace(clientNamespace)), SchemaAwareServiceDecorators, StandardResourceContainerDecorator, new GoogleSchemaGenerator(GoogleSchemaGenerator.DefaultSchemaDecorators, DataNamespace(clientNamespace))) { } /// <summary> /// Returns a list of all schema aware resource decorators /// </summary> public static IList<IResourceDecorator> GetSchemaAwareResourceDecorators(string schemaNamespace) { var typeProvider = new DefaultObjectTypeProvider(schemaNamespace); return (new List<IResourceDecorator> { new SubresourceClassDecorator(), new EnumResourceDecorator(), new StandardServiceFieldResourceDecorator(), new StandardResourceNameResourceDecorator(), new StandardConstructorResourceDecorator(), new RequestMethodResourceDecorator(typeProvider) { AddOptionalParameters = false }, }).AsReadOnly (); } /// <summary> /// Creates a cached web discovery device /// </summary> internal static IDiscoveryService CreateDefaultCachingDiscovery(string serviceUrl) { // Set up how discovery works. string cacheDirectory = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GoogleApis.Tools.CodeGenCache"); if (Directory.Exists(cacheDirectory) == false) { Directory.CreateDirectory(cacheDirectory); } var webfetcher = new CachedWebDiscoveryDevice(new Uri(serviceUrl), new DirectoryInfo(cacheDirectory)); return new DiscoveryService(webfetcher); } /// <summary> /// Generates the given service saving to the outputFile in the language passed in. /// </summary> public static void GenerateService(string serviceName, string version, string clientNamespace, string language, string outputFile) { // Generate the discovery URL for that service string url = string.Format(GoogleDiscoveryURL, serviceName, version); var discovery = CreateDefaultCachingDiscovery(url); // Build the service based on discovery information. var service = discovery.GetService(DiscoveryVersion.Version_1_0, new FactoryParameters()); var generator = new GoogleServiceGenerator(service, clientNamespace); var generatedCode = generator.GenerateCode(); var provider = CodeDomProvider.CreateProvider(language); using (StreamWriter sw = new StreamWriter(outputFile, false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); // Generate source code using the code provider. provider.GenerateCodeFromCompileUnit(generatedCode, tw, new CodeGeneratorOptions()); // Close the output file. tw.Close(); } } [VisibleForTestOnly] internal CodeNamespace GenerateSchemaCode() { if (schemaGenerator != null) { return schemaGenerator.GenerateSchemaClasses(service); } return null; } [VisibleForTestOnly] internal CodeNamespace GenerateClientCode() { var clientNamespace = CreateNamespace(codeClientNamespace); ResourceContainerGenerator resourceContainerGenerator = new ResourceContainerGenerator(resourceContainerDecorators); var requestClassGenerator = new RequestClassGenerator( GetSchemaAwareCommonRequestDecorators(DataNamespace(codeClientNamespace), service), GetSchemaAwareRequestDecorators(DataNamespace(codeClientNamespace), service), GetSchemaAwareUploadDecorators(DataNamespace(codeClientNamespace), service)); var serviceClass = new ServiceClassGenerator(service, serviceDecorators, resourceContainerGenerator).CreateServiceClass(); string serviceClassName = serviceClass.Name; clientNamespace.Types.Add(serviceClass); CreateResources( clientNamespace, serviceClassName, service, requestClassGenerator, resourceContainerGenerator); return clientNamespace; } /// <summary> /// Generates the code for this service /// </summary> public CodeCompileUnit GenerateCode() { logger.Debug("Starting Code Generation..."); LogDecorators(); var compileUnit = new CodeCompileUnit(); var schemaCode = GenerateSchemaCode(); if (schemaCode != null) { compileUnit.Namespaces.Add(schemaCode); } compileUnit.Namespaces.Add(GenerateClientCode()); logger.Debug("Generation Complete."); return compileUnit; } private void CreateResources(CodeNamespace clientNamespace, string serviceClassName, IResource resource, RequestClassGenerator requestClassGenerator, ResourceContainerGenerator resourceContainerGenerator) { foreach (var res in resource.Resources.Values.Concat(resource)) { // Create the current list of used names. IEnumerable<string> usedNames = resource.Resources.Keys; // Create a class for the resource. logger.Debug("Adding Resource {0}", res.Name); var resourceGenerator = new ResourceClassGenerator( res, serviceClassName, resourceDecorators, requestClassGenerator, resourceContainerGenerator, usedNames); var generatedClass = resourceGenerator.CreateClass(); clientNamespace.Types.Add(generatedClass); } } private void LogDecorators() { if (logger.IsDebugEnabled) { logger.Debug("With Service Decorators:"); foreach (IServiceDecorator dec in serviceDecorators) { logger.Debug(">>>>" + dec); } logger.Debug("With Resource Decorators:"); foreach (IResourceDecorator dec in resourceDecorators) { logger.Debug(">>>>" + dec); } logger.Debug("With Resource Container Decorators:"); foreach (IResourceContainerDecorator dec in resourceContainerDecorators) { logger.Debug(">>>>" + dec); } } } private CodeNamespace CreateNamespace(string nameSpace) { return new CodeNamespace(nameSpace); } private static string DataNamespace(string clientNamespace) { return clientNamespace + DataNamespaceExtension; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature { [ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService { private static readonly ImmutableArray<SyntaxKind> _declarationKinds = ImmutableArray.Create( SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.DelegateDeclaration, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression); private static readonly ImmutableArray<SyntaxKind> _declarationAndInvocableKinds = _declarationKinds.Concat(ImmutableArray.Create( SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.NameMemberCref)); private static readonly ImmutableArray<SyntaxKind> _updatableAncestorKinds = ImmutableArray.Create( SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.NameMemberCref); private static readonly ImmutableArray<SyntaxKind> _updatableNodeKinds = ImmutableArray.Create( SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.ThisConstructorInitializer, SyntaxKind.BaseConstructorInitializer, SyntaxKind.ObjectCreationExpression, SyntaxKind.Attribute, SyntaxKind.DelegateDeclaration, SyntaxKind.NameMemberCref, SyntaxKind.AnonymousMethodExpression, SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression); public override async Task<ISymbol> GetInvocationSymbolAsync( Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position != tree.Length ? position : Math.Max(0, position - 1)); // Allow the user to invoke Change-Sig if they've written: Foo(a, b, c);$$ if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent is StatementSyntax) { token = token.GetPreviousToken(); position = token.Span.End; } var matchingNode = GetMatchingNode(token.Parent, restrictToDeclarations); if (matchingNode == null) { return null; } // Don't show change-signature in the random whitespace/trivia for code. if (!matchingNode.Span.IntersectsWith(position)) { return null; } // If we're actually on the declaration of some symbol, ensure that we're // in a good location for that symbol (i.e. not in the attributes/constraints). if (!InSymbolHeader(matchingNode, position)) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken); if (symbol != null) { return symbol; } if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objectCreation = matchingNode as ObjectCreationExpressionSyntax; if (token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type)) { var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol; if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && (typeSymbol as ITypeSymbol).TypeKind == TypeKind.Delegate) { return typeSymbol; } } } var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken); return symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault(); } private SyntaxNode GetMatchingNode(SyntaxNode node, bool restrictToDeclarations) { var matchKinds = restrictToDeclarations ? _declarationKinds : _declarationAndInvocableKinds; for (var current = node; current != null; current = current.Parent) { if (restrictToDeclarations && current.Kind() == SyntaxKind.Block || current.Kind() == SyntaxKind.ArrowExpressionClause) { return null; } if (matchKinds.Contains(current.Kind())) { return current; } } return null; } private bool InSymbolHeader(SyntaxNode matchingNode, int position) { // Caret has to be after the attributes if the symbol has any. var lastAttributes = matchingNode.ChildNodes().LastOrDefault(n => n is AttributeListSyntax); var start = lastAttributes?.GetLastToken().GetNextToken().SpanStart ?? matchingNode.SpanStart; if (position < start) { return false; } // If the symbol has a parameter list, then the caret shouldn't be past the end of it. var parameterList = matchingNode.ChildNodes().LastOrDefault(n => n is ParameterListSyntax); if (parameterList != null) { return position <= parameterList.FullSpan.End; } // Case we haven't handled yet. Just assume we're in the header. return true; } public override SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node) { if (_updatableNodeKinds.Contains(node.Kind())) { return node; } // TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression); var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind())); if (matchingNode == null) { return null; } var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode); if (nodeContainingOriginal == null) { return null; } return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null; } private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode) { switch (matchingNode.Kind()) { case SyntaxKind.InvocationExpression: return (matchingNode as InvocationExpressionSyntax).Expression; case SyntaxKind.ElementAccessExpression: return (matchingNode as ElementAccessExpressionSyntax).ArgumentList; case SyntaxKind.ObjectCreationExpression: return (matchingNode as ObjectCreationExpressionSyntax).Type; case SyntaxKind.ConstructorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.Attribute: case SyntaxKind.DelegateDeclaration: case SyntaxKind.NameMemberCref: return matchingNode; default: return null; } } public override SyntaxNode ChangeSignature( Document document, ISymbol declarationSymbol, SyntaxNode potentiallyUpdatedNode, SyntaxNode originalNode, SignatureChange signaturePermutation, CancellationToken cancellationToken) { var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode; // Update <param> tags. if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) || updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) || updatedNode.IsKind(SyntaxKind.IndexerDeclaration) || updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(updatedNode, declarationSymbol, signaturePermutation); if (updatedLeadingTrivia != null) { updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia); } } // Update declarations parameter lists if (updatedNode.IsKind(SyntaxKind.MethodDeclaration)) { var method = updatedNode as MethodDeclarationSyntax; var updatedParameters = PermuteDeclaration(method.ParameterList.Parameters, signaturePermutation); return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = updatedNode as ConstructorDeclarationSyntax; var updatedParameters = PermuteDeclaration(constructor.ParameterList.Parameters, signaturePermutation); return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration)) { var indexer = updatedNode as IndexerDeclarationSyntax; var updatedParameters = PermuteDeclaration(indexer.ParameterList.Parameters, signaturePermutation); return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration)) { var delegateDeclaration = updatedNode as DelegateDeclarationSyntax; var updatedParameters = PermuteDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation); return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression)) { var anonymousMethod = updatedNode as AnonymousMethodExpressionSyntax; // Delegates may omit parameters in C# if (anonymousMethod.ParameterList == null) { return anonymousMethod; } var updatedParameters = PermuteDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation); return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression)) { var lambda = updatedNode as SimpleLambdaExpressionSyntax; if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any()) { Debug.Assert(false, "Updating a simple lambda expression without removing its parameter"); } else { // No parameters. Change to a parenthesized lambda expression var emptyParameterList = SyntaxFactory.ParameterList() .WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia()) .WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia()); return SyntaxFactory.ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.Body); } } if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression)) { var lambda = updatedNode as ParenthesizedLambdaExpressionSyntax; var updatedParameters = PermuteDeclaration(lambda.ParameterList.Parameters, signaturePermutation); return lambda.WithParameterList(lambda.ParameterList.WithParameters(updatedParameters)); } // Update reference site argument lists if (updatedNode.IsKind(SyntaxKind.InvocationExpression)) { var invocation = updatedNode as InvocationExpressionSyntax; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbolInfo = semanticModel.GetSymbolInfo(originalNode as InvocationExpressionSyntax, cancellationToken); var methodSymbol = symbolInfo.Symbol as IMethodSymbol; var isReducedExtensionMethod = false; if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension) { isReducedExtensionMethod = true; } var newArguments = PermuteArgumentList(document, declarationSymbol, invocation.ArgumentList.Arguments, signaturePermutation, isReducedExtensionMethod); return invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ObjectCreationExpression)) { var objCreation = updatedNode as ObjectCreationExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer) || updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer)) { var objCreation = updatedNode as ConstructorInitializerSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation); return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression)) { var elementAccess = updatedNode as ElementAccessExpressionSyntax; var newArguments = PermuteArgumentList(document, declarationSymbol, elementAccess.ArgumentList.Arguments, signaturePermutation); return elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } if (updatedNode.IsKind(SyntaxKind.Attribute)) { var attribute = updatedNode as AttributeSyntax; var newArguments = PermuteAttributeArgumentList(document, declarationSymbol, attribute.ArgumentList.Arguments, signaturePermutation); return attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation)); } // Handle references in crefs if (updatedNode.IsKind(SyntaxKind.NameMemberCref)) { var nameMemberCref = updatedNode as NameMemberCrefSyntax; if (nameMemberCref.Parameters == null || !nameMemberCref.Parameters.Parameters.Any()) { return nameMemberCref; } var newParameters = PermuteDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation); var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters); return nameMemberCref.WithParameters(newCrefParameterList); } Debug.Assert(false, "Unknown reference location"); return null; } private SeparatedSyntaxList<T> PermuteDeclaration<T>(SeparatedSyntaxList<T> list, SignatureChange updatedSignature) where T : SyntaxNode { var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var newParameters = new List<T>(); foreach (var newParam in reorderedParameters) { var pos = originalParameters.IndexOf(newParam); var param = list[pos]; newParameters.Add(param); } var numSeparatorsToSkip = originalParameters.Count - reorderedParameters.Count; return SyntaxFactory.SeparatedList(newParameters, GetSeparators(list, numSeparatorsToSkip)); } private static SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<AttributeArgumentSyntax> arguments, SignatureChange updatedSignature) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private static SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList( Document document, ISymbol declarationSymbol, SeparatedSyntaxList<ArgumentSyntax> arguments, SignatureChange updatedSignature, bool isReducedExtensionMethod = false) { var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature, isReducedExtensionMethod); var numSeparatorsToSkip = arguments.Count - newArguments.Count; return SyntaxFactory.SeparatedList(newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip)); } private List<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature) { if (!node.HasLeadingTrivia) { return null; } var paramNodes = node .DescendantNodes(descendIntoTrivia: true) .OfType<XmlElementSyntax>() .Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName); var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature); if (permutedParamNodes == null) { return null; } return GetPermutedTrivia(node, permutedParamNodes); } private List<XmlElementSyntax> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature) { // Only reorder if count and order match originally. var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var declaredParameters = declarationSymbol.GetParameters(); if (paramNodes.Count() != declaredParameters.Count()) { return null; } var dictionary = new Dictionary<string, XmlElementSyntax>(); int i = 0; foreach (var paramNode in paramNodes) { var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase)); if (nameAttribute == null) { return null; } var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault(); if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name) { return null; } dictionary.Add(originalParameters[i].Name.ToString(), paramNode); i++; } // Everything lines up, so permute them. var permutedParams = new List<XmlElementSyntax>(); foreach (var parameter in reorderedParameters) { permutedParams.Add(dictionary[parameter.Name]); } return permutedParams; } private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElementSyntax> permutedParamNodes) { var updatedLeadingTrivia = new List<SyntaxTrivia>(); var index = 0; foreach (var trivia in node.GetLeadingTrivia()) { if (!trivia.HasStructure) { updatedLeadingTrivia.Add(trivia); continue; } var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax; if (structuredTrivia == null) { updatedLeadingTrivia.Add(trivia); continue; } var updatedNodeList = new List<XmlNodeSyntax>(); var structuredContent = structuredTrivia.Content.ToList(); for (int i = 0; i < structuredContent.Count; i++) { var content = structuredContent[i]; if (!content.IsKind(SyntaxKind.XmlElement)) { updatedNodeList.Add(content); continue; } var xmlElement = content as XmlElementSyntax; if (xmlElement.StartTag.Name.ToString() != DocumentationCommentXmlNames.ParameterElementName) { updatedNodeList.Add(content); continue; } // Found a param tag, so insert the next one from the reordered list if (index < permutedParamNodes.Count) { updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia())); index++; } else { // Inspecting a param element that we are deleting but not replacing. } } var newDocComments = SyntaxFactory.DocumentationCommentTrivia(structuredTrivia.Kind(), SyntaxFactory.List(updatedNodeList.AsEnumerable())); newDocComments = newDocComments.WithEndOfComment(structuredTrivia.EndOfComment); newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia()); var newTrivia = SyntaxFactory.Trivia(newDocComments); updatedLeadingTrivia.Add(newTrivia); } return updatedLeadingTrivia; } private static List<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip = 0) where T : SyntaxNode { var separators = new List<SyntaxToken>(); for (int i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++) { separators.Add(arguments.GetSeparator(i)); } return separators; } public override async Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsFromDelegateInvoke( SymbolAndProjectId<IMethodSymbol> symbolAndProjectId, Document document, CancellationToken cancellationToken) { var symbol = symbolAndProjectId.Symbol; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodes = root.DescendantNodes().ToImmutableArray(); var convertedMethodGroups = nodes .WhereAsArray( n => { if (!n.IsKind(SyntaxKind.IdentifierName) || !semanticModel.GetMemberGroup(n, cancellationToken).Any()) { return false; } ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType; if (convertedType != null) { convertedType = convertedType.OriginalDefinition; } if (convertedType != null) { convertedType = SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken) ?? convertedType; } return convertedType == symbol.ContainingType; }) .SelectAsArray(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol); return convertedMethodGroups.SelectAsArray(symbolAndProjectId.WithSymbol); } protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document) { return new[] { new ChangeSignatureFormattingRule() }.Concat(Formatter.GetDefaultFormattingRules(document)); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Net; using System.Web; using Codentia.Common.Helper; using Codentia.Common.Logging; using Codentia.Common.Logging.BL; using Codentia.Common.Net.FTP; namespace Codentia.Common.Net { /// <summary> /// Management class for interfacing with Mattched IT CDN system /// </summary> public static class CDNManager { /// <summary> /// Puts the file. Requires CDN credentials to be stored in app.config /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileNameAndPath">The file name and path.</param> public static void PutFile(string applicationName, string domainName, string folder, string fileNameAndPath) { ParameterCheckHelper.CheckIsValidString(applicationName, "applicationName", false); ParameterCheckHelper.CheckIsValidString(domainName, "domainName", false); ParameterCheckHelper.CheckIsValidString(folder, "folder", false); ParameterCheckHelper.CheckIsValidString(fileNameAndPath, "fileNameAndPath", false); if (!File.Exists(fileNameAndPath)) { throw new Exception(string.Format("file: '{0}' does not exist", fileNameAndPath)); } // ftp to cdn and write the file FTPClient ftp = new FTPClient(ConfigurationManager.AppSettings["CDNFtpHost"], 21, "/", ConfigurationManager.AppSettings["CDNFtpUser"], ConfigurationManager.AppSettings["CDNFtpPassword"], FTPTransferMode.Binary); ftp.RemotePath = string.Format("/{0}/{1}/{2}/{3}/{4}", ConfigurationManager.AppSettings["CDNFtpRemotePath"], applicationName, SiteHelper.SiteEnvironment, domainName, folder); ftp.UploadFile(fileNameAndPath); ftp.Close(); } /// <summary> /// Upload the contents of a folder (flat - no recursion) to CDN using app.config credentials /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="folderPath">The folder path.</param> public static void PutFiles(string applicationName, string domainName, string folder, string folderPath) { ParameterCheckHelper.CheckIsValidString(applicationName, "applicationName", false); ParameterCheckHelper.CheckIsValidString(domainName, "domainName", false); ParameterCheckHelper.CheckIsValidString(folder, "folder", false); ParameterCheckHelper.CheckIsValidString(folderPath, "local folder", false); // ftp to cdn and store all files in the folder FTPClient ftp = new FTPClient(ConfigurationManager.AppSettings["CDNFtpHost"], 21, "/", ConfigurationManager.AppSettings["CDNFtpUser"], ConfigurationManager.AppSettings["CDNFtpPassword"], FTPTransferMode.Binary); ftp.RemotePath = string.Format("/{0}/{1}/{2}/{3}/{4}", ConfigurationManager.AppSettings["CDNFtpRemotePath"], applicationName, SiteHelper.SiteEnvironment, domainName, folder); string[] files = Directory.GetFiles(folderPath); for (int i = 0; i < files.Length; i++) { ftp.UploadFile(files[i]); } ftp.Close(); } /// <summary> /// Ensures the path exists. /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> public static void EnsurePathExists(string applicationName, string domainName, string folder) { ParameterCheckHelper.CheckIsValidString(applicationName, "applicationName", false); ParameterCheckHelper.CheckIsValidString(domainName, "domainName", false); ParameterCheckHelper.CheckIsValidString(folder, "folder", false); // ftp to cdn and write the file FTPClient ftp = new FTPClient(ConfigurationManager.AppSettings["CDNFtpHost"], 21, "/", ConfigurationManager.AppSettings["CDNFtpUser"], ConfigurationManager.AppSettings["CDNFtpPassword"], FTPTransferMode.Binary); // go to base path (must exist) ftp.RemotePath = string.Format("/{0}/{1}/{2}", ConfigurationManager.AppSettings["CDNFtpRemotePath"], applicationName, SiteHelper.SiteEnvironment); ftp.Connect(); // test for client folders and create if necessary try { ftp.RemotePath = domainName; } catch (Exception) { LogManager.Instance.AddToLog(LogMessageType.Information, "CDNManager.EnsurePathExists", string.Format("domainName {0} does not exist in {1} - creating..", domainName, ftp.RemotePath)); ftp.MKDir(domainName); ftp.RemotePath = domainName; } try { LogManager.Instance.AddToLog(LogMessageType.Information, "CDNManager.EnsurePathExists", string.Format("folder {0} does not exist in {1} - creating..", folder, ftp.RemotePath)); ftp.RemotePath = folder; } catch (Exception) { ftp.MKDir(folder); } ftp.Close(); } /// <summary> /// Gets the public URL. /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> /// <returns>string (url)</returns> public static string GetPublicUrl(string applicationName, string domainName, string folder, string fileName) { return string.Format("http://cdn.mattchedit.com/{0}/{1}/{2}/{3}/{4}", applicationName, SiteHelper.SiteEnvironment, domainName, folder, fileName); } /// <summary> /// Writes the file for download as if it were a local resource (handling of images in secure context, etc) /// </summary> /// <param name="response">The response.</param> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> public static void WriteImage(HttpResponse response, string applicationName, string domainName, string folder, string fileName) { // get the file via http and output it with the appropriate mime type based on it's extension // top table here http://www.w3schools.com/media/media_mimeref.asp (must set content type appropriately) byte[] imageContent = null; string sourceUrl = CDNManager.GetPublicUrl(applicationName, domainName, folder, fileName); try { WebRequest requestPic = WebRequest.Create(sourceUrl); WebResponse responsePic = requestPic.GetResponse(); // create an image object, using the filename we just retrieved System.Drawing.Image image = System.Drawing.Image.FromStream(responsePic.GetResponseStream()); // make a memory stream to work with the image bytes MemoryStream imageStream = new MemoryStream(); image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); // make byte array the same size as the image imageContent = new byte[imageStream.Length]; // rewind the memory stream imageStream.Position = 0; // load the byte array with the image imageStream.Read(imageContent, 0, (int)imageStream.Length); // return byte array to caller with image type response.ContentType = "image/jpeg"; } catch (Exception ex) { LogManager.Instance.AddToLog(LogMessageType.FatalError, "CDNManager.WriteImage", string.Format("applicationName={0}, domainName={1}, folder={2}, fileName={3}, sourceUrl={4}", applicationName, domainName, folder, fileName, sourceUrl)); LogManager.Instance.AddToLog(ex, "CDNManager.WriteImage"); } if (imageContent != null) { try { response.BinaryWrite(imageContent); } catch (Exception) { // do nothing, this is for test purposes } } response.End(); } /// <summary> /// Gets the binary file contents. /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> /// <returns>byte array</returns> public static byte[] GetBinaryFileContents(string applicationName, string domainName, string folder, string fileName) { List<byte> fileContents = new List<byte>(); string sourceUrl = CDNManager.GetPublicUrl(applicationName, domainName, folder, fileName); try { WebRequest requestPic = WebRequest.Create(sourceUrl); WebResponse responsePic = requestPic.GetResponse(); // create an image object, using the filename we just retrieved // 50kB chunking byte[] buffer = new byte[51200]; int index = 0; BinaryReader reader = new BinaryReader(responsePic.GetResponseStream()); int bytesRead = 0; while ((bytesRead = reader.Read(buffer, index, buffer.Length)) > 0) { byte[] actuallyRead = new byte[bytesRead]; Array.Copy(buffer, 0, actuallyRead, 0, bytesRead); fileContents.AddRange(actuallyRead); } } catch (Exception ex) { LogManager.Instance.AddToLog(LogMessageType.NonFatalError, "CDNManager.GetBinaryFileContents", string.Format("applicationName={0}, domainName={1}, folder={2}, fileName={3}, sourceUrl={4}", applicationName, domainName, folder, fileName, sourceUrl)); LogManager.Instance.AddToLog(ex, "CDNManager.GetBinaryFileContents"); } return fileContents.ToArray(); } /// <summary> /// Writes the file. /// </summary> /// <param name="response">The response.</param> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> public static void WriteBinaryFile(HttpResponse response, string applicationName, string domainName, string folder, string fileName) { byte[] contents = GetBinaryFileContents(applicationName, domainName, folder, fileName); string sourceUrl = CDNManager.GetPublicUrl(applicationName, domainName, folder, fileName); try { response.ContentType = "application/octet-stream"; response.AddHeader("content-disposition", string.Format("attachment; filename=\"{0}\"", fileName)); response.BinaryWrite(contents); } catch (Exception ex) { LogManager.Instance.AddToLog(LogMessageType.NonFatalError, "CDNManager.WriteBinaryFile", string.Format("applicationName={0}, domainName={1}, folder={2}, fileName={3}, sourceUrl={4}", applicationName, domainName, folder, fileName, sourceUrl)); LogManager.Instance.AddToLog(ex, "CDNManager.WriteBinaryFile"); } response.End(); } /// <summary> /// Deletes the file. /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileName">Name of the file.</param> public static void DeleteFile(string applicationName, string domainName, string folder, string fileName) { ParameterCheckHelper.CheckIsValidString(applicationName, "applicationName", false); ParameterCheckHelper.CheckIsValidString(domainName, "domainName", false); ParameterCheckHelper.CheckIsValidString(folder, "folder", false); ParameterCheckHelper.CheckIsValidString(fileName, "fileName", false); // ftp to cdn and write the file FTPClient ftp = new FTPClient(ConfigurationManager.AppSettings["CDNFtpHost"], 21, "/", ConfigurationManager.AppSettings["CDNFtpUser"], ConfigurationManager.AppSettings["CDNFtpPassword"], FTPTransferMode.Binary); ftp.RemotePath = string.Format("/{0}/{1}/{2}/{3}/{4}", ConfigurationManager.AppSettings["CDNFtpRemotePath"], applicationName, SiteHelper.SiteEnvironment, domainName, folder); ftp.DeleteRemoteFile(fileName); ftp.Close(); } /// <summary> /// Files the exists. /// </summary> /// <param name="applicationName">Name of the application.</param> /// <param name="domainName">Name of the domain.</param> /// <param name="folder">The folder.</param> /// <param name="fileNameAndPath">The file name and path.</param> /// <returns>bool - true if file exists, otherwise false</returns> public static bool FileExists(string applicationName, string domainName, string folder, string fileNameAndPath) { ParameterCheckHelper.CheckIsValidString(applicationName, "applicationName", false); ParameterCheckHelper.CheckIsValidString(domainName, "domainName", false); ParameterCheckHelper.CheckIsValidString(folder, "folder", false); ParameterCheckHelper.CheckIsValidString(fileNameAndPath, "fileNameAndPath", false); // ftp to cdn and write the file FTPClient ftp = new FTPClient(ConfigurationManager.AppSettings["CDNFtpHost"], 21, "/", ConfigurationManager.AppSettings["CDNFtpUser"], ConfigurationManager.AppSettings["CDNFtpPassword"], FTPTransferMode.Binary); ftp.RemotePath = string.Format("/{0}/{1}/{2}/{3}/{4}", ConfigurationManager.AppSettings["CDNFtpRemotePath"], applicationName, SiteHelper.SiteEnvironment, domainName, folder); string[] listResults = ftp.GetFiles(fileNameAndPath); ftp.Close(); return listResults.Length == 1; } } }
using System.Collections.Generic; using UnityEngine; using System.Collections; /* Source: http://wiki.unity3d.com/index.php?title=TinyXmlReader See site for usage. Extended to handle comments and headers. */ using System.Linq; public class TinyXmlReader { private string xmlString = ""; private int idx = 0; public TinyXmlReader(string newXmlString) { xmlString = newXmlString; } public enum TagType { OPENING = 0, CLOSING = 1, COMMENT = 2, HEADER = 3}; public string tagName = ""; public TagType tagType = TagType.OPENING; public string content = ""; // properly looks for the next index of _c, without stopping at line endings, allowing tags to be break lines int IndexOf(char _c, int _i) { int i = _i; while (i < xmlString.Length) { if (xmlString[i] == _c) return i; ++i; } return -1; } int IndexOf(string _s, int _i) { if (string.IsNullOrEmpty(_s)) return -1; int i = _i; while (i < (xmlString.Length - _s.Length)) { if (xmlString.Substring(i, _s.Length) == _s) return i; ++i; } return -1; } string ExtractCDATA(int _i) { return string.Empty; } public bool Read() { if (idx > -1) idx = xmlString.IndexOf("<", idx); if (idx == -1) { return false; } ++idx; int endOfTag = IndexOf('>', idx); if (endOfTag == -1) return false; // All contents of the tag, incl. name and attributes string tagContents = xmlString.Substring(idx, endOfTag - idx); int endOfName = IndexOf(' ', idx); if ((endOfName == -1) || (endOfTag < endOfName)) endOfName = endOfTag; tagName = xmlString.Substring(idx, endOfName - idx); idx = endOfTag; // Fill in the tag name if (tagName.StartsWith("/")) { tagType = TagType.CLOSING; tagName = tagName.Remove(0, 1); // Remove the "/" at the front } else if (tagName.StartsWith("?")) { tagType = TagType.HEADER; tagName = tagName.Remove(0, 1); // Remove the "?" at the front } else if(tagName.StartsWith("!--")) { tagType = TagType.COMMENT; tagName = string.Empty; // A comment doesn't have a tag name } else { tagType = TagType.OPENING; } // Set the contents of the tag with respect to the type of the tag switch (tagType) { case TagType.OPENING: content = xmlString.Substring(idx + 1); int startOfCloseTag = IndexOf("<", idx); if (startOfCloseTag == -1) return false; // Check that the startOfCloseTag is not actually the start of a tag containing CDATA if (xmlString.Substring(startOfCloseTag, 9) == "<![CDATA[") { int startOfCDATA = startOfCloseTag; int endOfCDATA = IndexOf("]]>", startOfCDATA + 9); startOfCloseTag = IndexOf("<", endOfCDATA + 3); if (endOfCDATA == -1) return false; string CDATAContent = xmlString.Substring(startOfCDATA + 9, endOfCDATA - (startOfCDATA + 9)); string preContent = xmlString.Substring(idx + 1, startOfCDATA - (idx + 1)); string postContent = xmlString.Substring(endOfCDATA + 3, startOfCloseTag - (endOfCDATA + 3)); content = preContent + CDATAContent + postContent; idx = startOfCloseTag; } else { content = xmlString.Substring(idx + 1, startOfCloseTag - idx - 1); } break; case TagType.COMMENT: if ((tagContents.Length - 5) < 0) return false; content = tagContents.Substring(3, tagContents.Length - 5); break; case TagType.HEADER: if ((tagContents.Length - 1) < 0) return false; content = tagContents.Substring(tagName.Length + 1, tagContents.Length - tagName.Length - 2); break; default: content = string.Empty; break; } return true; } // returns false when the endingTag is encountered public bool Read(string endingTag) { bool retVal = Read(); if ((tagName == endingTag) && (tagType == TagType.CLOSING)) { retVal = false; } return retVal; } public static Dictionary<string, string> DictionaryFromXMLString(string xmlString) { Dictionary<string, string> data = new Dictionary<string, string>(); TinyXmlReader xmlreader = new TinyXmlReader(xmlString); int depth = -1; // While still reading valid data while (xmlreader.Read()) { if (xmlreader.tagType == TinyXmlReader.TagType.OPENING) ++depth; else if (xmlreader.tagType == TinyXmlReader.TagType.CLOSING) --depth; // Useful data is found at depth level 1 if ((depth == 1) && (xmlreader.tagType == TinyXmlReader.TagType.OPENING)) { if( !data.ContainsKey(xmlreader.tagName) ) { data.Add(xmlreader.tagName, xmlreader.content); } else { Debug.LogWarning("Data already contained key " + xmlreader.tagName + " with value "+ data[ xmlreader.tagName ] +". Replacing value " + xmlreader.content); data[ xmlreader.tagName ] = xmlreader.content; } } } return data; } public static string DictionaryToXMLString(Dictionary<string, string> data, string root = "Root") { if (data == null) return string.Empty; List<string> keys = data.Keys.ToList(); List<string> values = data.Values.ToList(); string rawdata = string.Empty; rawdata += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n"; rawdata += "<"+root +">\r\n"; for (int i = 0; i < data.Count; ++i) { string key = keys[i]; string value = values[i]; if (value.Contains('<') || value.Contains('>') || value.Contains('&')) value = "<![CDATA[" + value + "]]>"; rawdata += "\t<" + key + ">" + value + "</" + key + ">\r\n"; } rawdata += "</"+ root +">\r\n"; return rawdata; } }
// // 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 Hyak.Common; using Microsoft.Azure.Management.DataFactories.Models; namespace Microsoft.Azure.Management.DataFactories.Models { /// <summary> /// The properties for the HDInsight linkedService. /// </summary> public partial class HDInsightOnDemandLinkedService : LinkedServiceProperties { private IList<string> _additionalLinkedServiceNames; /// <summary> /// Optional. Specify additional Azure storage accounts that need to be /// accessible from the cluster. /// </summary> public IList<string> AdditionalLinkedServiceNames { get { return this._additionalLinkedServiceNames; } set { this._additionalLinkedServiceNames = value; } } private int _clusterSize; /// <summary> /// Required. HDInsight cluster size. /// </summary> public int ClusterSize { get { return this._clusterSize; } set { this._clusterSize = value; } } private IDictionary<string, string> _coreConfiguration; /// <summary> /// Optional. Allows user to override default values for core /// configuration. /// </summary> public IDictionary<string, string> CoreConfiguration { get { return this._coreConfiguration; } set { this._coreConfiguration = value; } } private IDictionary<string, string> _hBaseConfiguration; /// <summary> /// Optional. Allows user to override default values for HBase /// configuration. /// </summary> public IDictionary<string, string> HBaseConfiguration { get { return this._hBaseConfiguration; } set { this._hBaseConfiguration = value; } } private HCatalogProperties _hcatalog; /// <summary> /// Optional. Hcatalog integration properties. /// </summary> public HCatalogProperties Hcatalog { get { return this._hcatalog; } set { this._hcatalog = value; } } private IDictionary<string, string> _hdfsConfiguration; /// <summary> /// Optional. Allows user to override default values for Hdfs /// configuration. /// </summary> public IDictionary<string, string> HdfsConfiguration { get { return this._hdfsConfiguration; } set { this._hdfsConfiguration = value; } } private IDictionary<string, string> _hiveConfiguration; /// <summary> /// Optional. Allows user to override default values for HIVE /// configuration. /// </summary> public IDictionary<string, string> HiveConfiguration { get { return this._hiveConfiguration; } set { this._hiveConfiguration = value; } } private string _hiveCustomLibrariesContainer; /// <summary> /// Optional. The name of the blob container that contains custom jar /// files for HIVE consumption. /// </summary> public string HiveCustomLibrariesContainer { get { return this._hiveCustomLibrariesContainer; } set { this._hiveCustomLibrariesContainer = value; } } private string _linkedServiceName; /// <summary> /// Required. Storage service name. /// </summary> public string LinkedServiceName { get { return this._linkedServiceName; } set { this._linkedServiceName = value; } } private IDictionary<string, string> _mapReduceConfiguration; /// <summary> /// Optional. Allows user to override default values for mapreduce /// configuration. /// </summary> public IDictionary<string, string> MapReduceConfiguration { get { return this._mapReduceConfiguration; } set { this._mapReduceConfiguration = value; } } private IDictionary<string, string> _oozieConfiguration; /// <summary> /// Optional. Allows user to override default values for oozie /// configuration. /// </summary> public IDictionary<string, string> OozieConfiguration { get { return this._oozieConfiguration; } set { this._oozieConfiguration = value; } } private IDictionary<string, string> _stormConfiguration; /// <summary> /// Optional. Allows user to override default values for Storm /// configuration. /// </summary> public IDictionary<string, string> StormConfiguration { get { return this._stormConfiguration; } set { this._stormConfiguration = value; } } private TimeSpan _timeToLive; /// <summary> /// Required. Time to live. /// </summary> public TimeSpan TimeToLive { get { return this._timeToLive; } set { this._timeToLive = value; } } private string _version; /// <summary> /// Optional. HDInsight version. /// </summary> public string Version { get { return this._version; } set { this._version = value; } } private IDictionary<string, string> _yarnConfiguration; /// <summary> /// Optional. Allows user to override default values for YARN /// configuration. /// </summary> public IDictionary<string, string> YarnConfiguration { get { return this._yarnConfiguration; } set { this._yarnConfiguration = value; } } /// <summary> /// Initializes a new instance of the HDInsightOnDemandLinkedService /// class. /// </summary> public HDInsightOnDemandLinkedService() { this.AdditionalLinkedServiceNames = new LazyList<string>(); this.CoreConfiguration = new LazyDictionary<string, string>(); this.HBaseConfiguration = new LazyDictionary<string, string>(); this.HdfsConfiguration = new LazyDictionary<string, string>(); this.HiveConfiguration = new LazyDictionary<string, string>(); this.MapReduceConfiguration = new LazyDictionary<string, string>(); this.OozieConfiguration = new LazyDictionary<string, string>(); this.StormConfiguration = new LazyDictionary<string, string>(); this.YarnConfiguration = new LazyDictionary<string, string>(); } /// <summary> /// Initializes a new instance of the HDInsightOnDemandLinkedService /// class with required arguments. /// </summary> public HDInsightOnDemandLinkedService(int clusterSize, TimeSpan timeToLive, string linkedServiceName) : this() { if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } this.ClusterSize = clusterSize; this.TimeToLive = timeToLive; this.LinkedServiceName = linkedServiceName; } } }
/* * @(#)NumberTheory.cs 3.0.0 2016-05-07 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``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 <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. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * [email protected] * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ using System; namespace org.mariuszgromada.math.mxparser.mathcollection { /** * NumberTheory - summation / products etc... * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:[email protected]">[email protected]</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * * @version 3.0.0 */ [CLSCompliant(true)] public sealed class NumberTheory { /** * Minimum function. * * @param a the a function parameter * @param b the b function parameter * * @return if a,b <> Double.NaN returns Math.min(a, b), * otherwise returns Double.NaN. */ public static double min(double a, double b) { if (Double.IsNaN(a) || Double.IsNaN(b)) return Double.NaN; return Math.Min(a, b); } /** * Minimum function. * * @param numbers the a function parameter * * @return if each number form numbers <> Double.NaN returns the smallest number, * otherwise returns Double.NaN. */ public static double min(params double[] numbers) { double min = Double.PositiveInfinity; foreach (double number in numbers) { if (Double.IsNaN(number)) return Double.NaN; if (number < min) min = number; } return min; } /** * Maximum function. * * @param a the a function parameter * @param b the b function parameter * * @return if a,b <> Double.NaN returns Math.max(a, b), * otherwise returns Double.NaN. */ public static double max(double a, double b) { if (Double.IsNaN(a) || Double.IsNaN(b)) return Double.NaN; return Math.Max(a, b); } /** * Maximum function. * * @param numbers the a function parameter * * @return if each number form numbers <> Double.NaN returns the highest number, * otherwise returns Double.NaN. */ public static double max(params double[] numbers) { double max = Double.NegativeInfinity; foreach (double number in numbers) { if (Double.IsNaN(number)) return Double.NaN; if (number > max) max = number; } return max; } /** * Greatest common divisor (GCD) * * @param a the a function parameter * @param b the b function parameter * @return GCD(a,b) */ public static double gcd(int a, int b) { a = Math.Abs(a); b = Math.Abs(b); if (a == 0) return b; while (b != 0) if (a > b) a -= b; else b -= a; return a; } /** * Greatest common divisor (GCD) * * @param a the a function parameter * @param b the b function parameter * * @return if a, b <> Double.NaN returns gcd( (int)Math.round(a),(int)Math.round(b) ), * otherwise returns Double.NaN. */ public static double gcd(double a, double b) { if (Double.IsNaN(a) || Double.IsNaN(a)) return Double.NaN; return gcd((int)Math.Round(a), (int)Math.Round(b)); } /** * Greatest common divisor (GCD) * * @param numbers the numbers * * @return GCD(a_1,...,a_n) a_1,...,a_n in numbers */ public static double gcd(params int[] numbers) { if (numbers.Length == 1) return numbers[0]; if (numbers.Length == 2) return gcd(numbers[0], numbers[1]); for (int i = 1; i < numbers.Length; i++) numbers[i] = (int)gcd(numbers[i - 1], numbers[i]); return numbers[numbers.Length - 1]; } /** * Greatest common divisor (GCD) * * @param numbers the numbers * * @return if each number form numbers <> Double.NaN returns * GCD(a_1,...,a_n) a_1,...,a_n in numbers, * otherwise returns Double.NaN. */ public static double gcd(params double[] numbers) { int[] intNumbers = new int[numbers.Length]; for (int i = 0; i < numbers.Length; i++) { double n = numbers[i]; if (Double.IsNaN(n)) return Double.NaN; intNumbers[i] = (int)Math.Round(n); } return gcd(intNumbers); } /** * Latest common multiply (LCM) * * @param a the a function parameter * @param b the b function parameter * * @return LCM(a,b) */ public static double lcm(int a, int b) { if ((a == 0) || (b == 0)) return 0; return Math.Abs(a * b) / gcd(a, b); } /** * Latest common multiply (LCM) * * @param a the a function parameter * @param b the b function parameter * * @return if a, b <> Double.NaN returns lcm( (int)Math.round(a), (int)Math.round(b) ), * otherwise returns Double.NaN. */ public static double lcm(double a, double b) { if (Double.IsNaN(a) || Double.IsNaN(a)) return Double.NaN; return lcm((int)Math.Round(a), (int)Math.Round(b)); } /** * Latest common multiply (LCM) * * @param numbers the numbers * * @return LCM(a_1,...,a_n) a_1,...,a_n in numbers */ public static double lcm(params int[] numbers) { if (numbers.Length == 1) return numbers[0]; if (numbers.Length == 2) return lcm(numbers[0], numbers[1]); for (int i = 1; i < numbers.Length; i++) numbers[i] = (int)lcm(numbers[i - 1], numbers[i]); return numbers[numbers.Length - 1]; } /** * Latest common multiply (LCM) * * @param numbers the numbers * * @return if each number form numbers <> Double.NaN returns * LCM(a_1,...,a_n) a_1,...,a_n in numbers, * otherwise returns Double.NaN. */ public static double lcm(params double[] numbers) { int[] intNumbers = new int[numbers.Length]; for (int i = 0; i < numbers.Length; i++) { double n = numbers[i]; if (Double.IsNaN(n)) return Double.NaN; intNumbers[i] = (int)Math.Round(n); if (intNumbers[i] == 0) return 0; } return lcm(intNumbers); } /** * Adding numbers. * * @param numbers the numbers * * @return if each number from numbers <> Double.NaN returns * sum(a_1,...,a_n) a_1,...,a_n in numbers, * otherwise returns Double.NaN. */ public static double sum(params double[] numbers) { if (numbers.Length == 0) return Double.NaN; if (numbers.Length == 1) return numbers[0]; double sum = 0; foreach (double xi in numbers) { if (Double.IsNaN(xi)) return Double.NaN; sum += xi; } return sum; } /** * Numbers multiplication. * * @param numbers the numbers * * @return if each number from numbers <> Double.NaN returns * prod(a_1,...,a_n) a_1,...,a_n in numbers, * otherwise returns Double.NaN. */ public static double prod(params double[] numbers) { if (numbers.Length == 0) return Double.NaN; if (numbers.Length == 1) return numbers[0]; double prod = 1; foreach (double xi in numbers) { if (Double.IsNaN(xi)) return Double.NaN; prod *= xi; } return prod; } /** * Prime test * * @param n * * @return true if number is prime, otherwise false */ public static bool primeTest(long n) { /* * 2 is a prime :-) */ if (n == 2) return true; /* * Even number is not a prime */ if (n % 2 == 0) return false; /* * Everything <= 1 is not a prime */ if (n <= 1) return false; /* * Will be searching for divisors till sqrt(n) */ long top = (long)Math.Sqrt(n); /* * Supporting variable indicating odd end of primes cache */ long primesCacheOddEnd = 3; /* * If prime cache exist */ if (mXparser.primesCache != null) if (mXparser.primesCache.cacheStatus == PrimesCache.CACHING_FINISHED) { /* * If prime cache is ready and number we are querying * is in cache the cache answer will be returned */ if (n <= mXparser.primesCache.maxNumInCache) return mXparser.primesCache.isPrime[(int)n]; else { /* * If number is bigger than maximum stored in cache * the we are querying each prime in cache * and checking if it is a divisor of n */ long topCache = Math.Min(top, mXparser.primesCache.maxNumInCache); long i; for (i = 3; i <= topCache; i += 2) { if (mXparser.primesCache.isPrime[(int)i] == true) if (n % i == 0) return false; } /* * If no prime divisor of n in primes cache * we are seting the odd end of prime cache */ primesCacheOddEnd = i; } } /* * Finally we are checking any odd number that * still left and is below sqrt(n) agains being * divisor of n */ for (long i = primesCacheOddEnd; i <= top; i += 2) if (n % i == 0) return false; return true; } /** * Prime test * * @param n * * @return true if number is prime, otherwise false */ public static double primeTest(double n) { if (Double.IsNaN(n)) return Double.NaN; bool isPrime = primeTest((long)n); if (isPrime == true) return 1; else return 0; } /** * Prime counting function * * @param n number * * @return Number of primes below or equal x */ public static long primeCount(long n) { if (n <= 1) return 0; if (n == 2) return 1; long numberOfPrimes = 1; for (long i = 3; i <= n; i++) if (primeTest(i) == true) numberOfPrimes++; return numberOfPrimes; } /** * Prime counting function * * @param n number * * @return Number of primes below or equal x */ public static double primeCount(double n) { return primeCount((long)n); } /** * Summation operator (SIGMA FROM i = a, to b, f(i) by delta * * @param f the expression * @param index the name of index argument * @param from FROM index = form * @param to TO index = to * @param delta BY delta * * @return summation operation (for empty summation operations returns 0). */ public static double sigmaSummation(Expression f, Argument index, double from, double to, double delta) { double result = 0; if ((Double.IsNaN(delta)) || (Double.IsNaN(from)) || (Double.IsNaN(to)) || (delta == 0)) return Double.NaN; if ((to >= from) && (delta > 0)) { double i; for (i = from; i < to; i += delta) result += mXparser.getFunctionValue(f, index, i); if (delta - (i - to) > 0.5 * delta) result += mXparser.getFunctionValue(f, index, to); } else if ((to <= from) && (delta < 0)) { double i; for (i = from; i > to; i += delta) result += mXparser.getFunctionValue(f, index, i); if (delta - (to - i) > 0.5 * delta) result += mXparser.getFunctionValue(f, index, to); } else if (from == to) result += mXparser.getFunctionValue(f, index, from); return result; } /** * Product operator * * @param f the expression * @param index the name of index argument * @param from FROM index = form * @param to TO index = to * @param delta BY delta * * @return product operation (for empty product operations returns 1). * * @see Expression * @see Argument */ public static double piProduct(Expression f, Argument index, double from, double to, double delta) { if ((Double.IsNaN(delta)) || (Double.IsNaN(from)) || (Double.IsNaN(to)) || (delta == 0)) return Double.NaN; double result = 1; if ((to >= from) && (delta > 0)) { double i; for (i = from; i < to; i += delta) result *= mXparser.getFunctionValue(f, index, i); if (delta - (i - to) > 0.5 * delta) result *= mXparser.getFunctionValue(f, index, to); } else if ((to <= from) && (delta < 0)) { double i; for (i = from; i > to; i += delta) result *= mXparser.getFunctionValue(f, index, i); if (delta - (to - i) > 0.5 * delta) result *= mXparser.getFunctionValue(f, index, to); } else if (from == to) result *= mXparser.getFunctionValue(f, index, from); return result; } /** * Minimum value - iterative operator. * * @param f the expression * @param index the name of index argument * @param from FROM index = form * @param to TO index = to * @param delta BY delta * * @return product operation (for empty product operations returns 1). * * @see Expression * @see Argument */ public static double min(Expression f, Argument index, double from, double to, double delta) { if ((Double.IsNaN(delta)) || (Double.IsNaN(from)) || (Double.IsNaN(to)) || (delta == 0)) return Double.NaN; double min = Double.PositiveInfinity; double v; if ((to >= from) && (delta > 0)) { for (double i = from; i < to; i += delta) { v = mXparser.getFunctionValue(f, index, i); if (v < min) min = v; } v = mXparser.getFunctionValue(f, index, to); if (v < min) min = v; } else if ((to <= from) && (delta < 0)) { for (double i = from; i > to; i += delta) { v = mXparser.getFunctionValue(f, index, i); if (v < min) min = v; } v = mXparser.getFunctionValue(f, index, to); if (v < min) min = v; } else if (from == to) min = mXparser.getFunctionValue(f, index, from); return min; } /** * Maximum value - iterative operator. * * @param f the expression * @param index the name of index argument * @param from FROM index = form * @param to TO index = to * @param delta BY delta * * @return product operation (for empty product operations returns 1). * * @see Expression * @see Argument */ public static double max(Expression f, Argument index, double from, double to, double delta) { if ((Double.IsNaN(delta)) || (Double.IsNaN(from)) || (Double.IsNaN(to)) || (delta == 0)) return Double.NaN; double max = Double.NegativeInfinity; double v; if ((to >= from) && (delta > 0)) { for (double i = from; i < to; i += delta) { v = mXparser.getFunctionValue(f, index, i); if (v > max) max = v; } v = mXparser.getFunctionValue(f, index, to); if (v > max) max = v; } else if ((to <= from) && (delta < 0)) { for (double i = from; i > to; i += delta) { v = mXparser.getFunctionValue(f, index, i); if (v > max) max = v; } v = mXparser.getFunctionValue(f, index, to); if (v > max) max = v; } else if (from == to) max = mXparser.getFunctionValue(f, index, from); return max; } } }
using System; using System.IO; using System.Net; using System.Text; using System.Web; using Newtonsoft.Json.Linq; namespace LoveSeat.Support { /// <summary> /// Repersent a web request for CouchDB database. /// </summary> public class CouchRequest { private const string INVALID_USERNAME_OR_PASSWORD = "reason=Name or password is incorrect"; private const string NOT_AUTHORIZED = "reason=You are not authorized to access this db."; private const int STREAM_BUFFER_SIZE = 4096; private readonly HttpWebRequest request; public CouchRequest(string uri) : this(uri, new Cookie(), null) { } /// <summary> /// Request with Cookie authentication /// </summary> /// <param name="uri"></param> /// <param name="authCookie"></param> /// <param name="eTag"></param> public CouchRequest(string uri, Cookie authCookie, string eTag) { request = (HttpWebRequest)WebRequest.Create(uri); request.Headers.Clear(); //important if (!string.IsNullOrEmpty(eTag)) request.Headers.Add("If-None-Match", eTag); request.Headers.Add("Accept-Charset", "utf-8"); request.Headers.Add("Accept-Language", "en-us"); request.Referer = uri; request.ContentType = "application/json"; request.KeepAlive = true; if (authCookie != null) request.Headers.Add("Cookie", "AuthSession=" + authCookie.Value); } /// <summary> /// Basic Authorization Header /// </summary> /// <param name="uri"></param> /// <param name="username"></param> /// <param name="password"></param> public CouchRequest(string uri, string username, string password) { request = (HttpWebRequest)WebRequest.Create(uri); request.Headers.Clear(); //important // Deal with Authorization Header if (username != null) { string authValue = "Basic "; string userNAndPassword = username + ":" + password; // Base64 encode string b64 = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(userNAndPassword)); authValue = authValue + b64; request.Headers.Add("Authorization", authValue); } request.Headers.Add("Accept-Charset", "utf-8"); request.Headers.Add("Accept-Language", "en-us"); request.ContentType = "application/json"; request.Accept = "application/json"; request.KeepAlive = true; } public CouchRequest Put() { request.Method = "PUT"; return this; } public CouchRequest Get() { request.Method = "GET"; return this; } public CouchRequest Post() { request.Method = "POST"; return this; } public CouchRequest Delete() { request.Method = "DELETE"; return this; } public CouchRequest Data(Stream data) { using (var body = request.GetRequestStream()) { var buffer = new byte[STREAM_BUFFER_SIZE]; var bytesRead = 0; while (0 != (bytesRead = data.Read(buffer, 0, buffer.Length))) { body.Write(buffer, 0, bytesRead); } } return this; } public CouchRequest Data(string data) { using (var body = request.GetRequestStream()) { var encodedData = Encoding.UTF8.GetBytes(data); body.Write(encodedData, 0, encodedData.Length); } return this; } public CouchRequest Data(byte[] attachment) { using (var body = request.GetRequestStream()) { body.Write(attachment, 0, attachment.Length); } return this; } public CouchRequest Data(JObject obj) { return Data(obj.ToString()); } public CouchRequest ContentType(string contentType) { request.ContentType = contentType; return this; } public CouchRequest Form() { request.ContentType = "application/x-www-form-urlencoded"; return this; } public CouchRequest Json() { request.ContentType = "application/json"; return this; } public CouchRequest Timeout(int? timeoutMs) { if (timeoutMs.HasValue) { request.Timeout = timeoutMs.Value; } else { request.Timeout = (int)TimeSpan.FromHours(1).TotalMilliseconds; } return this; } public HttpWebRequest GetRequest() { return request; } /// <summary> /// Get the response from CouchDB. /// </summary> /// <returns></returns> public CouchResponse GetCouchResponse() { bool failedAuth = false; try { using (var response = (HttpWebResponse)request.GetResponse()) { string msg = ""; if (isAuthenticateOrAuthorized(response, ref msg) == false) { failedAuth = true; throw new WebException(msg); } if (response.StatusCode == HttpStatusCode.BadRequest) { throw new CouchException(request, response, response.GetResponseString() + "\n" + request.RequestUri); } return new CouchResponse(response); } } catch (WebException webEx) { if (failedAuth == true) { throw webEx; } var response = (HttpWebResponse)webEx.Response; if (response == null) throw new HttpException("Request failed to receive a response", webEx); if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new CouchException(request, response, response.GetResponseString() + "\n" + request.RequestUri); } return new CouchResponse(response); } throw new HttpException("Request failed to receive a response"); } public HttpWebResponse GetHttpResponse() { bool failedAuth = false; try { var response = (HttpWebResponse)request.GetResponse(); string msg = ""; if (isAuthenticateOrAuthorized(response, ref msg) == false) { failedAuth = true; throw new WebException(msg, new System.Exception(msg)); } return response; } catch (WebException webEx) { if (failedAuth == true) { throw; } var response = (HttpWebResponse)webEx.Response; if (response == null) throw new HttpException("Request failed to receive a response", webEx); return response; } throw new HttpException("Request failed to receive a response"); } /// <summary> /// Checks response if username and password was valid /// </summary> /// <param name="response"></param> private bool isAuthenticateOrAuthorized(HttpWebResponse response, ref string message) { //"reason=Name or password is incorrect" // Check if query string is okay string[] split = response.ResponseUri.Query.Split('&'); if (split.Length > 0) { for (int i = 0; i < split.Length; i++) { string temp = System.Web.HttpUtility.UrlDecode(split[i]); if (temp.Contains(INVALID_USERNAME_OR_PASSWORD) == true) { message = "Invalid username or password"; return false; } else if (temp.Contains(NOT_AUTHORIZED) == true) { message = "Not Authorized to access database"; return false; } } } return true; }// end private void checkResponse(... } }
using UnityEditor; using UnityEditor.AnimatedValues; using UnityEngine; namespace UnityStandardAssets.CinematicEffects { [CustomEditor(typeof(DepthOfField))] class DepthOfFieldEditor : Editor { [CustomPropertyDrawer(typeof(DepthOfField.GradientRangeAttribute))] internal sealed class GradientRangeDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType != SerializedPropertyType.Float) { EditorGUI.LabelField(position, label.text, "Use GradientRange with float."); return; } var savedbackgroundColor = GUI.backgroundColor; var gradientRange = (DepthOfField.GradientRangeAttribute)attribute; float range01 = (property.floatValue - gradientRange.min) / (gradientRange.max - gradientRange.min); GUI.backgroundColor = Color.Lerp(Color.green, Color.yellow, range01); EditorGUI.Slider(position, property, gradientRange.min, gradientRange.max, label); GUI.backgroundColor = savedbackgroundColor; } } SerializedProperty m_UIMode; SerializedProperty m_VisualizeBluriness; SerializedProperty m_FocusPlane; SerializedProperty m_FocusRange; SerializedProperty m_NearPlane; SerializedProperty m_NearRadius; SerializedProperty m_HighQualityUpsampling; SerializedProperty m_DilateNearBlur; SerializedProperty m_PrefilterBlur; SerializedProperty m_MedianFilter; SerializedProperty m_FarPlane; SerializedProperty m_FarRadius; SerializedProperty m_ApertureShape; SerializedProperty m_UseBokehTexture; SerializedProperty m_ApertureOrientation; SerializedProperty m_BoostPoint; SerializedProperty m_NearBoostAmount; SerializedProperty m_FarBoostAmount; SerializedProperty m_FStops; SerializedProperty m_Radius; SerializedProperty m_FocusTransform; SerializedProperty m_Dx11BokehThreshold; SerializedProperty m_Dx11SpawnHeuristic; SerializedProperty m_Dx11BokehTexture; SerializedProperty m_Dx11BokehScale; SerializedProperty m_Dx11BokehIntensity; SerializedObject m_TargetSerializedDOFObject; SerializedProperty m_Quality; SerializedProperty m_CustomizeQualitySettings; bool useBokehTexture { get { return m_UseBokehTexture.boolValue; } } bool useAdvancedOrExplicitView { get { return (m_UIMode.enumValueIndex != (int)DepthOfField.UIMode.Basic); } } bool useExplicitView { get { return (m_UIMode.enumValueIndex == (int)DepthOfField.UIMode.Explicit); } } bool useBlurOrientation { get { return ((m_ApertureShape.enumValueIndex == (int)DepthOfField.ApertureShape.Hexagonal) || (m_ApertureShape.enumValueIndex == (int)DepthOfField.ApertureShape.Octogonal)); } } AnimBool showQualitySettings = new AnimBool(); AnimBool showBoostSettings = new AnimBool(); AnimBool showBlurOrientation = new AnimBool(); AnimBool showDX11BlurSettings = new AnimBool(); AnimBool showExplicitSettings = new AnimBool(); void OnEnable() { m_TargetSerializedDOFObject = new SerializedObject(target); m_UIMode = m_TargetSerializedDOFObject.FindProperty("uiMode"); m_VisualizeBluriness = m_TargetSerializedDOFObject.FindProperty("visualizeBluriness"); m_FocusPlane = m_TargetSerializedDOFObject.FindProperty("focusPlane"); m_FocusRange = m_TargetSerializedDOFObject.FindProperty("focusRange"); m_NearPlane = m_TargetSerializedDOFObject.FindProperty("nearPlane"); m_NearRadius = m_TargetSerializedDOFObject.FindProperty("nearRadius"); m_FarPlane = m_TargetSerializedDOFObject.FindProperty("farPlane"); m_FarRadius = m_TargetSerializedDOFObject.FindProperty("farRadius"); m_ApertureShape = m_TargetSerializedDOFObject.FindProperty("apertureShape"); m_ApertureOrientation = m_TargetSerializedDOFObject.FindProperty("apertureOrientation"); m_UseBokehTexture = m_TargetSerializedDOFObject.FindProperty("useBokehTexture"); m_BoostPoint = m_TargetSerializedDOFObject.FindProperty("boostPoint"); m_NearBoostAmount = m_TargetSerializedDOFObject.FindProperty("nearBoostAmount"); m_FarBoostAmount = m_TargetSerializedDOFObject.FindProperty("farBoostAmount"); m_FStops = m_TargetSerializedDOFObject.FindProperty("fStops"); m_Radius = m_TargetSerializedDOFObject.FindProperty("radius"); m_FocusTransform = m_TargetSerializedDOFObject.FindProperty("focusTransform"); m_Dx11BokehThreshold = m_TargetSerializedDOFObject.FindProperty("textureBokehThreshold"); m_Dx11SpawnHeuristic = m_TargetSerializedDOFObject.FindProperty("textureBokehSpawnHeuristic"); m_Dx11BokehTexture = m_TargetSerializedDOFObject.FindProperty("bokehTexture"); m_Dx11BokehScale = m_TargetSerializedDOFObject.FindProperty("textureBokehScale"); m_Dx11BokehIntensity = m_TargetSerializedDOFObject.FindProperty("textureBokehIntensity"); m_HighQualityUpsampling = m_TargetSerializedDOFObject.FindProperty("highQualityUpsampling"); m_DilateNearBlur = m_TargetSerializedDOFObject.FindProperty("dilateNearBlur"); m_PrefilterBlur = m_TargetSerializedDOFObject.FindProperty("prefilterBlur"); m_MedianFilter = m_TargetSerializedDOFObject.FindProperty("medianFilter"); m_Quality = m_TargetSerializedDOFObject.FindProperty("quality"); m_CustomizeQualitySettings = m_TargetSerializedDOFObject.FindProperty("customizeQualitySettings"); InitializedAnimBools(); } void InitializedAnimBools() { showQualitySettings.valueChanged.AddListener(Repaint); showQualitySettings.value = useAdvancedOrExplicitView; showBlurOrientation.valueChanged.AddListener(Repaint); showBlurOrientation.value = useBlurOrientation; showDX11BlurSettings.valueChanged.AddListener(Repaint); showDX11BlurSettings.value = useBokehTexture; showBoostSettings.valueChanged.AddListener(Repaint); showBoostSettings.value = useAdvancedOrExplicitView; showExplicitSettings.valueChanged.AddListener(Repaint); showExplicitSettings.value = useExplicitView; } void UpdateAnimBoolTargets() { showQualitySettings.target = useAdvancedOrExplicitView; showBlurOrientation.target = useBlurOrientation; showDX11BlurSettings.target = useBokehTexture; showBoostSettings.target = useAdvancedOrExplicitView; showExplicitSettings.target = useExplicitView; } void SyncParametersAndQualityLevel(bool fromQualityLevelToParams) { const float prefilterBlurQuality = 10.0f; const float medianFilterQuality = 30.0f; const float dilateNearBlurQuality = 50.0f; const float medianFilterQualityHigh = 70.0f; const float highUpsamplingQuality = 90.0f; if (fromQualityLevelToParams) { int medianFilterEnumValue = 0; if (m_Quality.floatValue >= medianFilterQuality) ++medianFilterEnumValue; if (m_Quality.floatValue >= medianFilterQualityHigh) ++medianFilterEnumValue; m_MedianFilter.enumValueIndex = medianFilterEnumValue; m_DilateNearBlur.boolValue = (m_Quality.floatValue >= dilateNearBlurQuality); m_PrefilterBlur.boolValue = (m_Quality.floatValue >= prefilterBlurQuality); m_HighQualityUpsampling.boolValue = (m_Quality.floatValue >= highUpsamplingQuality); } else { const float stepBack = 5.0f; //trying to find a quality level matching the parameters (going down first and climbing back) if (!m_HighQualityUpsampling.boolValue) m_Quality.floatValue = Mathf.Min(highUpsamplingQuality - stepBack, m_Quality.floatValue); if (!m_PrefilterBlur.boolValue) m_Quality.floatValue = Mathf.Min(prefilterBlurQuality - stepBack, m_Quality.floatValue); if (!m_DilateNearBlur.boolValue) m_Quality.floatValue = Mathf.Min(dilateNearBlurQuality - stepBack, m_Quality.floatValue); if (m_MedianFilter.enumValueIndex == (int)DepthOfField.FilterQuality.Normal) m_Quality.floatValue = Mathf.Min(medianFilterQualityHigh - stepBack, m_Quality.floatValue); if (m_MedianFilter.enumValueIndex == (int)DepthOfField.FilterQuality.None) m_Quality.floatValue = Mathf.Min(medianFilterQuality - stepBack, m_Quality.floatValue); if (m_HighQualityUpsampling.boolValue) m_Quality.floatValue = Mathf.Max(highUpsamplingQuality, m_Quality.floatValue); if (m_PrefilterBlur.boolValue) m_Quality.floatValue = Mathf.Max(prefilterBlurQuality, m_Quality.floatValue); if (m_DilateNearBlur.boolValue) m_Quality.floatValue = Mathf.Max(dilateNearBlurQuality, m_Quality.floatValue); if (m_MedianFilter.enumValueIndex == (int)DepthOfField.FilterQuality.High) m_Quality.floatValue = Mathf.Max(medianFilterQualityHigh, m_Quality.floatValue); if (m_MedianFilter.enumValueIndex == (int)DepthOfField.FilterQuality.Normal) m_Quality.floatValue = Mathf.Max(medianFilterQuality - 1, m_Quality.floatValue); } } private void OnQualityLevelInspectorGUI() { SyncParametersAndQualityLevel(!m_CustomizeQualitySettings.boolValue); GUI.enabled = !m_CustomizeQualitySettings.boolValue; EditorGUILayout.PropertyField(m_Quality); GUI.enabled = true; if (m_UIMode.enumValueIndex == (int)DepthOfField.UIMode.Basic) { m_CustomizeQualitySettings.boolValue = false; } if (EditorGUILayout.BeginFadeGroup(showQualitySettings.faded)) { ++EditorGUI.indentLevel; EditorGUILayout.PropertyField(m_CustomizeQualitySettings); ++EditorGUI.indentLevel; GUI.enabled = m_CustomizeQualitySettings.boolValue; EditorGUILayout.PropertyField(m_PrefilterBlur, new GUIContent(" Smooth Bokeh")); EditorGUILayout.PropertyField(m_MedianFilter, new GUIContent(" More smooth Bokeh")); EditorGUILayout.PropertyField(m_DilateNearBlur, new GUIContent(" Dilate near blur")); EditorGUILayout.PropertyField(m_HighQualityUpsampling, new GUIContent(" Smooth Edges")); GUI.enabled = true; EditorGUI.indentLevel -= 2; } EditorGUILayout.EndFadeGroup(); } private void OnBokehTextureInspectorGUI() { EditorGUILayout.PropertyField(m_UseBokehTexture); if (EditorGUILayout.BeginFadeGroup(showDX11BlurSettings.faded)) { if (!ImageEffectHelper.supportsDX11) { EditorGUILayout.HelpBox("Bokeh Texture not supported (need shader model 5)", MessageType.Info); } } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(showDX11BlurSettings.faded)) { if (ImageEffectHelper.supportsDX11) { EditorGUILayout.PropertyField(m_Dx11BokehTexture, new GUIContent(" Texture")); EditorGUILayout.PropertyField(m_Dx11BokehScale, new GUIContent(" Scale")); EditorGUILayout.PropertyField(m_Dx11BokehIntensity, new GUIContent(" Intensity")); EditorGUILayout.PropertyField(m_Dx11BokehThreshold, new GUIContent(" Min Luminance")); EditorGUILayout.PropertyField(m_Dx11SpawnHeuristic, new GUIContent(" Spawn Heuristic")); } } EditorGUILayout.EndFadeGroup(); EditorGUILayout.Separator(); } public override void OnInspectorGUI() { m_TargetSerializedDOFObject.Update(); UpdateAnimBoolTargets(); EditorGUILayout.LabelField("Simulates camera lens defocus", EditorStyles.miniLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(m_VisualizeBluriness); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(m_UIMode, new GUIContent("Mode")); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(m_ApertureShape); if (EditorGUILayout.BeginFadeGroup(showBlurOrientation.faded)) { EditorGUILayout.PropertyField(m_ApertureOrientation); } EditorGUILayout.EndFadeGroup(); if ((m_ApertureShape.enumValueIndex == (int)DepthOfField.ApertureShape.Circular) || (m_ApertureShape.enumValueIndex == (int)DepthOfField.ApertureShape.Hexagonal) || (m_ApertureShape.enumValueIndex == (int)DepthOfField.ApertureShape.Octogonal) ) { EditorGUILayout.Separator(); OnQualityLevelInspectorGUI(); } EditorGUILayout.Separator(); EditorGUILayout.PropertyField(m_FocusPlane); EditorGUILayout.PropertyField(m_FocusTransform, new GUIContent("Focus on Transform")); EditorGUILayout.Separator(); if (m_UIMode.enumValueIndex == (int)DepthOfField.UIMode.Basic) { EditorGUILayout.PropertyField(m_FStops, new GUIContent("F-Stops")); EditorGUILayout.PropertyField(m_FocusRange); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(m_Radius, new GUIContent("Max Blur")); m_NearRadius.floatValue = m_Radius.floatValue; m_FarRadius.floatValue = m_Radius.floatValue; m_UseBokehTexture.boolValue = false; } else { if (EditorGUILayout.BeginFadeGroup(1 - showExplicitSettings.faded)) { EditorGUILayout.Slider(m_FStops, 1.0f, 128.0f, new GUIContent("F-Stops")); EditorGUILayout.PropertyField(m_FocusRange); } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(showExplicitSettings.faded)) { EditorGUILayout.PropertyField(m_FocusRange); EditorGUILayout.PropertyField(m_NearPlane); EditorGUILayout.PropertyField(m_FarPlane); } EditorGUILayout.EndFadeGroup(); EditorGUILayout.Separator(); OnBokehTextureInspectorGUI(); if (EditorGUILayout.BeginFadeGroup(showDX11BlurSettings.faded)) { EditorGUILayout.PropertyField(m_Radius, new GUIContent("Max Blur")); m_NearRadius.floatValue = m_Radius.floatValue; m_FarRadius.floatValue = m_Radius.floatValue; } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(1 - showDX11BlurSettings.faded)) { EditorGUILayout.PropertyField(m_NearRadius, new GUIContent("Near Max Blur")); EditorGUILayout.PropertyField(m_FarRadius, new GUIContent("Far Max Blur")); m_Radius.floatValue = (m_FarRadius.floatValue + m_NearRadius.floatValue) * 0.5f; } EditorGUILayout.EndFadeGroup(); } EditorGUILayout.Separator(); if (EditorGUILayout.BeginFadeGroup(showBoostSettings.faded)) { EditorGUILayout.PropertyField(m_BoostPoint); EditorGUILayout.PropertyField(m_NearBoostAmount); EditorGUILayout.PropertyField(m_FarBoostAmount); } EditorGUILayout.EndFadeGroup(); m_TargetSerializedDOFObject.ApplyModifiedProperties(); } } }
/* * Copyright (c) 2013 Mario Freitas ([email protected]) * * 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.Text; namespace URLClient { public class HTTPRequest { /// <summary>GET, HEAD, POST, PUT, DELETE, ...</summary> public string method; /// <summary>HTTP/HTTPS URL for the request.</summary> public URL url; /// <summary>Username to use for authentication.</summary> public string authUser; /// <summary>Password to use for authentication.</summary> public string authPassword; /// <summary>Headers to be sent to the server.</summary> public HTTPHeaderList headers; /// <summary>Content handler for this request.</summary> public HTTPRequestContentHandler contentHandler; public HTTPRequest() : this(null) { } public HTTPRequest(string url, HTTPHeaderList headers = null) { method = "GET"; SetURL(url); if (headers == null) { headers = new HTTPHeaderList(); } authUser = null; authPassword = null; contentHandler = null; } #region HTTP url public HTTPRequest SetURL(URL url) { if ((url == null) || ((url.Scheme != "http") && (url.Scheme != "https"))) { url = null; } this.url = url; return this; } public HTTPRequest SetURL(string url) { return SetURL(URL.Parse(url)); } public HTTPRequest AppendQueryParameter(string name, string value, bool escape = true) { url.AppendQueryParameter(name, value, escape); return this; } #endregion #region HTTP method public HTTPRequest SetMethod(string method) { this.method = method; return this; } public HTTPRequest Get() { return SetMethod("GET"); } public HTTPRequest Head() { return SetMethod("HEAD"); } public HTTPRequest Post() { return SetMethod("POST"); } public HTTPRequest Post(byte[] content, string contentType = null) { SetContentBytes(content, contentType); return SetMethod("POST"); } public HTTPRequest Post(string content, string contentType = null, Encoding enc = null) { SetContentString(content, contentType); return SetMethod("POST"); } public HTTPRequest Put() { return SetMethod("PUT"); } public HTTPRequest Delete() { return SetMethod("DELETE"); } public HTTPRequest Options() { return SetMethod("DELETE"); } #endregion #region HTTP content public HTTPRequest SetContentHandler(HTTPRequestContentHandler handler) { contentHandler = handler; return this; } public HTTPRequest SetContentFromPath(string srcPath, string contentType = null) { contentHandler = new HTTPRequestContentUploadHandler(srcPath); if (contentType != null) { SetHeader("Content-Type", contentType); } return this; } public HTTPRequest SetContentBytes(byte[] content, string contentType = null) { contentHandler = new HTTPRequestContentBytesHandler(content); if (contentType != null) { SetHeader("Content-Type", contentType); } return this; } public HTTPRequest SetContentString(string content, string contentType = null, Encoding enc = null) { if (content == null) { return SetContentBytes(null, contentType); } if (enc == null) { enc = Encoding.UTF8; } return SetContentBytes(enc.GetBytes(content), contentType); } #endregion #region HTTP header public HTTPRequest SetHeader(string name, string value) { if (headers == null) { headers = new HTTPHeaderList(); } headers[name] = value; return this; } public HTTPRequest AppendCookie(string name, string value, bool escape = true) { string cookie = (headers == null) ? null : headers["Cookie"]; if (escape == true) { name = HTTPUtils.URLEncode(name); value = HTTPUtils.URLEncode(value); } if (string.IsNullOrEmpty(cookie)) { cookie = name + "=" + value; } else { cookie += "; " + name + "=" + value; } return SetHeader("Cookie", cookie); } public HTTPRequest AppendRange(ulong firstBytePos, ulong lastBytePos) { string range = (headers == null) ? null : headers["Range"]; if (string.IsNullOrEmpty(range)) { range = "bytes=" + firstBytePos + "-" + lastBytePos; } else { range += "," + firstBytePos + "-" + lastBytePos; } return SetHeader("Range", range); } public HTTPRequest AppendRange(ulong firstBytePos) { string range = (headers == null) ? null : headers["Range"]; if (string.IsNullOrEmpty(range)) { range = "bytes=" + firstBytePos + "-"; } else { range += "," + firstBytePos + "-"; } return SetHeader("Range", range); } public HTTPRequest AppendRangeSuffix(ulong suffixLength) { string range = (headers == null) ? null : headers["Range"]; if (string.IsNullOrEmpty(range)) { range = "bytes=-" + suffixLength; } else { range += ",-" + suffixLength; } return SetHeader("Range", range); } public HTTPRequest RemoveHeader(string name) { if (headers != null) { headers.Remove(name); } return this; } public HTTPRequest ClearHeaders() { if (headers != null) { headers.Clear(); } return this; } public HTTPRequest SetUserAgent(string contentType) { return SetHeader("User-Agent", contentType); } public HTTPRequest SetContentType(string type, string subtype, string parameter = null) { string mediaType = type + "/" + subtype; if (string.IsNullOrEmpty(parameter) == false) { mediaType += "; " + parameter; } return SetHeader("Content-Type", mediaType); } #endregion #region Authentication public HTTPRequest SetAuthCredential(string user, string password) { authUser = user; authPassword = password; return this; } #endregion public override string ToString() { return string.Format("HTTPRequest<method={0},url={1},headers={2}>", method, ((url == null) ? "" : url.ToString(true, false)), headers); } } }
using System.Threading.Tasks; using Shouldly; using Spectre.Cli.Internal.Exceptions; using Spectre.Cli.Tests.Data; using Spectre.Cli.Tests.Data.Settings; using Spectre.Cli.Tests.Fakes; using Xunit; namespace Spectre.Cli.Tests.Unit { public sealed class CommandAppTests { [Fact] public async Task Should_Pass_Case_1() { // Given var resolver = new FakeTypeResolver(); var settings = new DogSettings(); resolver.Register(settings); var app = new CommandApp(new FakeTypeRegistrar(resolver)); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddBranch<MammalSettings>("mammal", mammal => { mammal.AddCommand<DogCommand>("dog"); mammal.AddCommand<HorseCommand>("horse"); }); }); }); // When var result = await app.RunAsync( new[] { "animal", "--alive", "mammal", "--name", "Rufus", "dog", "12", "--good-boy" }); // Then result.ShouldBe(0); settings.Age.ShouldBe(12); settings.GoodBoy.ShouldBe(true); settings.IsAlive.ShouldBe(true); settings.Name.ShouldBe("Rufus"); } [Fact] public void Should_Pass_Case_2() { // Given var resolver = new FakeTypeResolver(); var settings = new DogSettings(); resolver.Register(settings); var app = new CommandApp(new FakeTypeRegistrar(resolver)); app.Configure(config => { config.PropagateExceptions(); config.AddCommand<DogCommand>("dog"); }); // When var result = app.Run(new[] { "dog", "12", "4", "--good-boy", "--name", "Rufus", "--alive" }); // Then result.ShouldBe(0); settings.Legs.ShouldBe(12); settings.Age.ShouldBe(4); settings.GoodBoy.ShouldBe(true); settings.IsAlive.ShouldBe(true); settings.Name.ShouldBe("Rufus"); } [Fact] public void Should_Pass_Case_3() { // Given var resolver = new FakeTypeResolver(); var settings = new DogSettings(); resolver.Register(settings); var app = new CommandApp(new FakeTypeRegistrar(resolver)); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // When var result = app.Run(new[] { "animal", "dog", "12", "--good-boy", "--name", "Rufus" }); // Then result.ShouldBe(0); settings.Age.ShouldBe(12); settings.GoodBoy.ShouldBe(true); settings.IsAlive.ShouldBe(false); settings.Name.ShouldBe("Rufus"); } [Fact] public void Should_Pass_Case_4() { // Given var resolver = new FakeTypeResolver(); var settings = new DogSettings(); resolver.Register(settings); var app = new CommandApp(new FakeTypeRegistrar(resolver)); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); }); }); // When var result = app.Run(new[] { "animal", "4", "dog", "12", "--good-boy", "--name", "Rufus" }); // Then result.ShouldBe(0); settings.Legs.ShouldBe(4); settings.Age.ShouldBe(12); settings.GoodBoy.ShouldBe(true); settings.IsAlive.ShouldBe(false); settings.Name.ShouldBe("Rufus"); } [Fact] public void Should_Register_Commands_When_Configuring_Application() { // Given var registrar = new FakeTypeRegistrar(); var app = new CommandApp(registrar); // When app.Configure(config => { config.PropagateExceptions(); config.AddCommand<GenericCommand<FooCommandSettings>>("foo"); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // Then registrar.Registrations.ContainsKey(typeof(ICommand)).ShouldBeTrue(); registrar.Registrations[typeof(ICommand)].Count.ShouldBe(3); registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(GenericCommand<FooCommandSettings>)); registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(DogCommand)); registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(HorseCommand)); } [Fact] public void Should_Register_Default_Command_When_Configuring_Application() { // Given var registrar = new FakeTypeRegistrar(); var app = new CommandApp<DogCommand>(registrar); // When app.Configure(config => { config.PropagateExceptions(); }); // Then registrar.Registrations.ContainsKey(typeof(ICommand)).ShouldBeTrue(); registrar.Registrations.ContainsKey(typeof(DogSettings)); registrar.Registrations[typeof(ICommand)].Count.ShouldBe(1); registrar.Registrations[typeof(ICommand)].ShouldContain(typeof(DogCommand)); } [Fact] public void Should_Register_Default_Command_Settings_When_Configuring_Application() { // Given var registrar = new FakeTypeRegistrar(); var app = new CommandApp<DogCommand>(registrar); // When app.Configure(config => { config.PropagateExceptions(); }); // Then registrar.Registrations.ContainsKey(typeof(DogSettings)); registrar.Registrations[typeof(DogSettings)].Count.ShouldBe(1); registrar.Registrations[typeof(DogSettings)].ShouldContain(typeof(DogSettings)); } [Fact] public void Should_Register_Command_Settings_When_Configuring_Application() { // Given var registrar = new FakeTypeRegistrar(); var app = new CommandApp(registrar); // When app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // Then registrar.Registrations.ContainsKey(typeof(DogSettings)).ShouldBeTrue(); registrar.Registrations[typeof(DogSettings)].Count.ShouldBe(1); registrar.Registrations[typeof(DogSettings)].ShouldContain(typeof(DogSettings)); registrar.Registrations.ContainsKey(typeof(MammalSettings)).ShouldBeTrue(); registrar.Registrations[typeof(MammalSettings)].Count.ShouldBe(1); registrar.Registrations[typeof(MammalSettings)].ShouldContain(typeof(MammalSettings)); } [Fact] public void Should_Throw_When_Encountering_Unknown_Option_In_Strict_Mode() { // Given var registrar = new FakeTypeRegistrar(); var app = new CommandApp(registrar); app.Configure(config => { config.PropagateExceptions(); config.UseStrictParsing(); config.AddCommand<DogCommand>("dog"); }); // When var result = Record.Exception(() => app.Run(new[] { "dog", "--foo" })); // Then result.ShouldBeOfType<ParseException>().And(ex => { ex.Message.ShouldBe("Unknown option 'foo'."); }); } [Fact] public void Should_Add_Unknown_Option_To_Remaining_Arguments_In_Relaxed_Mode() { // Given var capturedContext = default(CommandContext); var resolver = new FakeTypeResolver(); var command = new InterceptingCommand<DogSettings>((context, _) => { capturedContext = context; }); resolver.Register(new DogSettings()); resolver.Register(command); var registrar = new FakeTypeRegistrar(resolver); var app = new CommandApp(registrar); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<InterceptingCommand<DogSettings>>("dog"); }); }); // When var result = app.Run(new[] { "animal", "4", "dog", "12", "--foo", "bar" }); // Then capturedContext.ShouldNotBeNull(); capturedContext.Remaining.Parsed.Count.ShouldBe(1); capturedContext.ShouldHaveRemainingArgument("foo", values: new[] { "bar" }); } [Fact] public void Should_Add_Unknown_Boolean_Option_To_Remaining_Arguments_In_Relaxed_Mode() { // Given var capturedContext = default(CommandContext); var resolver = new FakeTypeResolver(); var command = new InterceptingCommand<DogSettings>((context, _) => { capturedContext = context; }); resolver.Register(new DogSettings()); resolver.Register(command); var registrar = new FakeTypeRegistrar(resolver); var app = new CommandApp(registrar); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<InterceptingCommand<DogSettings>>("dog"); }); }); // When var result = app.Run(new[] { "animal", "4", "dog", "12", "--foo" }); // Then capturedContext.ShouldNotBeNull(); capturedContext.Remaining.Parsed.Count.ShouldBe(1); capturedContext.ShouldHaveRemainingArgument("foo", values: new[] { (string)null }); } public sealed class Remaining_Arguments { [Fact] public void Should_Register_Remaining_Parsed_Arguments_With_Context() { // Given var capturedContext = default(CommandContext); var resolver = new FakeTypeResolver(); var command = new InterceptingCommand<DogSettings>((context, _) => { capturedContext = context; }); resolver.Register(new DogSettings()); resolver.Register(command); var app = new CommandApp(new FakeTypeRegistrar(resolver)); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<InterceptingCommand<DogSettings>>("dog"); }); }); // When app.Run(new[] { "animal", "4", "dog", "12", "--", "--foo", "bar", "--foo", "baz", "-bar", "\"baz\"", "qux" }); // Then capturedContext.Remaining.Parsed.Count.ShouldBe(4); capturedContext.ShouldHaveRemainingArgument("foo", values: new[] { "bar", "baz" }); capturedContext.ShouldHaveRemainingArgument("b", values: new[] { (string)null }); capturedContext.ShouldHaveRemainingArgument("a", values: new[] { (string)null }); capturedContext.ShouldHaveRemainingArgument("r", values: new[] { (string)null }); } [Fact] public void Should_Register_Remaining_Raw_Arguments_With_Context() { // Given var capturedContext = default(CommandContext); var resolver = new FakeTypeResolver(); var command = new InterceptingCommand<DogSettings>((context, _) => { capturedContext = context; }); resolver.Register(new DogSettings()); resolver.Register(command); var app = new CommandApp(new FakeTypeRegistrar(resolver)); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<InterceptingCommand<DogSettings>>("dog"); }); }); // When app.Run(new[] { "animal", "4", "dog", "12", "--", "--foo", "bar", "-bar", "\"baz\"", "qux" }); // Then capturedContext.Remaining.Raw.Count.ShouldBe(5); capturedContext.Remaining.Raw[0].ShouldBe("--foo"); capturedContext.Remaining.Raw[1].ShouldBe("bar"); capturedContext.Remaining.Raw[2].ShouldBe("-bar"); capturedContext.Remaining.Raw[3].ShouldBe("\"baz\""); capturedContext.Remaining.Raw[4].ShouldBe("qux"); } } public sealed class Validation { [Fact] public void Should_Throw_If_Attribute_Validation_Fails() { // Given var app = new CommandApp(new FakeTypeRegistrar()); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // When var result = Record.Exception(() => app.Run(new[] { "animal", "3", "dog", "7", "--name", "Rufus" })); // Then result.ShouldBeOfType<RuntimeException>().And(e => { e.Message.ShouldBe("Animals must have an even number of legs."); }); } [Fact] public void Should_Throw_If_Settings_Validation_Fails() { // Given var app = new CommandApp(new FakeTypeRegistrar()); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // When var result = Record.Exception(() => app.Run(new[] { "animal", "4", "dog", "7", "--name", "Tiger" })); // Then result.ShouldBeOfType<RuntimeException>().And(e => { e.Message.ShouldBe("Tiger is not a dog name!"); }); } [Fact] public void Should_Throw_If_Command_Validation_Fails() { // Given var app = new CommandApp(new FakeTypeRegistrar()); app.Configure(config => { config.PropagateExceptions(); config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // When var result = Record.Exception(() => app.Run(new[] { "animal", "4", "dog", "101", "--name", "Rufus" })); // Then result.ShouldBeOfType<RuntimeException>().And(e => { e.Message.ShouldBe("Dog is too old..."); }); } } public sealed class Exception_Handling { [Fact] public void Should_Not_Propagate_Runtime_Exceptions_If_Not_Explicitly_Told_To_Do_So() { // Given var app = new CommandApp(new FakeTypeRegistrar()); app.Configure(config => { config.AddBranch<AnimalSettings>("animal", animal => { animal.AddCommand<DogCommand>("dog"); animal.AddCommand<HorseCommand>("horse"); }); }); // When var result = app.Run(new[] { "animal", "4", "dog", "101", "--name", "Rufus" }); // Then result.ShouldBe(-1); } [Fact] public void Should_Not_Propagate_Exceptions_If_Not_Explicitly_Told_To_Do_So() { // Given var app = new CommandApp(new FakeTypeRegistrar()); app.Configure(config => { config.AddCommand<ThrowingCommand>("throw"); }); // When var result = app.Run(new[] { "throw" }); // Then result.ShouldBe(-1); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace NewEmployee.WebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; using Orleans.Runtime.Messaging; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { /// <summary> /// A directory for routes to clients (external clients and hosted clients). /// </summary> /// <remarks> /// <see cref="ClientDirectory"/> maintains routing information for all known clients and offers consumers the ability to lookup /// clients by their <see cref="GrainId"/>. /// To accomplish this, <see cref="ClientDirectory"/> monitors locally connected clients and cluster membership changes. In addition, /// known routes are periodically shared with remote silos in a ring-fashion. Each silo will push updates to the next silo in the ring. /// When a silo receives an update, it incorporates it into its routing table. If the update caused a change in the routing table, then /// the silo will propagate its updates routing table to the next silo. This process continues until all silos converge. /// Each <see cref="ClientDirectory"/> maintains an internal version number which represents its view of the locally connected clients. /// This version number is propagated around the ring during updates and is used to determine when a remote silo's set of locally connected clients /// has updated. /// The process of removing defunct clients is left to the <see cref="IConnectedClientCollection"/> implementation on each silo. /// </remarks> internal sealed class ClientDirectory : SystemTarget, ILocalClientDirectory, IRemoteClientDirectory, ILifecycleParticipant<ISiloLifecycle> { private readonly SimpleConsistentRingProvider _consistentRing; private readonly IInternalGrainFactory _grainFactory; private readonly ILogger<ClientDirectory> _logger; private readonly IAsyncTimer _refreshTimer; private readonly SiloAddress _localSilo; private readonly IClusterMembershipService _clusterMembershipService; private readonly SiloMessagingOptions _messagingOptions; private readonly CancellationTokenSource _shutdownCancellation = new CancellationTokenSource(); private readonly object _lockObj = new object(); private readonly GrainId _localHostedClientId; private readonly IConnectedClientCollection _connectedClients; private Action _schedulePublishUpdate; private Task _runTask; private MembershipVersion _observedMembershipVersion = MembershipVersion.MinValue; private long _observedConnectedClientsVersion = -1; private long _localVersion = 1; private IRemoteClientDirectory[] _remoteDirectories = Array.Empty<IRemoteClientDirectory>(); private ImmutableHashSet<GrainId> _localClients = ImmutableHashSet<GrainId>.Empty; private ImmutableDictionary<GrainId, List<ActivationAddress>> _currentSnapshot = ImmutableDictionary<GrainId, List<ActivationAddress>>.Empty; private ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)> _table = ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)>.Empty; // For synchronization with remote silos. private Task _nextPublishTask; private SiloAddress _previousSuccessor; private ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)> _publishedTable; public ClientDirectory( IInternalGrainFactory grainFactory, ILocalSiloDetails siloDetails, IOptions<SiloMessagingOptions> messagingOptions, ILoggerFactory loggerFactory, IClusterMembershipService clusterMembershipService, IAsyncTimerFactory timerFactory, IConnectedClientCollection connectedClients) : base(Constants.ClientDirectoryType, siloDetails.SiloAddress, loggerFactory) { _consistentRing = new SimpleConsistentRingProvider(siloDetails, clusterMembershipService); _grainFactory = grainFactory; _localSilo = siloDetails.SiloAddress; _clusterMembershipService = clusterMembershipService; _messagingOptions = messagingOptions.Value; _logger = loggerFactory.CreateLogger<ClientDirectory>(); _refreshTimer = timerFactory.Create(_messagingOptions.ClientRegistrationRefresh, "ClientDirectory.RefreshTimer"); _connectedClients = connectedClients; _localHostedClientId = HostedClient.CreateHostedClientGrainId(_localSilo).GrainId; _schedulePublishUpdate = () => SchedulePublishUpdates(); } public ValueTask<List<ActivationAddress>> Lookup(GrainId grainId) { if (TryLocalLookup(grainId, out var clientRoutes)) { return new ValueTask<List<ActivationAddress>>(clientRoutes); } return LookupClientAsync(grainId); async ValueTask<List<ActivationAddress>> LookupClientAsync(GrainId grainId) { var seed = ThreadSafeRandom.Next(); var attemptsRemaining = 5; List<ActivationAddress> result = null; while (attemptsRemaining-- > 0 && _remoteDirectories is var remoteDirectories && remoteDirectories.Length > 0) { try { // Cycle through remote directories. var remoteDirectory = remoteDirectories[(ushort)seed++ % remoteDirectories.Length]; // Ask the remote directory for updates to our view. var versionVector = _table.ToImmutableDictionary(e => e.Key, e => e.Value.Version); var delta = await remoteDirectory.GetClientRoutes(versionVector); // If updates were found, update our view if (delta is object && delta.Count > 0) { UpdateRoutingTable(delta); } } catch (Exception exception) when (attemptsRemaining > 0) { _logger.LogError(exception, "Exception calling remote client directory"); } // Try again to find the requested client's routes. // Note that this occurs whether the remote update call succeeded or failed. if (TryLocalLookup(grainId, out result) && result.Count > 0) { break; } } if (ShouldPublish()) { _schedulePublishUpdate(); } // Try one last time to find the requested client's routes. if (result is null && !TryLocalLookup(grainId, out result)) { result = new List<ActivationAddress>(0); } return result; } } public bool TryLocalLookup(GrainId grainId, out List<ActivationAddress> addresses) { EnsureRefreshed(); if (_currentSnapshot.TryGetValue(grainId, out var clientRoutes) && clientRoutes.Count > 0) { addresses = clientRoutes; return true; } addresses = null; return false; } private void EnsureRefreshed() { if (IsStale()) { lock (_lockObj) { if (IsStale()) { UpdateRoutingTable(update: null); } } } bool IsStale() { return _observedMembershipVersion < _clusterMembershipService.CurrentSnapshot.Version || _observedConnectedClientsVersion != _connectedClients.Version; } } public Task OnUpdateClientRoutes(ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)> update) { UpdateRoutingTable(update); if (ShouldPublish()) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Client table updated, publishing to successor"); } _schedulePublishUpdate(); } else { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Client table not updated"); } } return Task.CompletedTask; } public Task<ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)>> GetClientRoutes(ImmutableDictionary<SiloAddress, long> knownRoutes) { EnsureRefreshed(); // Return a collection containing all missing or out-dated routes, based on the known-routes version vector provided by the caller. var table = _table; var resultBuilder = ImmutableDictionary.CreateBuilder<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)>(); foreach (var entry in table) { var silo = entry.Key; var routes = entry.Value; var version = routes.Version; if (!knownRoutes.TryGetValue(silo, out var knownVersion) || knownVersion < version) { resultBuilder[silo] = routes; } } return Task.FromResult(resultBuilder.ToImmutable()); } private void UpdateRoutingTable(ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)> update) { lock (_lockObj) { var membershipSnapshot = _clusterMembershipService.CurrentSnapshot; var table = default(ImmutableDictionary<SiloAddress, (ImmutableHashSet<GrainId> ConnectedClients, long Version)>.Builder); // Incorporate updates. if (update is object) { foreach (var pair in update) { var silo = pair.Key; var updatedView = pair.Value; // Include only updates for non-defunct silos. if ((!_table.TryGetValue(silo, out var localView) || localView.Version < updatedView.Version) && !membershipSnapshot.GetSiloStatus(silo).IsTerminating()) { table ??= _table.ToBuilder(); table[silo] = updatedView; } } } // Ensure that the remote directories are up-to-date. if (membershipSnapshot.Version > _observedMembershipVersion) { var remotesBuilder = new List<IRemoteClientDirectory>(membershipSnapshot.Members.Count); foreach (var member in membershipSnapshot.Members.Values) { if (member.SiloAddress.Equals(_localSilo)) continue; if (member.Status != SiloStatus.Active) continue; remotesBuilder.Add(_grainFactory.GetSystemTarget<IRemoteClientDirectory>(Constants.ClientDirectoryType, member.SiloAddress)); } _remoteDirectories = remotesBuilder.ToArray(); } // Remove defunct silos. foreach (var member in membershipSnapshot.Members.Values) { var silo = member.SiloAddress; if (member.Status.IsTerminating()) { // Remove the silo only if it is in the table. This prevents us from rebuilding data structures unnecessarily. if (_table.ContainsKey(silo)) { table ??= _table.ToBuilder(); table.Remove(silo); } } else if (member.Status == SiloStatus.Active) { // If the silo has just become active and we have not yet received a set of connected clients from it, // add the hosted client automatically, to expedite the process. if (!_table.ContainsKey(silo) && (table is null || !table.ContainsKey(silo))) { table ??= _table.ToBuilder(); // Note that it is added with version 0, which is below the initial version generated by each silo, 1. table[silo] = (ImmutableHashSet.Create(HostedClient.CreateHostedClientGrainId(silo).GrainId), 0); } } } _observedMembershipVersion = membershipSnapshot.Version; // Update locally connected clients. var (clients, version) = GetConnectedClients(_localClients, _localVersion); if (version > _localVersion) { table ??= _table.ToBuilder(); table[_localSilo] = (clients, version); _localClients = clients; _localVersion = version; } // If there were changes to the routing table then the table and snapshot need to be rebuilt. if (table is object) { _table = table.ToImmutable(); var clientsBuilder = ImmutableDictionary.CreateBuilder<GrainId, List<ActivationAddress>>(); foreach (var entry in _table) { foreach (var client in entry.Value.ConnectedClients) { if (!clientsBuilder.TryGetValue(client, out var clientRoutes)) { clientRoutes = clientsBuilder[client] = new List<ActivationAddress>(); } clientRoutes.Add(Gateway.GetClientActivationAddress(client, entry.Key)); } } _currentSnapshot = clientsBuilder.ToImmutable(); } } } /// <summary> /// Gets the collection of locally connected clients. /// </summary> private (ImmutableHashSet<GrainId> Clients, long Version) GetConnectedClients(ImmutableHashSet<GrainId> previousClients, long previousVersion) { var connectedClientsVersion = _connectedClients.Version; if (connectedClientsVersion <= _observedConnectedClientsVersion) { return (previousClients, previousVersion); } var clients = ImmutableHashSet.CreateBuilder<GrainId>(); clients.Add(_localHostedClientId); foreach (var client in _connectedClients.GetConnectedClientIds()) { clients.Add(client); } // Regardless of whether changes occurred, mark this version as observed. _observedConnectedClientsVersion = connectedClientsVersion; // If no changes actually occurred, avoid signalling a change. if (clients.Count == previousClients.Count && previousClients.SetEquals(clients)) { return (previousClients, previousVersion); } return (clients.ToImmutable(), previousVersion + 1); } private async Task Run() { var membershipUpdates = _clusterMembershipService.MembershipUpdates.GetAsyncEnumerator(_shutdownCancellation.Token); Task<bool> membershipTask = null; Task<bool> timerTask = _refreshTimer.NextTick(ThreadSafeRandom.NextTimeSpan(_messagingOptions.ClientRegistrationRefresh)); while (true) { membershipTask ??= membershipUpdates.MoveNextAsync().AsTask(); timerTask ??= _refreshTimer.NextTick(); // Wait for either of the tasks to complete. await Task.WhenAny(membershipTask, timerTask); if (timerTask.IsCompleted) { if (!await timerTask) { break; } timerTask = null; } if (membershipTask.IsCompleted) { if (!await membershipTask) { break; } membershipTask = null; } if (ShouldPublish()) { await PublishUpdates(); } } } private bool ShouldPublish() { EnsureRefreshed(); lock (_lockObj) { if (_nextPublishTask is Task task && !task.IsCompleted) { return false; } if (!ReferenceEquals(_table, _publishedTable)) { return true; } // If there is no successor, or the successor is equal to the successor the last time the table was published, // then there is no need to publish. var successor = _consistentRing.Successor; if (successor is null || successor.Equals(_previousSuccessor)) { return false; } return true; } } private void SchedulePublishUpdates() { lock (_lockObj) { if (_nextPublishTask is Task task && !task.IsCompleted) { return; } _nextPublishTask = this.RunOrQueueTask(() => PublishUpdates()); } } private async Task PublishUpdates() { // Publish clients to the next two silos in the ring var successor = _consistentRing.Successor; if (successor is null) { return; } if (successor.Equals(_previousSuccessor)) { _publishedTable = null; } var newRoutes = _table; var previousRoutes = _publishedTable; if (ReferenceEquals(previousRoutes, newRoutes)) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Skipping publishing of routes because target silo already has them"); } return; } // Try to find the minimum amount of information required to update the successor. var builder = newRoutes.ToBuilder(); if (previousRoutes is object) { foreach (var pair in previousRoutes) { var silo = pair.Key; var (_, version) = pair.Value; if (silo.Equals(successor)) { // No need to publish updates to the silo which originated them. continue; } if (!builder.TryGetValue(silo, out var published)) { continue; } if (version == published.Version) { // The target has already seen the latest version for this silo. builder.Remove(silo); } } } try { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Publishing routes to {Silo}", successor); } var remote = _grainFactory.GetSystemTarget<IRemoteClientDirectory>(Constants.ClientDirectoryType, successor); await remote.OnUpdateClientRoutes(_table); // Record the current lower bound of what the successor knows, so that it can be used to minimize // data transfer next time an update is performed. if (ReferenceEquals(_publishedTable, previousRoutes)) { _publishedTable = newRoutes; _previousSuccessor = successor; } if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Successfully routes to {Silo}", successor); } _nextPublishTask = null; if (ShouldPublish()) { _schedulePublishUpdate(); } } catch (Exception exception) { _logger.LogError(exception, "Exception publishing client routing table to silo {SiloAddress}", successor); } } void ILifecycleParticipant<ISiloLifecycle>.Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe( nameof(ClientDirectory), ServiceLifecycleStage.RuntimeGrainServices, ct => { this.RunOrQueueTask(() => _runTask = this.Run()).Ignore(); return Task.CompletedTask; }, async ct => { _shutdownCancellation.Cancel(); _refreshTimer?.Dispose(); if (_runTask is Task task) { await Task.WhenAny(ct.WhenCancelled(), task); } }); } internal class TestAccessor { private readonly ClientDirectory _instance; public TestAccessor(ClientDirectory instance) => _instance = instance; public Action SchedulePublishUpdate { get => _instance._schedulePublishUpdate; set => _instance._schedulePublishUpdate = value; } public long ObservedConnectedClientsVersion { get => _instance._observedConnectedClientsVersion; set => _instance._observedConnectedClientsVersion = value; } public Task PublishUpdates() => _instance.PublishUpdates(); } } }
// 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.IO; using System.Threading; namespace System.Net.Security { // // This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context. // internal class SslStreamInternal { private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private static readonly AsyncProtocolCallback s_resumeAsyncWriteCallback = new AsyncProtocolCallback(ResumeAsyncWriteCallback); private static readonly AsyncProtocolCallback s_resumeAsyncReadCallback = new AsyncProtocolCallback(ResumeAsyncReadCallback); private static readonly AsyncProtocolCallback s_readHeaderCallback = new AsyncProtocolCallback(ReadHeaderCallback); private static readonly AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback); private const int PinnableReadBufferSize = 4096 * 4 + 32; // We read in 16K chunks + headers. private static PinnableBufferCache s_PinnableReadBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableReadBufferSize); private const int PinnableWriteBufferSize = 4096 + 1024; // We write in 4K chunks + encryption overhead. private static PinnableBufferCache s_PinnableWriteBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableWriteBufferSize); private SslState _sslState; private int _nestedWrite; private int _nestedRead; // Never updated directly, special properties are used. This is the read buffer. private byte[] _internalBuffer; private bool _internalBufferFromPinnableCache; private byte[] _pinnableOutputBuffer; // Used for writes when we can do it. private byte[] _pinnableOutputBufferInUse; // Remembers what UNENCRYPTED buffer is using _PinnableOutputBuffer. private int _internalOffset; private int _internalBufferCount; private FixedSizeReader _reader; internal SslStreamInternal(SslState sslState) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net._SslStream.SslStream", this.GetHashCode()); } _sslState = sslState; _reader = new FixedSizeReader(_sslState.InnerStream); } // If we have a read buffer from the pinnable cache, return it. private void FreeReadBuffer() { if (_internalBufferFromPinnableCache) { s_PinnableReadBufferCache.FreeBuffer(_internalBuffer); _internalBufferFromPinnableCache = false; } _internalBuffer = null; } ~SslStreamInternal() { if (_internalBufferFromPinnableCache) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Read Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_internalBuffer)); } FreeReadBuffer(); } if (_pinnableOutputBuffer != null) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Write Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_pinnableOutputBuffer)); } s_PinnableWriteBufferCache.FreeBuffer(_pinnableOutputBuffer); } } internal int ReadByte() { if (Interlocked.Exchange(ref _nestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "ReadByte", "read")); } // If there's any data in the buffer, take one byte, and we're done. try { if (InternalBufferCount > 0) { int b = InternalBuffer[InternalOffset]; SkipBytes(1); return b; } } finally { // Regardless of whether we were able to read a byte from the buffer, // reset the read tracking. If we weren't able to read a byte, the // subsequent call to Read will set the flag again. _nestedRead = 0; } // Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does. // This allocation is unfortunate but should be relatively rare, as it'll only occur once // per buffer fill internally by Read. byte[] oneByte = new byte[1]; int bytesRead = Read(oneByte, 0, 1); Debug.Assert(bytesRead == 0 || bytesRead == 1); return bytesRead == 1 ? oneByte[0] : -1; } internal int Read(byte[] buffer, int offset, int count) { return ProcessRead(buffer, offset, count, null); } internal void Write(byte[] buffer, int offset, int count) { ProcessWrite(buffer, offset, count, null); } internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessRead(buffer, offset, count, asyncRequest); return bufferResult; } internal int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); } if (Interlocked.Exchange(ref _nestedRead, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. bufferResult.InternalWaitForCompletion(); if (bufferResult.Result is Exception) { if (bufferResult.Result is IOException) { throw (Exception)bufferResult.Result; } throw new IOException(SR.net_io_read, (Exception)bufferResult.Result); } return (int)bufferResult.Result; } internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { LazyAsyncResult lazyResult = new LazyAsyncResult(this, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(lazyResult); ProcessWrite(buffer, offset, count, asyncRequest); return lazyResult; } internal void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); } if (Interlocked.Exchange(ref _nestedWrite, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. lazyResult.InternalWaitForCompletion(); if (lazyResult.Result is Exception) { if (lazyResult.Result is IOException) { throw (Exception)lazyResult.Result; } throw new IOException(SR.net_io_write, (Exception)lazyResult.Result); } } internal bool DataAvailable { get { return InternalBufferCount != 0; } } private byte[] InternalBuffer { get { return _internalBuffer; } } private int InternalOffset { get { return _internalOffset; } } private int InternalBufferCount { get { return _internalBufferCount; } } private void SkipBytes(int decrCount) { _internalOffset += decrCount; _internalBufferCount -= decrCount; } // // This will set the internal offset to "curOffset" and ensure internal buffer. // If not enough, reallocate and copy up to "curOffset". // private void EnsureInternalBufferSize(int curOffset, int addSize) { if (_internalBuffer == null || _internalBuffer.Length < addSize + curOffset) { bool wasPinnable = _internalBufferFromPinnableCache; byte[] saved = _internalBuffer; int newSize = addSize + curOffset; if (newSize <= PinnableReadBufferSize) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize IS pinnable", this.GetHashCode(), newSize); } _internalBufferFromPinnableCache = true; _internalBuffer = s_PinnableReadBufferCache.AllocateBuffer(); } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize NOT pinnable", this.GetHashCode(), newSize); } _internalBufferFromPinnableCache = false; _internalBuffer = new byte[newSize]; } if (saved != null && curOffset != 0) { Buffer.BlockCopy(saved, 0, _internalBuffer, 0, curOffset); } if (wasPinnable) { s_PinnableReadBufferCache.FreeBuffer(saved); } } _internalOffset = curOffset; _internalBufferCount = curOffset + addSize; } // // Validates user parameters for all Read/Write methods. // private void ValidateParameters(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count), SR.net_offset_plus_count); } } // // Sync write method. // private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _nestedWrite, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Write", "write")); } bool failed = false; try { StartWriting(buffer, offset, count, asyncRequest); } catch (Exception e) { _sslState.FinishWrite(); failed = true; if (e is IOException) { throw; } throw new IOException(SR.net_io_write, e); } finally { if (asyncRequest == null || failed) { _nestedWrite = 0; } } } private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (asyncRequest != null) { asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncWriteCallback); } // We loop to this method from the callback. // If the last chunk was just completed from async callback (count < 0), we complete user request. if (count >= 0 ) { byte[] outBuffer = null; if (_pinnableOutputBufferInUse == null) { if (_pinnableOutputBuffer == null) { _pinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer(); } _pinnableOutputBufferInUse = buffer; outBuffer = _pinnableOutputBuffer; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count); } } do { // Request a write IO slot. if (_sslState.CheckEnqueueWrite(asyncRequest)) { // Operation is async and has been queued, return. return; } int chunkBytes = Math.Min(count, _sslState.MaxDataSize); int encryptedBytes; SecurityStatusPal status = _sslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { // Re-handshake status is not supported. ProtocolToken message = new ProtocolToken(null, status); throw new IOException(SR.net_io_encrypt, message.GetException()); } if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer", this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } if (asyncRequest != null) { // Prepare for the next request. asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, s_resumeAsyncWriteCallback); IAsyncResult ar = _sslState.InnerStream.BeginWrite(outBuffer, 0, encryptedBytes, s_writeCallback, asyncRequest); if (!ar.CompletedSynchronously) { return; } _sslState.InnerStream.EndWrite(ar); } else { _sslState.InnerStream.Write(outBuffer, 0, encryptedBytes); } offset += chunkBytes; count -= chunkBytes; // Release write IO slot. _sslState.FinishWrite(); } while (count != 0); } if (asyncRequest != null) { asyncRequest.CompleteUser(); } if (buffer == _pinnableOutputBufferInUse) { _pinnableOutputBufferInUse = null; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode()); } } } // // Combined sync/async read method. For sync request asyncRequest==null. // private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _nestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest!=null? "BeginRead":"Read"), "read")); } bool failed = false; try { int copyBytes; if (InternalBufferCount != 0) { copyBytes = InternalBufferCount > count ? count : InternalBufferCount; if (copyBytes != 0) { Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes); SkipBytes(copyBytes); } if (asyncRequest != null) { asyncRequest.CompleteUser((object) copyBytes); } return copyBytes; } return StartReading(buffer, offset, count, asyncRequest); } catch (Exception e) { _sslState.FinishRead(null); failed = true; if (e is IOException) { throw; } throw new IOException(SR.net_io_read, e); } finally { if (asyncRequest == null || failed) { _nestedRead = 0; } } } // // To avoid recursion when decrypted 0 bytes this method will loop until a decrypted result at least 1 byte. // private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { int result = 0; if (InternalBufferCount != 0) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:{0}", InternalBufferCount); } Debug.Fail("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:" + InternalBufferCount); } do { if (asyncRequest != null) { asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncReadCallback); } int copyBytes = _sslState.CheckEnqueueRead(buffer, offset, count, asyncRequest); if (copyBytes == 0) { // Queued but not completed! return 0; } if (copyBytes != -1) { if (asyncRequest != null) { asyncRequest.CompleteUser((object)copyBytes); } return copyBytes; } } // When we read -1 bytes means we have decrypted 0 bytes or rehandshaking, need looping. while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1); return result; } private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { int readBytes = 0; // // Always pass InternalBuffer for SSPI "in place" decryption. // A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption. // // Reset internal buffer for a new frame. EnsureInternalBufferSize(0, SecureChannel.ReadHeaderSize); if (asyncRequest != null) { asyncRequest.SetNextRequest(InternalBuffer, 0, SecureChannel.ReadHeaderSize, s_readHeaderCallback); _reader.AsyncReadPacket(asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return 0; } readBytes = asyncRequest.Result; } else { readBytes = _reader.ReadPacket(InternalBuffer, 0, SecureChannel.ReadHeaderSize); } return StartFrameBody(readBytes, buffer, offset, count, asyncRequest); } private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { //EOF : Reset the buffer as we did not read anything into it. SkipBytes(InternalBufferCount); if (asyncRequest != null) { asyncRequest.CompleteUser((object)0); } return 0; } // Now readBytes is a payload size. readBytes = _sslState.GetRemainingFrameSize(InternalBuffer, readBytes); if (readBytes < 0) { throw new IOException(SR.net_frame_read_size); } EnsureInternalBufferSize(SecureChannel.ReadHeaderSize, readBytes); if (asyncRequest != null) { asyncRequest.SetNextRequest(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes, s_readFrameCallback); _reader.AsyncReadPacket(asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return 0; } readBytes = asyncRequest.Result; } else { readBytes = _reader.ReadPacket(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes); } return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest); } // // readBytes == SSL Data Payload size on input or 0 on EOF. // private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { // EOF throw new IOException(SR.net_io_eof); } // Set readBytes to total number of received bytes. readBytes += SecureChannel.ReadHeaderSize; // Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_. int data_offset = 0; SecurityStatusPal status = _sslState.DecryptData(InternalBuffer, ref data_offset, ref readBytes); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { byte[] extraBuffer = null; if (readBytes != 0) { extraBuffer = new byte[readBytes]; Buffer.BlockCopy(InternalBuffer, data_offset, extraBuffer, 0, readBytes); } // Reset internal buffer count. SkipBytes(InternalBufferCount); return ProcessReadErrorCode(status, buffer, offset, count, asyncRequest, extraBuffer); } if (readBytes == 0 && count != 0) { // Read again since remote side has sent encrypted 0 bytes. SkipBytes(InternalBufferCount); return -1; } // Decrypted data start from "data_offset" offset, the total count can be shrunk after decryption. EnsureInternalBufferSize(0, data_offset + readBytes); SkipBytes(data_offset); if (readBytes > count) { readBytes = count; } Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes); // This will adjust both the remaining internal buffer count and the offset. SkipBytes(readBytes); _sslState.FinishRead(null); if (asyncRequest != null) { asyncRequest.CompleteUser((object)readBytes); } return readBytes; } // // Only processing SEC_I_RENEGOTIATE. // private int ProcessReadErrorCode(SecurityStatusPal status, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer) { ProtocolToken message = new ProtocolToken(null, status); if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::***Processing an error Status = " + message.Status.ToString()); } if (message.Renegotiate) { _sslState.ReplyOnReAuthentication(extraBuffer); // Loop on read. return -1; } if (message.CloseConnection) { _sslState.FinishRead(null); if (asyncRequest != null) { asyncRequest.CompleteUser((object)0); } return 0; } throw new IOException(SR.net_io_decrypt, message.GetException()); } private static void WriteCallback(IAsyncResult transportResult) { if (transportResult.CompletedSynchronously) { return; } if (!(transportResult.AsyncState is AsyncProtocolRequest)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SslStream::WriteCallback | State type is wrong, expected AsyncProtocolRequest."); } Debug.Fail("SslStream::WriteCallback|State type is wrong, expected AsyncProtocolRequest."); } AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState; var sslStream = (SslStreamInternal)asyncRequest.AsyncObject; try { sslStream._sslState.InnerStream.EndWrite(transportResult); sslStream._sslState.FinishWrite(); if (asyncRequest.Count == 0) { // This was the last chunk. asyncRequest.Count = -1; } sslStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } sslStream._sslState.FinishWrite(); asyncRequest.CompleteWithError(e); } } // // This is used in a rare situation when async Read is resumed from completed handshake. // private static void ResumeAsyncReadCallback(AsyncProtocolRequest request) { try { ((SslStreamInternal)request.AsyncObject).StartReading(request.Buffer, request.Offset, request.Count, request); } catch (Exception e) { if (request.IsUserCompleted) { // This will throw on a worker thread. throw; } ((SslStreamInternal)request.AsyncObject)._sslState.FinishRead(null); request.CompleteWithError(e); } } // // This is used in a rare situation when async Write is resumed from completed handshake. // private static void ResumeAsyncWriteCallback(AsyncProtocolRequest asyncRequest) { try { ((SslStreamInternal)asyncRequest.AsyncObject).StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } ((SslStreamInternal)asyncRequest.AsyncObject)._sslState.FinishWrite(); asyncRequest.CompleteWithError(e); } } private static void ReadHeaderCallback(AsyncProtocolRequest asyncRequest) { try { SslStreamInternal sslStream = (SslStreamInternal)asyncRequest.AsyncObject; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; if (-1 == sslStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest)) { // in case we decrypted 0 bytes start another reading. sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } asyncRequest.CompleteWithError(e); } } private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest) { try { SslStreamInternal sslStream = (SslStreamInternal)asyncRequest.AsyncObject; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; if (-1 == sslStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest)) { // in case we decrypted 0 bytes start another reading. sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } asyncRequest.CompleteWithError(e); } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AppServicesClient { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class KeepConnectionOpenScenario : Page { private MainPage rootPage; private AppServiceConnection connection; public KeepConnectionOpenScenario() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } private async void OpenConnection_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { //Is a connection already open? if (connection != null) { rootPage.NotifyUser("A connection already exists", NotifyType.ErrorMessage); return; } //Set up a new app service connection connection = new AppServiceConnection(); connection.AppServiceName = "com.microsoft.randomnumbergenerator"; connection.PackageFamilyName = "Microsoft.SDKSamples.AppServicesProvider.CS_8wekyb3d8bbwe"; connection.ServiceClosed += Connection_ServiceClosed; AppServiceConnectionStatus status = await connection.OpenAsync(); //If the new connection opened successfully we're done here if (status == AppServiceConnectionStatus.Success) { rootPage.NotifyUser("Connection is open", NotifyType.StatusMessage); } else { //Something went wrong. Lets figure out what it was and show the //user a meaningful message switch (status) { case AppServiceConnectionStatus.AppNotInstalled: rootPage.NotifyUser("The app AppServicesProvider is not installed. Deploy AppServicesProvider to this device and try again.", NotifyType.ErrorMessage); break; case AppServiceConnectionStatus.AppUnavailable: rootPage.NotifyUser("The app AppServicesProvider is not available. This could be because it is currently being updated or was installed to a removable device that is no longer available.", NotifyType.ErrorMessage); break; case AppServiceConnectionStatus.AppServiceUnavailable: rootPage.NotifyUser(string.Format("The app AppServicesProvider is installed but it does not provide the app service {0}.", connection.AppServiceName), NotifyType.ErrorMessage); break; case AppServiceConnectionStatus.Unknown: rootPage.NotifyUser("An unkown error occurred while we were trying to open an AppServiceConnection.", NotifyType.ErrorMessage); break; } //Clean up before we go connection.Dispose(); connection = null; } } private async void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Dispose the connection reference we're holding if (connection != null) { connection.Dispose(); connection = null; } }); } private void CloseConnection_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { //Is there an open connection? if (connection == null) { rootPage.NotifyUser("There's no open connection to close", NotifyType.ErrorMessage); return; } //Close the open connection connection.Dispose(); connection = null; //Let the user know we closed the connection rootPage.NotifyUser("Connection is closed", NotifyType.StatusMessage); } private async void GenerateRandomNumber_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { //Is there an open connection? if (connection == null) { rootPage.NotifyUser("You need to open a connection before trying to generate a random number.", NotifyType.ErrorMessage); return; } //Parse user input int minValueInput = 0; bool valueParsed = int.TryParse(MinValue.Text, out minValueInput); if (!valueParsed) { rootPage.NotifyUser("The Minimum Value should be a valid integer", NotifyType.ErrorMessage); return; } int maxValueInput = 0; valueParsed = int.TryParse(MaxValue.Text, out maxValueInput); if (!valueParsed) { rootPage.NotifyUser("The Maximum Value should be a valid integer", NotifyType.ErrorMessage); return; } if (maxValueInput <= minValueInput) { rootPage.NotifyUser("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage); return; } //Send a message to the app service var inputs = new ValueSet(); inputs.Add("minvalue", minValueInput); inputs.Add("maxvalue", maxValueInput); AppServiceResponse response = await connection.SendMessageAsync(inputs); //If the service responded display the message. We're done! if (response.Status == AppServiceResponseStatus.Success) { if (!response.Message.ContainsKey("result")) { rootPage.NotifyUser("The app service response message does not contain a key called \"result\"", NotifyType.StatusMessage); return; } var resultText = response.Message["result"].ToString(); if (!string.IsNullOrEmpty(resultText)) { Result.Text = resultText; rootPage.NotifyUser("App service responded with a result", NotifyType.StatusMessage); } else { rootPage.NotifyUser("App service did not respond with a result", NotifyType.ErrorMessage); } } else { //Something went wrong. Show the user a meaningful //message depending upon the status switch (response.Status) { case AppServiceResponseStatus.Failure: rootPage.NotifyUser("The service failed to acknowledge the message we sent it. It may have been terminated because the client was suspended.", NotifyType.ErrorMessage); break; case AppServiceResponseStatus.ResourceLimitsExceeded: rootPage.NotifyUser("The service exceeded the resources allocated to it and had to be terminated.", NotifyType.ErrorMessage); break; case AppServiceResponseStatus.Unknown: default: rootPage.NotifyUser("An unkown error occurred while we were trying to send a message to the service.", NotifyType.ErrorMessage); break; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; namespace Microsoft.DotNet.Cli.Build { public class AzurePublisher { public enum Product { SharedFramework, Host, HostFxr, Sdk, } private const string s_dotnetBlobContainerName = "dotnet"; private string _connectionString { get; set; } private string _containerName { get; set; } private CloudBlobContainer _blobContainer { get; set; } public AzurePublisher(string containerName = s_dotnetBlobContainerName) { _connectionString = EnvVars.EnsureVariable("CONNECTION_STRING").Trim('"'); _containerName = containerName; _blobContainer = GetDotnetBlobContainer(_connectionString, containerName); } public AzurePublisher(string accountName, string accountKey, string containerName = s_dotnetBlobContainerName) { _containerName = containerName; _blobContainer = GetDotnetBlobContainer(accountName, accountKey, containerName); } private CloudBlobContainer GetDotnetBlobContainer(string connectionString, string containerName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); return GetDotnetBlobContainer(storageAccount, containerName); } private CloudBlobContainer GetDotnetBlobContainer(string accountName, string accountKey, string containerName) { var storageCredentials = new StorageCredentials(accountName, accountKey); var storageAccount = new CloudStorageAccount(storageCredentials, true); return GetDotnetBlobContainer(storageAccount, containerName); } private CloudBlobContainer GetDotnetBlobContainer(CloudStorageAccount storageAccount, string containerName) { CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); return blobClient.GetContainerReference(containerName); } public string UploadFile(string file, Product product, string version) { string url = CalculateRelativePathForFile(file, product, version); CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(url); blob.UploadFromFileAsync(file).Wait(); SetBlobPropertiesBasedOnFileType(blob); return url; } public void PublishStringToBlob(string blob, string content) { CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob); blockBlob.UploadTextAsync(content).Wait(); SetBlobPropertiesBasedOnFileType(blockBlob); } public void CopyBlob(string sourceBlob, string targetBlob) { CloudBlockBlob source = _blobContainer.GetBlockBlobReference(sourceBlob); CloudBlockBlob target = _blobContainer.GetBlockBlobReference(targetBlob); // Create the empty blob using (MemoryStream ms = new MemoryStream()) { target.UploadFromStreamAsync(ms).Wait(); } // Copy actual blob data target.StartCopyAsync(source).Wait(); } public void SetBlobPropertiesBasedOnFileType(string path) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path); SetBlobPropertiesBasedOnFileType(blob); } private void SetBlobPropertiesBasedOnFileType(CloudBlockBlob blockBlob) { if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".svg") { blockBlob.Properties.ContentType = "image/svg+xml"; blockBlob.Properties.CacheControl = "no-cache"; blockBlob.SetPropertiesAsync().Wait(); } else if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".version") { blockBlob.Properties.ContentType = "text/plain"; blockBlob.Properties.CacheControl = "no-cache"; blockBlob.SetPropertiesAsync().Wait(); } } public IEnumerable<string> ListBlobs(Product product, string version) { string virtualDirectory = $"{product}/{version}"; return ListBlobs(virtualDirectory); } public IEnumerable<string> ListBlobs(string virtualDirectory) { CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(virtualDirectory); BlobContinuationToken continuationToken = new BlobContinuationToken(); var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result; return blobFiles.Results.Select(bf => bf.Uri.PathAndQuery.Replace($"/{_containerName}/", string.Empty)); } public string AcquireLeaseOnBlob( string blob, TimeSpan? maxWaitDefault = null, TimeSpan? delayDefault = null) { TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(120); TimeSpan delay = delayDefault ?? TimeSpan.FromMilliseconds(500); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // This will throw an exception with HTTP code 409 when we cannot acquire the lease // But we should block until we can get this lease, with a timeout (maxWaitSeconds) while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds) { try { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); Task<string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null); task.Wait(); return task.Result; } catch (Exception e) { Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}"); Thread.Sleep(delay); } } throw new Exception($"Unable to acquire lease on {blob}"); } public void ReleaseLeaseOnBlob(string blob, string leaseId) { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); AccessCondition ac = new AccessCondition() { LeaseId = leaseId }; cloudBlob.ReleaseLeaseAsync(ac).Wait(); } public bool IsLatestSpecifiedVersion(string version) { Task<bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync(); task.Wait(); return task.Result; } public void DropLatestSpecifiedVersion(string version) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(version); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } public void CreateBlobIfNotExists(string path) { Task<bool> task = _blobContainer.GetBlockBlobReference(path).ExistsAsync(); task.Wait(); if (!task.Result) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } } public bool TryDeleteBlob(string path) { try { DeleteBlob(path); return true; } catch (Exception e) { Console.WriteLine($"Deleting blob {path} failed with \r\n{e.Message}"); return false; } } private void DeleteBlob(string path) { _blobContainer.GetBlockBlobReference(path).DeleteAsync().Wait(); } private static string CalculateRelativePathForFile(string file, Product product, string version) { return $"{product}/{version}/{Path.GetFileName(file)}"; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Web.Mvc.Liquid.Tags { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.ServiceModel; using System.Text.RegularExpressions; using System.Threading; using DotLiquid; using DotLiquid.Exceptions; using DotLiquid.Util; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Query; using Adxstudio.Xrm.Core; using Adxstudio.Xrm.Services; using Adxstudio.Xrm.Services.Query; using Condition = Adxstudio.Xrm.Services.Query.Condition; public class EntityList : Block { public const string ScopeVariableName = "__entitylist__"; private static readonly Regex Syntax = new Regex(@"((?<variable>\w+)\s*=\s*)?(?<attributes>.*)"); private IDictionary<string, string> _attributes; private string _variableName; public override void Initialize(string tagName, string markup, List<string> tokens) { var syntaxMatch = Syntax.Match(markup); if (syntaxMatch.Success) { _variableName = syntaxMatch.Groups["variable"].Value.Trim(); _attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer); R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => _attributes[key] = value); } else { throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [[var] =] (name:[string] | id:[string] | key:[string]) (languagecode:[integer])", tagName); } base.Initialize(tagName, markup, tokens); } public override void Render(Context context, TextWriter result) { IPortalLiquidContext portalLiquidContext; if (!context.TryGetPortalLiquidContext(out portalLiquidContext)) { return; } var drop = GetEntityListDrop(portalLiquidContext, context); if (drop == null) { return; } context.Stack(() => { context[string.IsNullOrEmpty(_variableName) ? "entitylist" : _variableName] = drop; context[ScopeVariableName] = drop; RenderAll(NodeList, context, result); }); } private EntityListDrop GetEntityListDrop(IPortalLiquidContext portalLiquidContext, Context context) { using (var serviceContext = portalLiquidContext.PortalViewContext.CreateServiceContext()) { try { string idVariable; if (_attributes.TryGetValue("id", out idVariable)) { return GetEntityListById(portalLiquidContext, context, idVariable); } string nameVariable; if (_attributes.TryGetValue("name", out nameVariable)) { return GetEntityListByNameOrKey(portalLiquidContext, context, nameVariable); } string keyVariable; if (_attributes.TryGetValue("key", out keyVariable)) { var keyValue = context[keyVariable]; Guid id; if (keyValue != null && Guid.TryParse(keyValue.ToString(), out id)) { return GetEntityListById(portalLiquidContext, context, keyVariable); } return GetEntityListByNameOrKey(portalLiquidContext, context, keyVariable); } } catch (FaultException<OrganizationServiceFault>) { return null; } } return null; } private EntityListDrop GetEntityListById(IPortalLiquidContext portalLiquidContext, Context context, string idVariable) { var idValue = context[idVariable]; if (idValue == null) { return null; } Guid id; if (!Guid.TryParse(idValue.ToString(), out id)) { return null; } var portalOrgService = portalLiquidContext.PortalOrganizationService; var entityList = portalOrgService.RetrieveSingle( "adx_entitylist", FetchAttribute.All, new[] { new Condition("adx_entitylistid", ConditionOperator.Equal, id), new Condition("statecode", ConditionOperator.Equal, 0) }); return GetEntityListDrop(portalLiquidContext, context, entityList); } private EntityListDrop GetEntityListByNameOrKey(IPortalLiquidContext portalLiquidContext, Context context, string nameVariable) { var nameValue = context[nameVariable]; if (nameValue == null) { return null; } var name = nameValue.ToString(); if (string.IsNullOrWhiteSpace(name)) { return null; } Entity entityList; var portalOrgService = portalLiquidContext.PortalOrganizationService; var entityMetadata = portalOrgService.GetEntityMetadata("adx_entitylist", EntityFilters.Attributes); // Must check if new attribute exists to maintain compatability with previous schema versions and prevent runtime // exceptions when portal code updates are pushed to web apps where new solutions have not yet been applied. if (entityMetadata != null && entityMetadata.Attributes != null && entityMetadata.Attributes.Select(a => a.LogicalName).Contains("adx_key")) { var fetch = new Fetch { Entity = new FetchEntity("adx_entitylist") { Attributes = FetchAttribute.All, Filters = new[] { new Filter { Type = LogicalOperator.And, Conditions = new[] { new Condition("statecode", ConditionOperator.Equal, 0) }, Filters = new List<Filter> { new Filter { Type = LogicalOperator.Or, Conditions = new List<Condition> { new Condition("adx_name", ConditionOperator.Equal, name), new Condition("adx_key", ConditionOperator.Equal, name) } } } } } } }; entityList = portalOrgService.RetrieveSingle(fetch); } else { entityList = portalOrgService.RetrieveSingle( "adx_entitylist", FetchAttribute.All, new[] { new Condition("adx_name", ConditionOperator.Equal, name), new Condition("statecode", ConditionOperator.Equal, 0) }); } return GetEntityListDrop(portalLiquidContext, context, entityList); } private EntityListDrop GetEntityListDrop(IPortalLiquidContext portalLiquidContext, Context context, Entity entityList) { if (entityList == null) { return null; } return new EntityListDrop( portalLiquidContext, entityList, GetLazyGridDataUrl(portalLiquidContext), GetLazyModalFormTemplateUrl(portalLiquidContext), GetLazyWebPageUrl(portalLiquidContext.PortalViewContext, entityList.GetAttributeValue<EntityReference>("adx_webpageforcreate")), GetLazyWebPageUrl(portalLiquidContext.PortalViewContext, entityList.GetAttributeValue<EntityReference>("adx_webpagefordetailsview")), GetLazyLanguageCode(portalLiquidContext, context)); } private Lazy<int> GetLazyLanguageCode(IPortalLiquidContext portalLiquidContext, Context context) { string languageCodeVariable; int? languageCode = null; if (_attributes.TryGetValue("language_code", out languageCodeVariable) || _attributes.TryGetValue("languagecode", out languageCodeVariable)) { languageCode = context[languageCodeVariable] as int?; } // Note: entity list only supports CRM languages, so get the CrmLcid rather than the potentially custom language Lcid. return languageCode.HasValue && languageCode.Value > 0 ? new Lazy<int>(() => languageCode.Value, LazyThreadSafetyMode.None) : new Lazy<int>(() => portalLiquidContext.ContextLanguageInfo?.GetCrmLcid() ?? CultureInfo.CurrentCulture.LCID, LazyThreadSafetyMode.None); } private Lazy<string> GetLazyWebPageUrl(IPortalViewContext portalViewContext, EntityReference webPage) { if (portalViewContext == null) { return new Lazy<string>(() => null, LazyThreadSafetyMode.None); } if (webPage == null) { return new Lazy<string>(() => null, LazyThreadSafetyMode.None); } return new Lazy<string>(() => { var urlProvider = portalViewContext.UrlProvider; if (urlProvider == null) { return null; } using (var serviceContext = portalViewContext.CreateServiceContext()) { var entity = serviceContext.CreateQuery("adx_webpage") .FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webpageid") == webPage.Id && e.GetAttributeValue<int?>("statecode") == 0); return entity == null ? null : urlProvider.GetUrl(serviceContext, entity); } }, LazyThreadSafetyMode.None); } private static Lazy<string> GetLazyGridDataUrl(IPortalLiquidContext portalLiquidContext) { var url = portalLiquidContext.UrlHelper.RouteUrl("PortalGetGridData", new { __portalScopeId__ = portalLiquidContext.PortalViewContext.Website.EntityReference.Id }); return new Lazy<string>(() => url, LazyThreadSafetyMode.None); } private static Lazy<string> GetLazyModalFormTemplateUrl(IPortalLiquidContext portalLiquidContext) { var url = portalLiquidContext.UrlHelper.RouteUrl("PortalModalFormTemplatePath", new { __portalScopeId__ = portalLiquidContext.PortalViewContext.Website.EntityReference.Id }); return new Lazy<string>(() => url, LazyThreadSafetyMode.None); } } }
// 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.Numerics.Hashing; namespace System.Drawing { /// <summary> /// Represents an ordered pair of x and y coordinates that /// define a point in a two-dimensional plane. /// </summary> [Serializable] public struct Point : IEquatable<Point> { /// <summary> /// Creates a new instance of the <see cref='System.Drawing.Point'/> class /// with member data left uninitialized. /// </summary> public static readonly Point Empty = new Point(); private int _x; private int _y; /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.Point'/> class /// with the specified coordinates. /// </summary> public Point(int x, int y) { _x = x; _y = y; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Point'/> class /// from a <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public Point(Size sz) { _x = sz.Width; _y = sz.Height; } /// <summary> /// Initializes a new instance of the Point class using /// coordinates specified by an integer value. /// </summary> public Point(int dw) { _x = LowInt16(dw); _y = HighInt16(dw); } /// <summary> /// <para> /// Gets a value indicating whether this <see cref='System.Drawing.Point'/> is empty. /// </para> /// </summary> public bool IsEmpty => _x == 0 && _y == 0; /// <summary> /// Gets the x-coordinate of this <see cref='System.Drawing.Point'/>. /// </summary> public int X { get { return _x; } set { _x = value; } } /// <summary> /// <para> /// Gets the y-coordinate of this <see cref='System.Drawing.Point'/>. /// </para> /// </summary> public int Y { get { return _y; } set { _y = value; } } /// <summary> /// <para> /// Creates a <see cref='System.Drawing.PointF'/> with the coordinates of the specified /// <see cref='System.Drawing.Point'/> /// </para> /// </summary> public static implicit operator PointF(Point p) => new PointF(p.X, p.Y); /// <summary> /// <para> /// Creates a <see cref='System.Drawing.Size'/> with the coordinates of the specified <see cref='System.Drawing.Point'/> . /// </para> /// </summary> public static explicit operator Size(Point p) => new Size(p.X, p.Y); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point operator +(Point pt, Size sz) => Add(pt, sz); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by the negative of a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point operator -(Point pt, Size sz) => Subtract(pt, sz); /// <summary> /// <para> /// Compares two <see cref='System.Drawing.Point'/> objects. The result specifies /// whether the values of the <see cref='System.Drawing.Point.X'/> and <see cref='System.Drawing.Point.Y'/> properties of the two <see cref='System.Drawing.Point'/> /// objects are equal. /// </para> /// </summary> public static bool operator ==(Point left, Point right) => left.X == right.X && left.Y == right.Y; /// <summary> /// <para> /// Compares two <see cref='System.Drawing.Point'/> objects. The result specifies whether the values /// of the <see cref='System.Drawing.Point.X'/> or <see cref='System.Drawing.Point.Y'/> properties of the two /// <see cref='System.Drawing.Point'/> /// objects are unequal. /// </para> /// </summary> public static bool operator !=(Point left, Point right) => !(left == right); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point Add(Point pt, Size sz) => new Point(unchecked(pt.X + sz.Width), unchecked(pt.Y + sz.Height)); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by the negative of a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point Subtract(Point pt, Size sz) => new Point(unchecked(pt.X - sz.Width), unchecked(pt.Y - sz.Height)); /// <summary> /// Converts a PointF to a Point by performing a ceiling operation on /// all the coordinates. /// </summary> public static Point Ceiling(PointF value) => new Point(unchecked((int)Math.Ceiling(value.X)), unchecked((int)Math.Ceiling(value.Y))); /// <summary> /// Converts a PointF to a Point by performing a truncate operation on /// all the coordinates. /// </summary> public static Point Truncate(PointF value) => new Point(unchecked((int)value.X), unchecked((int)value.Y)); /// <summary> /// Converts a PointF to a Point by performing a round operation on /// all the coordinates. /// </summary> public static Point Round(PointF value) => new Point(unchecked((int)Math.Round(value.X)), unchecked((int)Math.Round(value.Y))); /// <summary> /// <para> /// Specifies whether this <see cref='System.Drawing.Point'/> contains /// the same coordinates as the specified <see cref='System.Object'/>. /// </para> /// </summary> public override bool Equals(object obj) => obj is Point && Equals((Point)obj); public bool Equals(Point other) => this == other; /// <summary> /// <para> /// Returns a hash code. /// </para> /// </summary> public override int GetHashCode() => HashHelpers.Combine(X, Y); /// <summary> /// Translates this <see cref='System.Drawing.Point'/> by the specified amount. /// </summary> public void Offset(int dx, int dy) { unchecked { X += dx; Y += dy; } } /// <summary> /// Translates this <see cref='System.Drawing.Point'/> by the specified amount. /// </summary> public void Offset(Point p) => Offset(p.X, p.Y); /// <summary> /// <para> /// Converts this <see cref='System.Drawing.Point'/> /// to a human readable /// string. /// </para> /// </summary> public override string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + "}"; private static short HighInt16(int n) => unchecked((short)((n >> 16) & 0xffff)); private static short LowInt16(int n) => unchecked((short)(n & 0xffff)); } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using dnlib.IO; namespace dnlib.DotNet { /// <summary> /// Searches for a type according to custom attribute search rules: first try the /// current assembly, and if that fails, try mscorlib /// </summary> sealed class CAAssemblyRefFinder : IAssemblyRefFinder { readonly ModuleDef module; /// <summary> /// Constructor /// </summary> /// <param name="module">The module to search first</param> public CAAssemblyRefFinder(ModuleDef module) => this.module = module; /// <inheritdoc/> public AssemblyRef FindAssemblyRef(TypeRef nonNestedTypeRef) { var modAsm = module.Assembly; if (modAsm is not null) { var type = modAsm.Find(nonNestedTypeRef); // If the user added a new type with the same name as a corelib type, don't return it, // only return the type if it is this module's original type. if (type is TypeDefMD td && td.ReaderModule == module) return module.UpdateRowId(new AssemblyRefUser(modAsm)); } else if (module.Find(nonNestedTypeRef) is not null) return AssemblyRef.CurrentAssembly; var corLibAsm = module.Context.AssemblyResolver.Resolve(module.CorLibTypes.AssemblyRef, module); if (corLibAsm is not null) { var type = corLibAsm.Find(nonNestedTypeRef); if (type is not null) return module.CorLibTypes.AssemblyRef; } if (modAsm is not null) return module.UpdateRowId(new AssemblyRefUser(modAsm)); return AssemblyRef.CurrentAssembly; } } /// <summary> /// Thrown by CustomAttributeReader when it fails to parse a custom attribute blob /// </summary> [Serializable] public class CABlobParserException : Exception { /// <summary> /// Default constructor /// </summary> public CABlobParserException() { } /// <summary> /// Constructor /// </summary> /// <param name="message">Error message</param> public CABlobParserException(string message) : base(message) { } /// <summary> /// Constructor /// </summary> /// <param name="message">Error message</param> /// <param name="innerException">Other exception</param> public CABlobParserException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Constructor /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected CABlobParserException(SerializationInfo info, StreamingContext context) : base(info, context) { } } /// <summary> /// Reads custom attributes from the #Blob stream /// </summary> public struct CustomAttributeReader { readonly ModuleDef module; DataReader reader; readonly uint caBlobOffset; readonly GenericParamContext gpContext; GenericArguments genericArguments; RecursionCounter recursionCounter; bool verifyReadAllBytes; /// <summary> /// Reads a custom attribute /// </summary> /// <param name="readerModule">Reader module</param> /// <param name="ctor">Custom attribute constructor</param> /// <param name="offset">Offset of custom attribute in the #Blob stream</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> public static CustomAttribute Read(ModuleDefMD readerModule, ICustomAttributeType ctor, uint offset) => Read(readerModule, ctor, offset, new GenericParamContext()); /// <summary> /// Reads a custom attribute /// </summary> /// <param name="readerModule">Reader module</param> /// <param name="ctor">Custom attribute constructor</param> /// <param name="offset">Offset of custom attribute in the #Blob stream</param> /// <param name="gpContext">Generic parameter context</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> public static CustomAttribute Read(ModuleDefMD readerModule, ICustomAttributeType ctor, uint offset, GenericParamContext gpContext) { var caReader = new CustomAttributeReader(readerModule, offset, gpContext); try { if (ctor is null) return caReader.CreateRaw(ctor); return caReader.Read(ctor); } catch (CABlobParserException) { return caReader.CreateRaw(ctor); } catch (IOException) { return caReader.CreateRaw(ctor); } } CustomAttribute CreateRaw(ICustomAttributeType ctor) => new CustomAttribute(ctor, GetRawBlob()); /// <summary> /// Reads a custom attribute /// </summary> /// <param name="module">Owner module</param> /// <param name="caBlob">CA blob</param> /// <param name="ctor">Custom attribute constructor</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> public static CustomAttribute Read(ModuleDef module, byte[] caBlob, ICustomAttributeType ctor) => Read(module, ByteArrayDataReaderFactory.CreateReader(caBlob), ctor, new GenericParamContext()); /// <summary> /// Reads a custom attribute /// </summary> /// <param name="module">Owner module</param> /// <param name="reader">A reader positioned at the the first byte of the CA blob</param> /// <param name="ctor">Custom attribute constructor</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> public static CustomAttribute Read(ModuleDef module, DataReader reader, ICustomAttributeType ctor) => Read(module, ref reader, ctor, new GenericParamContext()); /// <summary> /// Reads a custom attribute /// </summary> /// <param name="module">Owner module</param> /// <param name="caBlob">CA blob</param> /// <param name="ctor">Custom attribute constructor</param> /// <param name="gpContext">Generic parameter context</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> public static CustomAttribute Read(ModuleDef module, byte[] caBlob, ICustomAttributeType ctor, GenericParamContext gpContext) => Read(module, ByteArrayDataReaderFactory.CreateReader(caBlob), ctor, gpContext); /// <summary> /// Reads a custom attribute /// </summary> /// <param name="module">Owner module</param> /// <param name="reader">A stream positioned at the the first byte of the CA blob</param> /// <param name="ctor">Custom attribute constructor</param> /// <param name="gpContext">Generic parameter context</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> public static CustomAttribute Read(ModuleDef module, DataReader reader, ICustomAttributeType ctor, GenericParamContext gpContext) => Read(module, ref reader, ctor, gpContext); /// <summary> /// Reads a custom attribute /// </summary> /// <param name="module">Owner module</param> /// <param name="reader">A stream positioned at the the first byte of the CA blob</param> /// <param name="ctor">Custom attribute constructor</param> /// <param name="gpContext">Generic parameter context</param> /// <returns>A new <see cref="CustomAttribute"/> instance</returns> static CustomAttribute Read(ModuleDef module, ref DataReader reader, ICustomAttributeType ctor, GenericParamContext gpContext) { var caReader = new CustomAttributeReader(module, ref reader, gpContext); CustomAttribute ca; try { if (ctor is null) ca = caReader.CreateRaw(ctor); else ca = caReader.Read(ctor); } catch (CABlobParserException) { ca = caReader.CreateRaw(ctor); } catch (IOException) { ca = caReader.CreateRaw(ctor); } return ca; } /// <summary> /// Reads custom attribute named arguments /// </summary> /// <param name="module">Owner module</param> /// <param name="reader">A reader positioned at the the first byte of the CA blob</param> /// <param name="numNamedArgs">Number of named arguments to read from <paramref name="reader"/></param> /// <param name="gpContext">Generic parameter context</param> /// <returns>A list of <see cref="CANamedArgument"/>s or <c>null</c> if some error /// occurred.</returns> internal static List<CANamedArgument> ReadNamedArguments(ModuleDef module, ref DataReader reader, int numNamedArgs, GenericParamContext gpContext) { try { var caReader = new CustomAttributeReader(module, ref reader, gpContext); var namedArgs = caReader.ReadNamedArguments(numNamedArgs); reader.CurrentOffset = caReader.reader.CurrentOffset; return namedArgs; } catch (CABlobParserException) { return null; } catch (IOException) { return null; } } CustomAttributeReader(ModuleDefMD readerModule, uint offset, GenericParamContext gpContext) { module = readerModule; caBlobOffset = offset; reader = readerModule.BlobStream.CreateReader(offset); genericArguments = null; recursionCounter = new RecursionCounter(); verifyReadAllBytes = false; this.gpContext = gpContext; } CustomAttributeReader(ModuleDef module, ref DataReader reader, GenericParamContext gpContext) { this.module = module; caBlobOffset = 0; this.reader = reader; genericArguments = null; recursionCounter = new RecursionCounter(); verifyReadAllBytes = false; this.gpContext = gpContext; } byte[] GetRawBlob() => reader.ToArray(); CustomAttribute Read(ICustomAttributeType ctor) { var methodSig = ctor?.MethodSig; if (methodSig is null) throw new CABlobParserException("ctor is null or not a method"); if (ctor is MemberRef mrCtor && mrCtor.Class is TypeSpec owner && owner.TypeSig is GenericInstSig gis) { genericArguments = new GenericArguments(); genericArguments.PushTypeArgs(gis.GenericArguments); } var methodSigParams = methodSig.Params; bool isEmpty = methodSigParams.Count == 0 && reader.Position == reader.Length; if (!isEmpty && reader.ReadUInt16() != 1) throw new CABlobParserException("Invalid CA blob prolog"); var ctorArgs = new List<CAArgument>(methodSigParams.Count); int count = methodSigParams.Count; for (int i = 0; i < count; i++) ctorArgs.Add(ReadFixedArg(FixTypeSig(methodSigParams[i]))); // Some tools don't write the next ushort if there are no named arguments. int numNamedArgs = reader.Position == reader.Length ? 0 : reader.ReadUInt16(); var namedArgs = ReadNamedArguments(numNamedArgs); // verifyReadAllBytes will be set when we guess the underlying type of an enum. // To make sure we guessed right, verify that we read all bytes. if (verifyReadAllBytes && reader.Position != reader.Length) throw new CABlobParserException("Not all CA blob bytes were read"); return new CustomAttribute(ctor, ctorArgs, namedArgs, caBlobOffset); } List<CANamedArgument> ReadNamedArguments(int numNamedArgs) { if ((uint)numNamedArgs >= 0x4000_0000 || numNamedArgs * 4 > reader.BytesLeft) return null; var namedArgs = new List<CANamedArgument>(numNamedArgs); for (int i = 0; i < numNamedArgs; i++) { if (reader.Position == reader.Length) break; namedArgs.Add(ReadNamedArgument()); } return namedArgs; } TypeSig FixTypeSig(TypeSig type) => SubstituteGenericParameter(type.RemoveModifiers()).RemoveModifiers(); TypeSig SubstituteGenericParameter(TypeSig type) { if (genericArguments is null) return type; return genericArguments.Resolve(type); } CAArgument ReadFixedArg(TypeSig argType) { if (!recursionCounter.Increment()) throw new CABlobParserException("Too much recursion"); if (argType is null) throw new CABlobParserException("null argType"); CAArgument result; if (argType is SZArraySig arrayType) result = ReadArrayArgument(arrayType); else result = ReadElem(argType); recursionCounter.Decrement(); return result; } CAArgument ReadElem(TypeSig argType) { if (argType is null) throw new CABlobParserException("null argType"); var value = ReadValue((SerializationType)argType.ElementType, argType, out var realArgType); if (realArgType is null) throw new CABlobParserException("Invalid arg type"); // One example when this is true is when prop/field type is object and // value type is string[] if (value is CAArgument) return (CAArgument)value; return new CAArgument(realArgType, value); } object ReadValue(SerializationType etype, TypeSig argType, out TypeSig realArgType) { if (!recursionCounter.Increment()) throw new CABlobParserException("Too much recursion"); object result; switch (etype) { case SerializationType.Boolean: realArgType = module.CorLibTypes.Boolean; result = reader.ReadByte() != 0; break; case SerializationType.Char: realArgType = module.CorLibTypes.Char; result = reader.ReadChar(); break; case SerializationType.I1: realArgType = module.CorLibTypes.SByte; result = reader.ReadSByte(); break; case SerializationType.U1: realArgType = module.CorLibTypes.Byte; result = reader.ReadByte(); break; case SerializationType.I2: realArgType = module.CorLibTypes.Int16; result = reader.ReadInt16(); break; case SerializationType.U2: realArgType = module.CorLibTypes.UInt16; result = reader.ReadUInt16(); break; case SerializationType.I4: realArgType = module.CorLibTypes.Int32; result = reader.ReadInt32(); break; case SerializationType.U4: realArgType = module.CorLibTypes.UInt32; result = reader.ReadUInt32(); break; case SerializationType.I8: realArgType = module.CorLibTypes.Int64; result = reader.ReadInt64(); break; case SerializationType.U8: realArgType = module.CorLibTypes.UInt64; result = reader.ReadUInt64(); break; case SerializationType.R4: realArgType = module.CorLibTypes.Single; result = reader.ReadSingle(); break; case SerializationType.R8: realArgType = module.CorLibTypes.Double; result = reader.ReadDouble(); break; case SerializationType.String: realArgType = module.CorLibTypes.String; result = ReadUTF8String(); break; // It's ET.ValueType if it's eg. a ctor enum arg type case (SerializationType)ElementType.ValueType: if (argType is null) throw new CABlobParserException("Invalid element type"); realArgType = argType; result = ReadEnumValue(GetEnumUnderlyingType(argType)); break; // It's ET.Object if it's a ctor object arg type case (SerializationType)ElementType.Object: case SerializationType.TaggedObject: realArgType = ReadFieldOrPropType(); var arraySig = realArgType as SZArraySig; if (arraySig is not null) result = ReadArrayArgument(arraySig); else result = ReadValue((SerializationType)realArgType.ElementType, realArgType, out var tmpType); break; // It's ET.Class if it's eg. a ctor System.Type arg type case (SerializationType)ElementType.Class: var tdr = argType as TypeDefOrRefSig; if (tdr is not null && tdr.DefinitionAssembly.IsCorLib() && tdr.Namespace == "System") { if (tdr.TypeName == "Type") { result = ReadValue(SerializationType.Type, tdr, out realArgType); break; } if (tdr.TypeName == "String") { result = ReadValue(SerializationType.String, tdr, out realArgType); break; } if (tdr.TypeName == "Object") { result = ReadValue(SerializationType.TaggedObject, tdr, out realArgType); break; } } // Assume it's an enum that couldn't be resolved realArgType = argType; result = ReadEnumValue(null); break; case SerializationType.Type: realArgType = argType; result = ReadType(true); break; case SerializationType.Enum: realArgType = ReadType(false); result = ReadEnumValue(GetEnumUnderlyingType(realArgType)); break; default: throw new CABlobParserException("Invalid element type"); } recursionCounter.Decrement(); return result; } object ReadEnumValue(TypeSig underlyingType) { if (underlyingType is not null) { if (underlyingType.ElementType < ElementType.Boolean || underlyingType.ElementType > ElementType.U8) throw new CABlobParserException("Invalid enum underlying type"); return ReadValue((SerializationType)underlyingType.ElementType, underlyingType, out var realArgType); } // We couldn't resolve the type ref. It should be an enum, but we don't know for sure. // Most enums use Int32 as the underlying type. Assume that's true also in this case. // Since we're guessing, verify that we've read all CA blob bytes. If we haven't, then // we probably guessed wrong. verifyReadAllBytes = true; return reader.ReadInt32(); } TypeSig ReadType(bool canReturnNull) { var name = ReadUTF8String(); if (canReturnNull && name is null) return null; var asmRefFinder = new CAAssemblyRefFinder(module); var type = TypeNameParser.ParseAsTypeSigReflection(module, UTF8String.ToSystemStringOrEmpty(name), asmRefFinder, gpContext); if (type is null) throw new CABlobParserException("Could not parse type"); return type; } /// <summary> /// Gets the enum's underlying type /// </summary> /// <param name="type">An enum type</param> /// <returns>The underlying type or <c>null</c> if we couldn't resolve the type ref</returns> /// <exception cref="CABlobParserException">If <paramref name="type"/> is not an enum or <c>null</c></exception> static TypeSig GetEnumUnderlyingType(TypeSig type) { if (type is null) throw new CABlobParserException("null enum type"); var td = GetTypeDef(type); if (td is null) return null; if (!td.IsEnum) throw new CABlobParserException("Not an enum"); return td.GetEnumUnderlyingType().RemoveModifiers(); } /// <summary> /// Converts <paramref name="type"/> to a <see cref="TypeDef"/>, possibly resolving /// a <see cref="TypeRef"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="TypeDef"/> or <c>null</c> if we couldn't resolve the /// <see cref="TypeRef"/> or if <paramref name="type"/> is a type spec</returns> static TypeDef GetTypeDef(TypeSig type) { if (type is TypeDefOrRefSig tdr) { var td = tdr.TypeDef; if (td is not null) return td; var tr = tdr.TypeRef; if (tr is not null) return tr.Resolve(); } return null; } CAArgument ReadArrayArgument(SZArraySig arrayType) { if (!recursionCounter.Increment()) throw new CABlobParserException("Too much recursion"); var arg = new CAArgument(arrayType); int arrayCount = reader.ReadInt32(); if (arrayCount == -1) { // -1 if it's null } else if (arrayCount < 0 || arrayCount > reader.BytesLeft) throw new CABlobParserException("Array is too big"); else { var array = new List<CAArgument>(arrayCount); arg.Value = array; for (int i = 0; i < arrayCount; i++) array.Add(ReadFixedArg(FixTypeSig(arrayType.Next))); } recursionCounter.Decrement(); return arg; } CANamedArgument ReadNamedArgument() { var isField = (SerializationType)reader.ReadByte() switch { SerializationType.Property => false, SerializationType.Field => true, _ => throw new CABlobParserException("Named argument is not a field/property"), }; var fieldPropType = ReadFieldOrPropType(); var name = ReadUTF8String(); var argument = ReadFixedArg(fieldPropType); return new CANamedArgument(isField, fieldPropType, name, argument); } TypeSig ReadFieldOrPropType() { if (!recursionCounter.Increment()) throw new CABlobParserException("Too much recursion"); var result = (SerializationType)reader.ReadByte() switch { SerializationType.Boolean => module.CorLibTypes.Boolean, SerializationType.Char => module.CorLibTypes.Char, SerializationType.I1 => module.CorLibTypes.SByte, SerializationType.U1 => module.CorLibTypes.Byte, SerializationType.I2 => module.CorLibTypes.Int16, SerializationType.U2 => module.CorLibTypes.UInt16, SerializationType.I4 => module.CorLibTypes.Int32, SerializationType.U4 => module.CorLibTypes.UInt32, SerializationType.I8 => module.CorLibTypes.Int64, SerializationType.U8 => module.CorLibTypes.UInt64, SerializationType.R4 => module.CorLibTypes.Single, SerializationType.R8 => module.CorLibTypes.Double, SerializationType.String => module.CorLibTypes.String, SerializationType.SZArray => new SZArraySig(ReadFieldOrPropType()), SerializationType.Type => new ClassSig(module.CorLibTypes.GetTypeRef("System", "Type")), SerializationType.TaggedObject => module.CorLibTypes.Object, SerializationType.Enum => ReadType(false), _ => throw new CABlobParserException("Invalid type"), }; recursionCounter.Decrement(); return result; } UTF8String ReadUTF8String() { if (reader.ReadByte() == 0xFF) return null; reader.Position--; if (!reader.TryReadCompressedUInt32(out uint len)) throw new CABlobParserException("Could not read compressed UInt32"); if (len == 0) return UTF8String.Empty; return new UTF8String(reader.ReadBytes((int)len)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AngularMaterialDotNet.API.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading; using Analysis.EDM; using Data.EDM; using EDMConfig; using MongoDB.Bson; using MongoDB.Bson.Serialization; namespace SonOfSirCachealot { public class BlockStore { #region Adding blocks public ThreadMonitor Monitor = new ThreadMonitor(); public void AddBlocks(string[] paths) { Monitor.ClearStats(); Monitor.SetQueueLength(paths.Length); new Thread(new ThreadStart(() => paths.AsParallel().ForAll((e) => AddBlock(e, "cgate11Fixed")) )).Start(); // spawn a progress monitor thread Monitor.UpdateProgressUntilFinished(); } public void AddBlocksJSON(string jsonPaths) { string[] paths = BsonSerializer.Deserialize<string[]>(jsonPaths); AddBlocks(paths); } private void AddBlock(string path, string normConfig) { Monitor.JobStarted(); string fileName = path.Split('\\').Last(); try { Controller.log("Adding block " + fileName); using (BlockDatabaseDataContext dc = new BlockDatabaseDataContext()) { BlockSerializer bls = new BlockSerializer(); Block b = bls.DeserializeBlockFromZippedXML(path, "block.xml"); Controller.log("Loaded " + fileName); // at the moment the block data is normalized by dividing each "top" TOF through // by the integral of the corresponding "norm" TOF over the gate in the function below. // TODO: this could be improved! //b.Normalise(DemodulationConfig.GetStandardDemodulationConfig(normConfig, b).GatedDetectorExtractSpecs["norm"]); // add some of the single point data to the Shot TOFs so that it gets analysed string[] spvsToTOFulise = new string[] { "NorthCurrent", "SouthCurrent", "MiniFlux1", "MiniFlux2", "MiniFlux3", "ProbePD", "PumpPD"}; b.TOFuliseSinglePointData(spvsToTOFulise); // extract the metadata and config into a DB object DBBlock dbb = new DBBlock(); dbb.cluster = (string)b.Config.Settings["cluster"]; dbb.clusterIndex = (int)b.Config.Settings["clusterIndex"]; dbb.include = false; dbb.eState = (bool)b.Config.Settings["eState"]; dbb.bState = (bool)b.Config.Settings["bState"]; try { dbb.rfState = (bool)b.Config.Settings["rfState"]; } catch (Exception) { // blocks from the old days had no rfState recorded in them. dbb.rfState = true; } dbb.ePlus = (double)b.Config.Settings["ePlus"]; dbb.eMinus = (double)b.Config.Settings["eMinus"]; dbb.blockTime = (DateTime)b.TimeStamp; byte[] bts = serializeAsByteArray(b.Config); dbb.configBytes = bts; // extract the TOFChannelSets List<string> detectorsToExtract = new List<string> { "top", "norm", "magnetometer", "gnd", "battery","topNormed","NorthCurrent", "SouthCurrent", "MiniFlux1", "MiniFlux2", "MiniFlux3", "ProbePD", "PumpPD" }; foreach (string detector in detectorsToExtract) { BlockDemodulator demod = new BlockDemodulator(); TOFChannelSet tcs = demod.TOFDemodulateBlock(b, b.detectors.IndexOf(detector), true); byte[] tcsBytes = serializeAsByteArray(tcs); DBTOFChannelSet t = new DBTOFChannelSet(); t.tcsData = tcsBytes; t.detector = detector; t.FileID = Guid.NewGuid(); dbb.DBTOFChannelSets.Add(t); } Controller.log("Demodulated " + fileName); // add to the database dc.DBBlocks.InsertOnSubmit(dbb); dc.SubmitChanges(); Controller.log("Added " + fileName); } } catch (Exception e) { Controller.errorLog("Error adding " + fileName); Controller.errorLog("Error adding block " + path + "\n" + e.StackTrace); } finally { Monitor.JobFinished(); } } private static byte[] serializeAsByteArray(object bc) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, bc); byte[] buffer = new Byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, (int)ms.Length); ms.Close(); return buffer; } private static object deserializeFromByteArray(byte[] ba) { BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(ba); return bf.Deserialize(ms); } private static TOFChannelSet deserializeTCS(byte[] ba) { return (TOFChannelSet)deserializeFromByteArray(ba); } private static BlockConfig deserializeBC(byte[] ba) { return (BlockConfig)deserializeFromByteArray(ba); } #endregion #region Querying public string processJSONQuery(string jsonQuery) { BlockStoreQuery query = BsonSerializer.Deserialize<BlockStoreQuery>(jsonQuery); return processQuery(query).ToJson<BlockStoreResponse>(); } public BlockStoreResponse processQuery(BlockStoreQuery query) { BlockStoreResponse bsr = new BlockStoreResponse(); bsr.BlockResponses = new List<BlockStoreBlockResponse>(); foreach(int blockID in query.BlockIDs) bsr.BlockResponses.Add(processBlockQuery(query.BlockQuery, blockID)); return bsr; } private BlockStoreBlockResponse processBlockQuery(BlockStoreBlockQuery query, int blockID) { BlockStoreBlockResponse br = new BlockStoreBlockResponse(); br.BlockID = blockID; br.DetectorResponses = new Dictionary<string, BlockStoreDetectorResponse>(); br.Settings = getBlockConfig(blockID); foreach (BlockStoreDetectorQuery q in query.DetectorQueries) br.DetectorResponses.Add(q.Detector, processDetectorQuery(q, blockID)); return br; } private BlockConfig getBlockConfig(int blockID) { BlockConfig bc = new BlockConfig(); using (BlockDatabaseDataContext dc = new BlockDatabaseDataContext()) { IEnumerable<DBBlock> bs = from DBBlock dbb in dc.DBBlocks where (dbb.blockID == blockID) select dbb; // there should only be one item - better to check or not? DBBlock dbbb = bs.First(); bc = deserializeBC(dbbb.configBytes.ToArray()); } return bc; } private BlockStoreDetectorResponse processDetectorQuery(BlockStoreDetectorQuery query, int blockID) { BlockStoreDetectorResponse dr = new BlockStoreDetectorResponse(); dr.Channels = new Dictionary<string, TOFChannel>(); using (BlockDatabaseDataContext dc = new BlockDatabaseDataContext()) { IEnumerable<DBTOFChannelSet> tcss = from DBTOFChannelSet tcs in dc.DBTOFChannelSets where (tcs.detector == query.Detector) && (tcs.blockID == blockID) select tcs; // there should only be one item - better to check or not? DBTOFChannelSet tc = tcss.First(); TOFChannelSet t = deserializeTCS(tc.tcsData.ToArray()); // TODO: Handle special channels foreach (string channel in query.Channels) dr.Channels.Add(channel, (TOFChannel)t.GetChannel(channel)); } return dr; } #endregion #region Querying (average) // querying for average TOFs uses different code - this is because of the need to keep // memory consumption under control, and the urge to re-use the old averaging code. // The result is that the averaging must be done at the TOFChannelSet level. public string processJSONQueryAverage(string jsonQuery) { BlockStoreQuery query = BsonSerializer.Deserialize<BlockStoreQuery>(jsonQuery); return processBlockQueryAverage(query.BlockQuery, query.BlockIDs).ToJson<BlockStoreBlockResponse>(); } private BlockStoreBlockResponse processBlockQueryAverage(BlockStoreBlockQuery query, int[] blockIDs) { BlockStoreBlockResponse br = new BlockStoreBlockResponse(); br.BlockID = -1; br.DetectorResponses = new Dictionary<string, BlockStoreDetectorResponse>(); br.Settings = getBlockConfig(blockIDs[0]); foreach (BlockStoreDetectorQuery q in query.DetectorQueries) br.DetectorResponses.Add(q.Detector, processDetectorQueryAverage(q, blockIDs)); return br; } private BlockStoreDetectorResponse processDetectorQueryAverage(BlockStoreDetectorQuery query, int[] blockIDs) { BlockStoreDetectorResponse dr = new BlockStoreDetectorResponse(); dr.Channels = new Dictionary<string, TOFChannel>(); using (BlockDatabaseDataContext dc = new BlockDatabaseDataContext()) { IEnumerable<DBTOFChannelSet> tcss = from DBTOFChannelSet tcs in dc.DBTOFChannelSets where (tcs.detector == query.Detector) && blockIDs.Contains(tcs.blockID) select tcs; // accumulate the average TCS TOFChannelSetAccumulator tcsa = new TOFChannelSetAccumulator(); foreach (DBTOFChannelSet dbTcs in tcss) { TOFChannelSet t = deserializeTCS(dbTcs.tcsData.ToArray()); tcsa.Add(t); } // TODO: Handle special channels TOFChannelSet averageTCS = tcsa.GetResult(); foreach (string channel in query.Channels) dr.Channels.Add(channel, (TOFChannel)averageTCS.GetChannel(channel)); } return dr; } #endregion #region Including blocks public void SetIncluded(string cluster, int clusterIndex, bool included) { using (BlockDatabaseDataContext dc = new BlockDatabaseDataContext()) { IEnumerable<DBBlock> b = from DBBlock dbb in dc.DBBlocks where (dbb.cluster == cluster) && (dbb.clusterIndex == clusterIndex) select dbb; foreach (DBBlock dbb in b) dbb.include = included; dc.SubmitChanges(); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar; using Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.NavigationBar { [ExportLanguageService(typeof(INavigationBarItemService), LanguageNames.CSharp), Shared] internal class CSharpNavigationBarItemService : AbstractNavigationBarItemService { private static readonly SymbolDisplayFormat s_memberFormat = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeParamsRefOut, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); public override async Task<IList<NavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken) { var typesInFile = await GetTypesInFileAsync(document, cancellationToken).ConfigureAwait(false); var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return GetMembersInTypes(tree, typesInFile, cancellationToken); } private IList<NavigationBarItem> GetMembersInTypes( SyntaxTree tree, IEnumerable<INamedTypeSymbol> types, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.NavigationBar_ItemService_GetMembersInTypes_CSharp, cancellationToken)) { var typeSymbolIndexProvider = new NavigationBarSymbolIdIndexProvider(caseSensitive: true); var items = new List<NavigationBarItem>(); foreach (var type in types) { var memberSymbolIndexProvider = new NavigationBarSymbolIdIndexProvider(caseSensitive: true); var memberItems = new List<NavigationBarItem>(); foreach (var member in type.GetMembers()) { if (member.IsImplicitlyDeclared || member.Kind == SymbolKind.NamedType || IsAccessor(member)) { continue; } var method = member as IMethodSymbol; if (method != null && method.PartialImplementationPart != null) { memberItems.Add(CreateItemForMember( method, memberSymbolIndexProvider.GetIndexForSymbolId(method.GetSymbolKey()), tree, cancellationToken)); memberItems.Add(CreateItemForMember( method.PartialImplementationPart, memberSymbolIndexProvider.GetIndexForSymbolId(method.PartialImplementationPart.GetSymbolKey()), tree, cancellationToken)); } else { Debug.Assert(method == null || method.PartialDefinitionPart == null, "NavBar expected GetMembers to return partial method definition parts but the implementation part was returned."); memberItems.Add(CreateItemForMember( member, memberSymbolIndexProvider.GetIndexForSymbolId(member.GetSymbolKey()), tree, cancellationToken)); } } memberItems.Sort((x, y) => { var textComparison = x.Text.CompareTo(y.Text); return textComparison != 0 ? textComparison : x.Grayed.CompareTo(y.Grayed); }); var symbolId = type.GetSymbolKey(); items.Add(new NavigationBarSymbolItem( text: type.ToDisplayString(s_typeFormat), glyph: type.GetGlyph(), indent: 0, spans: GetSpansInDocument(type, tree, cancellationToken), navigationSymbolId: symbolId, navigationSymbolIndex: typeSymbolIndexProvider.GetIndexForSymbolId(symbolId), childItems: memberItems)); } items.Sort((x1, x2) => x1.Text.CompareTo(x2.Text)); return items; } } private async Task<IEnumerable<INamedTypeSymbol>> GetTypesInFileAsync(Document document, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); return GetTypesInFile(semanticModel, cancellationToken); } private static IEnumerable<INamedTypeSymbol> GetTypesInFile(SemanticModel semanticModel, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.NavigationBar_ItemService_GetTypesInFile_CSharp, cancellationToken)) { var types = new HashSet<INamedTypeSymbol>(); var nodesToVisit = new Stack<SyntaxNode>(); nodesToVisit.Push(semanticModel.SyntaxTree.GetRoot(cancellationToken)); while (!nodesToVisit.IsEmpty()) { if (cancellationToken.IsCancellationRequested) { return SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>(); } var node = nodesToVisit.Pop(); var type = node.TypeSwitch( (BaseTypeDeclarationSyntax t) => semanticModel.GetDeclaredSymbol(t, cancellationToken), (EnumDeclarationSyntax e) => semanticModel.GetDeclaredSymbol(e, cancellationToken), (DelegateDeclarationSyntax d) => semanticModel.GetDeclaredSymbol(d, cancellationToken)); if (type != null) { types.Add((INamedTypeSymbol)type); } if (node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is BaseFieldDeclarationSyntax || node is StatementSyntax || node is ExpressionSyntax) { // quick bail out to prevent us from creating every nodes exist in current file continue; } foreach (var child in node.ChildNodes()) { nodesToVisit.Push(child); } } return types; } } private static readonly SymbolDisplayFormat s_typeFormat = SymbolDisplayFormat.CSharpErrorMessageFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeVariance); private static bool IsAccessor(ISymbol member) { if (member.Kind == SymbolKind.Method) { var method = (IMethodSymbol)member; return method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.PropertySet; } return false; } private NavigationBarItem CreateItemForMember(ISymbol member, int symbolIndex, SyntaxTree tree, CancellationToken cancellationToken) { var spans = GetSpansInDocument(member, tree, cancellationToken); return new NavigationBarSymbolItem( member.ToDisplayString(s_memberFormat), member.GetGlyph(), spans, member.GetSymbolKey(), symbolIndex, grayed: spans.Count == 0); } private IList<TextSpan> GetSpansInDocument(ISymbol symbol, SyntaxTree tree, CancellationToken cancellationToken) { var spans = new List<TextSpan>(); if (!cancellationToken.IsCancellationRequested) { if (symbol.Kind == SymbolKind.Field) { if (symbol.ContainingType.TypeKind == TypeKind.Enum) { AddEnumMemberSpan(symbol, tree, spans); } else { AddFieldSpan(symbol, tree, spans); } } else { foreach (var reference in symbol.DeclaringSyntaxReferences) { if (reference.SyntaxTree.Equals(tree)) { var span = reference.Span; spans.Add(span); } } } } return spans; } /// <summary> /// Computes a span for a given field symbol, expanding to the outer /// </summary> private static void AddFieldSpan(ISymbol symbol, SyntaxTree tree, List<TextSpan> spans) { var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault(r => r.SyntaxTree == tree); if (reference == null) { return; } var declaringNode = reference.GetSyntax(); int spanStart = declaringNode.SpanStart; int spanEnd = declaringNode.Span.End; var fieldDeclaration = declaringNode.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null) { var variables = fieldDeclaration.Declaration.Variables; if (variables.FirstOrDefault() == declaringNode) { spanStart = fieldDeclaration.SpanStart; } if (variables.LastOrDefault() == declaringNode) { spanEnd = fieldDeclaration.Span.End; } } spans.Add(TextSpan.FromBounds(spanStart, spanEnd)); } private static void AddEnumMemberSpan(ISymbol symbol, SyntaxTree tree, List<TextSpan> spans) { // Ideally we want the span of this to include the trailing comma, so let's find // the declaration var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault(r => r.SyntaxTree == tree); if (reference == null) { return; } var declaringNode = reference.GetSyntax(); var enumMember = declaringNode as EnumMemberDeclarationSyntax; if (enumMember != null) { var enumDeclaration = enumMember.GetAncestor<EnumDeclarationSyntax>(); if (enumDeclaration != null) { var index = enumDeclaration.Members.IndexOf(enumMember); if (index != -1 && index < enumDeclaration.Members.SeparatorCount) { // Cool, we have a comma, so do it var start = enumMember.SpanStart; var end = enumDeclaration.Members.GetSeparator(index).Span.End; spans.Add(TextSpan.FromBounds(start, end)); return; } } } spans.Add(declaringNode.Span); } protected internal override VirtualTreePoint? GetSymbolItemNavigationPoint(Document document, NavigationBarSymbolItem item, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var symbols = item.NavigationSymbolId.Resolve(compilation, cancellationToken: cancellationToken); var symbol = symbols.Symbol; if (symbol == null) { if (item.NavigationSymbolIndex < symbols.CandidateSymbols.Length) { symbol = symbols.CandidateSymbols[item.NavigationSymbolIndex.Value]; } else { return null; } } var location = symbol.Locations.FirstOrDefault(l => l.SourceTree.Equals(document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken))); if (location == null) { location = symbol.Locations.FirstOrDefault(); } if (location == null) { return null; } return new VirtualTreePoint(location.SourceTree, location.SourceTree.GetText(cancellationToken), location.SourceSpan.Start); } [Conditional("DEBUG")] private static void ValidateSpanFromBounds(ITextSnapshot snapshot, int start, int end) { Contract.Requires(start >= 0 && end <= snapshot.Length && start <= end); } [Conditional("DEBUG")] private static void ValidateSpan(ITextSnapshot snapshot, int start, int length) { ValidateSpanFromBounds(snapshot, start, start + length); } public override void NavigateToItem(Document document, NavigationBarItem item, ITextView textView, CancellationToken cancellationToken) { NavigateToSymbolItem(document, (NavigationBarSymbolItem)item, cancellationToken); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System.Text; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")] public class GroupsModule : ISharedRegionModule, IGroupsModule { /// <summary> /// ; To use this module, you must specify the following in your OpenSim.ini /// [GROUPS] /// Enabled = true /// /// Module = GroupsModule /// NoticesEnabled = true /// DebugEnabled = true /// /// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector /// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php /// XmlRpcServiceReadKey = 1234 /// XmlRpcServiceWriteKey = 1234 /// /// MessagingModule = GroupsMessagingModule /// MessagingEnabled = true /// /// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for /// ; a problem discovered on some Windows based region servers. Only disable /// ; if you see a large number (dozens) of the following Exceptions: /// ; System.Net.WebException: The request was aborted: The request was canceled. /// /// XmlRpcDisableKeepAlive = false /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule; private IGroupsMessagingModule m_groupsMessagingModule; private IGroupsServicesConnector m_groupData; // Configuration settings private bool m_groupsEnabled = false; private bool m_groupNoticesEnabled = true; private bool m_debugEnabled = false; private int m_levelGroupCreate = 0; #region Region Module interfaceBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false); if (!m_groupsEnabled) { return; } if (groupsConfig.GetString("Module", "Default") != Name) { m_groupsEnabled = false; return; } m_log.InfoFormat("[GROUPS]: Initializing {0}", this.Name); m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false); m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0); } } public void AddRegion(Scene scene) { if (m_groupsEnabled) { scene.RegisterModuleInterface<IGroupsModule>(this); scene.AddCommand( "Debug", this, "debug groups verbose", "debug groups verbose <true|false>", "This setting turns on very verbose groups debugging", HandleDebugGroupsVerbose); } } private void HandleDebugGroupsVerbose(object modules, string[] args) { if (args.Length < 4) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } bool verbose = false; if (!bool.TryParse(args[3], out verbose)) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } m_debugEnabled = verbose; MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled); } public void RegionLoaded(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData == null) { m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No Groups Service Connector, then nothing works... if (m_groupData == null) { m_groupsEnabled = false; m_log.Error("[GROUPS]: Could not get IGroupsServicesConnector"); Close(); return; } } if (m_msgTransferModule == null) { m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_msgTransferModule == null) { m_groupsEnabled = false; m_log.Warn("[GROUPS]: Could not get IMessageTransferModule"); } } if (m_groupsMessagingModule == null) { m_groupsMessagingModule = scene.RequestModuleInterface<IGroupsMessagingModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_groupsMessagingModule == null) m_log.Warn("[GROUPS]: Could not get IGroupsMessagingModule"); } lock (m_sceneList) { m_sceneList.Add(scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; // The InstantMessageModule itself doesn't do this, // so lets see if things explode if we don't do it // scene.EventManager.OnClientClosed += OnClientClosed; } public void RemoveRegion(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_sceneList) { m_sceneList.Remove(scene); } } public void Close() { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module."); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "GroupsModule"; } } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region EventHandlers private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); client.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnRequestAvatarProperties += OnRequestAvatarProperties; // Used for Notices and Group Invites/Accept/Reject client.OnInstantMessage += OnInstantMessage; // Send client their groups information. SendAgentGroupDataUpdate(client, client.AgentId); } private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); //GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray(); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } /* * This becomes very problematic in a shared module. In a shared module you may have more then one * reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections. * The OnClientClosed event does not provide anything to indicate which one of those should be closed * nor does it provide what scene it was from so that the specific reference can be looked up. * The InstantMessageModule.cs does not currently worry about unregistering the handles, * and it should be an issue, since it's the client that references us not the other way around * , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed private void OnClientClosed(UUID AgentId) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; client.OnInstantMessage -= OnInstantMessage; m_ActiveClients.Remove(AgentId); } else { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here."); } } } */ private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID = UUID.Zero; string activeGroupTitle = string.Empty; string activeGroupName = string.Empty; ulong activeGroupPowers = (ulong)GroupPowers.None; GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient), dataForAgentID); if (membership != null) { activeGroupID = membership.GroupID; activeGroupTitle = membership.GroupTitle; activeGroupPowers = membership.GroupPowers; } SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle); SendScenePresenceUpdate(dataForAgentID, activeGroupTitle); } private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null); if (group != null) { GroupName = group.GroupName; } else { GroupName = "Unknown"; } remoteClient.SendGroupNameReply(GroupID, GroupName); } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called for {1}, message type {2}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name, (InstantMessageDialog)im.dialog); // Group invitations if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) { UUID inviteID = new UUID(im.imSessionID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); if (inviteInfo == null) { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Received an Invite IM for an invite that does not exist {0}.", inviteID); return; } if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID); UUID fromAgentID = new UUID(im.fromAgentID); if ((inviteInfo != null) && (fromAgentID == inviteInfo.AgentID)) { // Accept if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice."); // and the sessionid is the role m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = UUID.Zero.Guid; msg.toAgentID = inviteInfo.AgentID.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Groups"; msg.message = string.Format("You have been added to the group."); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, inviteInfo.AgentID); UpdateAllClientsWithGroupInfo(inviteInfo.AgentID); // TODO: If the inviter is still online, they need an agent dataupdate // and maybe group membership updates for the invitee m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } // Reject if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } } } // Group notices if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) { if (!m_groupNoticesEnabled) { return; } UUID GroupID = new UUID(im.toAgentID); if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null) != null) { UUID NoticeID = UUID.Random(); string Subject = im.message.Substring(0, im.message.IndexOf('|')); string Message = im.message.Substring(Subject.Length + 1); InventoryItemBase item = null; bool hasAttachment = false; UUID itemID = UUID.Zero; //Assignment to quiet compiler UUID ownerID = UUID.Zero; //Assignment to quiet compiler byte[] bucket; if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0) { string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket); binBucket = binBucket.Remove(0, 14).Trim(); OSDMap binBucketOSD = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket); if (binBucketOSD is OSD) { OSDMap binBucketMap = (OSDMap)binBucketOSD; itemID = binBucketMap["item_id"].AsUUID(); ownerID = binBucketMap["owner_id"].AsUUID(); //Attempt to get the details of the attached item. //If sender doesn't own the attachment, the item //variable will be set to null and attachment will //not be included with the group notice. Scene scene = (Scene)remoteClient.Scene; item = new InventoryItemBase(itemID, ownerID); item = scene.InventoryService.GetItem(item); if (item != null) { //Got item details so include the attachment. hasAttachment = true; } } else { m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType()); } } if (hasAttachment) { //Bucket contains information about attachment. // //Byte offset and description of bucket data: //0: 1 byte indicating if attachment is present //1: 1 byte indicating the type of attachment //2: 16 bytes - Group UUID //18: 16 bytes - UUID of the attachment owner //34: 16 bytes - UUID of the attachment //50: variable - Name of the attachment //??: NUL byte to terminate the attachment name byte[] name = Encoding.UTF8.GetBytes(item.Name); bucket = new byte[51 + name.Length];//3 bytes, 3 UUIDs, and name bucket[0] = 1; //Has attachment flag bucket[1] = (byte)item.InvType; //Type of Attachment GroupID.ToBytes(bucket, 2); ownerID.ToBytes(bucket, 18); itemID.ToBytes(bucket, 34); name.CopyTo(bucket, 50); } else { bucket = new byte[19]; bucket[0] = 0; //Has attachment flag bucket[1] = 0; //Type of attachment GroupID.ToBytes(bucket, 2); bucket[18] = 0; //NUL terminate name of attachment } m_groupData.AddGroupNotice(GetRequestingAgentID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket); if (OnNewGroupNotice != null) { OnNewGroupNotice(GroupID, NoticeID); } if (m_debugEnabled) { foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), GroupID)) { if (m_debugEnabled) { UserAccount targetUser = m_sceneList[0].UserAccountService.GetUserAccount( remoteClient.Scene.RegionInfo.ScopeID, member.AgentID); if (targetUser != null) { m_log.DebugFormat( "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices); } else { m_log.DebugFormat( "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, member.AgentID, member.AcceptNotices); } } } } GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); if (m_groupsMessagingModule != null) m_groupsMessagingModule.SendMessageToGroup( msg, GroupID, remoteClient.AgentId, gmd => gmd.AcceptNotices); } } if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted) { //Is bucket large enough to hold UUID of the attachment? if (im.binaryBucket.Length < 16) return; UUID noticeID = new UUID(im.imSessionID); if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Requesting notice {0} for {1}", noticeID, remoteClient.AgentId); GroupNoticeInfo notice = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), noticeID); if (notice != null) { UUID giver = new UUID(notice.BinaryBucket, 18); UUID attachmentUUID = new UUID(notice.BinaryBucket, 34); if (m_debugEnabled) m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId); string message; InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId, giver, attachmentUUID, out message); if (itemCopy == null) { remoteClient.SendAgentAlertMessage(message, false); return; } remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0); } else { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.", noticeID, remoteClient.AgentId); } } // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue if ((im.dialog == 210)) { // This is sent from the region that the ejectee was ejected from // if it's being delivered here, then the ejectee is here // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); IClientAPI ejectee = GetActiveClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.imSessionID); ejectee.SendAgentDropGroup(groupID); } } } private void OnGridInstantMessage(GridInstantMessage msg) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); // If a message from a group arrives here, it may need to be forwarded to a local client if (msg.fromGroup == true) { switch (msg.dialog) { case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); IClientAPI localClient = GetActiveClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); } break; } } } #endregion #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public GroupRecord GetGroupRecord(UUID GroupID) { return m_groupData.GetGroupRecord(UUID.Zero, GroupID, null); } public GroupRecord GetGroupRecord(string name) { return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name); } public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); // Changing active group changes title, active powers, all kinds of things // anyone who is in any region that can see this client, should probably be // updated with new group info. At a minimum, they should get ScenePresence // updated with new title. UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); } /// <summary> /// Get the Role Titles for an Agent, for a specific group /// </summary> public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData(); title.Name = role.Name; if (agentMembership != null) { title.Selected = agentMembership.ActiveRole == role.RoleID; } title.UUID = role.RoleID; titles.Add(title); } return titles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name); List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupMembersData member in data) { m_log.DebugFormat("[GROUPS]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner); } } return data; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID); return data; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupRoleMembersData member in data) { m_log.DebugFormat("[GROUPS]: Member({0}) - Role({1})", member.MemberID, member.RoleID); } } return data; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = groupID; profile.GroupMembershipCount = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID).Count; profile.GroupRolesCount = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID).Count; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; // TODO: Get this from the currency server? profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } return profile; } public GroupMembershipData[] GetMembershipData(UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMemberships(UUID.Zero, agentID).ToArray(); } public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called with groupID={1}, agentID={2}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID); return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID); } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Note: Permissions checking for modification rights is handled by the Groups Server/Service m_groupData.UpdateGroup(GetRequestingAgentID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish); } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // Note: Permissions checking for modification rights is handled by the Groups Server/Service if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentGroupInfo(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, acceptNotices, listInProfile); } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name) != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } // check user level ScenePresence avatar = null; Scene scene = (Scene)remoteClient.Scene; scene.TryGetScenePresence(remoteClient.AgentId, out avatar); if (avatar != null) { if (avatar.UserLevel < m_levelGroupCreate) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got insufficient permissions to create a group."); return UUID.Zero; } } // check funds // is there is a money module present ? IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>(); if (money != null) { // do the transaction, that is if the agent has got sufficient funds if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have got insufficient funds to create a group."); return UUID.Zero; } money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, MoneyTransactionType.GroupCreate); } UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient)); remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly"); // Update the founder with new group information. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); return groupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // ToDo: check if agent is a member of group and is allowed to see notices? return m_groupData.GetGroupNotices(GetRequestingAgentID(remoteClient), groupID).ToArray(); } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero, avatarID); if (membership != null) { return membership.GroupTitle; } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroupRole(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, titleRoleID); // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID) UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient)); } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Security Checks are handled in the Groups Service. switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: m_groupData.AddGroupRole(GetRequestingAgentID(remoteClient), groupID, UUID.Random(), name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.Delete: m_groupData.RemoveGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID); break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (m_debugEnabled) { GroupPowers gp = (GroupPowers)powers; m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); } m_groupData.UpdateGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID, name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check switch (changes) { case 0: // Add m_groupData.AddAgentToGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); break; case 1: // Remove m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); break; default: m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupNoticeInfo data = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), groupNoticeID); if (data != null) { GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested); OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient)); } } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GridInstantMessage msg = new GridInstantMessage(); byte[] bucket; msg.imSessionID = groupNoticeID.Guid; msg.toAgentID = agentID.Guid; msg.dialog = dialog; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID, groupNoticeID); if (info != null) { msg.fromAgentID = info.GroupID.Guid; msg.timestamp = info.noticeData.Timestamp; msg.fromAgentName = info.noticeData.FromName; msg.message = info.noticeData.Subject + "|" + info.Message; if (info.BinaryBucket[0] > 0) { //32 is due to not needing space for two of the UUIDs. //(Don't need UUID of attachment or its owner in IM) //50 offset gets us to start of attachment name. //We are skipping the attachment flag, type, and //the three UUID fields at the start of the bucket. bucket = new byte[info.BinaryBucket.Length-32]; bucket[0] = 1; //Has attachment bucket[1] = info.BinaryBucket[1]; Array.Copy(info.BinaryBucket, 50, bucket, 18, info.BinaryBucket.Length-50); } else { bucket = new byte[19]; bucket[0] = 0; //No attachment bucket[1] = 0; //Attachment type bucket[18] = 0; //NUL terminate name } info.GroupID.ToBytes(bucket, 2); msg.binaryBucket = bucket; } else { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Group Notice {0} not found, composing empty message.", groupNoticeID); msg.fromAgentID = UUID.Zero.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = string.Empty; msg.message = string.Empty; msg.binaryBucket = new byte[0]; } return msg; } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Send agent information about his groups SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Should check to see if OpenEnrollment, or if there's an outstanding invitation m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero); remoteClient.SendJoinGroupReply(groupID, true); // Should this send updates to everyone in the group? SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); remoteClient.SendLeaveGroupReply(groupID, true); remoteClient.SendAgentDropGroup(groupID); // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient)); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) { EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID); } public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check? m_groupData.RemoveAgentFromGroup(agentID, ejecteeID, groupID); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; remoteClient.SendEjectGroupMemberReply(agentID, groupID, true); } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; client.SendEjectGroupMemberReply(agentID, groupID, true); } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (acc != null) { agentName = acc.FirstName + " " + acc.LastName; } else { agentName = "Unknown member"; } } } GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null); UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); if ((groupInfo == null) || (account == null)) { return; } // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, ejecteeID); // Message to ejector // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; msg.toAgentID = agentID.Guid; msg.timestamp = 0; msg.fromAgentName = agentName; if (account != null) { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, account.FirstName + " " + account.LastName); } else { msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, "Unknown member"); } msg.dialog = (byte)210; //interop msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, agentID); // SL sends out messages to everyone in the group // Who all should receive updates and what should they be updated with? UpdateAllClientsWithGroupInfo(ejecteeID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) { InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID); } public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (account != null) { agentName = account.FirstName + " " + account.LastName; } else { agentName = "Unknown member"; } } } // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); m_groupData.AddAgentToGroupInvite(agentID, InviteID, groupID, roleID, invitedAgentID); // Check to see if the invite went through, if it did not then it's possible // the remoteClient did not validate or did not have permission to invite. GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(agentID, InviteID); if (inviteInfo != null) { if (m_msgTransferModule != null) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = agentID.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("{0} has invited you to join a group. There is no cost to join this group.", agentName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[20]; OutgoingInstantMessage(msg, invitedAgentID); } } } public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query) { return m_groupData.FindGroups(GetRequestingAgentID(remoteClient), query); } #endregion #region Client/Update Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null) { if (!sp.IsChildAgent) { return sp.ControllingClient; } else { child = sp.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } /// <summary> /// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'. /// </summary> private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDArray AgentData = new OSDArray(1); OSDMap AgentDataMap = new OSDMap(1); AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID)); AgentData.Add(AgentDataMap); OSDArray GroupData = new OSDArray(data.Length); OSDArray NewGroupData = new OSDArray(data.Length); foreach (GroupMembershipData membership in data) { if (GetRequestingAgentID(remoteClient) != dataForAgentID) { if (!membership.ListInProfile) { // If we're sending group info to remoteclient about another agent, // filter out groups the other agent doesn't want to share. continue; } } OSDMap GroupDataMap = new OSDMap(6); OSDMap NewGroupDataMap = new OSDMap(1); GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID)); GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers)); GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices)); GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture)); GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution)); GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName)); NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile)); GroupData.Add(GroupDataMap); NewGroupData.Add(NewGroupDataMap); } OSDMap llDataStruct = new OSDMap(3); llDataStruct.Add("AgentData", AgentData); llDataStruct.Add("GroupData", GroupData); llDataStruct.Add("NewGroupData", NewGroupData); if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: {0}", OSDParser.SerializeJsonString(llDataStruct)); } IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(queue.BuildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient)); } } private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title); ScenePresence presence = null; foreach (Scene scene in m_sceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { if (presence.Grouptitle != Title) { presence.Grouptitle = Title; if (! presence.IsChildAgent) presence.SendAvatarDataToAllAgents(); } } } } /// <summary> /// Send updates to all clients who might be interested in groups data for dataForClientID /// </summary> private void UpdateAllClientsWithGroupInfo(UUID dataForClientID) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Probably isn't nessesary to update every client in every scene. // Need to examine client updates and do only what's nessesary. lock (m_sceneList) { foreach (Scene scene in m_sceneList) { scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); }); } } } /// <summary> /// Update remoteClient with group information about dataForAgentID /// </summary> private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero); // Need to send a group membership update to the client // UDP version doesn't seem to behave nicely. But we're going to send it out here // with an empty group membership to hopefully remove groups being displayed due // to the core Groups Stub remoteClient.SendGroupMembership(new GroupMembershipData[0]); GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID); SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray); remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray); if (remoteClient.AgentId == dataForAgentID) remoteClient.RefreshGroupMembership(); } /// <summary> /// Get a list of groups memberships for the agent that are marked "ListInProfile" /// (unless that agent has a godLike aspect, in which case get all groups) /// </summary> /// <param name="dataForAgentID"></param> /// <returns></returns> private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) { List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId, dataForAgentID); GroupMembershipData[] membershipArray; // cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for // those with a GodLike aspect. Scene cScene = (Scene)requestingClient.Scene; bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId); if (isGod) { membershipArray = membershipData.ToArray(); } else { if (requestingClient.AgentId != dataForAgentID) { Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership) { return membership.ListInProfile; }; membershipArray = membershipData.FindAll(showInProfile).ToArray(); } else { membershipArray = membershipData.ToArray(); } } if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); foreach (GroupMembershipData membership in membershipArray) { m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers); } } return membershipArray; } private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, dataForAgentID); string firstname, lastname; if (account != null) { firstname = account.FirstName; lastname = account.LastName; } else { firstname = "Unknown"; lastname = "Unknown"; } remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); } #endregion #region IM Backed Processes private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI localClient = GetActiveClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name); localClient.SendInstantMessage(msg); } else if (m_msgTransferModule != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Message Sent: {0}", success?"Succeeded":"Failed"); }); } } public void NotifyChange(UUID groupID) { // Notify all group members of a chnge in group roles and/or // permissions // } #endregion private UUID GetRequestingAgentID(IClientAPI client) { UUID requestingAgentID = UUID.Zero; if (client != null) { requestingAgentID = client.AgentId; } return requestingAgentID; } } public class GroupNoticeInfo { public GroupNoticeData noticeData = new GroupNoticeData(); public UUID GroupID = UUID.Zero; public string Message = string.Empty; public byte[] BinaryBucket = new byte[0]; } }
namespace System.ServiceModel.Activities.Diagnostics { using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.PerformanceData; using System.Runtime; using System.Security; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Administration; using System.ServiceModel.Diagnostics; sealed class WorkflowServiceHostPerformanceCounters : PerformanceCountersBase { static object syncRoot = new object(); static Guid workflowServiceHostProviderId = new Guid("{f6c5ad57-a5be-4259-9060-b2c4ebfccd96}"); static Guid workflowServiceHostCounterSetId = new Guid("{1f7207c2-0b8c-48de-9dcd-64ff98cc24e1}"); // Double-checked locking pattern requires volatile for read/write synchronization static volatile CounterSet workflowServiceHostCounterSet; // Defines the counter set // The strings defined here are not used in the counter set and defined only to implement CounterNames property. // CounterNames is not used currently and hence these strings need not be localized. // The Counter Names and description are defined in the manifest which will be localized and installed by the setup. static readonly string[] perfCounterNames = { "Workflows Created", "Workflows Created Per Second", "Workflows Executing", "Workflows Completed", "Workflows Completed Per Second", "Workflows Aborted", "Workflows Aborted Per Second", "Workflows In Memory", "Workflows Persisted", "Workflows Persisted Per Second", "Workflows Terminated", "Workflows Terminated Per Second", "Workflows Loaded", "Workflows Loaded Per Second", "Workflows Unloaded", "Workflows Unloaded Per Second", "Workflows Suspended", "Workflows Suspended Per Second", "Workflows Idle Per Second", "Average Workflow Load Time", "Average Workflow Load Time Base", "Average Workflow Persist Time", "Average Workflow Persist Time Base", }; WorkflowServiceHost serviceHost; const int maxCounterLength = 64; const int hashLength = 2; CounterSetInstance workflowServiceHostCounterSetInstance; // Instance of the counter set bool initialized; CounterData[] counters; string instanceName; bool isPerformanceCounterEnabled; internal override string InstanceName { get { return this.instanceName; } } internal override string[] CounterNames { get { return perfCounterNames; } } internal override int PerfCounterStart { get { return (int)PerfCounters.WorkflowsCreated; } } internal override int PerfCounterEnd { get { return (int)PerfCounters.TotalCounters; } } internal bool PerformanceCountersEnabled { get { return this.isPerformanceCounterEnabled; } } internal override bool Initialized { get { return this.initialized; } } internal WorkflowServiceHostPerformanceCounters(WorkflowServiceHost serviceHost) { this.serviceHost = serviceHost; } internal static void EnsureCounterSet() { if (workflowServiceHostCounterSet == null) { lock (syncRoot) { if (workflowServiceHostCounterSet == null) { CounterSet localCounterSet = CreateCounterSet(); // Add the counters to the counter set definition. localCounterSet.AddCounter((int)PerfCounters.WorkflowsCreated, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsCreatedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsExecuting, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsCompleted, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsCompletedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsAborted, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsAbortedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsInMemory, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsPersisted, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsPersistedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsTerminated, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsTerminatedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsLoaded, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsLoadedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsUnloaded, CounterType.RawData32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsUnloadedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsSuspended, CounterType.RawData32, perfCounterNames[(int)PerfCounters.WorkflowsSuspended]); localCounterSet.AddCounter((int)PerfCounters.WorkflowsSuspendedPerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.WorkflowsIdlePerSecond, CounterType.RateOfCountPerSecond32); localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowLoadTime, CounterType.AverageTimer32); localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowLoadTimeBase, CounterType.AverageBase); localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowPersistTime, CounterType.AverageTimer32); localCounterSet.AddCounter((int)PerfCounters.AverageWorkflowPersistTimeBase, CounterType.AverageBase); workflowServiceHostCounterSet = localCounterSet; } } } } static internal string CreateFriendlyInstanceName(ServiceHostBase serviceHost) { // instance name is: serviceName@uri ServiceInfo serviceInfo = new ServiceInfo(serviceHost); string serviceName = serviceInfo.ServiceName; string uri; if (!TryGetFullVirtualPath(serviceHost, out uri)) { uri = serviceInfo.FirstAddress; } int length = serviceName.Length + uri.Length + 2; if (length > maxCounterLength) { int count = 0; InstanceNameTruncOptions tasks = GetCompressionTasks( length, serviceName.Length, uri.Length); //if necessary, compress service name to 8 chars with a 2 char hash code if ((tasks & InstanceNameTruncOptions.Service32) > 0) { count = 32; serviceName = GetHashedString(serviceName, count - hashLength, serviceName.Length - count + hashLength, true); } //if necessary, compress uri to 36 chars with a 2 char hash code if ((tasks & InstanceNameTruncOptions.Uri31) > 0) { count = 31; uri = GetHashedString(uri, 0, uri.Length - count + hashLength, false); } } // replace '/' with '|' because perfmon fails when '/' is in perfcounter instance name return serviceName + "@" + uri.Replace('/', '|'); } static bool TryGetFullVirtualPath(ServiceHostBase serviceHost, out string uri) { VirtualPathExtension pathExtension = serviceHost.Extensions.Find<VirtualPathExtension>(); if (pathExtension == null) { uri = null; return false; } uri = pathExtension.ApplicationVirtualPath + pathExtension.VirtualPath.ToString().Replace("~", ""); return uri != null; } static InstanceNameTruncOptions GetCompressionTasks(int totalLen, int serviceLen, int uriLen) { InstanceNameTruncOptions bitmask = 0; if (totalLen > maxCounterLength) { int workingLen = totalLen; //note: order of if statements important (see spec)! if (workingLen > maxCounterLength && serviceLen > 32) { bitmask |= InstanceNameTruncOptions.Service32; //compress service name to 16 chars workingLen -= serviceLen - 32; } if (workingLen > maxCounterLength && uriLen > 31) { bitmask |= InstanceNameTruncOptions.Uri31; //compress uri to 31 chars } } return bitmask; } [Fx.Tag.SecurityNote(Critical = "Calls into Sys.Diag.PerformanceData.CounterSet..ctor marked as SecurityCritical", Safe = "We only make the call if PartialTrustHelper.AppDomainFullyTrusted is true.")] [SecuritySafeCritical] static CounterSet CreateCounterSet() { if (PartialTrustHelpers.AppDomainFullyTrusted) { return new CounterSet(workflowServiceHostProviderId, workflowServiceHostCounterSetId, CounterSetInstanceType.Multiple); } else return null; } [Fx.Tag.SecurityNote(Critical = "Calls into Sys.Diag.PerformanceData.CounterSetInstance.CreateCounterSetInstance marked as SecurityCritical", Safe = "We only make the call if PartialTrustHelper.AppDomainFullyTrusted is true.")] [SecuritySafeCritical] static CounterSetInstance CreateCounterSetInstance(string name) { CounterSetInstance workflowServiceHostCounterSetInstance = null; if (PartialTrustHelpers.AppDomainFullyTrusted) { try { workflowServiceHostCounterSetInstance = workflowServiceHostCounterSet.CreateCounterSetInstance(name); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } // A conflicting instance name already exists and probably the unmanaged resource is not yet disposed. FxTrace.Exception.AsWarning(exception); workflowServiceHostCounterSetInstance = null; } } return workflowServiceHostCounterSetInstance; } internal void InitializePerformanceCounters() { this.instanceName = CreateFriendlyInstanceName(this.serviceHost); if (PerformanceCounters.PerformanceCountersEnabled) { EnsureCounterSet(); // Create an instance of the counter set (contains the counter data). this.workflowServiceHostCounterSetInstance = CreateCounterSetInstance(this.InstanceName); if (this.workflowServiceHostCounterSetInstance != null) { this.counters = new CounterData[(int)PerfCounters.TotalCounters]; for (int i = 0; i < (int)PerfCounters.TotalCounters; i++) { this.counters[i] = this.workflowServiceHostCounterSetInstance.Counters[i]; this.counters[i].Value = 0; } // Enable perf counter only if CounterSetInstance is created without instance name conflict. this.isPerformanceCounterEnabled = PerformanceCounters.PerformanceCountersEnabled; } } this.initialized = true; } protected override void Dispose(bool disposing) { try { if (disposing && this.workflowServiceHostCounterSetInstance != null) { this.workflowServiceHostCounterSetInstance.Dispose(); this.workflowServiceHostCounterSetInstance = null; this.isPerformanceCounterEnabled = false; } } finally { base.Dispose(disposing); } } internal void WorkflowCreated() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsCreated].Increment(); this.counters[(int)PerfCounters.WorkflowsCreatedPerSecond].Increment(); } } internal void WorkflowExecuting(bool increment) { if (PerformanceCountersEnabled) { if (increment) { this.counters[(int)PerfCounters.WorkflowsExecuting].Increment(); } else { this.counters[(int)PerfCounters.WorkflowsExecuting].Decrement(); } } } internal void WorkflowCompleted() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsCompleted].Increment(); this.counters[(int)PerfCounters.WorkflowsCompletedPerSecond].Increment(); } } internal void WorkflowAborted() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsAborted].Increment(); this.counters[(int)PerfCounters.WorkflowsAbortedPerSecond].Increment(); } } internal void WorkflowInMemory() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsInMemory].Increment(); } } internal void WorkflowOutOfMemory() { if (PerformanceCountersEnabled) { if (this.counters[(int)PerfCounters.WorkflowsInMemory].RawValue > 0 ) this.counters[(int)PerfCounters.WorkflowsInMemory].Decrement(); } } internal void WorkflowPersisted() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsPersisted].Increment(); this.counters[(int)PerfCounters.WorkflowsPersistedPerSecond].Increment(); } } internal void WorkflowTerminated() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsTerminated].Increment(); this.counters[(int)PerfCounters.WorkflowsTerminatedPerSecond].Increment(); } } internal void WorkflowLoaded() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsLoaded].Increment(); this.counters[(int)PerfCounters.WorkflowsLoadedPerSecond].Increment(); } } internal void WorkflowUnloaded() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsUnloaded].Increment(); this.counters[(int)PerfCounters.WorkflowsUnloadedPerSecond].Increment(); } } internal void WorkflowSuspended() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsSuspended].Increment(); this.counters[(int)PerfCounters.WorkflowsSuspendedPerSecond].Increment(); } } internal void WorkflowIdle() { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.WorkflowsIdlePerSecond].Increment(); } } internal void WorkflowLoadDuration(long time) { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.AverageWorkflowLoadTime].IncrementBy(time); this.counters[(int)PerfCounters.AverageWorkflowLoadTimeBase].Increment(); } } internal void WorkflowPersistDuration(long time) { if (PerformanceCountersEnabled) { this.counters[(int)PerfCounters.AverageWorkflowPersistTime].IncrementBy(time); this.counters[(int)PerfCounters.AverageWorkflowPersistTimeBase].Increment(); } } internal enum PerfCounters : int { WorkflowsCreated = 0, WorkflowsCreatedPerSecond, WorkflowsExecuting, WorkflowsCompleted, WorkflowsCompletedPerSecond, WorkflowsAborted, WorkflowsAbortedPerSecond, WorkflowsInMemory, WorkflowsPersisted, WorkflowsPersistedPerSecond, WorkflowsTerminated, WorkflowsTerminatedPerSecond, WorkflowsLoaded, WorkflowsLoadedPerSecond, WorkflowsUnloaded, WorkflowsUnloadedPerSecond, WorkflowsSuspended, WorkflowsSuspendedPerSecond, WorkflowsIdlePerSecond, AverageWorkflowLoadTime, AverageWorkflowLoadTimeBase, AverageWorkflowPersistTime, AverageWorkflowPersistTimeBase, TotalCounters = AverageWorkflowPersistTimeBase + 1 } // Truncate options for the Instance name in ServiceName@uri format. [Flags] enum InstanceNameTruncOptions : uint { NoBits = 0, Service32 = 0x01, //compress service name to 16 chars Uri31 = 0x04 //compress uri to 31 chars } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using CSharpGuidelinesAnalyzer.Extensions; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace CSharpGuidelinesAnalyzer.Rules.Maintainability { [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class SwitchStatementShouldHaveDefaultCaseAnalyzer : DiagnosticAnalyzer { private const string Title = "Non-exhaustive switch statement requires a default case clause"; private const string MessageFormat = "Non-exhaustive switch statement requires a default case clause"; private const string Description = "Always add a default block after the last case in a switch statement."; public const string DiagnosticId = "AV1536"; [NotNull] private static readonly AnalyzerCategory Category = AnalyzerCategory.Maintainability; [NotNull] private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category.DisplayName, DiagnosticSeverity.Warning, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [NotNull] [ItemCanBeNull] private static readonly ISymbol[] NullSymbolArray = { null }; [NotNull] private static readonly Action<CompilationStartAnalysisContext> RegisterCompilationStartAction = RegisterCompilationStart; #pragma warning disable RS1008 // Avoid storing per-compilation data into the fields of a diagnostic analyzer. [NotNull] private static readonly Action<OperationAnalysisContext, INamedTypeSymbol> AnalyzeSwitchStatementAction = (context, systemBoolean) => context.SkipInvalid(_ => AnalyzeSwitchStatement(context, systemBoolean)); #pragma warning restore RS1008 // Avoid storing per-compilation data into the fields of a diagnostic analyzer. [ItemNotNull] public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize([NotNull] AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(RegisterCompilationStartAction); } private static void RegisterCompilationStart([NotNull] CompilationStartAnalysisContext startContext) { INamedTypeSymbol systemBoolean = KnownTypes.SystemBoolean(startContext.Compilation); if (systemBoolean != null) { startContext.RegisterOperationAction(context => AnalyzeSwitchStatementAction(context, systemBoolean), OperationKind.Switch); } } private static void AnalyzeSwitchStatement(OperationAnalysisContext context, [NotNull] INamedTypeSymbol systemBoolean) { var switchStatement = (ISwitchOperation)context.Operation; if (HasDefaultOrPatternCase(switchStatement)) { return; } context.CancellationToken.ThrowIfCancellationRequested(); AnalyzeSwitchExhaustiveness(switchStatement, systemBoolean, context); } private static void AnalyzeSwitchExhaustiveness([NotNull] ISwitchOperation switchStatement, [NotNull] INamedTypeSymbol systemBoolean, OperationAnalysisContext context) { var analysisContext = new SwitchAnalysisContext(switchStatement, systemBoolean, context); if (IsSwitchExhaustive(analysisContext) == false) { Location location = switchStatement.TryGetLocationForKeyword() ?? switchStatement.Syntax.GetLocation(); context.ReportDiagnostic(Diagnostic.Create(Rule, location)); } } private static bool HasDefaultOrPatternCase([NotNull] ISwitchOperation switchStatement) { return switchStatement.Cases.SelectMany(@case => @case.Clauses).Any(IsDefaultOrPatternCase); } private static bool IsDefaultOrPatternCase([NotNull] ICaseClauseOperation clause) { return clause.CaseKind == CaseKind.Default || clause.CaseKind == CaseKind.Pattern; } [CanBeNull] private static bool? IsSwitchExhaustive([NotNull] SwitchAnalysisContext analysisContext) { IdentifierInfo identifierInfo = analysisContext.SwitchStatement.Value.TryGetIdentifierInfo(); return identifierInfo != null ? IsSwitchExhaustive(analysisContext, identifierInfo) : null; } [CanBeNull] private static bool? IsSwitchExhaustive([NotNull] SwitchAnalysisContext analysisContext, [NotNull] IdentifierInfo identifierInfo) { return IsSwitchExhaustiveForBooleanTypes(identifierInfo, analysisContext) ?? IsSwitchExhaustiveForEnumerationTypes(identifierInfo, analysisContext); } [CanBeNull] private static bool? IsSwitchExhaustiveForBooleanTypes([NotNull] IdentifierInfo identifierInfo, [NotNull] SwitchAnalysisContext analysisContext) { bool isBoolean = identifierInfo.Type.SpecialType == SpecialType.System_Boolean; bool isNullableBoolean = identifierInfo.Type.IsNullableBoolean(); if (isBoolean || isNullableBoolean) { ImmutableArray<ISymbol> possibleValues = isBoolean ? ImmutableArray.Create(analysisContext.BooleanTrue, analysisContext.BooleanFalse) : ImmutableArray.Create(analysisContext.BooleanTrue, analysisContext.BooleanFalse, null); return HasCaseClausesFor(possibleValues, analysisContext); } return null; } [CanBeNull] private static bool? IsSwitchExhaustiveForEnumerationTypes([NotNull] IdentifierInfo identifierInfo, [NotNull] SwitchAnalysisContext analysisContext) { bool isEnumeration = identifierInfo.Type.BaseType is { SpecialType: SpecialType.System_Enum }; bool isNullableEnumeration = identifierInfo.Type.IsNullableEnumeration(); if (isEnumeration || isNullableEnumeration) { ITypeSymbol enumType = isEnumeration ? (INamedTypeSymbol)identifierInfo.Type : ((INamedTypeSymbol)identifierInfo.Type).TypeArguments[0]; ISymbol[] possibleValues = isEnumeration ? enumType.GetMembers().OfType<IFieldSymbol>().Cast<ISymbol>().ToArray() : enumType.GetMembers().OfType<IFieldSymbol>().Concat(NullSymbolArray).ToArray(); return HasCaseClausesFor(possibleValues, analysisContext); } return null; } [CanBeNull] private static bool? HasCaseClausesFor([NotNull] [ItemCanBeNull] ICollection<ISymbol> expectedValues, [NotNull] SwitchAnalysisContext analysisContext) { var collector = new CaseClauseCollector(); ICollection<ISymbol> caseClauseValues = collector.TryGetSymbolsForCaseClauses(analysisContext); return caseClauseValues == null ? null : HasCaseClauseForExpectedValues(expectedValues, caseClauseValues); } [CanBeNull] private static bool? HasCaseClauseForExpectedValues([NotNull] [ItemCanBeNull] ICollection<ISymbol> expectedValues, [NotNull] [ItemCanBeNull] ICollection<ISymbol> caseClauseValues) { foreach (ISymbol expectedValue in expectedValues) { if (!caseClauseValues.Contains(expectedValue)) { return false; } } return true; } private sealed class CaseClauseCollector { [NotNull] [ItemCanBeNull] private readonly HashSet<ISymbol> caseClauseValues = new HashSet<ISymbol>(); [CanBeNull] [ItemCanBeNull] public ICollection<ISymbol> TryGetSymbolsForCaseClauses([NotNull] SwitchAnalysisContext analysisContext) { IEnumerable<ISingleValueCaseClauseOperation> caseClauses = analysisContext.SwitchStatement.Cases.SelectMany(@case => @case.Clauses.OfType<ISingleValueCaseClauseOperation>()); foreach (ISingleValueCaseClauseOperation caseClause in caseClauses) { analysisContext.CancellationToken.ThrowIfCancellationRequested(); if (ProcessAsLiteralSyntax(analysisContext, caseClause) || ProcessAsField(caseClause) || ProcessAsConversion(analysisContext, caseClause)) { continue; } // Switch statements with non-constant case expressions are not supported // because they make exhaustiveness analysis non-trivial. #pragma warning disable AV1135 // Do not return null for strings, collections or tasks return null; #pragma warning restore AV1135 // Do not return null for strings, collections or tasks } return caseClauseValues; } private bool ProcessAsConversion([NotNull] SwitchAnalysisContext analysisContext, [NotNull] ISingleValueCaseClauseOperation caseClause) { var conversion = caseClause.Value as IConversionOperation; var memberSyntax = conversion?.Syntax as MemberAccessExpressionSyntax; IFieldSymbol field = analysisContext.GetFieldOrNull(memberSyntax); if (field != null) { caseClauseValues.Add(field); return true; } return false; } private bool ProcessAsLiteralSyntax([NotNull] SwitchAnalysisContext analysisContext, [NotNull] ISingleValueCaseClauseOperation caseClause) { if (caseClause.Value.Syntax is LiteralExpressionSyntax literalSyntax) { if (ProcessLiteralSyntaxAsTrueKeyword(analysisContext, literalSyntax) || ProcessLiteralSyntaxAsFalseKeyword(analysisContext, literalSyntax) || ProcessLiteralSyntaxAsNullKeyword(literalSyntax)) { return true; } } return false; } private bool ProcessLiteralSyntaxAsTrueKeyword([NotNull] SwitchAnalysisContext analysisContext, [NotNull] LiteralExpressionSyntax literalSyntax) { if (literalSyntax.Token.IsKind(SyntaxKind.TrueKeyword)) { caseClauseValues.Add(analysisContext.BooleanTrue); return true; } return false; } private bool ProcessLiteralSyntaxAsFalseKeyword([NotNull] SwitchAnalysisContext analysisContext, [NotNull] LiteralExpressionSyntax literalSyntax) { if (literalSyntax.Token.IsKind(SyntaxKind.FalseKeyword)) { caseClauseValues.Add(analysisContext.BooleanFalse); return true; } return false; } private bool ProcessLiteralSyntaxAsNullKeyword([NotNull] LiteralExpressionSyntax literalSyntax) { if (literalSyntax.Token.IsKind(SyntaxKind.NullKeyword)) { caseClauseValues.Add(null); return true; } return false; } private bool ProcessAsField([NotNull] ISingleValueCaseClauseOperation caseClause) { if (caseClause.Value is IFieldReferenceOperation enumField) { caseClauseValues.Add(enumField.Field); return true; } return false; } } private sealed class SwitchAnalysisContext { [NotNull] private readonly Compilation compilation; public CancellationToken CancellationToken { get; } [NotNull] public ISwitchOperation SwitchStatement { get; } [NotNull] public ISymbol BooleanTrue { get; } [NotNull] public ISymbol BooleanFalse { get; } public SwitchAnalysisContext([NotNull] ISwitchOperation switchStatement, [NotNull] INamedTypeSymbol systemBoolean, OperationAnalysisContext context) { Guard.NotNull(switchStatement, nameof(switchStatement)); Guard.NotNull(systemBoolean, nameof(systemBoolean)); SwitchStatement = switchStatement; compilation = context.Compilation; CancellationToken = context.CancellationToken; BooleanTrue = systemBoolean.GetMembers("TrueString").Single(); BooleanFalse = systemBoolean.GetMembers("FalseString").Single(); } [CanBeNull] public IFieldSymbol GetFieldOrNull([CanBeNull] MemberAccessExpressionSyntax memberSyntax) { if (memberSyntax != null) { SemanticModel model = compilation.GetSemanticModel(memberSyntax.SyntaxTree); return model.GetSymbolInfo(memberSyntax, CancellationToken).Symbol as IFieldSymbol; } return null; } } } }
/* * 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 OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Server.Handlers.Grid { public class GridServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 414 private static string LogHeader = "[GRID HANDLER]"; #pragma warning restore 414 private IGridService m_GridService; public GridServerPostHandler(IGridService service) : base("POST", "/grid") { m_GridService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "register": return Register(request); case "deregister": return Deregister(request); case "get_neighbours": return GetNeighbours(request); case "get_region_by_uuid": return GetRegionByUUID(request); case "get_region_by_position": return GetRegionByPosition(request); case "get_region_by_name": return GetRegionByName(request); case "get_regions_by_name": return GetRegionsByName(request); case "get_region_range": return GetRegionRange(request); case "get_default_regions": return GetDefaultRegions(request); case "get_default_hypergrid_regions": return GetDefaultHypergridRegions(request); case "get_fallback_regions": return GetFallbackRegions(request); case "get_hyperlinks": return GetHyperlinks(request); case "get_region_flags": return GetRegionFlags(request); } m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method); } catch (Exception e) { m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } return FailureResult(); } #region Method-specific handlers private byte[] Deregister(Dictionary<string, object> request) { UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to deregister region"); bool result = m_GridService.DeregisterRegion(regionID); if (result) return SuccessResult(); else return FailureResult(); } private byte[] GetDefaultHypergridRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); List<GridRegion> rinfos = m_GridService.GetDefaultHypergridRegions(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetDefaultRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); List<GridRegion> rinfos = m_GridService.GetDefaultRegions(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetFallbackRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get fallback regions"); int x = 0, y = 0; if (request.ContainsKey("X")) Int32.TryParse(request["X"].ToString(), out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get fallback regions"); if (request.ContainsKey("Y")) Int32.TryParse(request["Y"].ToString(), out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get fallback regions"); List<GridRegion> rinfos = m_GridService.GetFallbackRegions(scopeID, x, y); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetHyperlinks(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetHyperlinks"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get linked regions"); List<GridRegion> rinfos = m_GridService.GetHyperlinks(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetNeighbours(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); List<GridRegion> rinfos = m_GridService.GetNeighbours(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetRegionByName(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by name"); string regionName = string.Empty; if (request.ContainsKey("NAME")) regionName = request["NAME"].ToString(); else m_log.WarnFormat("[GRID HANDLER]: no name in request to get region by name"); GridRegion rinfo = m_GridService.GetRegionByName(scopeID, regionName); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetRegionByPosition(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by position"); int x = 0, y = 0; if (request.ContainsKey("X")) Int32.TryParse(request["X"].ToString(), out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get region by position"); if (request.ContainsKey("Y")) Int32.TryParse(request["Y"].ToString(), out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position"); // m_log.DebugFormat("{0} GetRegionByPosition: loc=<{1},{2}>", LogHeader, x, y); GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetRegionByUUID(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); GridRegion rinfo = m_GridService.GetRegionByUUID(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetRegionFlags(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); int flags = m_GridService.GetRegionFlags(scopeID, regionID); // m_log.DebugFormat("[GRID HANDLER]: flags for region {0}: {1}", regionID, flags); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = flags.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetRegionRange(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); int xmin = 0, xmax = 0, ymin = 0, ymax = 0; if (request.ContainsKey("XMIN")) Int32.TryParse(request["XMIN"].ToString(), out xmin); else m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range"); if (request.ContainsKey("XMAX")) Int32.TryParse(request["XMAX"].ToString(), out xmax); else m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range"); if (request.ContainsKey("YMIN")) Int32.TryParse(request["YMIN"].ToString(), out ymin); else m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range"); if (request.ContainsKey("YMAX")) Int32.TryParse(request["YMAX"].ToString(), out ymax); else m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range"); List<GridRegion> rinfos = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] GetRegionsByName(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get regions by name"); string regionName = string.Empty; if (request.ContainsKey("NAME")) regionName = request["NAME"].ToString(); else m_log.WarnFormat("[GRID HANDLER]: no NAME in request to get regions by name"); int max = 0; if (request.ContainsKey("MAX")) Int32.TryParse(request["MAX"].ToString(), out max); else m_log.WarnFormat("[GRID HANDLER]: no MAX in request to get regions by name"); List<GridRegion> rinfos = m_GridService.GetRegionsByName(scopeID, regionName, max); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private byte[] Register(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to register region"); int versionNumberMin = 0, versionNumberMax = 0; if (request.ContainsKey("VERSIONMIN")) Int32.TryParse(request["VERSIONMIN"].ToString(), out versionNumberMin); else m_log.WarnFormat("[GRID HANDLER]: no minimum protocol version in request to register region"); if (request.ContainsKey("VERSIONMAX")) Int32.TryParse(request["VERSIONMAX"].ToString(), out versionNumberMax); else m_log.WarnFormat("[GRID HANDLER]: no maximum protocol version in request to register region"); // Check the protocol version if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax && versionNumberMax < ProtocolVersions.ServerProtocolVersionMax)) { // Can't do, there is no overlap in the acceptable ranges return FailureResult(); } Dictionary<string, object> rinfoData = new Dictionary<string, object>(); GridRegion rinfo = null; try { foreach (KeyValuePair<string, object> kvp in request) rinfoData[kvp.Key] = kvp.Value.ToString(); rinfo = new GridRegion(rinfoData); } catch (Exception e) { m_log.DebugFormat("[GRID HANDLER]: exception unpacking region data: {0}", e); } string result = "Error communicating with grid service"; if (rinfo != null) result = m_GridService.RegisterRegion(scopeID, rinfo); if (result == String.Empty) return SuccessResult(); else return FailureResult(result); } #endregion Method-specific handlers #region Misc private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } private byte[] FailureResult() { return FailureResult(String.Empty); } private byte[] FailureResult(string msg) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Message", ""); message.AppendChild(doc.CreateTextNode(msg)); rootElement.AppendChild(message); return DocToBytes(doc); } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return DocToBytes(doc); } #endregion Misc } }
// Copyright 2018 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 Google.Api.Gax; using System; using System.Linq; namespace Google.Cloud.Spanner.V1 { /// <summary> /// Resource name for the 'database' resource. /// </summary> public sealed partial class DatabaseName : IResourceName, IEquatable<DatabaseName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/instances/{instance}/databases/{database}"); /// <summary> /// Parses the given database resource name in string form into a new /// <see cref="DatabaseName"/> instance. /// </summary> /// <param name="databaseName">The database resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DatabaseName"/> if successful.</returns> public static DatabaseName Parse(string databaseName) { GaxPreconditions.CheckNotNull(databaseName, nameof(databaseName)); TemplatedResourceName resourceName = s_template.ParseName(databaseName); return new DatabaseName(resourceName[0], resourceName[1], resourceName[2]); } /// <summary> /// Tries to parse the given database resource name in string form into a new /// <see cref="DatabaseName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="databaseName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="databaseName">The database resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="DatabaseName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string databaseName, out DatabaseName result) { GaxPreconditions.CheckNotNull(databaseName, nameof(databaseName)); TemplatedResourceName resourceName; if (s_template.TryParseName(databaseName, out resourceName)) { result = new DatabaseName(resourceName[0], resourceName[1], resourceName[2]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="DatabaseName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param> /// <param name="databaseId">The database ID. Must not be <c>null</c>.</param> public DatabaseName(string projectId, string instanceId, string databaseId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceId = GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId)); DatabaseId = GaxPreconditions.CheckNotNull(databaseId, nameof(databaseId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The instance ID. Never <c>null</c>. /// </summary> public string InstanceId { get; } /// <summary> /// The database ID. Never <c>null</c>. /// </summary> public string DatabaseId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, InstanceId, DatabaseId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as DatabaseName); /// <inheritdoc /> public bool Equals(DatabaseName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(DatabaseName a, DatabaseName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(DatabaseName a, DatabaseName b) => !(a == b); } /// <summary> /// Resource name for the 'session' resource. /// </summary> public sealed partial class SessionName : IResourceName, IEquatable<SessionName> { private static readonly PathTemplate s_template = new PathTemplate("projects/{project}/instances/{instance}/databases/{database}/sessions/{session}"); /// <summary> /// Parses the given session resource name in string form into a new /// <see cref="SessionName"/> instance. /// </summary> /// <param name="sessionName">The session resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SessionName"/> if successful.</returns> public static SessionName Parse(string sessionName) { GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName)); TemplatedResourceName resourceName = s_template.ParseName(sessionName); return new SessionName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); } /// <summary> /// Tries to parse the given session resource name in string form into a new /// <see cref="SessionName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="ArgumentNullException"/> if <paramref name="sessionName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="sessionName">The session resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="SessionName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionName, out SessionName result) { GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName)); TemplatedResourceName resourceName; if (s_template.TryParseName(sessionName, out resourceName)) { result = new SessionName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="SessionName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="instanceId">The instance ID. Must not be <c>null</c>.</param> /// <param name="databaseId">The database ID. Must not be <c>null</c>.</param> /// <param name="sessionId">The session ID. Must not be <c>null</c>.</param> public SessionName(string projectId, string instanceId, string databaseId, string sessionId) { ProjectId = GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); InstanceId = GaxPreconditions.CheckNotNull(instanceId, nameof(instanceId)); DatabaseId = GaxPreconditions.CheckNotNull(databaseId, nameof(databaseId)); SessionId = GaxPreconditions.CheckNotNull(sessionId, nameof(sessionId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The instance ID. Never <c>null</c>. /// </summary> public string InstanceId { get; } /// <summary> /// The database ID. Never <c>null</c>. /// </summary> public string DatabaseId { get; } /// <summary> /// The session ID. Never <c>null</c>. /// </summary> public string SessionId { get; } /// <inheritdoc /> public ResourceNameKind Kind => ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, InstanceId, DatabaseId, SessionId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as SessionName); /// <inheritdoc /> public bool Equals(SessionName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(SessionName a, SessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(SessionName a, SessionName b) => !(a == b); } public partial class BeginTransactionRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get { return string.IsNullOrEmpty(Session) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Session); } set { Session = value != null ? value.ToString() : ""; } } } public partial class CommitRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get { return string.IsNullOrEmpty(Session) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Session); } set { Session = value != null ? value.ToString() : ""; } } } public partial class CreateSessionRequest { /// <summary> /// <see cref="DatabaseName"/>-typed view over the <see cref="Database"/> resource name property. /// </summary> public DatabaseName DatabaseAsDatabaseName { get { return string.IsNullOrEmpty(Database) ? null : Google.Cloud.Spanner.V1.DatabaseName.Parse(Database); } set { Database = value != null ? value.ToString() : ""; } } } public partial class DeleteSessionRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public SessionName SessionName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ExecuteSqlRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get { return string.IsNullOrEmpty(Session) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Session); } set { Session = value != null ? value.ToString() : ""; } } } public partial class GetSessionRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public SessionName SessionName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ReadRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get { return string.IsNullOrEmpty(Session) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Session); } set { Session = value != null ? value.ToString() : ""; } } } public partial class RollbackRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public SessionName SessionAsSessionName { get { return string.IsNullOrEmpty(Session) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Session); } set { Session = value != null ? value.ToString() : ""; } } } public partial class Session { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public SessionName SessionName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Spanner.V1.SessionName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } }
// // MRControllable.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System; using System.Collections; using System.Collections.Generic; using AssemblyCSharp; namespace PortableRealm { public abstract class MRControllable : MRIControllable, MRISerializable, MRISpellTarget { #region Properties // How the controllable is moving. public abstract MRGame.eMoveType MoveType {get; set;} /// <summary> /// Returns the current attack strength of the controllable. /// </summary> /// <value>The current strength.</value> public abstract MRGame.eStrength CurrentStrength { get; } /// <summary> /// Returns the current attack speed of the controllable. /// </summary> /// <value>The current attack speed.</value> public abstract int CurrentAttackSpeed { get; } /// <summary> /// Returns the current move speed of the controllable. /// </summary> /// <value>The current move speed.</value> public abstract int CurrentMoveSpeed { get; } /// <summary> /// Returns the current sharpness of the controllable's active weapon. /// </summary> /// <value>The current sharpness.</value> public abstract int CurrentSharpness { get; } /// <summary> /// Returns the type of weapon used by the denizen. /// </summary> /// <value>The type of the weapon.</value> public abstract MRWeapon.eWeaponType WeaponType { get; } /// <summary> /// Gets the length of the controllable's active weapon. /// </summary> /// <value>The length of the weapon.</value> public abstract int WeaponLength { get; } /// <summary> /// Returns the attack direction being used this round. /// </summary> /// <value>The attack type.</value> public abstract MRCombatManager.eAttackType AttackType { get; } /// <summary> /// Returns the maneuver direction being used this round. /// </summary> /// <value>The defense type.</value> public abstract MRCombatManager.eDefenseType DefenseType { get; } /// <summary> /// Returns a value used for sorting counters in stacks. /// </summary> /// <value>The sort value.</value> public abstract int SortValue { get; } public GameObject Counter { get{ return mCounter; } } // Where the controllable is. public virtual MRILocation Location { get{ return mLocation; } set{ MRILocation oldLocation = mLocation; mLocation = value; if (oldLocation != null) oldLocation.RemovePiece(this); if (mLocation != null) { mLocation.AddPieceToTop(this); mLocation.Pieces.SortBySize(); } } } // Returns a list of hidden roads/paths the controllable has discovered. public virtual IList<MRRoad> DiscoveredRoads { get{ return mDiscoveredRoads; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="MRControllable"/> is hidden. /// </summary> /// <value><c>true</c> if hidden; otherwise, <c>false</c>.</value> public virtual bool Hidden { get{ return mHidden; } set{ mHidden = value; } } // base weight of the controllable public virtual MRGame.eStrength BaseWeight { get{ return mWeight; } } // base vulnerability of the controllable public MRGame.eStrength BaseVulnerability { get { return BaseWeight; } } // current vulnerability of the controllable public MRGame.eStrength CurrentVulnerability { get { return mVulnerability; } set { mVulnerability = value; } } // Actual gold the controllable has public virtual int BaseGold { get { return mGold; } set { mGold = value; if (mGold < 0) mGold = 0; } } // Effective gold the controllable has public virtual int EffectiveGold { get { return BaseGold; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="MRIControlable"/> is blocked. /// </summary> /// <value><c>true</c> if blocked; otherwise, <c>false</c>.</value> public virtual bool Blocked { get{ return mBlocked; } set{ mBlocked = value; if (mBlocked) { Hidden = false; // cancel any remaining activities MRActivityList activities = ActivitiesForDay(MRGame.DayOfMonth); if (activities != null) { foreach (MRActivity activity in activities.Activities) { if (!activity.Executed) activity.Canceled = true; } } } } } /// <summary> /// Gets or sets the combat target. /// </summary> /// <value>The combat target.</value> public virtual MRIControllable CombatTarget { get { return mCombatTarget; } set { if (mCombatTarget != null) mCombatTarget.RemoveAttacker(this); mCombatTarget = value; if (value != null) { Hidden = false; mCombatTarget.AddAttacker(this); } } } /// <summary> /// Returns the list of things attacking this target. /// </summary> /// <value>The attackers.</value> public virtual IList<MRIControllable> Attackers { get { return mAttackers; } } /// <summary> /// Returns the list of attackers who killed this controllable. /// </summary> /// <value>The killers.</value> public virtual IList<MRIControllable> Killers { get{ return mKillers; } } // The combat sheet the controllable is on. public virtual MRCombatSheetData CombatSheet { get { return mCombatSheet; } set { mCombatSheet = value; } } // The controllable this controllable is luring in combat. public virtual MRIControllable Luring { get { return mLuring; } set { mLuring = value; } } // The controllable luring this controllable in combat. public virtual MRIControllable Lurer { get { return mLurer; } set { mLurer = value; } } /// <summary> /// Returns if the controllable is dead. /// </summary> /// <value><c>true</c> if the controllable is dead; otherwise, <c>false</c>.</value> public virtual bool IsDead { get { return KillerCount > 0; } } /// <summary> /// Returns how many combatants killed this controllable (due to simultanious attacks) /// </summary> /// <value>The killer count.</value> public int KillerCount { get{ return mKillers.Count; } } /// <summary> /// Returns if this is a red-side up tremendous monster. /// </summary> /// <value><c>true</c> if this instance is red side monster; otherwise, <c>false</c>.</value> public virtual bool IsRedSideMonster { get { return false; } } /**********************/ // MRIGamePiece properties public uint Id { get{ return mId; } protected set{ mId = value; MRGame.TheGame.AddGamePiece(this); } } public virtual int Layer { get{ return mCounter.layer; } set{ if (value >= 0 && value < 32) { mCounter.layer = value; // todo: figure out why we need both of these to get the counter displayed correctly for (int i = 0; i < mCounter.transform.childCount; ++i) { Transform childTransform = mCounter.transform.GetChild(i); childTransform.gameObject.layer = value; } foreach (Transform transform in mCounter.GetComponentsInChildren<Transform>()) { transform.gameObject.layer = value; } } else { Debug.LogError("Trying to set controllable " + Name + " to layer " + value); } } } public virtual Vector3 Position { get{ return mCounter.transform.position; } set{ mCounter.transform.position = value; UpdateAttackerPositions(); } } public virtual Vector3 LocalScale { get{ return mCounter.transform.localScale; } set{ mCounter.transform.localScale = value; UpdateAttackerPositions(); } } public virtual Vector3 LossyScale { get { return mCounter.transform.lossyScale; } } public virtual Quaternion Rotation { get { return mCounter.transform.rotation; } set { mCounter.transform.rotation = value; UpdateAttackerPositions(); } } public virtual Vector3 EulerAngles { get { return mCounter.transform.localEulerAngles; } set { mCounter.transform.localEulerAngles = value; UpdateAttackerPositions(); } } public virtual Transform Parent { get{ return mCounter.transform.parent; } set { mCounter.transform.parent = value; } } public Bounds Bounds { get{ if (mCounter != null) { SpriteRenderer renderer = mCounter.GetComponentInChildren<SpriteRenderer>(); if (renderer) return renderer.sprite.bounds; } return new Bounds(); } } public virtual Vector3 OldScale { get { return mOldScale; } set { mOldScale = value; } } public virtual string Name { get{ return mName; } } public virtual MRGamePieceStack Stack { get{ return mStack; } set{ mStack = value; } } public virtual bool Visible { get{ return mCounter.activeSelf; } set{ mCounter.SetActive(value); } } #endregion #region Methods // Does initialization associated with birdsong. public abstract void StartBirdsong(); // Does initialization associated with sunrise. public abstract void StartSunrise(); // Does initialization associated with daylight. public abstract void StartDaylight(); // Does initialization associated with sunset. public abstract void StartSunset(); // Does initialization associated with evening. public abstract void StartEvening(); // Does initialization associated with midnight. public virtual void StartMidnight() { Blocked = false; CurrentVulnerability = BaseVulnerability; } // Tests if the controllable is allowed to do the activity. public abstract bool CanExecuteActivity(MRActivity activity); // Tells the controllable an activity was performed public abstract void ExecutedActivity(MRActivity activity); public abstract bool IsValidTarget(MRSpell spell); protected MRControllable() { } protected MRControllable(JSONObject jsonData, int index) { mName = ((JSONString)jsonData["name"]).Value; string weight = ((JSONString)jsonData["weight"]).Value; mWeight = weight.Strength(); mVulnerability = mWeight; mIndex = index; Id = MRUtility.IdForName(mName, index); } /// <summary> /// Cleans up resources used by the instance prior to being removed. /// </summary> public virtual void Destroy() { MRGame.TheGame.RemoveGamePiece(this); // remove ourself from the board if (Stack != null) Stack.RemovePiece(this); if (mCounter != null) { GameObject.DestroyObject(mCounter); mCounter = null; } } void OnDestroy() { Destroy (); } // Tests if this controllable activates a map chit to summon monsters public virtual bool ActivatesChit(MRMapChit chit) { return true; } /// <summary> /// Returns the die pool for a given roll type /// </summary> /// <returns>The pool.</returns> /// <param name="roll">Roll type.</param> public virtual MRDiePool DiePool(MRGame.eRollTypes roll) { return MRDiePool.DefaultPool; } // Returns the activity list for a given day. If the activity list doesn't exist, it will be created. public virtual MRActivityList ActivitiesForDay(int day) { // note day is base-1 while (mActivities.Count < day) { MRActivityList activityList = new MRActivityList(this); activityList.AddActivity(MRActivity.CreateActivity(MRGame.eActivity.None)); // activityList.AddActivity(MRActivity.CreateActivity(MRGame.eActivity.None)); mActivities.Add(activityList); } return mActivities[day - 1]; } // Removes all blank activities from the end of the activities lists public virtual void CleanupActivities() { foreach (MRActivityList activities in mActivities) { while (activities.Activities.Count > 0) { MRActivity activity = activities.Activities[activities.Activities.Count - 1]; if (activity.Activity == MRGame.eActivity.None) activities.Activities.Remove(activity); else break; } } } // Flags a site as being discovered public virtual void DiscoverSite(MRMapChit.eSiteChitType site) { mDiscoveredSites.Set((int)site, true); } // Returns if a site has been discovered public virtual bool DiscoveredSite(MRMapChit.eSiteChitType site) { return mDiscoveredSites.Get((int)site); } // Flags a treasure as being discovered public virtual void DiscoverTreasure(uint treasureId) { if (!mDiscoveredTreasues.Contains(treasureId)) mDiscoveredTreasues.Add(treasureId); } // Returns if a treasure has been discovered public virtual bool DiscoveredTreasure(uint treasureId) { return mDiscoveredTreasues.Contains(treasureId); } // Returns if a site can be looted by the controllable public virtual bool CanLootSite(MRSiteChit site) { if (!DiscoveredSite(site.SiteType)) return false; return true; } // Returns if a twit site can be looted by the controllable public virtual bool CanLootTwit(MRTreasure twit) { if (!DiscoveredTreasure(twit.Id)) return false; return true; } // Called when a site is looted by the controllable public virtual void OnSiteLooted(MRSiteChit site, bool success) { if (site.SiteType == MRMapChit.eSiteChitType.Vault) MRSiteChit.VaultOpened = true; } // Called when a twit site is looted by the controllable public virtual void OnTwitLooted(MRTreasure twit, bool success) { } // Adds a controllable to the list of things attacking this target public virtual void AddAttacker(MRIControllable attacker) { if (!mAttackers.Contains(attacker)) { mAttackers.Insert(0, attacker); UpdateAttackerPositions(); } } // Removes a controllable from the list of things attacking this target public virtual void RemoveAttacker(MRIControllable attacker) { if (attacker != null) { if (attacker is MRCharacter) ((MRCharacter)attacker).PositionAttentionChit(null, Vector3.zero); mAttackers.Remove(attacker); UpdateAttackerPositions(); } } // Called when the controllable hits its target public virtual void HitTarget(MRIControllable target, bool targetDead) { // do nothing } // Called when the controllable misses its target public virtual void MissTarget(MRIControllable target) { // do nothing } /// <summary> /// Awards the spoils of combat for killing a combatant. /// </summary> /// <param name="killed">Combatant that was killed.</param> /// <param name="awardFraction">Fraction of the spoils to award (due to shared kills).</param> public abstract void AwardSpoils(MRIControllable killed, float awardFraction); /// <summary> /// If this controllable is being attacked, shows the attacker chits over this chit. /// </summary> protected virtual void UpdateAttackerPositions() { if (mAttackers.Count > 0) { Vector3 cornerPosition = new Vector3(); SpriteRenderer sprite = mCounter.GetComponentInChildren<SpriteRenderer>(); Bounds bounds = mCounter.GetComponentInChildren<SpriteRenderer>().bounds; Vector3 scale1 = mCounter.transform.localScale; // Vector3 scale2 = mCounter.transform.lossyScale; cornerPosition.x = bounds.extents.x / scale1.x; cornerPosition.y = bounds.extents.y / scale1.y; float angle = mCounter.transform.localEulerAngles.y; if (angle > 100.0f) cornerPosition.x = -cornerPosition.x; foreach (MRIControllable attacker in mAttackers) { if (attacker is MRCharacter) { MRCharacter character = (MRCharacter)attacker; character.PositionAttentionChit(mCounter, cornerPosition); } } } } public virtual bool Load(JSONObject root) { if (root == null) return false; if (root["id"] != null) { if (MRGame.TheGame.GetPieceId(root["id"]) != mId) return false; } mGold = ((JSONNumber)root["gold"]).IntValue; mHidden = ((JSONBoolean)root["hidden"]).Value; mBlocked = ((JSONBoolean)root["blocked"]).Value; mDiscoveredRoads.Clear(); if (root["roads"] != null) { JSONArray roads = (JSONArray)root["roads"]; for (int i = 0; i < roads.Count; ++i) { string roadName = ((JSONString)roads[i]).Value; MRRoad road; if (MRGame.TheGame.TheMap.Roads.TryGetValue(roadName, out road)) mDiscoveredRoads.Add(road); else { Debug.LogError("Controllable " + mId + " load unknown road " + roadName); } } } mDiscoveredTreasues.Clear(); if (root["treasures"] != null) { JSONArray treasures = (JSONArray)root["treasures"]; for (int i = 0; i < treasures.Count; ++i) { mDiscoveredTreasues.Add((uint)((JSONNumber)treasures[i]).IntValue); } } int[] sites = new int[1]; if (root["sites"] != null) { sites[0] = ((JSONNumber)root["sites"]).IntValue; mDiscoveredSites = new BitArray(sites); } mActivities.Clear(); if (root["activities"] != null) { JSONArray activities = (JSONArray)root["activities"]; for (int i = 0; i < activities.Count; ++i) { MRActivityList activityList = new MRActivityList(this); activityList.Load((JSONObject)activities[i]); mActivities.Add(activityList); } } if (root["location"] != null) { uint locationId = ((JSONNumber)root["location"]).UintValue; MRILocation location = MRGame.TheGame.GetLocation(locationId); if (location != null) { Location = location; } else { Debug.LogError("Invalid location " + locationId + " for creature " + Name); return false; } } if (root["vulnerability"] != null) { int vulnerability = ((JSONNumber)root["vulnerability"]).IntValue; mVulnerability = (MRGame.eStrength)vulnerability; } return true; } public virtual void Save(JSONObject root) { root["id"] = new JSONNumber(mId); root["gold"] = new JSONNumber(mGold); root["hidden"] = new JSONBoolean(mHidden); root["blocked"] = new JSONBoolean(mBlocked); root["vulnerability"] = new JSONNumber((int)mVulnerability); if (Location != null) { root["location"] = new JSONNumber(Location.Id); } JSONArray roads = new JSONArray(mDiscoveredRoads.Count); for (int i = 0; i < mDiscoveredRoads.Count; ++i) { roads[i] = new JSONString(mDiscoveredRoads[i].Name); } root["roads"] = roads; JSONArray treasures = new JSONArray(mDiscoveredTreasues.Count); for (int i = 0; i < mDiscoveredTreasues.Count; ++i) { treasures[i] = new JSONNumber(mDiscoveredTreasues[i]); } root["treasures"] = treasures; int[] sites = new int[1]; mDiscoveredSites.CopyTo(sites, 0); root["sites"] = new JSONNumber(sites[0]); JSONArray activities = new JSONArray(mActivities.Count); for (int i = 0; i < mActivities.Count; ++i) { JSONObject activityList = new JSONObject(); mActivities[i].Save(activityList); activities[i] = activityList; } root["activities"] = activities; } // Add an item to the controllable's items. public abstract void AddItem(MRItem item); // Returns the weight of the heaviest item owned by the controllable public abstract MRGame.eStrength GetHeaviestWeight(bool includeHorse, bool includeSelf); /**********************/ // MRIGamePiece methods public abstract void Update(); #endregion #region Members protected string mName; protected GameObject mCounter; protected Vector3 mOldScale; protected MRILocation mLocation; protected IList<MRRoad> mDiscoveredRoads = new List<MRRoad>(); protected IList<MRActivityList> mActivities = new List<MRActivityList>(); protected BitArray mDiscoveredSites = new BitArray(Enum.GetValues(typeof(MRMapChit.eSiteChitType)).Length); protected IList<uint> mDiscoveredTreasues = new List<uint>(); protected MRGame.eStrength mWeight; protected MRGame.eStrength mVulnerability; protected int mGold; protected bool mHidden; protected bool mBlocked; protected MRIControllable mCombatTarget; protected IList<MRIControllable> mAttackers = new List<MRIControllable>(); protected IList<MRIControllable> mKillers = new List<MRIControllable>(); protected MRGamePieceStack mStack; protected MRCombatSheetData mCombatSheet; protected MRIControllable mLuring; protected MRIControllable mLurer; protected int mIndex; private uint mId; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // This RegexCode class is internal to the regular expression package. // It provides operator constants for use by the Builder and the Machine. // Implementation notes: // // Regexps are built into RegexCodes, which contain an operation array, // a string table, and some constants. // // Each operation is one of the codes below, followed by the integer // operands specified for each op. // // Strings and sets are indices into a string table. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { internal sealed class RegexCode { // The following primitive operations come directly from the parser // lef/back operands description internal const int Onerep = 0; // lef,back char,min,max a {n} internal const int Notonerep = 1; // lef,back char,min,max .{n} internal const int Setrep = 2; // lef,back set,min,max [\d]{n} internal const int Oneloop = 3; // lef,back char,min,max a {,n} internal const int Notoneloop = 4; // lef,back char,min,max .{,n} internal const int Setloop = 5; // lef,back set,min,max [\d]{,n} internal const int Onelazy = 6; // lef,back char,min,max a {,n}? internal const int Notonelazy = 7; // lef,back char,min,max .{,n}? internal const int Setlazy = 8; // lef,back set,min,max [\d]{,n}? internal const int One = 9; // lef char a internal const int Notone = 10; // lef char [^a] internal const int Set = 11; // lef set [a-z\s] \w \s \d internal const int Multi = 12; // lef string abcd internal const int Ref = 13; // lef group \# internal const int Bol = 14; // ^ internal const int Eol = 15; // $ internal const int Boundary = 16; // \b internal const int Nonboundary = 17; // \B internal const int Beginning = 18; // \A internal const int Start = 19; // \G internal const int EndZ = 20; // \Z internal const int End = 21; // \Z internal const int Nothing = 22; // Reject! // Primitive control structures internal const int Lazybranch = 23; // back jump straight first internal const int Branchmark = 24; // back jump branch first for loop internal const int Lazybranchmark = 25; // back jump straight first for loop internal const int Nullcount = 26; // back val set counter, null mark internal const int Setcount = 27; // back val set counter, make mark internal const int Branchcount = 28; // back jump,limit branch++ if zero<=c<limit internal const int Lazybranchcount = 29; // back jump,limit same, but straight first internal const int Nullmark = 30; // back save position internal const int Setmark = 31; // back save position internal const int Capturemark = 32; // back group define group internal const int Getmark = 33; // back recall position internal const int Setjump = 34; // back save backtrack state internal const int Backjump = 35; // zap back to saved state internal const int Forejump = 36; // zap backtracking state internal const int Testref = 37; // backtrack if ref undefined internal const int Goto = 38; // jump just go internal const int Prune = 39; // prune it baby internal const int Stop = 40; // done! internal const int ECMABoundary = 41; // \b internal const int NonECMABoundary = 42; // \B // Modifiers for alternate modes internal const int Mask = 63; // Mask to get unmodified ordinary operator internal const int Rtl = 64; // bit to indicate that we're reverse scanning. internal const int Back = 128; // bit to indicate that we're backtracking. internal const int Back2 = 256; // bit to indicate that we're backtracking on a second branch. internal const int Ci = 512; // bit to indicate that we're case-insensitive. internal readonly int[] _codes; // the code internal readonly String[] _strings; // the string/set table internal readonly int _trackcount; // how many instructions use backtracking internal readonly Dictionary<Int32, Int32> _caps; // mapping of user group numbers -> impl group slots internal readonly int _capsize; // number of impl group slots internal readonly RegexPrefix _fcPrefix; // the set of candidate first characters (may be null) internal readonly RegexBoyerMoore _bmPrefix; // the fixed prefix string as a Boyer-Moore machine (may be null) internal readonly int _anchors; // the set of zero-length start anchors (RegexFCD.Bol, etc) internal readonly bool _rightToLeft; // true if right to left internal RegexCode(int[] codes, List<String> stringlist, int trackcount, Dictionary<Int32, Int32> caps, int capsize, RegexBoyerMoore bmPrefix, RegexPrefix fcPrefix, int anchors, bool rightToLeft) { Debug.Assert(codes != null, "codes cannot be null."); Debug.Assert(stringlist != null, "stringlist cannot be null."); _codes = codes; _strings = new String[stringlist.Count]; _trackcount = trackcount; _caps = caps; _capsize = capsize; _bmPrefix = bmPrefix; _fcPrefix = fcPrefix; _anchors = anchors; _rightToLeft = rightToLeft; stringlist.CopyTo(0, _strings, 0, stringlist.Count); } internal static bool OpcodeBacktracks(int Op) { Op &= Mask; switch (Op) { case Oneloop: case Notoneloop: case Setloop: case Onelazy: case Notonelazy: case Setlazy: case Lazybranch: case Branchmark: case Lazybranchmark: case Nullcount: case Setcount: case Branchcount: case Lazybranchcount: case Setmark: case Capturemark: case Getmark: case Setjump: case Backjump: case Forejump: case Goto: return true; default: return false; } } #if DEBUG internal static int OpcodeSize(int opcode) { opcode &= Mask; switch (opcode) { case Nothing: case Bol: case Eol: case Boundary: case Nonboundary: case ECMABoundary: case NonECMABoundary: case Beginning: case Start: case EndZ: case End: case Nullmark: case Setmark: case Getmark: case Setjump: case Backjump: case Forejump: case Stop: return 1; case One: case Notone: case Multi: case Ref: case Testref: case Goto: case Nullcount: case Setcount: case Lazybranch: case Branchmark: case Lazybranchmark: case Prune: case Set: return 2; case Capturemark: case Branchcount: case Lazybranchcount: case Onerep: case Notonerep: case Oneloop: case Notoneloop: case Onelazy: case Notonelazy: case Setlazy: case Setrep: case Setloop: return 3; default: throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, opcode.ToString(CultureInfo.CurrentCulture))); } } private static readonly String[] CodeStr = new String[] { "Onerep", "Notonerep", "Setrep", "Oneloop", "Notoneloop", "Setloop", "Onelazy", "Notonelazy", "Setlazy", "One", "Notone", "Set", "Multi", "Ref", "Bol", "Eol", "Boundary", "Nonboundary", "Beginning", "Start", "EndZ", "End", "Nothing", "Lazybranch", "Branchmark", "Lazybranchmark", "Nullcount", "Setcount", "Branchcount", "Lazybranchcount", "Nullmark", "Setmark", "Capturemark", "Getmark", "Setjump", "Backjump", "Forejump", "Testref", "Goto", "Prune", "Stop", #if ECMA "ECMABoundary", "NonECMABoundary", #endif }; internal static String OperatorDescription(int Opcode) { bool isCi = ((Opcode & Ci) != 0); bool isRtl = ((Opcode & Rtl) != 0); bool isBack = ((Opcode & Back) != 0); bool isBack2 = ((Opcode & Back2) != 0); return CodeStr[Opcode & Mask] + (isCi ? "-Ci" : "") + (isRtl ? "-Rtl" : "") + (isBack ? "-Back" : "") + (isBack2 ? "-Back2" : ""); } internal String OpcodeDescription(int offset) { StringBuilder sb = new StringBuilder(); int opcode = _codes[offset]; sb.AppendFormat("{0:D6} ", offset); sb.Append(OpcodeBacktracks(opcode & Mask) ? '*' : ' '); sb.Append(OperatorDescription(opcode)); sb.Append('('); opcode &= Mask; switch (opcode) { case One: case Notone: case Onerep: case Notonerep: case Oneloop: case Notoneloop: case Onelazy: case Notonelazy: sb.Append("Ch = "); sb.Append(RegexCharClass.CharDescription((char)_codes[offset + 1])); break; case Set: case Setrep: case Setloop: case Setlazy: sb.Append("Set = "); sb.Append(RegexCharClass.SetDescription(_strings[_codes[offset + 1]])); break; case Multi: sb.Append("String = "); sb.Append(_strings[_codes[offset + 1]]); break; case Ref: case Testref: sb.Append("Index = "); sb.Append(_codes[offset + 1]); break; case Capturemark: sb.Append("Index = "); sb.Append(_codes[offset + 1]); if (_codes[offset + 2] != -1) { sb.Append(", Unindex = "); sb.Append(_codes[offset + 2]); } break; case Nullcount: case Setcount: sb.Append("Value = "); sb.Append(_codes[offset + 1]); break; case Goto: case Lazybranch: case Branchmark: case Lazybranchmark: case Branchcount: case Lazybranchcount: sb.Append("Addr = "); sb.Append(_codes[offset + 1]); break; } switch (opcode) { case Onerep: case Notonerep: case Oneloop: case Notoneloop: case Onelazy: case Notonelazy: case Setrep: case Setloop: case Setlazy: sb.Append(", Rep = "); if (_codes[offset + 2] == Int32.MaxValue) sb.Append("inf"); else sb.Append(_codes[offset + 2]); break; case Branchcount: case Lazybranchcount: sb.Append(", Limit = "); if (_codes[offset + 2] == Int32.MaxValue) sb.Append("inf"); else sb.Append(_codes[offset + 2]); break; } sb.Append(')'); return sb.ToString(); } internal void Dump() { int i; Debug.WriteLine("Direction: " + (_rightToLeft ? "right-to-left" : "left-to-right")); Debug.WriteLine("Firstchars: " + (_fcPrefix == null ? "n/a" : RegexCharClass.SetDescription(_fcPrefix.Prefix))); Debug.WriteLine("Prefix: " + (_bmPrefix == null ? "n/a" : Regex.Escape(_bmPrefix.ToString()))); Debug.WriteLine("Anchors: " + RegexFCD.AnchorDescription(_anchors)); Debug.WriteLine(""); if (_bmPrefix != null) { Debug.WriteLine("BoyerMoore:"); Debug.WriteLine(_bmPrefix.Dump(" ")); } for (i = 0; i < _codes.Length;) { Debug.WriteLine(OpcodeDescription(i)); i += OpcodeSize(_codes[i]); } Debug.WriteLine(""); } #endif } }
using Common; using Common.fx; using fxcore2; using System; using System.Text; using System.Threading; namespace fxCoreLink { public class MarketTrade : IMarketTrade { Logger log = Logger.LogManager("MarketTrade"); private O2GSession mSession; MailSender mailSender = new MailSender(); string mOfferID = string.Empty; string mAccountID = string.Empty; bool mHasAccount = false; bool mHasOffer = true; double pegStopOffset = 0.0; double pegLimitOffset = 0.0; double mRateLimit = 0.0; double mBid = 0.0; double mAsk = 0.0; double mPointSize = 0.0; int trailStepStop = 0; // dynamic string cond_dist = "n/a"; double condDistEntryLimit = 0.0; double condDistLimitTrade = 0.0; public MarketTrade(O2GSession session, Display display, MailSender mailSender, string cond_dist) { this.mSession = session; this.display = display; this.mailSender = mailSender; this.cond_dist = cond_dist; } private Display display; public string trade(string mInstrument, int mAmount, string mBuySell, int stopPips, bool trailingStop, int limitPips, double expectedPrice, string customId) { if (trailingStop) trailStepStop = 1; return trade(mInstrument, mAmount, mBuySell, stopPips, limitPips, expectedPrice, customId); } // returns OrderID public string trade(string mInstrument, int mAmount, string mBuySell, int stopPips, int limitPips, double expectedPrice, string customId) { string returnId = null; string mOrderType = "OM"; O2GRequestFactory requestFactory = null; //int entryPips = 0; MarketResponseListener responseListener = new MarketResponseListener(mSession, display); try { mSession.subscribeResponse(responseListener); GetAccount(mSession); if (mHasAccount) GetOfferRate(mSession, mInstrument, mBuySell, mOrderType, stopPips, limitPips); if (mHasAccount && mHasOffer) { requestFactory = mSession.getRequestFactory(); if (requestFactory != null) { O2GValueMap valueMap = requestFactory.createValueMap(); valueMap.setString(O2GRequestParamsEnum.Command, Constants.Commands.CreateOrder); valueMap.setString(O2GRequestParamsEnum.OrderType, mOrderType); valueMap.setString(O2GRequestParamsEnum.AccountID, mAccountID); valueMap.setString(O2GRequestParamsEnum.OfferID, mOfferID); valueMap.setString(O2GRequestParamsEnum.BuySell, mBuySell); //valueMap.setDouble(O2GRequestParamsEnum.Rate, mRate); valueMap.setInt(O2GRequestParamsEnum.Amount, mAmount); valueMap.setString(O2GRequestParamsEnum.CustomID, customId); //valueMap.setDouble(O2GRequestParamsEnum.RateStop, mRateStop); valueMap.setString(O2GRequestParamsEnum.PegTypeStop, Constants.Peg.FromClose); valueMap.setDouble(O2GRequestParamsEnum.PegOffsetStop, pegStopOffset); if (limitPips != 0) { valueMap.setDouble(O2GRequestParamsEnum.PegOffsetLimit, pegLimitOffset); valueMap.setString(O2GRequestParamsEnum.PegTypeLimit, Constants.Peg.FromClose); } // # of pips in notation of instrument (i.e. 0.005 for 5 pips on USD/JPY) valueMap.setInt(O2GRequestParamsEnum.TrailStepStop, trailStepStop); //valueMap.setDouble(O2GRequestParamsEnum.TrailStep, 0.1); log.debug(string.Format("Market order request, {0} {1}, stop={2}, limPips={3}, limitPrice={7}, expPrice={4}, customId={5}, cond_dist={6}, condDistEntryLimit={8}, condDistLimitTrade={9}", mInstrument, mBuySell, pegStopOffset, limitPips, expectedPrice, customId, cond_dist, mRateLimit, condDistEntryLimit, condDistLimitTrade)); O2GRequest request = requestFactory.createOrderRequest(valueMap); CtrlTimer.getInstance().startTimer("MarketRequest"); mSession.sendRequest(request); //Thread.Sleep(1000); //responseListener.manualEvent.WaitOne(1000, false); responseListener.manualEvent.WaitOne(); StringBuilder sb = new StringBuilder(); if (!responseListener.Error) { sb.Append("Created mkt order, " + mInstrument); sb.Append(", orderID=" + responseListener.OrderId); sb.Append(", customID=" + customId); //orderId = responseListener.OrderId; returnId = mOfferID; } else sb.Append("Failed mkt order: " + mInstrument + "; " + responseListener.ErrorDescription + "; " + "limit=" + mRateLimit + ", trailStepStop=" + trailStepStop + ", bid=" + mBid + ", ask=" + mAsk + ", pegStopOffset=" + pegStopOffset + ", pointSize=" + mPointSize + ", expectedPrice=" + expectedPrice ); log.debug(sb.ToString()); mailSender.sendMail("mkt", sb.ToString()); } } } catch (Exception e) { log.debug("Exception: {0}", e.ToString() + "; " + requestFactory.getLastError()); } finally { mSession.unsubscribeResponse(responseListener); } return returnId; } // Get current prices and calculate order price private void GetOfferRate(O2GSession session, string sInstrument, string mBuySell, string mOrderType, int stopPips, int limitPips) { double dBid = 0.0; double dAsk = 0.0; double dPointSize = 0.0; try { O2GLoginRules loginRules = session.getLoginRules(); O2GTradingSettingsProvider tsp = loginRules.getTradingSettingsProvider(); condDistEntryLimit = tsp.getCondDistEntryLimit(sInstrument); condDistLimitTrade = tsp.getCondDistLimitForTrade(sInstrument); if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Offers)) { O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers); O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GOffersTableResponseReader offersReader = responseFactory.createOffersTableReader(offersResponse); for (int i = 0; i < offersReader.Count; i++) { O2GOfferRow offer = offersReader.getRow(i); if (sInstrument == offer.Instrument) { if (offer.InstrumentType != 1) { // validity check, TODO-what else? log.debug("Instrument type = " + offer.InstrumentType + " for " + sInstrument); //return; } // TODO--sometimes pointsize is zero, but since not doing limits, it doesn't matter // returning at this point is causing other failures!!! // if (offer.PointSize == 0.0) { // validity check, TODO-what else? log.debug("PointSize = " + offer.PointSize + " for " + sInstrument); //return; } mOfferID = offer.OfferID; dBid = offer.Bid; dAsk = offer.Ask; dPointSize = offer.PointSize; mBid = dBid; mAsk = dAsk; mPointSize = dPointSize; // limit -- The offset must be negative for a sell position and positive for a buy position. if (mBuySell == Constants.Buy) { //mRateLimit = dBid + limitPips * dPointSize; pegStopOffset = -stopPips; pegLimitOffset = limitPips; } else if (mBuySell == Constants.Sell) { //mRateLimit = dAsk - limitPips * dPointSize; pegStopOffset = stopPips; pegLimitOffset = -limitPips; } mHasOffer = true; break; } } } if (!mHasOffer) log.debug("You specified invalid instrument. No action will be taken."); } catch (Exception e) { log.debug("Exception in GetOfferRate().\n\t " + e.Message); } } // Get account for trade private void GetAccount(O2GSession session) { try { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules != null && loginRules.isTableLoadedByDefault(O2GTableType.Accounts)) { string sAccountID = string.Empty; string sAccountKind = string.Empty; O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse); for (int i = 0; i < accountsReader.Count; i++) { O2GAccountRow account = accountsReader.getRow(i); sAccountID = account.AccountID; sAccountKind = account.AccountKind; if (sAccountKind == "32" || sAccountKind == "36") { mAccountID = sAccountID; mHasAccount = true; break; } } if (!mHasAccount) log.debug("You don't have any accounts available for trading. No action will be taken."); } } catch (Exception e) { log.debug("Exception in GetAccounts():\n\t " + e.Message); } } } public class MarketResponseListener : IO2GResponseListener, IDisposable { Logger log = Logger.LogManager("MarketResponseListener"); private Display display; O2GSession mSession; public ManualResetEvent manualEvent; public string OrderId; public MarketResponseListener(O2GSession session, Display display) { this.mSession = session; this.display = display; manualEvent = new ManualResetEvent(false); } public bool Error { get { return mError; } } private bool mError = false; public string ErrorDescription { get { return mErrorDescription; } } private string mErrorDescription; // Implementation of IO2GResponseListener interface public method onRequestCompleted public void onRequestCompleted(String requestID, O2GResponse response) { // if need to capture response, send to log! //log.debug("Request completed.\nrequestID= " + requestID); mError = false; mErrorDescription = ""; O2GOrderResponseReader reader = mSession.getResponseReaderFactory().createOrderResponseReader(response); this.OrderId = reader.OrderID; manualEvent.Set(); CtrlTimer.getInstance().stopTimer("MarketRequest"); } // Implementation of IO2GResponseListener interface public method onRequestFailed public void onRequestFailed(String requestID, String error) { //log.debug("Request failed.\nrequestID= " + requestID + "; error= " + error); mError = true; mErrorDescription = error; manualEvent.Set(); CtrlTimer.getInstance().stopTimer("MarketRequest"); } // Implementation of IO2GResponseListener interface public method onTablesUpdates public void onTablesUpdates(O2GResponse response) { } public void Dispose() { manualEvent.Dispose(); } } }