context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Password Hashing With PBKDF2 (http://crackstation.net/hashing-security.htm). * Copyright (c) 2013, Taylor Hornby * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Security.Cryptography; namespace Defuse_PasswordSecurity { internal class InvalidVerifierException : Exception { public InvalidVerifierException() { } public InvalidVerifierException(string message) : base(message) { } public InvalidVerifierException(string message, Exception inner) : base(message, inner) { } } internal class CannotPerformOperationException : Exception { public CannotPerformOperationException() { } public CannotPerformOperationException(string message) : base(message) { } public CannotPerformOperationException(string message, Exception inner) : base(message, inner) { } } internal class PasswordHash { // The following constants may be changed without breaking existing hashes. public const int SALT_BYTES = 24; public const int HASH_BYTES = 18; public const int PBKDF2_ITERATIONS = 32000; public const int HASH_SECTIONS = 5; public const int HASH_ALGORITHM_INDEX = 0; public const int ITERATION_INDEX = 1; public const int HASH_SIZE_INDEX = 2; public const int SALT_INDEX = 3; public const int PBKDF2_INDEX = 4; public static string CreateHash(string password) { // Generate a random salt var csprng = new RNGCryptoServiceProvider(); var salt = new byte[SALT_BYTES]; try { csprng.GetBytes(salt); } catch (CryptographicException ex) { throw new CannotPerformOperationException( "Random number generator not available.", ex ); } catch (ArgumentNullException ex) { throw new CannotPerformOperationException( "Invalid argument given to random number generator.", ex ); } // Hash the password and encode the parameters var hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTES); // format: algorithm:iterations:hashSize:salt:hash var parts = "sha1:" + PBKDF2_ITERATIONS + ":" + hash.Length + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash); return parts; } public static bool ValidatePassword(string password, string goodHash) { // Extract the parameters from the hash char[] delimiter = {':'}; var split = goodHash.Split(delimiter); if (split.Length != HASH_SECTIONS) { throw new InvalidVerifierException( "Fields are missing from the password verifier." ); } // Currently, we only support SHA1 with C#. if (split[HASH_ALGORITHM_INDEX] != "sha1") { throw new CannotPerformOperationException( "Unsupported hash type." ); } var iterations = 0; try { iterations = Int32.Parse(split[ITERATION_INDEX]); } catch (ArgumentNullException ex) { throw new CannotPerformOperationException( "Invalid argument given to Int32.Parse", ex ); } catch (FormatException ex) { throw new InvalidVerifierException( "Could not parse the iteration count as an integer.", ex ); } catch (OverflowException ex) { throw new InvalidVerifierException( "The iteration count is too large to be represented.", ex ); } if (iterations < 1) { throw new InvalidVerifierException( "Invalid number of iterations. Must be >= 1." ); } byte[] salt = null; try { salt = Convert.FromBase64String(split[SALT_INDEX]); } catch (ArgumentNullException ex) { throw new CannotPerformOperationException( "Invalid argument given to Convert.FromBase64String", ex ); } catch (FormatException ex) { throw new InvalidVerifierException( "Base64 decoding of salt failed.", ex ); } byte[] hash = null; try { hash = Convert.FromBase64String(split[PBKDF2_INDEX]); } catch (ArgumentNullException ex) { throw new CannotPerformOperationException( "Invalid argument given to Convert.FromBase64String", ex ); } catch (FormatException ex) { throw new InvalidVerifierException( "Base64 decoding of pbkdf2 output failed.", ex ); } var storedHashSize = 0; try { storedHashSize = Int32.Parse(split[HASH_SIZE_INDEX]); } catch (ArgumentNullException ex) { throw new CannotPerformOperationException( "Invalid argument given to Int32.Parse", ex ); } catch (FormatException ex) { throw new InvalidVerifierException( "Could not parse the hash size as an integer.", ex ); } catch (OverflowException ex) { throw new InvalidVerifierException( "The hash size is too large to be represented.", ex ); } if (storedHashSize != hash.Length) { throw new InvalidVerifierException( "Hash length doesn't match stored hash length." ); } var testHash = PBKDF2(password, salt, iterations, hash.Length); return SlowEquals(hash, testHash); } private static bool SlowEquals(byte[] a, byte[] b) { var diff = (uint) a.Length ^ (uint) b.Length; for (var i = 0; i < a.Length && i < b.Length; i++) { diff |= (uint) (a[i] ^ b[i]); } return diff == 0; } private static byte[] PBKDF2(string password, byte[] salt, int iterations, int outputBytes) { var pbkdf2 = new Rfc2898DeriveBytes(password, salt); pbkdf2.IterationCount = iterations; return pbkdf2.GetBytes(outputBytes); } } }
// // This code was created by Jeff Molofee '99 // // If you've found this code useful, please let me know. // // Visit me at www.demonews.com/hosted/nehe // //===================================================================== // Converted to C# and MonoMac by Kenneth J. Pouncey // http://www.cocoa-mono.org // // Copyright (c) 2011 Kenneth J. Pouncey // // // 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.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; using MonoMac.CoreVideo; using MonoMac.CoreGraphics; using MonoMac.OpenGL; namespace NeHeLesson9 { public partial class MyOpenGLView : MonoMac.AppKit.NSView { NSOpenGLContext openGLContext; NSOpenGLPixelFormat pixelFormat; MainWindowController controller; CVDisplayLink displayLink; NSObject notificationProxy; [Export("initWithFrame:")] public MyOpenGLView (RectangleF frame) : this(frame, null) { } public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame) { var attribs = new object [] { NSOpenGLPixelFormatAttribute.Accelerated, NSOpenGLPixelFormatAttribute.NoRecovery, NSOpenGLPixelFormatAttribute.DoubleBuffer, NSOpenGLPixelFormatAttribute.ColorSize, 24, NSOpenGLPixelFormatAttribute.DepthSize, 16 }; pixelFormat = new NSOpenGLPixelFormat (attribs); if (pixelFormat == null) Console.WriteLine ("No OpenGL pixel format"); // NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead openGLContext = new NSOpenGLContext (pixelFormat, context); openGLContext.MakeCurrentContext (); // Synchronize buffer swaps with vertical refresh rate openGLContext.SwapInterval = true; // Initialize our newly created view. InitGL (); SetupDisplayLink (); // Look for changes in view size // Note, -reshape will not be called automatically on size changes because NSView does not export it to override notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.GlobalFrameChangedNotification, HandleReshape); } public override void DrawRect (RectangleF dirtyRect) { // Ignore if the display link is still running if (!displayLink.IsRunning && controller != null) DrawView (); } public override bool AcceptsFirstResponder () { // We want this view to be able to receive key events return true; } public override void LockFocus () { base.LockFocus (); if (openGLContext.View != this) openGLContext.View = this; } public override void KeyDown (NSEvent theEvent) { controller.KeyDown (theEvent); } public override void MouseDown (NSEvent theEvent) { controller.MouseDown (theEvent); } // All Setup For OpenGL Goes Here public bool InitGL () { // Enable Texture Mapping GL.Enable (EnableCap.Texture2D); // Enables Smooth Shading GL.ShadeModel (ShadingModel.Smooth); // Set background color to black GL.ClearColor (0, 0, 0, 0.5f); // Setup Depth Testing // Depth Buffer setup GL.ClearDepth (1.0); // Really Nice Perspective Calculations GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest); GL.BlendFunc (BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One); GL.Enable (EnableCap.Blend); return true; } private void DrawView () { var previous = NSApplication.CheckForIllegalCrossThreadCalls; NSApplication.CheckForIllegalCrossThreadCalls = false; // This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop) // Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Make sure we draw to the right context openGLContext.MakeCurrentContext (); // Delegate to the scene object for rendering controller.Scene.DrawGLScene (); openGLContext.FlushBuffer (); openGLContext.CGLContext.Unlock (); NSApplication.CheckForIllegalCrossThreadCalls = previous; } private void SetupDisplayLink () { // Create a display link capable of being used with all active displays displayLink = new CVDisplayLink (); // Set the renderer output callback function displayLink.SetOutputCallback (MyDisplayLinkOutputCallback); // Set the display link for the current renderer CGLContext cglContext = openGLContext.CGLContext; CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat; displayLink.SetCurrentDisplay (cglContext, cglPixelFormat); } public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { CVReturn result = GetFrameForTime (inOutputTime); return result; } private CVReturn GetFrameForTime (CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { // Update the animation DrawView (); } return CVReturn.Success; } public NSOpenGLContext OpenGLContext { get { return openGLContext; } } public NSOpenGLPixelFormat PixelFormat { get { return pixelFormat; } } public MainWindowController MainController { set { controller = value; } } public void UpdateView () { // This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link // Add a mutex around to avoid the threads accessing the context simultaneously openGLContext.CGLContext.Lock (); // Delegate to the scene object to update for a change in the view size controller.Scene.ResizeGLScene (Bounds); openGLContext.Update (); openGLContext.CGLContext.Unlock (); } private void HandleReshape (NSNotification note) { UpdateView (); } public void StartAnimation () { if (displayLink != null && !displayLink.IsRunning) displayLink.Start (); } public void StopAnimation () { if (displayLink != null && displayLink.IsRunning) displayLink.Stop (); } // Clean up the notifications public void DeAllocate () { displayLink.Stop (); displayLink.SetOutputCallback (null); NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy); } [Export("toggleFullScreen:")] public void toggleFullScreen (NSObject sender) { controller.toggleFullScreen (sender); } } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using BusinessObjects.Common; namespace BusinessObjects.Documents { [Serializable] public partial class cDocuments_Enums_DispatchType: CoreBusinessClass<cDocuments_Enums_DispatchType> { #region Business Methods public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.String > nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Name { get { return GetProperty(nameProperty); } set { SetProperty(nameProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<bool> inactiveProperty = RegisterProperty<bool>(p => p.Inactive, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public bool Inactive { get { return GetProperty(inactiveProperty); } set { SetProperty(inactiveProperty, value); } } private static readonly PropertyInfo< System.String > descriptionProperty = RegisterProperty<System.String>(p => p.Description, string.Empty, (System.String)null); public System.String Description { get { return GetProperty(descriptionProperty); } set { SetProperty(descriptionProperty, (value ?? "").Trim()); } } protected static readonly PropertyInfo<System.Int32?> companyUsingServiceIdProperty = RegisterProperty<System.Int32?>(p => p.CompanyUsingServiceId, string.Empty); public System.Int32? CompanyUsingServiceId { get { return GetProperty(companyUsingServiceIdProperty); } set { SetProperty(companyUsingServiceIdProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; #endregion #region Factory Methods public static cDocuments_Enums_DispatchType NewDocuments_Enums_DispatchType() { return DataPortal.Create<cDocuments_Enums_DispatchType>(); } public static cDocuments_Enums_DispatchType GetDocuments_Enums_DispatchType(int uniqueId) { return DataPortal.Fetch<cDocuments_Enums_DispatchType>(new SingleCriteria<cDocuments_Enums_DispatchType, int>(uniqueId)); } internal static cDocuments_Enums_DispatchType GetDocuments_Enums_DispatchType(Documents_Enums_DispatchType data) { return DataPortal.Fetch<cDocuments_Enums_DispatchType>(data); } public static void DeleteDocuments_Enums_DispatchType(int uniqueId) { DataPortal.Delete<cDocuments_Enums_DispatchType>(new SingleCriteria<cDocuments_Enums_DispatchType, int>(uniqueId)); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cDocuments_Enums_DispatchType, int> criteria) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = ctx.ObjectContext.Documents_Enums_DispatchType.First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<string>(descriptionProperty, data.Description); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } } private void DataPortal_Fetch(Documents_Enums_DispatchType data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<string>(descriptionProperty, data.Description); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); MarkAsChild(); } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Enums_DispatchType(); data.Name = ReadProperty<string>(nameProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.Description = ReadProperty<string>(descriptionProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.AddToDocuments_Enums_DispatchType(data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_Enums_DispatchType(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Name = ReadProperty<string>(nameProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.Description = ReadProperty<string>(descriptionProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.SaveChanges(); } } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(SingleCriteria<cDocuments_Enums_DispatchType, int> criteria) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = ctx.ObjectContext.Documents_Enums_DispatchType.First(p => p.Id == criteria.Value); ctx.ObjectContext.Documents_Enums_DispatchType.DeleteObject(data); ctx.ObjectContext.SaveChanges(); } } #endregion } public partial class cDocuments_Enums_DispatchType_List : BusinessListBase<cDocuments_Enums_DispatchType_List, cDocuments_Enums_DispatchType> { public static cDocuments_Enums_DispatchType_List GetcDocuments_Enums_DispatchType_List() { return DataPortal.Fetch<cDocuments_Enums_DispatchType_List>(); } public static cDocuments_Enums_DispatchType_List GetcDocuments_Enums_DispatchType_List(int companyId, int includeInactiveId) { return DataPortal.Fetch<cDocuments_Enums_DispatchType_List>(new ActiveEnums_Criteria(companyId, includeInactiveId)); } private void DataPortal_Fetch() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var result = ctx.ObjectContext.Documents_Enums_DispatchType; foreach (var data in result) { var obj = cDocuments_Enums_DispatchType.GetDocuments_Enums_DispatchType(data); this.Add(obj); } } } private void DataPortal_Fetch(ActiveEnums_Criteria criteria) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var result = ctx.ObjectContext.Documents_Enums_DispatchType.Where(p => (p.CompanyUsingServiceId == criteria.CompanyId || (p.CompanyUsingServiceId ?? 0) == 0) && (p.Inactive == false || p.Id == criteria.IncludeInactiveId)); foreach (var data in result) { var obj = cDocuments_Enums_DispatchType.GetDocuments_Enums_DispatchType(data); this.Add(obj); } } } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace RoboVikingGame { public class Weapon : Component { private Texture2D attackTexture; public int cost; private float damage; private bool haveAttacked; private int oldLevel; private readonly Color overlayColor; private Vector2 pos; private float reach; private Rectangle rectangle; private float rotation; private readonly Vector2 scale; private Texture2D sprite; private string spriteName; private SpriteRenderer spriteRenderer; /// <summary> /// creates a weapon /// </summary> /// <param name="go"></param> /// <param name="level"></param> public Weapon(GameObject go, int level) : base(go) { overlayColor = Color.White; scale = Vector2.One; Level = level; UpdateSprite(); } public int Level { get; set; } public bool Attacking { get; set; } public Rectangle AttackBox => new Rectangle ( (int) (GameObject.Transform.Position.X + spriteRenderer.Offset.X - 15), (int) (GameObject.Transform.Position.Y + spriteRenderer.Offset.Y), spriteRenderer.Rectangle.Width + 30, spriteRenderer.Rectangle.Height ); /// <summary> /// runs a switch based on level and changes looks, cost and damage. /// </summary> private void UpdateSprite() { switch (Level) { case 1: spriteName = "stick"; reach = Level; damage = Level; cost = 20; break; case 2: spriteName = "shortsword"; reach = Level; damage = Level; cost = 50; break; case 3: spriteName = "handaxe"; reach = Level; damage = Level; cost = 80; break; case 4: spriteName = "battleaxe"; reach = Level; damage = Level; cost = 110; break; case 5: spriteName = "morningstar"; reach = Level; damage = Level; cost = 140; break; case 6: spriteName = "jala"; reach = Level; damage = Level; cost = 140; break; default: break; } damage = damage * 10; } /// <summary> /// updates the weapon and reloads the content /// </summary> public void UpdateStats() { UpdateSprite(); LoadContent(GameWorld.Instance.Content); } /// <summary> /// runs logic for leveling up and attacking /// </summary> public void Update() { if (oldLevel != Level) UpdateStats(); oldLevel = Level; if (Keyboard.GetState().IsKeyDown(Keys.Space)) { if (!Attacking) { Attacking = true; } } else { Attacking = false; haveAttacked = false; rotation = 0; pos = GameWorld.Instance.Player.GameObject.Transform.Position; spriteRenderer.OverlayColor = Color.White; } if (GameWorld.Instance.Player.Direction == Direction.Right) { if (Attacking) { pos = GameWorld.Instance.Player.GameObject.Transform.Position + new Vector2(5, -10); } else { pos = GameWorld.Instance.Player.GameObject.Transform.Position + new Vector2(-5, -10); } } else { if (Attacking) { pos = GameWorld.Instance.Player.GameObject.Transform.Position + new Vector2(-5, -10); } else { pos = GameWorld.Instance.Player.GameObject.Transform.Position + new Vector2(5, -10); } } if (Attacking && !haveAttacked) { for (var i = 0; i < GameWorld.Instance.StandardColliders.Count; i++) if (i <= GameWorld.Instance.StandardColliders.Count) if (GameWorld.Instance.StandardColliders[i].GameObject != GameObject) if (GameWorld.Instance.StandardColliders[i].CollisionBox.Intersects(AttackBox)) { var en = GameWorld.Instance.StandardColliders[i].GameObject.GetComponent("Enemy") as Enemy; if (en != null) { haveAttacked = true; if (GameWorld.Instance.Player.Direction == Direction.Left) { if (en.GameObject.Transform.Position.X < GameObject.Transform.Position.X + AttackBox.Width / 2) en.TakeDamage(damage); } else { if (en.GameObject.Transform.Position.X > GameObject.Transform.Position.X + AttackBox.Width / 2) en.TakeDamage(damage); } break; } } haveAttacked = true; } } /// <summary> /// draws the weapon /// </summary> /// <param name="spriteBatch"></param> public void Draw(SpriteBatch spriteBatch) { if (GameWorld.Instance.Player.Direction == Direction.Left) spriteBatch.Draw(sprite, new Vector2(pos.X - 40, pos.Y), rectangle, overlayColor, rotation, Vector2.Zero, scale, SpriteEffects.FlipHorizontally, 0.7f); else spriteBatch.Draw(sprite, new Vector2(pos.X + 40, pos.Y), rectangle, overlayColor, rotation, Vector2.Zero, scale, SpriteEffects.None, 0.7f); #if DEBUG var topLine = new Rectangle(AttackBox.X, AttackBox.Y, AttackBox.Width, 1); var bottomLine = new Rectangle(AttackBox.X, AttackBox.Y + AttackBox.Height, AttackBox.Width, 1); var rightLine = new Rectangle(AttackBox.X + AttackBox.Width, AttackBox.Y, 1, AttackBox.Height); var leftLine = new Rectangle(AttackBox.X, AttackBox.Y, 1, AttackBox.Height); spriteBatch.Draw(attackTexture, topLine, null, Color.Blue, 0, Vector2.Zero, SpriteEffects.None, 1); spriteBatch.Draw(attackTexture, bottomLine, null, Color.Blue, 0, Vector2.Zero, SpriteEffects.None, 1); spriteBatch.Draw(attackTexture, rightLine, null, Color.Blue, 0, Vector2.Zero, SpriteEffects.None, 1); spriteBatch.Draw(attackTexture, leftLine, null, Color.Blue, 0, Vector2.Zero, SpriteEffects.None, 1); #endif } /// <summary> /// loads all content /// </summary> /// <param name="content"></param> public void LoadContent(ContentManager content) { attackTexture = content.Load<Texture2D>("CollisionTexture"); sprite = content.Load<Texture2D>(spriteName); rectangle = new Rectangle(0, 0, sprite.Width, sprite.Height); spriteRenderer = GameObject.GetComponent("SpriteRenderer") as SpriteRenderer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; namespace System.Runtime.Serialization { #if NET_NATIVE public class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext #else internal class XmlObjectSerializerReadContextComplex : XmlObjectSerializerReadContext #endif { private bool _preserveObjectReferences; private SerializationMode _mode; private ISerializationSurrogateProvider _serializationSurrogateProvider; internal XmlObjectSerializerReadContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { _mode = SerializationMode.SharedContract; _preserveObjectReferences = serializer.PreserveObjectReferences; _serializationSurrogateProvider = serializer.SerializationSurrogateProvider; } internal XmlObjectSerializerReadContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override SerializationMode Mode { get { return _mode; } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, string name, string ns) { if (_mode == SerializationMode.SharedContract) { if (_serializationSurrogateProvider == null) return base.InternalDeserialize(xmlReader, declaredTypeID, declaredTypeHandle, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, Type.GetTypeFromHandle(declaredTypeHandle), null /*surrogateDataContract*/, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, declaredTypeID, Type.GetTypeFromHandle(declaredTypeHandle), name, ns); } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { if (_mode == SerializationMode.SharedContract) { if (_serializationSurrogateProvider == null) return base.InternalDeserialize(xmlReader, declaredType, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, declaredType, null /*surrogateDataContract*/, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } } internal override object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (_mode == SerializationMode.SharedContract) { if (_serializationSurrogateProvider == null) return base.InternalDeserialize(xmlReader, declaredType, dataContract, name, ns); else return InternalDeserializeWithSurrogate(xmlReader, declaredType, dataContract, name, ns); } else { return InternalDeserializeInSharedTypeMode(xmlReader, -1, declaredType, name, ns); } } private object InternalDeserializeInSharedTypeMode(XmlReaderDelegator xmlReader, int declaredTypeID, Type declaredType, string name, string ns) { object retObj = null; if (TryHandleNullOrRef(xmlReader, declaredType, name, ns, ref retObj)) return retObj; DataContract dataContract; string assemblyName = attributes.ClrAssembly; string typeName = attributes.ClrType; if (assemblyName != null && typeName != null) { Assembly assembly; Type type; dataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type); if (dataContract == null) { if (assembly == null) throw XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.AssemblyNotFound, assemblyName)); if (type == null) throw XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.ClrTypeNotFound, assembly.FullName, typeName)); } //Array covariance is not supported in XSD. If declared type is array, data is sent in format of base array if (declaredType != null && declaredType.IsArray) dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle); } else { if (assemblyName != null) throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, string.Format(SRSerialization.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))); else if (typeName != null) throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, string.Format(SRSerialization.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))); else if (declaredType == null) throw XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, string.Format(SRSerialization.AttributeNotFound, Globals.SerializationNamespace, Globals.ClrTypeLocalName, xmlReader.NodeType, xmlReader.NamespaceURI, xmlReader.LocalName))); dataContract = (declaredTypeID < 0) ? GetDataContract(declaredType) : GetDataContract(declaredTypeID, declaredType.TypeHandle); } return ReadDataContractValue(dataContract, xmlReader); } private object InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, string name, string ns) { DataContract dataContract = surrogateDataContract ?? GetDataContract(DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, declaredType)); if (this.IsGetOnlyCollection && dataContract.UnderlyingType != declaredType) { throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(declaredType)))); } ReadAttributes(xmlReader); string objectId = GetObjectId(); object oldObj = InternalDeserialize(xmlReader, name, ns, ref dataContract); object obj = DataContractSurrogateCaller.GetDeserializedObject(_serializationSurrogateProvider, oldObj, dataContract.UnderlyingType, declaredType); ReplaceDeserializedObject(objectId, oldObj, obj); return obj; } private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly) { throw new PlatformNotSupportedException(); } private DataContract ResolveDataContractInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly, out Type type) { type = ResolveDataContractTypeInSharedTypeMode(assemblyName, typeName, out assembly); if (type != null) { return GetDataContract(type); } return null; } protected override DataContract ResolveDataContractFromTypeName() { if (_mode == SerializationMode.SharedContract) { return base.ResolveDataContractFromTypeName(); } else { if (attributes.ClrAssembly != null && attributes.ClrType != null) { Assembly assembly; Type type; return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type); } } return null; } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (_serializationSurrogateProvider != null) { while (memberType.IsArray) memberType = memberType.GetElementType(); memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType); if (!DataContract.IsTypeSerializable(memberType)) throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.TypeNotSerializable, memberType))); return; } base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } internal override Type GetSurrogatedType(Type type) { if (_serializationSurrogateProvider == null) { return base.GetSurrogatedType(type); } else { type = DataContract.UnwrapNullableType(type); Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type); if (this.IsGetOnlyCollection && surrogateType != type) { throw /*System.Runtime.Serialization.*/DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(string.Format(SRSerialization.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(type)))); } else { return surrogateType; } } } #if USE_REFEMIT public override int GetArraySize() #else internal override int GetArraySize() #endif { return _preserveObjectReferences ? attributes.ArraySZSize : -1; } } }
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using System.Collections.Generic; using SharpNav.Collections.Generic; using SharpNav.Geometry; using SharpNav.Pathfinding; #if MONOGAME using Vector3 = Microsoft.Xna.Framework.Vector3; #elif OPENTK using Vector3 = OpenTK.Vector3; #elif SHARPDX using Vector3 = SharpDX.Vector3; #endif namespace SharpNav.Crowds { public class PathQueue { #region Fields public const int Invalid = 0; private const int MaxQueue = 8; private const int MaxKeepAlive = 2; //in number of times Update() is called private PathQuery[] queue; private int nextHandle = 1; private int queueHead; private NavMeshQuery navquery; private NavQueryFilter navqueryfilter; #endregion #region Constructors public PathQueue(int maxSearchNodeCount, ref TiledNavMesh nav) { this.navquery = new NavMeshQuery(nav, maxSearchNodeCount); this.navqueryfilter = new NavQueryFilter(); this.queue = new PathQuery[MaxQueue]; for (int i = 0; i < MaxQueue; i++) { queue[i].Index = 0; queue[i].Path = new Path(); } this.queueHead = 0; } #endregion #region Methods public void Update(int maxIters) { //update path request until there is nothing left to update //or up to maxIters pathfinder iterations have been consumed int iterCount = maxIters; for (int i = 0; i < MaxQueue; i++) { PathQuery q = queue[queueHead % MaxQueue]; //skip inactive requests if (q.Index == 0) { queueHead++; continue; } //handle completed request if (q.Status == Status.Success || q.Status == Status.Failure) { q.KeepAlive++; if (q.KeepAlive > MaxKeepAlive) { q.Index = 0; q.Status = 0; } queueHead++; continue; } //handle query start if (q.Status == 0) { q.Status = navquery.InitSlicedFindPath(ref q.Start, ref q.End, navqueryfilter, FindPathOptions.None).ToStatus(); } //handle query in progress if (q.Status == Status.InProgress) { int iters = 0; q.Status = navquery.UpdateSlicedFindPath(iterCount, ref iters).ToStatus(); iterCount -= iters; } if (q.Status == Status.Success) { q.Status = navquery.FinalizeSlicedFindPath(q.Path).ToStatus(); } if (iterCount <= 0) break; queueHead++; } } /// <summary> /// Request an empty slot in the path queue /// </summary> /// <param name="start">Start position</param> /// <param name="end">End position</param> /// <returns>Index of empty slot</returns> public int Request(NavPoint start, NavPoint end) { //find empty slot int slot = -1; for (int i = 0; i < MaxQueue; i++) { if (queue[i].Index == 0) { slot = i; break; } } //could not find slot if (slot == -1) return PathQueue.Invalid; int index = nextHandle++; if (nextHandle == 0) nextHandle++; PathQuery q = queue[slot]; q.Index = index; q.Start = start; q.End = end; q.Status = 0; q.PathCount = 0; q.KeepAlive = 0; queue[slot] = q; return index; } /// <summary> /// Get the status of the polygon in the path queue /// </summary> /// <param name="reference">The polygon reference</param> /// <returns>The status in the queue</returns> public Status GetRequestStatus(int index) { for (int i = 0; i < MaxQueue; i++) { if (queue[i].Index == index) return queue[i].Status; } return Status.Failure; } public bool GetPathResult(int index, out Path path) { path = null; for (int i = 0; i < MaxQueue; i++) { if (queue[i].Index == index) { PathQuery q = queue[i]; //free request for reuse q.Index = 0; q.Status = 0; path = new Path(q.Path); queue[i] = q; return true; } } return false; } #endregion private struct PathQuery { public int Index; //path find start and end location public NavPoint Start, End; //result public Path Path; public int PathCount; //state public Status Status; public int KeepAlive; } } }
using UnityEngine; //using Windows.Kinect; using System.Collections; using System.Runtime.InteropServices; using System; using System.IO; /// <summary> /// Interaction manager is the component that deals with hand interactions. /// </summary> public class InteractionManager : MonoBehaviour { /// <summary> /// The hand event types. /// </summary> public enum HandEventType : int { None = 0, Grip = 1, Release = 2 } [Tooltip("Index of the player, tracked by this component. 0 means the 1st player, 1 - the 2nd one, 2 - the 3rd one, etc.")] public int playerIndex = 0; [Tooltip("Whether to use the GUI hand-cursor as on-screen cursor.")] public bool useHandCursor = true; [Tooltip("Hand-cursor texture for the hand-grip state.")] public Texture gripHandTexture; [Tooltip("Hand-cursor texture for the hand-release state.")] public Texture releaseHandTexture; [Tooltip("Hand-cursor texture for the non-tracked state.")] public Texture normalHandTexture; [Tooltip("Smooth factor for cursor movement.")] public float smoothFactor = 3f; [Tooltip("Whether hand clicks (hand not moving for ~2 seconds) are enabled or not.")] public bool allowHandClicks = true; [Tooltip("Whether hand cursor and interactions control the mouse cursor or not.")] public bool controlMouseCursor = false; [Tooltip("Whether hand grips and releases control mouse dragging or not.")] public bool controlMouseDrag = false; // Bool to specify whether to convert Unity screen coordinates to full screen mouse coordinates //public bool convertMouseToFullScreen = false; [Tooltip("GUI-Text to display the interaction-manager debug messages.")] public GUIText debugText; private long primaryUserID = 0; private bool isLeftHandPrimary = false; private bool isRightHandPrimary = false; private bool isLeftHandPress = false; private bool isRightHandPress = false; private Vector3 cursorScreenPos = Vector3.zero; private bool dragInProgress = false; private KinectInterop.HandState leftHandState = KinectInterop.HandState.Unknown; private KinectInterop.HandState rightHandState = KinectInterop.HandState.Unknown; private HandEventType leftHandEvent = HandEventType.None; private HandEventType lastLeftHandEvent = HandEventType.Release; private Vector3 leftHandPos = Vector3.zero; private Vector3 leftHandScreenPos = Vector3.zero; private Vector3 leftIboxLeftBotBack = Vector3.zero; private Vector3 leftIboxRightTopFront = Vector3.zero; private bool isleftIboxValid = false; private bool isLeftHandInteracting = false; private float leftHandInteractingSince = 0f; private Vector3 lastLeftHandPos = Vector3.zero; private float lastLeftHandTime = 0f; private bool isLeftHandClick = false; private float leftHandClickProgress = 0f; private HandEventType rightHandEvent = HandEventType.None; private HandEventType lastRightHandEvent = HandEventType.Release; private Vector3 rightHandPos = Vector3.zero; private Vector3 rightHandScreenPos = Vector3.zero; private Vector3 rightIboxLeftBotBack = Vector3.zero; private Vector3 rightIboxRightTopFront = Vector3.zero; private bool isRightIboxValid = false; private bool isRightHandInteracting = false; private float rightHandInteractingSince = 0f; private Vector3 lastRightHandPos = Vector3.zero; private float lastRightHandTime = 0f; private bool isRightHandClick = false; private float rightHandClickProgress = 0f; // Bool to keep track whether Kinect and Interaction library have been initialized private bool interactionInited = false; // The single instance of FacetrackingManager private static InteractionManager instance; /// <summary> /// Gets the single InteractionManager instance. /// </summary> /// <value>The InteractionManager instance.</value> public static InteractionManager Instance { get { return instance; } } /// <summary> /// Determines whether the InteractionManager was successfully initialized. /// </summary> /// <returns><c>true</c> if InteractionManager was successfully initialized; otherwise, <c>false</c>.</returns> public bool IsInteractionInited() { return interactionInited; } /// <summary> /// Gets the current user ID, or 0 if no user is currently tracked. /// </summary> /// <returns>The user ID</returns> public long GetUserID() { return primaryUserID; } /// <summary> /// Gets the current left hand event (none, grip or release). /// </summary> /// <returns>The current left hand event.</returns> public HandEventType GetLeftHandEvent() { return leftHandEvent; } /// <summary> /// Gets the last detected left hand event (grip or release). /// </summary> /// <returns>The last left hand event.</returns> public HandEventType GetLastLeftHandEvent() { return lastLeftHandEvent; } /// <summary> /// Gets the current normalized viewport position of the left hand, in range [0, 1]. /// </summary> /// <returns>The left hand viewport position.</returns> public Vector3 GetLeftHandScreenPos() { return leftHandScreenPos; } /// <summary> /// Determines whether the left hand is primary for the user. /// </summary> /// <returns><c>true</c> if the left hand is primary for the user; otherwise, <c>false</c>.</returns> public bool IsLeftHandPrimary() { return isLeftHandPrimary; } /// <summary> /// Determines whether the left hand is pressing. /// </summary> /// <returns><c>true</c> if the left hand is pressing; otherwise, <c>false</c>.</returns> public bool IsLeftHandPress() { return isLeftHandPress; } /// <summary> /// Determines whether a left hand click is detected, false otherwise. /// </summary> /// <returns><c>true</c> if a left hand click is detected; otherwise, <c>false</c>.</returns> public bool IsLeftHandClickDetected() { if(isLeftHandClick) { isLeftHandClick = false; leftHandClickProgress = 0f; lastLeftHandPos = Vector3.zero; lastLeftHandTime = Time.realtimeSinceStartup; return true; } return false; } /// <summary> /// Gets the left hand click progress, in range [0, 1]. /// </summary> /// <returns>The left hand click progress.</returns> public float GetLeftHandClickProgress() { return leftHandClickProgress; } /// <summary> /// Gets the current right hand event (none, grip or release). /// </summary> /// <returns>The current right hand event.</returns> public HandEventType GetRightHandEvent() { return rightHandEvent; } /// <summary> /// Gets the last detected right hand event (grip or release). /// </summary> /// <returns>The last right hand event.</returns> public HandEventType GetLastRightHandEvent() { return lastRightHandEvent; } /// <summary> /// Gets the current normalized viewport position of the right hand, in range [0, 1]. /// </summary> /// <returns>The right hand viewport position.</returns> public Vector3 GetRightHandScreenPos() { return rightHandScreenPos; } /// <summary> /// Determines whether the right hand is primary for the user. /// </summary> /// <returns><c>true</c> if the right hand is primary for the user; otherwise, <c>false</c>.</returns> public bool IsRightHandPrimary() { return isRightHandPrimary; } /// <summary> /// Determines whether the right hand is pressing. /// </summary> /// <returns><c>true</c> if the right hand is pressing; otherwise, <c>false</c>.</returns> public bool IsRightHandPress() { return isRightHandPress; } /// <summary> /// Determines whether a right hand click is detected, false otherwise. /// </summary> /// <returns><c>true</c> if a right hand click is detected; otherwise, <c>false</c>.</returns> public bool IsRightHandClickDetected() { if(isRightHandClick) { isRightHandClick = false; rightHandClickProgress = 0f; lastRightHandPos = Vector3.zero; lastRightHandTime = Time.realtimeSinceStartup; return true; } return false; } /// <summary> /// Gets the right hand click progress, in range [0, 1]. /// </summary> /// <returns>The right hand click progress.</returns> public float GetRightHandClickProgress() { return rightHandClickProgress; } /// <summary> /// Gets the current cursor normalized viewport position. /// </summary> /// <returns>The cursor viewport position.</returns> public Vector3 GetCursorPosition() { return cursorScreenPos; } //----------------------------------- end of public functions --------------------------------------// void Start() { instance = this; interactionInited = true; } void OnDestroy() { // uninitialize Kinect interaction if(interactionInited) { interactionInited = false; instance = null; } } void Update () { KinectManager kinectManager = KinectManager.Instance; // update Kinect interaction if(kinectManager && kinectManager.IsInitialized()) { primaryUserID = kinectManager.GetUserIdByIndex(playerIndex); if(primaryUserID != 0) { HandEventType handEvent = HandEventType.None; // get the left hand state leftHandState = kinectManager.GetLeftHandState(primaryUserID); // check if the left hand is interacting isleftIboxValid = kinectManager.GetLeftHandInteractionBox(primaryUserID, ref leftIboxLeftBotBack, ref leftIboxRightTopFront, isleftIboxValid); //bool bLeftHandPrimaryNow = false; if(isleftIboxValid && //bLeftHandPrimaryNow && kinectManager.GetJointTrackingState(primaryUserID, (int)KinectInterop.JointType.HandLeft) != KinectInterop.TrackingState.NotTracked) { leftHandPos = kinectManager.GetJointPosition(primaryUserID, (int)KinectInterop.JointType.HandLeft); leftHandScreenPos.x = Mathf.Clamp01((leftHandPos.x - leftIboxLeftBotBack.x) / (leftIboxRightTopFront.x - leftIboxLeftBotBack.x)); leftHandScreenPos.y = Mathf.Clamp01((leftHandPos.y - leftIboxLeftBotBack.y) / (leftIboxRightTopFront.y - leftIboxLeftBotBack.y)); leftHandScreenPos.z = Mathf.Clamp01((leftIboxLeftBotBack.z - leftHandPos.z) / (leftIboxLeftBotBack.z - leftIboxRightTopFront.z)); bool wasLeftHandInteracting = isLeftHandInteracting; isLeftHandInteracting = (leftHandPos.x >= (leftIboxLeftBotBack.x - 1.0f)) && (leftHandPos.x <= (leftIboxRightTopFront.x + 0.5f)) && (leftHandPos.y >= (leftIboxLeftBotBack.y - 0.1f)) && (leftHandPos.y <= (leftIboxRightTopFront.y + 0.7f)) && (leftIboxLeftBotBack.z >= leftHandPos.z) && (leftIboxRightTopFront.z * 0.8f <= leftHandPos.z); //bLeftHandPrimaryNow = isLeftHandInteracting; if(!wasLeftHandInteracting && isLeftHandInteracting) { leftHandInteractingSince = Time.realtimeSinceStartup; } // check for left press isLeftHandPress = ((leftIboxRightTopFront.z - 0.1f) >= leftHandPos.z); // check for left hand click float fClickDist = (leftHandPos - lastLeftHandPos).magnitude; if(allowHandClicks && !dragInProgress && isLeftHandInteracting && (fClickDist < KinectInterop.Constants.ClickMaxDistance)) { if((Time.realtimeSinceStartup - lastLeftHandTime) >= KinectInterop.Constants.ClickStayDuration) { if(!isLeftHandClick) { isLeftHandClick = true; leftHandClickProgress = 1f; if(controlMouseCursor) { MouseControl.MouseClick(); isLeftHandClick = false; leftHandClickProgress = 0f; lastLeftHandPos = Vector3.zero; lastLeftHandTime = Time.realtimeSinceStartup; } } } else { leftHandClickProgress = (Time.realtimeSinceStartup - lastLeftHandTime) / KinectInterop.Constants.ClickStayDuration; } } else { isLeftHandClick = false; leftHandClickProgress = 0f; lastLeftHandPos = leftHandPos; lastLeftHandTime = Time.realtimeSinceStartup; } } else { isLeftHandInteracting = false; isLeftHandPress = false; } // get the right hand state rightHandState = kinectManager.GetRightHandState(primaryUserID); // check if the right hand is interacting isRightIboxValid = kinectManager.GetRightHandInteractionBox(primaryUserID, ref rightIboxLeftBotBack, ref rightIboxRightTopFront, isRightIboxValid); //bool bRightHandPrimaryNow = false; if(isRightIboxValid && //bRightHandPrimaryNow && kinectManager.GetJointTrackingState(primaryUserID, (int)KinectInterop.JointType.HandRight) != KinectInterop.TrackingState.NotTracked) { rightHandPos = kinectManager.GetJointPosition(primaryUserID, (int)KinectInterop.JointType.HandRight); rightHandScreenPos.x = Mathf.Clamp01((rightHandPos.x - rightIboxLeftBotBack.x) / (rightIboxRightTopFront.x - rightIboxLeftBotBack.x)); rightHandScreenPos.y = Mathf.Clamp01((rightHandPos.y - rightIboxLeftBotBack.y) / (rightIboxRightTopFront.y - rightIboxLeftBotBack.y)); rightHandScreenPos.z = Mathf.Clamp01((rightIboxLeftBotBack.z - rightHandPos.z) / (rightIboxLeftBotBack.z - rightIboxRightTopFront.z)); bool wasRightHandInteracting = isRightHandInteracting; isRightHandInteracting = (rightHandPos.x >= (rightIboxLeftBotBack.x - 0.5f)) && (rightHandPos.x <= (rightIboxRightTopFront.x + 1.0f)) && (rightHandPos.y >= (rightIboxLeftBotBack.y - 0.1f)) && (rightHandPos.y <= (rightIboxRightTopFront.y + 0.7f)) && (rightIboxLeftBotBack.z >= rightHandPos.z) && (rightIboxRightTopFront.z * 0.8f <= rightHandPos.z); //bRightHandPrimaryNow = isRightHandInteracting; if(!wasRightHandInteracting && isRightHandInteracting) { rightHandInteractingSince = Time.realtimeSinceStartup; } if(isLeftHandInteracting && isRightHandInteracting) { if(rightHandInteractingSince <= leftHandInteractingSince) isLeftHandInteracting = false; else isRightHandInteracting = false; } // check for right press isRightHandPress = ((rightIboxRightTopFront.z - 0.1f) >= rightHandPos.z); // check for right hand click float fClickDist = (rightHandPos - lastRightHandPos).magnitude; if(allowHandClicks && !dragInProgress && isRightHandInteracting && (fClickDist < KinectInterop.Constants.ClickMaxDistance)) { if((Time.realtimeSinceStartup - lastRightHandTime) >= KinectInterop.Constants.ClickStayDuration) { if(!isRightHandClick) { isRightHandClick = true; rightHandClickProgress = 1f; if(controlMouseCursor) { MouseControl.MouseClick(); isRightHandClick = false; rightHandClickProgress = 0f; lastRightHandPos = Vector3.zero; lastRightHandTime = Time.realtimeSinceStartup; } } } else { rightHandClickProgress = (Time.realtimeSinceStartup - lastRightHandTime) / KinectInterop.Constants.ClickStayDuration; } } else { isRightHandClick = false; rightHandClickProgress = 0f; lastRightHandPos = rightHandPos; lastRightHandTime = Time.realtimeSinceStartup; } } else { isRightHandInteracting = false; isRightHandPress = false; } // process left hand handEvent = HandStateToEvent(leftHandState, lastLeftHandEvent); if((isLeftHandInteracting != isLeftHandPrimary) || (isRightHandInteracting != isRightHandPrimary)) { if(controlMouseCursor && dragInProgress) { MouseControl.MouseRelease(); dragInProgress = false; } lastLeftHandEvent = HandEventType.Release; lastRightHandEvent = HandEventType.Release; } if(controlMouseCursor && (handEvent != lastLeftHandEvent)) { if(controlMouseDrag && !dragInProgress && (handEvent == HandEventType.Grip)) { dragInProgress = true; MouseControl.MouseDrag(); } else if(dragInProgress && (handEvent == HandEventType.Release)) { MouseControl.MouseRelease(); dragInProgress = false; } } leftHandEvent = handEvent; if(handEvent != HandEventType.None) { lastLeftHandEvent = handEvent; } // if the hand is primary, set the cursor position if(isLeftHandInteracting) { isLeftHandPrimary = true; if((leftHandClickProgress < 0.8f) /**&& !isLeftHandPress*/) { cursorScreenPos = Vector3.Lerp(cursorScreenPos, leftHandScreenPos, smoothFactor * Time.deltaTime); } // else // { // leftHandScreenPos = cursorScreenPos; // } if(controlMouseCursor && !useHandCursor) { MouseControl.MouseMove(cursorScreenPos, debugText); } } else { isLeftHandPrimary = false; } // process right hand handEvent = HandStateToEvent(rightHandState, lastRightHandEvent); if(controlMouseCursor && (handEvent != lastRightHandEvent)) { if(controlMouseDrag && !dragInProgress && (handEvent == HandEventType.Grip)) { dragInProgress = true; MouseControl.MouseDrag(); } else if(dragInProgress && (handEvent == HandEventType.Release)) { MouseControl.MouseRelease(); dragInProgress = false; } } rightHandEvent = handEvent; if(handEvent != HandEventType.None) { lastRightHandEvent = handEvent; } // if the hand is primary, set the cursor position if(isRightHandInteracting) { isRightHandPrimary = true; if((rightHandClickProgress < 0.8f) /**&& !isRightHandPress*/) { cursorScreenPos = Vector3.Lerp(cursorScreenPos, rightHandScreenPos, smoothFactor * Time.deltaTime); } // else // { // rightHandScreenPos = cursorScreenPos; // } if(controlMouseCursor && !useHandCursor) { MouseControl.MouseMove(cursorScreenPos, debugText); } } else { isRightHandPrimary = false; } } else { leftHandState = KinectInterop.HandState.NotTracked; rightHandState = KinectInterop.HandState.NotTracked; isLeftHandPrimary = false; isRightHandPrimary = false; isLeftHandPress = false; isRightHandPress = false; leftHandEvent = HandEventType.None; rightHandEvent = HandEventType.None; lastLeftHandEvent = HandEventType.Release; lastRightHandEvent = HandEventType.Release; if(controlMouseCursor && dragInProgress) { MouseControl.MouseRelease(); dragInProgress = false; } } } } // converts hand state to hand event type private HandEventType HandStateToEvent(KinectInterop.HandState handState, HandEventType lastEventType) { switch(handState) { case KinectInterop.HandState.Open: return HandEventType.Release; case KinectInterop.HandState.Closed: case KinectInterop.HandState.Lasso: return HandEventType.Grip; case KinectInterop.HandState.Unknown: return lastEventType; } return HandEventType.None; } void OnGUI() { if(!interactionInited) return; // display debug information if(debugText) { string sGuiText = string.Empty; //if(isLeftHandPrimary) { sGuiText += "LCursor: " + leftHandScreenPos.ToString(); if(lastLeftHandEvent == HandEventType.Grip) { sGuiText += " LeftGrip"; } else if(lastLeftHandEvent == HandEventType.Release) { sGuiText += " LeftRelease"; } if(isLeftHandClick) { sGuiText += " LeftClick"; } // else if(leftHandClickProgress > 0.5f) // { // sGuiText += String.Format(" {0:F0}%", leftHandClickProgress * 100); // } if(isLeftHandPress) { sGuiText += " LeftPress"; } } //if(isRightHandPrimary) { sGuiText += "\nRCursor: " + rightHandScreenPos.ToString(); if(lastRightHandEvent == HandEventType.Grip) { sGuiText += " RightGrip"; } else if(lastRightHandEvent == HandEventType.Release) { sGuiText += " RightRelease"; } if(isRightHandClick) { sGuiText += " RightClick"; } // else if(rightHandClickProgress > 0.5f) // { // sGuiText += String.Format(" {0:F0}%", rightHandClickProgress * 100); // } if(isRightHandPress) { sGuiText += " RightPress"; } } debugText.GetComponent<GUIText>().text = sGuiText; } // display the cursor status and position if(useHandCursor) { Texture texture = null; if(isLeftHandPrimary) { if(lastLeftHandEvent == HandEventType.Grip) texture = gripHandTexture; else if(lastLeftHandEvent == HandEventType.Release) texture = releaseHandTexture; } else if(isRightHandPrimary) { if(lastRightHandEvent == HandEventType.Grip) texture = gripHandTexture; else if(lastRightHandEvent == HandEventType.Release) texture = releaseHandTexture; } if(texture == null) { texture = normalHandTexture; } if(useHandCursor) { // if(handCursor.guiTexture && texture) // { // handCursor.guiTexture.texture = texture; // } if((texture != null) && (isLeftHandPrimary || isRightHandPrimary)) { //handCursor.transform.position = cursorScreenPos; // Vector3.Lerp(handCursor.transform.position, cursorScreenPos, 3 * Time.deltaTime); Rect rectTexture = new Rect(cursorScreenPos.x * Screen.width - texture.width / 2, (1f - cursorScreenPos.y) * Screen.height - texture.height / 2, texture.width, texture.height); GUI.DrawTexture(rectTexture, texture); if(controlMouseCursor) { MouseControl.MouseMove(cursorScreenPos, debugText); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Xml; using Xunit; namespace System.Data.Tests { public class DataSetReadXmlTest { private const string xml1 = ""; private const string xml2 = "<root/>"; private const string xml3 = "<root></root>"; private const string xml4 = "<root> </root>"; private const string xml5 = "<root>test</root>"; private const string xml6 = "<root><test>1</test></root>"; private const string xml7 = "<root><test>1</test><test2>a</test2></root>"; private const string xml8 = "<dataset><table><col1>foo</col1><col2>bar</col2></table></dataset>"; private const string xml29 = @"<PersonalSite><License Name='Sum Wang' Email='sumwang@somewhere.net' Mode='Trial' StartDate='01/01/2004' Serial='aaa' /></PersonalSite>"; private const string diff1 = @"<diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'> <NewDataSet> <Table1 diffgr:id='Table11' msdata:rowOrder='0' diffgr:hasChanges='inserted'> <Column1_1>ppp</Column1_1> <Column1_2>www</Column1_2> <Column1_3>xxx</Column1_3> </Table1> </NewDataSet> </diffgr:diffgram>"; private const string diff2 = diff1 + xml8; private const string schema1 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; private const string schema2 = schema1 + xml8; [Fact] public void ReadSimpleAuto() { DataSet ds; // empty XML ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1, XmlReadMode.Auto, XmlReadMode.Auto, "NewDataSet", 0); // simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2, XmlReadMode.Auto, XmlReadMode.InferSchema, "root", 0); // simple element2 ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3, XmlReadMode.Auto, XmlReadMode.InferSchema, "root", 0); // whitespace in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4, XmlReadMode.Auto, XmlReadMode.InferSchema, "root", 0); // text in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.Auto, XmlReadMode.InferSchema, "root", 0); // simple table pattern: // root becomes a table and test becomes a column. ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.Auto, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("xml6", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0); // simple table with 2 columns: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.Auto, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("xml7", ds.Tables[0], "root", 2, 1, 0, 0, 0, 0); // simple dataset with 1 table: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8, XmlReadMode.Auto, XmlReadMode.InferSchema, "dataset", 1); DataSetAssertion.AssertDataTable("xml8", ds.Tables[0], "table", 2, 1, 0, 0, 0, 0); } [Fact] public void ReadSimpleDiffgram() { DataSet ds; // empty XML ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // simple element2 ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // whitespace in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // text in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // simple table pattern: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // simple table with 2 columns: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); // simple dataset with 1 table: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); } [Fact] public void ReadSimpleFragment() { DataSet ds; // empty XML ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // simple element2 ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // whitespace in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // text in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // simple table pattern: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // simple table with 2 columns: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // simple dataset with 1 table: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); } [Fact] public void ReadSimpleIgnoreSchema() { DataSet ds; // empty XML ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // simple element2 ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // whitespace in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // text in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // simple table pattern: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // simple table with 2 columns: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); // simple dataset with 1 table: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); } [Fact] public void ReadSimpleInferSchema() { DataSet ds; // empty XML ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 0); // simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "root", 0); // simple element2 ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "root", 0); // whitespace in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "root", 0); // text in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "root", 0); // simple table pattern: // root becomes a table and test becomes a column. ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("xml6", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0); // simple table with 2 columns: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("xml7", ds.Tables[0], "root", 2, 1, 0, 0, 0, 0); // simple dataset with 1 table: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "dataset", 1); DataSetAssertion.AssertDataTable("xml8", ds.Tables[0], "table", 2, 1, 0, 0, 0, 0); } [Fact] public void ReadSimpleReadSchema() { DataSet ds; // empty XML ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyString", xml1, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "EmptyElement", xml2, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // simple element2 ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "StartEndTag", xml3, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // whitespace in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Whitespace", xml4, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // text in simple element ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // simple table pattern: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // simple table with 2 columns: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // simple dataset with 1 table: ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleDataSet", xml8, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); } [Fact] public void TestSimpleDiffXmlAll() { DataSet ds; // ignored ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Fragment", diff1, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", diff1, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "InferSchema", diff1, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "ReadSchema", diff1, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0); // Auto, DiffGram ... treated as DiffGram ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Auto", diff1, XmlReadMode.Auto, XmlReadMode.DiffGram, "NewDataSet", 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "DiffGram", diff1, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0); } [Fact] public void TestSimpleDiffPlusContentAll() { DataSet ds; // Fragment ... skipped ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Fragment", diff2, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 0); // others ... kept ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", diff2, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0, ReadState.Interactive); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "InferSchema", diff2, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 0, ReadState.Interactive); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "ReadSchema", diff2, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 0, ReadState.Interactive); // Auto, DiffGram ... treated as DiffGram ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Auto", diff2, XmlReadMode.Auto, XmlReadMode.DiffGram, "NewDataSet", 0, ReadState.Interactive); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "DiffGram", diff2, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 0, ReadState.Interactive); } [Fact] public void TestSimpleSchemaXmlAll() { DataSet ds; // ignored ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", schema1, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "InferSchema", schema1, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 0); // misc ... consume schema ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Fragment", schema1, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 1); DataSetAssertion.AssertDataTable("fragment", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "ReadSchema", schema1, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("readschema", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Auto", schema1, XmlReadMode.Auto, XmlReadMode.ReadSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("auto", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "DiffGram", schema1, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 1); } [Fact] public void TestSimpleSchemaPlusContentAll() { DataSet ds; // ignored ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "IgnoreSchema", schema2, XmlReadMode.IgnoreSchema, XmlReadMode.IgnoreSchema, "NewDataSet", 0, ReadState.Interactive); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "InferSchema", schema2, XmlReadMode.InferSchema, XmlReadMode.InferSchema, "NewDataSet", 0, ReadState.Interactive); // Fragment ... consumed both ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Fragment", schema2, XmlReadMode.Fragment, XmlReadMode.Fragment, "NewDataSet", 1); DataSetAssertion.AssertDataTable("fragment", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // rest ... treated as schema ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "Auto", schema2, XmlReadMode.Auto, XmlReadMode.ReadSchema, "NewDataSet", 1, ReadState.Interactive); DataSetAssertion.AssertDataTable("auto", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "DiffGram", schema2, XmlReadMode.DiffGram, XmlReadMode.DiffGram, "NewDataSet", 1, ReadState.Interactive); DataSetAssertion.AssertDataTable("diffgram", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "ReadSchema", schema2, XmlReadMode.ReadSchema, XmlReadMode.ReadSchema, "NewDataSet", 1, ReadState.Interactive); } [Fact] public void SequentialRead1() { // simple element -> simple table var ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.Auto, XmlReadMode.InferSchema, "root", 0); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.Auto, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("seq1", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0); } [Fact] public void SequentialRead2() { // simple element -> simple dataset var ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SingleText", xml5, XmlReadMode.Auto, XmlReadMode.InferSchema, "root", 0); DataSetAssertion.AssertReadXml(ds, "SimpleTable2", xml7, XmlReadMode.Auto, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("#1", ds.Tables[0], "root", 2, 1, 0, 0, 0, 0); // simple table -> simple dataset ds = new DataSet(); DataSetAssertion.AssertReadXml(ds, "SimpleTable", xml6, XmlReadMode.Auto, XmlReadMode.InferSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("#2", ds.Tables[0], "root", 1, 1, 0, 0, 0, 0); // Return value became IgnoreSchema, since there is // already schema information in the dataset. // Columns are kept 1 as old table holds. // Rows are up to 2 because of accumulative read. DataSetAssertion.AssertReadXml(ds, "SimpleTable2-2", xml7, XmlReadMode.Auto, XmlReadMode.IgnoreSchema, "NewDataSet", 1); DataSetAssertion.AssertDataTable("#3", ds.Tables[0], "root", 1, 2, 0, 0, 0, 0); } [Fact] public void ReadComplexElementDocument() { var ds = new DataSet(); ds.ReadXml(new StringReader(xml29)); } [Fact] public void IgnoreSchemaShouldFillData() { // no such dataset string xml1 = "<set><tab><col>test</col></tab></set>"; // no wrapper element string xml2 = "<tab><col>test</col></tab>"; // no such table string xml3 = "<tar><col>test</col></tar>"; var ds = new DataSet(); DataTable dt = new DataTable("tab"); ds.Tables.Add(dt); dt.Columns.Add("col"); ds.ReadXml(new StringReader(xml1), XmlReadMode.IgnoreSchema); DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0); Assert.Equal(1, dt.Rows.Count); dt.Clear(); ds.ReadXml(new StringReader(xml2), XmlReadMode.IgnoreSchema); Assert.Equal(1, dt.Rows.Count); dt.Clear(); ds.ReadXml(new StringReader(xml3), XmlReadMode.IgnoreSchema); Assert.Equal(0, dt.Rows.Count); } [Fact] public void NameConflictDSAndTable() { string xml = @"<PriceListDetails> <PriceListList> <Id>1</Id> </PriceListList> <PriceListDetails> <Id>1</Id> <Status>0</Status> </PriceListDetails> </PriceListDetails>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); Assert.NotNull(ds.Tables["PriceListDetails"]); } [Fact] public void ColumnOrder() { string xml = "<?xml version=\"1.0\" standalone=\"yes\"?>" + "<NewDataSet>" + " <Table>" + " <Name>Miguel</Name>" + " <FirstName>de Icaza</FirstName>" + " <Income>4000</Income>" + " </Table>" + " <Table>" + " <Name>25</Name>" + " <FirstName>250</FirstName>" + " <Address>Belgium</Address>" + " <Income>5000</Income>" + "</Table>" + "</NewDataSet>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); Assert.Equal(1, ds.Tables.Count); Assert.Equal("Table", ds.Tables[0].TableName); Assert.Equal(4, ds.Tables[0].Columns.Count); Assert.Equal("Name", ds.Tables[0].Columns[0].ColumnName); Assert.Equal(0, ds.Tables[0].Columns[0].Ordinal); Assert.Equal("FirstName", ds.Tables[0].Columns[1].ColumnName); Assert.Equal(1, ds.Tables[0].Columns[1].Ordinal); Assert.Equal("Address", ds.Tables[0].Columns[2].ColumnName); Assert.Equal(2, ds.Tables[0].Columns[2].Ordinal); Assert.Equal("Income", ds.Tables[0].Columns[3].ColumnName); Assert.Equal(3, ds.Tables[0].Columns[3].Ordinal); } [Fact] public void XmlSpace() { string xml = "<?xml version=\"1.0\" standalone=\"yes\"?>" + "<NewDataSet>" + " <Table>" + " <Name>Miguel</Name>" + " <FirstName xml:space=\"preserve\"> de Icaza</FirstName>" + " <Income>4000</Income>" + " </Table>" + " <Table>" + " <Name>Chris</Name>" + " <FirstName xml:space=\"preserve\">Toshok </FirstName>" + " <Income>3000</Income>" + " </Table>" + "</NewDataSet>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); Assert.Equal(1, ds.Tables.Count); Assert.Equal("Table", ds.Tables[0].TableName); Assert.Equal(3, ds.Tables[0].Columns.Count); Assert.Equal("Name", ds.Tables[0].Columns[0].ColumnName); Assert.Equal(0, ds.Tables[0].Columns[0].Ordinal); Assert.Equal("FirstName", ds.Tables[0].Columns[1].ColumnName); Assert.Equal(1, ds.Tables[0].Columns[1].Ordinal); Assert.Equal("Income", ds.Tables[0].Columns[2].ColumnName); Assert.Equal(2, ds.Tables[0].Columns[2].Ordinal); } public void TestSameParentChildName() { string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><resource type=\"parent\">" + "<resource type=\"child\" /></resource>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); DataSetAssertion.AssertReadXml(ds, "SameNameParentChild", xml, XmlReadMode.Auto, XmlReadMode.IgnoreSchema, "NewDataSet", 1); } public void TestSameColumnName() { string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><resource resource_Id_0=\"parent\">" + "<resource resource_Id_0=\"child\" /></resource>"; var ds = new DataSet(); ds.ReadXml(new StringReader(xml)); DataSetAssertion.AssertReadXml(ds, "SameColumnName", xml, XmlReadMode.Auto, XmlReadMode.IgnoreSchema, "NewDataSet", 1); } [Fact] public void DataSetExtendedPropertiesTest() { DataSet dataSet1 = new DataSet(); dataSet1.ExtendedProperties.Add("DS1", "extended0"); DataTable table = new DataTable("TABLE1"); table.ExtendedProperties.Add("T1", "extended1"); table.Columns.Add("C1", typeof(int)); table.Columns.Add("C2", typeof(string)); table.Columns[1].MaxLength = 20; table.Columns[0].ExtendedProperties.Add("C1Ext1", "extended2"); table.Columns[1].ExtendedProperties.Add("C2Ext1", "extended3"); dataSet1.Tables.Add(table); table.LoadDataRow(new object[] { 1, "One" }, false); table.LoadDataRow(new object[] { 2, "Two" }, false); string file = Path.Combine(Path.GetTempPath(), "schemas-test.xml"); try { dataSet1.WriteXml(file, XmlWriteMode.WriteSchema); } catch (Exception ex) { Assert.False(true); } finally { File.Delete(file); } DataSet dataSet2 = new DataSet(); dataSet2.ReadXml(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <NewDataSet> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" xmlns:msprop=""urn:schemas-microsoft-com:xml-msprop""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:UseCurrentLocale=""true"" msprop:DS1=""extended0""> <xs:complexType> <xs:choice minOccurs=""0"" maxOccurs=""unbounded""> <xs:element name=""TABLE1"" msprop:T1=""extended1""> <xs:complexType> <xs:sequence> <xs:element name=""C1"" type=""xs:int"" minOccurs=""0"" msprop:C1Ext1=""extended2"" /> <xs:element name=""C2"" type=""xs:string"" minOccurs=""0"" msprop:C2Ext1=""extended3"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <TABLE1> <C1>1</C1> <C2>One</C2> </TABLE1> <TABLE1> <C1>2</C1> <C2>Two</C2> </TABLE1> </NewDataSet>"), XmlReadMode.ReadSchema); Assert.Equal(dataSet1.ExtendedProperties["DS1"], dataSet2.ExtendedProperties["DS1"]); Assert.Equal(dataSet1.Tables[0].ExtendedProperties["T1"], dataSet2.Tables[0].ExtendedProperties["T1"]); Assert.Equal(dataSet1.Tables[0].Columns[0].ExtendedProperties["C1Ext1"], dataSet2.Tables[0].Columns[0].ExtendedProperties["C1Ext1"]); Assert.Equal(dataSet1.Tables[0].Columns[1].ExtendedProperties["C2Ext1"], dataSet2.Tables[0].Columns[1].ExtendedProperties["C2Ext1"]); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Buffers.Tests { public class BufferReferenceTests { public static void TestOwnedBuffer(Func<OwnedBuffer<byte>> create) { BufferLifetimeBasics(create()); MemoryHandleDoubleFree(create()); AsSpan(create()); Buffer(create()); Pin(create()); Dispose(create()); // OverRelease(create()); // TODO: corfxlab #1571 TestBuffer(() => { return create().Buffer; }); } static void MemoryAccessBasics(OwnedBuffer<byte> buffer) { var span = buffer.AsSpan(); span[10] = 10; Assert.Equal(buffer.Length, span.Length); Assert.Equal(10, span[10]); var memory = buffer.Buffer; Assert.Equal(buffer.Length, memory.Length); Assert.Equal(10, memory.Span[10]); var array = memory.ToArray(); Assert.Equal(buffer.Length, array.Length); Assert.Equal(10, array[10]); Span<byte> copy = new byte[20]; memory.Slice(10, 20).CopyTo(copy); Assert.Equal(10, copy[0]); } // tests OwnedBuffer.AsSpan overloads static void AsSpan(OwnedBuffer<byte> buffer) { var span = buffer.AsSpan(); var fullSlice = buffer.AsSpan(0, buffer.Length); for (int i = 0; i < span.Length; i++) { span[i] = (byte)(i % 254 + 1); Assert.Equal(span[i], fullSlice[i]); } var slice = buffer.AsSpan(5, buffer.Length - 5); Assert.Equal(span.Length - 5, slice.Length); for (int i = 0; i < slice.Length; i++) { Assert.Equal(span[i + 5], slice[i]); } Assert.Throws<ArgumentOutOfRangeException>(() => { buffer.AsSpan(buffer.Length, 1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { buffer.AsSpan(1, buffer.Length); }); } // tests that OwnedBuffer.Buffer and OwnedBuffer.ReadOnlyBuffer point to the same memory static void Buffer(OwnedBuffer<byte> buffer) { var rwBuffer = buffer.Buffer; var rwSpan = rwBuffer.Span; var roBuffer = buffer.ReadOnlyBuffer; var roSpan = roBuffer.Span; Assert.Equal(roSpan.Length, rwSpan.Length); for (int i = 0; i < roSpan.Length; i++) { var value = roSpan[i]; byte newValue = (byte)(value + 1); rwSpan[i] = newValue; Assert.Equal(newValue, roSpan[i]); } } static void Pin(OwnedBuffer<byte> buffer) { var memory = buffer.Buffer; Assert.False(buffer.IsRetained); var handle = memory.Retain(pin: true); unsafe { Assert.NotEqual(0L, new IntPtr(handle.PinnedPointer).ToInt64()); } Assert.True(buffer.IsRetained); handle.Dispose(); Assert.False(buffer.IsRetained); } static void Dispose(OwnedBuffer<byte> buffer) { var length = buffer.Length; buffer.Dispose(); Assert.True(buffer.IsDisposed); Assert.False(buffer.IsRetained); Assert.ThrowsAny<ObjectDisposedException>(() => { buffer.AsSpan(); }); Assert.ThrowsAny<ObjectDisposedException>(() => { buffer.AsSpan(0, length); }); Assert.ThrowsAny<ObjectDisposedException>(() => { buffer.Pin(); }); Assert.ThrowsAny<ObjectDisposedException>(() => { var rwBuffer = buffer.Buffer; }); Assert.ThrowsAny<ObjectDisposedException>(() => { var roBuffer = buffer.ReadOnlyBuffer; }); } static void OverRelease(OwnedBuffer<byte> buffer) { Assert.ThrowsAny<InvalidOperationException>(() => { buffer.Release(); }); } static void BufferLifetimeBasics(OwnedBuffer<byte> buffer) { Buffer<byte> copyStoredForLater; try { Buffer<byte> memory = buffer.Buffer; Buffer<byte> slice = memory.Slice(10); copyStoredForLater = slice; var handle = slice.Retain(); try { Assert.Throws<InvalidOperationException>(() => { // memory is reserved; premature dispose check fires buffer.Dispose(); }); } finally { handle.Dispose(); // release reservation } } finally { buffer.Dispose(); // can finish dispose with no exception } Assert.ThrowsAny<ObjectDisposedException>(() => { // memory is disposed; cannot use copy stored for later var span = copyStoredForLater.Span; }); Assert.True(buffer.IsDisposed); } static void MemoryHandleDoubleFree(OwnedBuffer<byte> buffer) { var memory = buffer.Buffer; var handle = memory.Retain(pin: true); Assert.True(buffer.IsRetained); buffer.Retain(); Assert.True(buffer.IsRetained); handle.Dispose(); Assert.True(buffer.IsRetained); handle.Dispose(); Assert.True(buffer.IsRetained); buffer.Release(); Assert.False(buffer.IsRetained); } public static void TestBuffer(Func<Buffer<byte>> create) { BufferBasics(create()); BufferLifetime(create()); } public static void TestBuffer(Func<ReadOnlyBuffer<byte>> create) { BufferBasics(create()); BufferLifetime(create()); } static void BufferBasics(Buffer<byte> buffer) { var span = buffer.Span; Assert.Equal(buffer.Length, span.Length); Assert.True(buffer.IsEmpty || buffer.Length != 0); Assert.True(!buffer.IsEmpty || buffer.Length == 0); for (int i = 0; i < span.Length; i++) span[i] = 100; var array = buffer.ToArray(); for (int i = 0; i < array.Length; i++) Assert.Equal(array[i], span[i]); if (buffer.TryGetArray(out var segment)) { Assert.Equal(segment.Count, array.Length); for (int i = 0; i < array.Length; i++) Assert.Equal(array[i], segment.Array[i + segment.Offset]); } if (buffer.Length > 0) { var slice = buffer.Slice(1); for (int i = 0; i < slice.Length; i++) slice.Span[i] = 101; for (int i = 0; i < slice.Length; i++) Assert.Equal(slice.Span[i], span[i + 1]); } } static void BufferLifetime(Buffer<byte> buffer) { var array = buffer.ToArray(); using (var pinned = buffer.Retain(pin: true)) { unsafe { var p = (byte*)pinned.PinnedPointer; Assert.True(null != p); for (int i = 0; i < buffer.Length; i++) { Assert.Equal(array[i], p[i]); } } } // TODO: the following using statement does not work ... // AutoDisposeBuffer is getting disposed above. Are we ok with this? //using(var handle = buffer.Retain()) //{ //} } static void BufferBasics(ReadOnlyBuffer<byte> buffer) { var span = buffer.Span; Assert.Equal(buffer.Length, span.Length); Assert.True(buffer.IsEmpty || buffer.Length != 0); Assert.True(!buffer.IsEmpty || buffer.Length == 0); var array = buffer.ToArray(); for (int i = 0; i < array.Length; i++) Assert.Equal(array[i], span[i]); if (buffer.Length > 0) { var slice = buffer.Slice(1); for (int i = 0; i < slice.Length; i++) Assert.Equal(slice.Span[i], span[i + 1]); } } static void BufferLifetime(ReadOnlyBuffer<byte> buffer) { var array = buffer.ToArray(); using (var pinned = buffer.Retain(pin: true)) { unsafe { var p = (byte*)pinned.PinnedPointer; Assert.True(null != p); for (int i = 0; i < buffer.Length; i++) { Assert.Equal(array[i], p[i]); } } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tenancy_config/reservation_status_colors.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.TenancyConfig { /// <summary>Holder for reflection information generated from tenancy_config/reservation_status_colors.proto</summary> public static partial class ReservationStatusColorsReflection { #region Descriptor /// <summary>File descriptor for tenancy_config/reservation_status_colors.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ReservationStatusColorsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci50ZW5hbmN5X2NvbmZpZy9yZXNlcnZhdGlvbl9zdGF0dXNfY29sb3JzLnBy", "b3RvEhpob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZxoccHJpbWl0aXZlL3N0", "YXR1c19jb2xvci5wcm90byK7DQoXUmVzZXJ2YXRpb25TdGF0dXNDb2xvcnMS", "SwofdW5ndWFyYW50ZWVkX25vdF9kdWVfaW5kaXZpZHVhbBgBIAEoDjIiLmhv", "bG1zLnR5cGVzLnByaW1pdGl2ZS5TdGF0dXNDb2xvchJGChp1bmd1YXJhbnRl", "ZWRfbm90X2R1ZV9ncm91cBgCIAEoDjIiLmhvbG1zLnR5cGVzLnByaW1pdGl2", "ZS5TdGF0dXNDb2xvchJHChtndWFyYW50ZWVkX2NvbG9yX2luZGl2aWR1YWwY", "AyABKA4yIi5ob2xtcy50eXBlcy5wcmltaXRpdmUuU3RhdHVzQ29sb3ISQgoW", "Z3VhcmFudGVlZF9jb2xvcl9ncm91cBgEIAEoDjIiLmhvbG1zLnR5cGVzLnBy", "aW1pdGl2ZS5TdGF0dXNDb2xvchJLCh91bmd1YXJhbnRlZWRfb3ZlcmR1ZV9p", "bmRpdmlkdWFsGAUgASgOMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlN0YXR1", "c0NvbG9yEkYKGnVuZ3VhcmFudGVlZF9vdmVyZHVlX2dyb3VwGAYgASgOMiIu", "aG9sbXMudHlwZXMucHJpbWl0aXZlLlN0YXR1c0NvbG9yEkQKGGFycml2YWxf", "Y29sb3JfaW5kaXZpZHVhbBgHIAEoDjIiLmhvbG1zLnR5cGVzLnByaW1pdGl2", "ZS5TdGF0dXNDb2xvchI/ChNhcnJpdmFsX2NvbG9yX2dyb3VwGAggASgOMiIu", "aG9sbXMudHlwZXMucHJpbWl0aXZlLlN0YXR1c0NvbG9yEkQKGGluaG91c2Vf", "Y29sb3JfaW5kaXZpZHVhbBgJIAEoDjIiLmhvbG1zLnR5cGVzLnByaW1pdGl2", "ZS5TdGF0dXNDb2xvchI/ChNpbmhvdXNlX2NvbG9yX2dyb3VwGAogASgOMiIu", "aG9sbXMudHlwZXMucHJpbWl0aXZlLlN0YXR1c0NvbG9yEkYKGmRlcGFydHVy", "ZV9jb2xvcl9pbmRpdmlkdWFsGAsgASgOMiIuaG9sbXMudHlwZXMucHJpbWl0", "aXZlLlN0YXR1c0NvbG9yEkEKFWRlcGFydHVyZV9jb2xvcl9ncm91cBgMIAEo", "DjIiLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5TdGF0dXNDb2xvchJIChxjaGVj", "a2VkX291dF9jb2xvcl9pbmRpdmlkdWFsGA0gASgOMiIuaG9sbXMudHlwZXMu", "cHJpbWl0aXZlLlN0YXR1c0NvbG9yEkMKF2NoZWNrZWRfb3V0X2NvbG9yX2dy", "b3VwGA4gASgOMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlN0YXR1c0NvbG9y", "EkQKGG5vX3Nob3dfY29sb3JfaW5kaXZpZHVhbBgPIAEoDjIiLmhvbG1zLnR5", "cGVzLnByaW1pdGl2ZS5TdGF0dXNDb2xvchI/ChNub19zaG93X2NvbG9yX2dy", "b3VwGBAgASgOMiIuaG9sbXMudHlwZXMucHJpbWl0aXZlLlN0YXR1c0NvbG9y", "EkUKGWNhbmNlbGVkX2NvbG9yX2luZGl2aWR1YWwYESABKA4yIi5ob2xtcy50", "eXBlcy5wcmltaXRpdmUuU3RhdHVzQ29sb3ISQAoUY2FuY2VsZWRfY29sb3Jf", "Z3JvdXAYEiABKA4yIi5ob2xtcy50eXBlcy5wcmltaXRpdmUuU3RhdHVzQ29s", "b3ISTgoiY2FuY2VsZWRfd2l0aF9mZWVfY29sb3JfaW5kaXZpZHVhbBgTIAEo", "DjIiLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5TdGF0dXNDb2xvchJJCh1jYW5j", "ZWxlZF93aXRoX2ZlZV9jb2xvcl9ncm91cBgUIAEoDjIiLmhvbG1zLnR5cGVz", "LnByaW1pdGl2ZS5TdGF0dXNDb2xvchJBChVvcGVuX2NvbG9yX2luZGl2aWR1", "YWwYFSABKA4yIi5ob2xtcy50eXBlcy5wcmltaXRpdmUuU3RhdHVzQ29sb3IS", "PAoQb3Blbl9jb2xvcl9ncm91cBgWIAEoDjIiLmhvbG1zLnR5cGVzLnByaW1p", "dGl2ZS5TdGF0dXNDb2xvchJMCiBhcnJpdmFsX292ZXJkdWVfY29sb3JfaW5k", "aXZpZHVhbBgXIAEoDjIiLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5TdGF0dXND", "b2xvchJHChthcnJpdmFsX292ZXJkdWVfY29sb3JfZ3JvdXAYGCABKA4yIi5o", "b2xtcy50eXBlcy5wcmltaXRpdmUuU3RhdHVzQ29sb3JCK1oNdGVuYW5jeWNv", "bmZpZ6oCGUhPTE1TLlR5cGVzLlRlbmFuY3lDb25maWdiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.StatusColorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.TenancyConfig.ReservationStatusColors), global::HOLMS.Types.TenancyConfig.ReservationStatusColors.Parser, new[]{ "UnguaranteedNotDueIndividual", "UnguaranteedNotDueGroup", "GuaranteedColorIndividual", "GuaranteedColorGroup", "UnguaranteedOverdueIndividual", "UnguaranteedOverdueGroup", "ArrivalColorIndividual", "ArrivalColorGroup", "InhouseColorIndividual", "InhouseColorGroup", "DepartureColorIndividual", "DepartureColorGroup", "CheckedOutColorIndividual", "CheckedOutColorGroup", "NoShowColorIndividual", "NoShowColorGroup", "CanceledColorIndividual", "CanceledColorGroup", "CanceledWithFeeColorIndividual", "CanceledWithFeeColorGroup", "OpenColorIndividual", "OpenColorGroup", "ArrivalOverdueColorIndividual", "ArrivalOverdueColorGroup" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ReservationStatusColors : pb::IMessage<ReservationStatusColors> { private static readonly pb::MessageParser<ReservationStatusColors> _parser = new pb::MessageParser<ReservationStatusColors>(() => new ReservationStatusColors()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReservationStatusColors> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.TenancyConfig.ReservationStatusColorsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationStatusColors() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationStatusColors(ReservationStatusColors other) : this() { unguaranteedNotDueIndividual_ = other.unguaranteedNotDueIndividual_; unguaranteedNotDueGroup_ = other.unguaranteedNotDueGroup_; guaranteedColorIndividual_ = other.guaranteedColorIndividual_; guaranteedColorGroup_ = other.guaranteedColorGroup_; unguaranteedOverdueIndividual_ = other.unguaranteedOverdueIndividual_; unguaranteedOverdueGroup_ = other.unguaranteedOverdueGroup_; arrivalColorIndividual_ = other.arrivalColorIndividual_; arrivalColorGroup_ = other.arrivalColorGroup_; inhouseColorIndividual_ = other.inhouseColorIndividual_; inhouseColorGroup_ = other.inhouseColorGroup_; departureColorIndividual_ = other.departureColorIndividual_; departureColorGroup_ = other.departureColorGroup_; checkedOutColorIndividual_ = other.checkedOutColorIndividual_; checkedOutColorGroup_ = other.checkedOutColorGroup_; noShowColorIndividual_ = other.noShowColorIndividual_; noShowColorGroup_ = other.noShowColorGroup_; canceledColorIndividual_ = other.canceledColorIndividual_; canceledColorGroup_ = other.canceledColorGroup_; canceledWithFeeColorIndividual_ = other.canceledWithFeeColorIndividual_; canceledWithFeeColorGroup_ = other.canceledWithFeeColorGroup_; openColorIndividual_ = other.openColorIndividual_; openColorGroup_ = other.openColorGroup_; arrivalOverdueColorIndividual_ = other.arrivalOverdueColorIndividual_; arrivalOverdueColorGroup_ = other.arrivalOverdueColorGroup_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationStatusColors Clone() { return new ReservationStatusColors(this); } /// <summary>Field number for the "unguaranteed_not_due_individual" field.</summary> public const int UnguaranteedNotDueIndividualFieldNumber = 1; private global::HOLMS.Types.Primitive.StatusColor unguaranteedNotDueIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor UnguaranteedNotDueIndividual { get { return unguaranteedNotDueIndividual_; } set { unguaranteedNotDueIndividual_ = value; } } /// <summary>Field number for the "unguaranteed_not_due_group" field.</summary> public const int UnguaranteedNotDueGroupFieldNumber = 2; private global::HOLMS.Types.Primitive.StatusColor unguaranteedNotDueGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor UnguaranteedNotDueGroup { get { return unguaranteedNotDueGroup_; } set { unguaranteedNotDueGroup_ = value; } } /// <summary>Field number for the "guaranteed_color_individual" field.</summary> public const int GuaranteedColorIndividualFieldNumber = 3; private global::HOLMS.Types.Primitive.StatusColor guaranteedColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor GuaranteedColorIndividual { get { return guaranteedColorIndividual_; } set { guaranteedColorIndividual_ = value; } } /// <summary>Field number for the "guaranteed_color_group" field.</summary> public const int GuaranteedColorGroupFieldNumber = 4; private global::HOLMS.Types.Primitive.StatusColor guaranteedColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor GuaranteedColorGroup { get { return guaranteedColorGroup_; } set { guaranteedColorGroup_ = value; } } /// <summary>Field number for the "unguaranteed_overdue_individual" field.</summary> public const int UnguaranteedOverdueIndividualFieldNumber = 5; private global::HOLMS.Types.Primitive.StatusColor unguaranteedOverdueIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor UnguaranteedOverdueIndividual { get { return unguaranteedOverdueIndividual_; } set { unguaranteedOverdueIndividual_ = value; } } /// <summary>Field number for the "unguaranteed_overdue_group" field.</summary> public const int UnguaranteedOverdueGroupFieldNumber = 6; private global::HOLMS.Types.Primitive.StatusColor unguaranteedOverdueGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor UnguaranteedOverdueGroup { get { return unguaranteedOverdueGroup_; } set { unguaranteedOverdueGroup_ = value; } } /// <summary>Field number for the "arrival_color_individual" field.</summary> public const int ArrivalColorIndividualFieldNumber = 7; private global::HOLMS.Types.Primitive.StatusColor arrivalColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor ArrivalColorIndividual { get { return arrivalColorIndividual_; } set { arrivalColorIndividual_ = value; } } /// <summary>Field number for the "arrival_color_group" field.</summary> public const int ArrivalColorGroupFieldNumber = 8; private global::HOLMS.Types.Primitive.StatusColor arrivalColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor ArrivalColorGroup { get { return arrivalColorGroup_; } set { arrivalColorGroup_ = value; } } /// <summary>Field number for the "inhouse_color_individual" field.</summary> public const int InhouseColorIndividualFieldNumber = 9; private global::HOLMS.Types.Primitive.StatusColor inhouseColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor InhouseColorIndividual { get { return inhouseColorIndividual_; } set { inhouseColorIndividual_ = value; } } /// <summary>Field number for the "inhouse_color_group" field.</summary> public const int InhouseColorGroupFieldNumber = 10; private global::HOLMS.Types.Primitive.StatusColor inhouseColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor InhouseColorGroup { get { return inhouseColorGroup_; } set { inhouseColorGroup_ = value; } } /// <summary>Field number for the "departure_color_individual" field.</summary> public const int DepartureColorIndividualFieldNumber = 11; private global::HOLMS.Types.Primitive.StatusColor departureColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor DepartureColorIndividual { get { return departureColorIndividual_; } set { departureColorIndividual_ = value; } } /// <summary>Field number for the "departure_color_group" field.</summary> public const int DepartureColorGroupFieldNumber = 12; private global::HOLMS.Types.Primitive.StatusColor departureColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor DepartureColorGroup { get { return departureColorGroup_; } set { departureColorGroup_ = value; } } /// <summary>Field number for the "checked_out_color_individual" field.</summary> public const int CheckedOutColorIndividualFieldNumber = 13; private global::HOLMS.Types.Primitive.StatusColor checkedOutColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor CheckedOutColorIndividual { get { return checkedOutColorIndividual_; } set { checkedOutColorIndividual_ = value; } } /// <summary>Field number for the "checked_out_color_group" field.</summary> public const int CheckedOutColorGroupFieldNumber = 14; private global::HOLMS.Types.Primitive.StatusColor checkedOutColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor CheckedOutColorGroup { get { return checkedOutColorGroup_; } set { checkedOutColorGroup_ = value; } } /// <summary>Field number for the "no_show_color_individual" field.</summary> public const int NoShowColorIndividualFieldNumber = 15; private global::HOLMS.Types.Primitive.StatusColor noShowColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor NoShowColorIndividual { get { return noShowColorIndividual_; } set { noShowColorIndividual_ = value; } } /// <summary>Field number for the "no_show_color_group" field.</summary> public const int NoShowColorGroupFieldNumber = 16; private global::HOLMS.Types.Primitive.StatusColor noShowColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor NoShowColorGroup { get { return noShowColorGroup_; } set { noShowColorGroup_ = value; } } /// <summary>Field number for the "canceled_color_individual" field.</summary> public const int CanceledColorIndividualFieldNumber = 17; private global::HOLMS.Types.Primitive.StatusColor canceledColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor CanceledColorIndividual { get { return canceledColorIndividual_; } set { canceledColorIndividual_ = value; } } /// <summary>Field number for the "canceled_color_group" field.</summary> public const int CanceledColorGroupFieldNumber = 18; private global::HOLMS.Types.Primitive.StatusColor canceledColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor CanceledColorGroup { get { return canceledColorGroup_; } set { canceledColorGroup_ = value; } } /// <summary>Field number for the "canceled_with_fee_color_individual" field.</summary> public const int CanceledWithFeeColorIndividualFieldNumber = 19; private global::HOLMS.Types.Primitive.StatusColor canceledWithFeeColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor CanceledWithFeeColorIndividual { get { return canceledWithFeeColorIndividual_; } set { canceledWithFeeColorIndividual_ = value; } } /// <summary>Field number for the "canceled_with_fee_color_group" field.</summary> public const int CanceledWithFeeColorGroupFieldNumber = 20; private global::HOLMS.Types.Primitive.StatusColor canceledWithFeeColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor CanceledWithFeeColorGroup { get { return canceledWithFeeColorGroup_; } set { canceledWithFeeColorGroup_ = value; } } /// <summary>Field number for the "open_color_individual" field.</summary> public const int OpenColorIndividualFieldNumber = 21; private global::HOLMS.Types.Primitive.StatusColor openColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor OpenColorIndividual { get { return openColorIndividual_; } set { openColorIndividual_ = value; } } /// <summary>Field number for the "open_color_group" field.</summary> public const int OpenColorGroupFieldNumber = 22; private global::HOLMS.Types.Primitive.StatusColor openColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor OpenColorGroup { get { return openColorGroup_; } set { openColorGroup_ = value; } } /// <summary>Field number for the "arrival_overdue_color_individual" field.</summary> public const int ArrivalOverdueColorIndividualFieldNumber = 23; private global::HOLMS.Types.Primitive.StatusColor arrivalOverdueColorIndividual_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor ArrivalOverdueColorIndividual { get { return arrivalOverdueColorIndividual_; } set { arrivalOverdueColorIndividual_ = value; } } /// <summary>Field number for the "arrival_overdue_color_group" field.</summary> public const int ArrivalOverdueColorGroupFieldNumber = 24; private global::HOLMS.Types.Primitive.StatusColor arrivalOverdueColorGroup_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.StatusColor ArrivalOverdueColorGroup { get { return arrivalOverdueColorGroup_; } set { arrivalOverdueColorGroup_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReservationStatusColors); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReservationStatusColors other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (UnguaranteedNotDueIndividual != other.UnguaranteedNotDueIndividual) return false; if (UnguaranteedNotDueGroup != other.UnguaranteedNotDueGroup) return false; if (GuaranteedColorIndividual != other.GuaranteedColorIndividual) return false; if (GuaranteedColorGroup != other.GuaranteedColorGroup) return false; if (UnguaranteedOverdueIndividual != other.UnguaranteedOverdueIndividual) return false; if (UnguaranteedOverdueGroup != other.UnguaranteedOverdueGroup) return false; if (ArrivalColorIndividual != other.ArrivalColorIndividual) return false; if (ArrivalColorGroup != other.ArrivalColorGroup) return false; if (InhouseColorIndividual != other.InhouseColorIndividual) return false; if (InhouseColorGroup != other.InhouseColorGroup) return false; if (DepartureColorIndividual != other.DepartureColorIndividual) return false; if (DepartureColorGroup != other.DepartureColorGroup) return false; if (CheckedOutColorIndividual != other.CheckedOutColorIndividual) return false; if (CheckedOutColorGroup != other.CheckedOutColorGroup) return false; if (NoShowColorIndividual != other.NoShowColorIndividual) return false; if (NoShowColorGroup != other.NoShowColorGroup) return false; if (CanceledColorIndividual != other.CanceledColorIndividual) return false; if (CanceledColorGroup != other.CanceledColorGroup) return false; if (CanceledWithFeeColorIndividual != other.CanceledWithFeeColorIndividual) return false; if (CanceledWithFeeColorGroup != other.CanceledWithFeeColorGroup) return false; if (OpenColorIndividual != other.OpenColorIndividual) return false; if (OpenColorGroup != other.OpenColorGroup) return false; if (ArrivalOverdueColorIndividual != other.ArrivalOverdueColorIndividual) return false; if (ArrivalOverdueColorGroup != other.ArrivalOverdueColorGroup) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (UnguaranteedNotDueIndividual != 0) hash ^= UnguaranteedNotDueIndividual.GetHashCode(); if (UnguaranteedNotDueGroup != 0) hash ^= UnguaranteedNotDueGroup.GetHashCode(); if (GuaranteedColorIndividual != 0) hash ^= GuaranteedColorIndividual.GetHashCode(); if (GuaranteedColorGroup != 0) hash ^= GuaranteedColorGroup.GetHashCode(); if (UnguaranteedOverdueIndividual != 0) hash ^= UnguaranteedOverdueIndividual.GetHashCode(); if (UnguaranteedOverdueGroup != 0) hash ^= UnguaranteedOverdueGroup.GetHashCode(); if (ArrivalColorIndividual != 0) hash ^= ArrivalColorIndividual.GetHashCode(); if (ArrivalColorGroup != 0) hash ^= ArrivalColorGroup.GetHashCode(); if (InhouseColorIndividual != 0) hash ^= InhouseColorIndividual.GetHashCode(); if (InhouseColorGroup != 0) hash ^= InhouseColorGroup.GetHashCode(); if (DepartureColorIndividual != 0) hash ^= DepartureColorIndividual.GetHashCode(); if (DepartureColorGroup != 0) hash ^= DepartureColorGroup.GetHashCode(); if (CheckedOutColorIndividual != 0) hash ^= CheckedOutColorIndividual.GetHashCode(); if (CheckedOutColorGroup != 0) hash ^= CheckedOutColorGroup.GetHashCode(); if (NoShowColorIndividual != 0) hash ^= NoShowColorIndividual.GetHashCode(); if (NoShowColorGroup != 0) hash ^= NoShowColorGroup.GetHashCode(); if (CanceledColorIndividual != 0) hash ^= CanceledColorIndividual.GetHashCode(); if (CanceledColorGroup != 0) hash ^= CanceledColorGroup.GetHashCode(); if (CanceledWithFeeColorIndividual != 0) hash ^= CanceledWithFeeColorIndividual.GetHashCode(); if (CanceledWithFeeColorGroup != 0) hash ^= CanceledWithFeeColorGroup.GetHashCode(); if (OpenColorIndividual != 0) hash ^= OpenColorIndividual.GetHashCode(); if (OpenColorGroup != 0) hash ^= OpenColorGroup.GetHashCode(); if (ArrivalOverdueColorIndividual != 0) hash ^= ArrivalOverdueColorIndividual.GetHashCode(); if (ArrivalOverdueColorGroup != 0) hash ^= ArrivalOverdueColorGroup.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (UnguaranteedNotDueIndividual != 0) { output.WriteRawTag(8); output.WriteEnum((int) UnguaranteedNotDueIndividual); } if (UnguaranteedNotDueGroup != 0) { output.WriteRawTag(16); output.WriteEnum((int) UnguaranteedNotDueGroup); } if (GuaranteedColorIndividual != 0) { output.WriteRawTag(24); output.WriteEnum((int) GuaranteedColorIndividual); } if (GuaranteedColorGroup != 0) { output.WriteRawTag(32); output.WriteEnum((int) GuaranteedColorGroup); } if (UnguaranteedOverdueIndividual != 0) { output.WriteRawTag(40); output.WriteEnum((int) UnguaranteedOverdueIndividual); } if (UnguaranteedOverdueGroup != 0) { output.WriteRawTag(48); output.WriteEnum((int) UnguaranteedOverdueGroup); } if (ArrivalColorIndividual != 0) { output.WriteRawTag(56); output.WriteEnum((int) ArrivalColorIndividual); } if (ArrivalColorGroup != 0) { output.WriteRawTag(64); output.WriteEnum((int) ArrivalColorGroup); } if (InhouseColorIndividual != 0) { output.WriteRawTag(72); output.WriteEnum((int) InhouseColorIndividual); } if (InhouseColorGroup != 0) { output.WriteRawTag(80); output.WriteEnum((int) InhouseColorGroup); } if (DepartureColorIndividual != 0) { output.WriteRawTag(88); output.WriteEnum((int) DepartureColorIndividual); } if (DepartureColorGroup != 0) { output.WriteRawTag(96); output.WriteEnum((int) DepartureColorGroup); } if (CheckedOutColorIndividual != 0) { output.WriteRawTag(104); output.WriteEnum((int) CheckedOutColorIndividual); } if (CheckedOutColorGroup != 0) { output.WriteRawTag(112); output.WriteEnum((int) CheckedOutColorGroup); } if (NoShowColorIndividual != 0) { output.WriteRawTag(120); output.WriteEnum((int) NoShowColorIndividual); } if (NoShowColorGroup != 0) { output.WriteRawTag(128, 1); output.WriteEnum((int) NoShowColorGroup); } if (CanceledColorIndividual != 0) { output.WriteRawTag(136, 1); output.WriteEnum((int) CanceledColorIndividual); } if (CanceledColorGroup != 0) { output.WriteRawTag(144, 1); output.WriteEnum((int) CanceledColorGroup); } if (CanceledWithFeeColorIndividual != 0) { output.WriteRawTag(152, 1); output.WriteEnum((int) CanceledWithFeeColorIndividual); } if (CanceledWithFeeColorGroup != 0) { output.WriteRawTag(160, 1); output.WriteEnum((int) CanceledWithFeeColorGroup); } if (OpenColorIndividual != 0) { output.WriteRawTag(168, 1); output.WriteEnum((int) OpenColorIndividual); } if (OpenColorGroup != 0) { output.WriteRawTag(176, 1); output.WriteEnum((int) OpenColorGroup); } if (ArrivalOverdueColorIndividual != 0) { output.WriteRawTag(184, 1); output.WriteEnum((int) ArrivalOverdueColorIndividual); } if (ArrivalOverdueColorGroup != 0) { output.WriteRawTag(192, 1); output.WriteEnum((int) ArrivalOverdueColorGroup); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (UnguaranteedNotDueIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UnguaranteedNotDueIndividual); } if (UnguaranteedNotDueGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UnguaranteedNotDueGroup); } if (GuaranteedColorIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) GuaranteedColorIndividual); } if (GuaranteedColorGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) GuaranteedColorGroup); } if (UnguaranteedOverdueIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UnguaranteedOverdueIndividual); } if (UnguaranteedOverdueGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UnguaranteedOverdueGroup); } if (ArrivalColorIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ArrivalColorIndividual); } if (ArrivalColorGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ArrivalColorGroup); } if (InhouseColorIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) InhouseColorIndividual); } if (InhouseColorGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) InhouseColorGroup); } if (DepartureColorIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DepartureColorIndividual); } if (DepartureColorGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) DepartureColorGroup); } if (CheckedOutColorIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CheckedOutColorIndividual); } if (CheckedOutColorGroup != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CheckedOutColorGroup); } if (NoShowColorIndividual != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NoShowColorIndividual); } if (NoShowColorGroup != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) NoShowColorGroup); } if (CanceledColorIndividual != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) CanceledColorIndividual); } if (CanceledColorGroup != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) CanceledColorGroup); } if (CanceledWithFeeColorIndividual != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) CanceledWithFeeColorIndividual); } if (CanceledWithFeeColorGroup != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) CanceledWithFeeColorGroup); } if (OpenColorIndividual != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OpenColorIndividual); } if (OpenColorGroup != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OpenColorGroup); } if (ArrivalOverdueColorIndividual != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) ArrivalOverdueColorIndividual); } if (ArrivalOverdueColorGroup != 0) { size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) ArrivalOverdueColorGroup); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReservationStatusColors other) { if (other == null) { return; } if (other.UnguaranteedNotDueIndividual != 0) { UnguaranteedNotDueIndividual = other.UnguaranteedNotDueIndividual; } if (other.UnguaranteedNotDueGroup != 0) { UnguaranteedNotDueGroup = other.UnguaranteedNotDueGroup; } if (other.GuaranteedColorIndividual != 0) { GuaranteedColorIndividual = other.GuaranteedColorIndividual; } if (other.GuaranteedColorGroup != 0) { GuaranteedColorGroup = other.GuaranteedColorGroup; } if (other.UnguaranteedOverdueIndividual != 0) { UnguaranteedOverdueIndividual = other.UnguaranteedOverdueIndividual; } if (other.UnguaranteedOverdueGroup != 0) { UnguaranteedOverdueGroup = other.UnguaranteedOverdueGroup; } if (other.ArrivalColorIndividual != 0) { ArrivalColorIndividual = other.ArrivalColorIndividual; } if (other.ArrivalColorGroup != 0) { ArrivalColorGroup = other.ArrivalColorGroup; } if (other.InhouseColorIndividual != 0) { InhouseColorIndividual = other.InhouseColorIndividual; } if (other.InhouseColorGroup != 0) { InhouseColorGroup = other.InhouseColorGroup; } if (other.DepartureColorIndividual != 0) { DepartureColorIndividual = other.DepartureColorIndividual; } if (other.DepartureColorGroup != 0) { DepartureColorGroup = other.DepartureColorGroup; } if (other.CheckedOutColorIndividual != 0) { CheckedOutColorIndividual = other.CheckedOutColorIndividual; } if (other.CheckedOutColorGroup != 0) { CheckedOutColorGroup = other.CheckedOutColorGroup; } if (other.NoShowColorIndividual != 0) { NoShowColorIndividual = other.NoShowColorIndividual; } if (other.NoShowColorGroup != 0) { NoShowColorGroup = other.NoShowColorGroup; } if (other.CanceledColorIndividual != 0) { CanceledColorIndividual = other.CanceledColorIndividual; } if (other.CanceledColorGroup != 0) { CanceledColorGroup = other.CanceledColorGroup; } if (other.CanceledWithFeeColorIndividual != 0) { CanceledWithFeeColorIndividual = other.CanceledWithFeeColorIndividual; } if (other.CanceledWithFeeColorGroup != 0) { CanceledWithFeeColorGroup = other.CanceledWithFeeColorGroup; } if (other.OpenColorIndividual != 0) { OpenColorIndividual = other.OpenColorIndividual; } if (other.OpenColorGroup != 0) { OpenColorGroup = other.OpenColorGroup; } if (other.ArrivalOverdueColorIndividual != 0) { ArrivalOverdueColorIndividual = other.ArrivalOverdueColorIndividual; } if (other.ArrivalOverdueColorGroup != 0) { ArrivalOverdueColorGroup = other.ArrivalOverdueColorGroup; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { unguaranteedNotDueIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 16: { unguaranteedNotDueGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 24: { guaranteedColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 32: { guaranteedColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 40: { unguaranteedOverdueIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 48: { unguaranteedOverdueGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 56: { arrivalColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 64: { arrivalColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 72: { inhouseColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 80: { inhouseColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 88: { departureColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 96: { departureColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 104: { checkedOutColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 112: { checkedOutColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 120: { noShowColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 128: { noShowColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 136: { canceledColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 144: { canceledColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 152: { canceledWithFeeColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 160: { canceledWithFeeColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 168: { openColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 176: { openColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 184: { arrivalOverdueColorIndividual_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } case 192: { arrivalOverdueColorGroup_ = (global::HOLMS.Types.Primitive.StatusColor) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: The CLR wrapper for all Win32 as well as ** ROTOR-style Unix PAL, etc. native operations ** ** ===========================================================*/ /** * Notes to PInvoke users: Getting the syntax exactly correct is crucial, and * more than a little confusing. Here's some guidelines. * * For handles, you should use a SafeHandle subclass specific to your handle * type. For files, we have the following set of interesting definitions: * * [DllImport(Interop.Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)] * private static extern SafeFileHandle CreateFile(...); * * [DllImport(Interop.Libraries.Kernel32, SetLastError=true)] * unsafe internal static extern int ReadFile(SafeFileHandle handle, ...); * * [DllImport(Interop.Libraries.Kernel32, SetLastError=true)] * internal static extern bool CloseHandle(IntPtr handle); * * P/Invoke will create the SafeFileHandle instance for you and assign the * return value from CreateFile into the handle atomically. When we call * ReadFile, P/Invoke will increment a ref count, make the call, then decrement * it (preventing handle recycling vulnerabilities). Then SafeFileHandle's * ReleaseHandle method will call CloseHandle, passing in the handle field * as an IntPtr. * * If for some reason you cannot use a SafeHandle subclass for your handles, * then use IntPtr as the handle type (or possibly HandleRef - understand when * to use GC.KeepAlive). If your code will run in SQL Server (or any other * long-running process that can't be recycled easily), use a constrained * execution region to prevent thread aborts while allocating your * handle, and consider making your handle wrapper subclass * CriticalFinalizerObject to ensure you can free the handle. As you can * probably guess, SafeHandle will save you a lot of headaches if your code * needs to be robust to thread aborts and OOM. * * * If you have a method that takes a native struct, you have two options for * declaring that struct. You can make it a value type ('struct' in CSharp), * or a reference type ('class'). This choice doesn't seem very interesting, * but your function prototype must use different syntax depending on your * choice. For example, if your native method is prototyped as such: * * bool GetVersionEx(OSVERSIONINFO & lposvi); * * * you must use EITHER THIS OR THE NEXT syntax: * * [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] * internal struct OSVERSIONINFO { ... } * * [DllImport(Interop.Libraries.Kernel32, CharSet=CharSet.Auto)] * internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi); * * OR: * * [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] * internal class OSVERSIONINFO { ... } * * [DllImport(Interop.Libraries.Kernel32, CharSet=CharSet.Auto)] * internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi); * * Note that classes require being marked as [In, Out] while value types must * be passed as ref parameters. * * Also note the CharSet.Auto on GetVersionEx - while it does not take a String * as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so * the size of the struct varies on different platforms, and there's a * GetVersionExA & a GetVersionExW. Also, the OSVERSIONINFO struct has a sizeof * field so the OS can ensure you've passed in the correctly-sized copy of an * OSVERSIONINFO. You must explicitly set this using Marshal.SizeOf(Object); * * For security reasons, if you're making a P/Invoke method to a Win32 method * that takes an ANSI String and that String is the name of some resource you've * done a security check on (such as a file name), you want to disable best fit * mapping in WideCharToMultiByte. Do this by setting BestFitMapping=false * in your DllImportAttribute. */ namespace Microsoft.Win32 { using System; using System.Security; using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using BOOL = System.Int32; using DWORD = System.UInt32; using ULONG = System.UInt32; /** * Win32 encapsulation for MSCORLIB. */ // Remove the default demands for all P/Invoke methods with this // global declaration on the class. internal static class Win32Native { internal const int KEY_QUERY_VALUE = 0x0001; internal const int KEY_SET_VALUE = 0x0002; internal const int KEY_CREATE_SUB_KEY = 0x0004; internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008; internal const int KEY_NOTIFY = 0x0010; internal const int KEY_CREATE_LINK = 0x0020; internal const int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~SYNCHRONIZE)); internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~SYNCHRONIZE)); internal const int KEY_WOW64_64KEY = 0x0100; // internal const int KEY_WOW64_32KEY = 0x0200; // internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges internal const int REG_NONE = 0; // No value type internal const int REG_SZ = 1; // Unicode nul terminated string internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string // (with environment variable references) internal const int REG_BINARY = 3; // Free form binary internal const int REG_DWORD = 4; // 32-bit number internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD) internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number internal const int REG_LINK = 6; // Symbolic Link (unicode) internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10; internal const int REG_QWORD = 11; // 64-bit number // Win32 ACL-related constants: internal const int READ_CONTROL = 0x00020000; internal const int SYNCHRONIZE = 0x00100000; internal const int MAXIMUM_ALLOWED = 0x02000000; internal const int STANDARD_RIGHTS_READ = READ_CONTROL; internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; // STANDARD_RIGHTS_REQUIRED (0x000F0000L) // SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3) // SEMAPHORE and Event both use 0x0002 // MUTEX uses 0x001 (MUTANT_QUERY_STATE) // Note that you may need to specify the SYNCHRONIZE bit as well // to be able to open a synchronization primitive. internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; internal const int EVENT_MODIFY_STATE = 0x00000002; internal const int MUTEX_MODIFY_STATE = 0x00000001; // CreateEventEx: flags internal const uint CREATE_EVENT_MANUAL_RESET = 0x1; internal const uint CREATE_EVENT_INITIAL_SET = 0x2; // CreateMutexEx: flags internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1; internal const int LMEM_FIXED = 0x0000; internal const int LMEM_ZEROINIT = 0x0040; internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class OSVERSIONINFOEX { public OSVERSIONINFOEX() { OSVersionInfoSize = (int)Marshal.SizeOf(this); } // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) internal int OSVersionInfoSize = 0; internal int MajorVersion = 0; internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string CSDVersion = null; internal ushort ServicePackMajor = 0; internal ushort ServicePackMinor = 0; internal short SuiteMask = 0; internal byte ProductType = 0; internal byte Reserved = 0; } [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = 0; // don't remove null, or this field will disappear in bcl.small internal unsafe byte* pSecurityDescriptor = null; internal int bInheritHandle = 0; } [StructLayout(LayoutKind.Sequential)] internal struct MEMORYSTATUSEX { // The length field must be set to the size of this data structure. internal int length; internal int memoryLoad; internal ulong totalPhys; internal ulong availPhys; internal ulong totalPageFile; internal ulong availPageFile; internal ulong totalVirtual; internal ulong availVirtual; internal ulong availExtendedVirtual; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct MEMORY_BASIC_INFORMATION { internal void* BaseAddress; internal void* AllocationBase; internal uint AllocationProtect; internal UIntPtr RegionSize; internal uint State; internal uint Protect; internal uint Type; } internal const String ADVAPI32 = "advapi32.dll"; internal const String SHELL32 = "shell32.dll"; internal const String SHIM = "mscoree.dll"; internal const String CRYPT32 = "crypt32.dll"; internal const String SECUR32 = "secur32.dll"; internal const String MSCORWKS = "coreclr.dll"; [DllImport(Interop.Libraries.Kernel32, EntryPoint = "LocalAlloc")] internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern IntPtr LocalFree(IntPtr handle); internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX)); return GlobalMemoryStatusExNative(ref buffer); } [DllImport(Interop.Libraries.Kernel32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")] private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer); // VirtualAlloc should generally be avoided, but is needed in // the MemoryFailPoint implementation (within a CER) to increase the // size of the page file, ignoring any host memory allocators. [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] unsafe internal static extern void* VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode); [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Ansi, ExactSpelling = true, EntryPoint = "lstrlenA")] internal static extern int lstrlenA(IntPtr ptr); [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")] internal static extern int lstrlenW(IntPtr ptr); [DllImport(Interop.Libraries.OleAut32, CharSet = CharSet.Unicode)] internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR [DllImport(Interop.Libraries.OleAut32)] internal static extern uint SysStringLen(IntPtr bstr); [DllImport(Interop.Libraries.OleAut32)] internal static extern void SysFreeString(IntPtr bstr); #if FEATURE_COMINTEROP [DllImport(Interop.Libraries.OleAut32)] internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); // BSTR [DllImport(Interop.Libraries.OleAut32)] internal static extern uint SysStringByteLen(IntPtr bstr); #endif [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern bool SetEvent(SafeWaitHandle handle); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern bool ResetEvent(SafeWaitHandle handle); [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateEventEx(SECURITY_ATTRIBUTES lpSecurityAttributes, string name, uint flags, uint desiredAccess); [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenEvent(uint desiredAccess, bool inheritHandle, string name); [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateMutexEx(SECURITY_ATTRIBUTES lpSecurityAttributes, string name, uint flags, uint desiredAccess); [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern bool ReleaseMutex(SafeWaitHandle handle); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern bool CloseHandle(IntPtr handle); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero); [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateSemaphoreEx(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h // Note, these are #defines used to extract handles, and are NOT handles. internal const int STD_INPUT_HANDLE = -10; internal const int STD_OUTPUT_HANDLE = -11; internal const int STD_ERROR_HANDLE = -12; [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one! internal const int PAGE_READWRITE = 0x04; internal const int MEM_COMMIT = 0x1000; internal const int MEM_RESERVE = 0x2000; internal const int MEM_RELEASE = 0x8000; internal const int MEM_FREE = 0x10000; [DllImport(Interop.Libraries.Kernel32)] internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2); [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern bool SetEnvironmentVariable(string lpName, string lpValue); [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] private static extern unsafe int GetEnvironmentVariable(string lpName, char* lpValue, int size); internal static unsafe int GetEnvironmentVariable(string lpName, Span<char> lpValue) { fixed (char* lpValuePtr = &MemoryMarshal.GetReference(lpValue)) { return GetEnvironmentVariable(lpName, lpValuePtr, lpValue.Length); } } [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode)] internal static unsafe extern char* GetEnvironmentStrings(); [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode)] internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings); [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] internal static extern uint GetCurrentProcessId(); [DllImport(Interop.Libraries.Ole32)] internal extern static int CoCreateGuid(out Guid guid); [DllImport(Interop.Libraries.Ole32)] internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb); [DllImport(Interop.Libraries.Ole32)] internal static extern void CoTaskMemFree(IntPtr ptr); [DllImport(Interop.Libraries.Ole32)] internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb); #if FEATURE_WIN32_REGISTRY [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out]StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref int lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref long lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, String lpData, int cbData); #endif // FEATURE_WIN32_REGISTRY [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize); [DllImport(Interop.Libraries.Kernel32)] internal static extern IntPtr LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime); internal const byte VER_GREATER_EQUAL = 0x3; internal const uint VER_MAJORVERSION = 0x0000002; internal const uint VER_MINORVERSION = 0x0000001; internal const uint VER_SERVICEPACKMAJOR = 0x0000020; internal const uint VER_SERVICEPACKMINOR = 0x0000010; [DllImport("kernel32.dll")] internal static extern bool VerifyVersionInfoW([In, Out] OSVERSIONINFOEX lpVersionInfo, uint dwTypeMask, ulong dwlConditionMask); [DllImport("kernel32.dll")] internal static extern ulong VerSetConditionMask(ulong dwlConditionMask, uint dwTypeBitMask, byte dwConditionMask); } }
using System; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Utilities; using Org.BouncyCastle.Utilities; namespace NPascalCoin.Crypto { public class RadioGatun32Digest : IDigest, IMemoable { #region Consts private const int ByteLength = 12; private const int DigestLengthBytes = 32; private const int MillSize = 19; private const int BeltWidth = 3; private const int BeltLength = 13; private const int NumberOfBlankIterations = 16; #endregion private int _bufferPos; private ulong _processedBytes; private readonly byte[] _buffer = new byte[ByteLength]; private readonly uint[] _mMill = new uint[MillSize]; private uint[][] _mBelt; private static uint RotateRight32(uint value, int distance) { return (value >> distance) | (value << (32 - distance)); } private void RoundFunction() { uint[] q = _mBelt[BeltLength - 1]; for (int i = BeltLength - 1; i > 0; i--) _mBelt[i] = _mBelt[i - 1]; _mBelt[0] = q; for (int i = 0; i < 12; i++) _mBelt[i + 1][i % BeltWidth] ^= _mMill[i + 1]; uint[] a = new uint[MillSize]; for (int i = 0; i < MillSize; i++) a[i] = _mMill[i] ^ (_mMill[(i + 1) % MillSize] | ~_mMill[(i + 2) % MillSize]); for (int i = 0; i < MillSize; i++) _mMill[i] = RotateRight32(a[(7 * i) % MillSize], i * (i + 1) / 2); for (int i = 0; i < MillSize; i++) a[i] = _mMill[i] ^ _mMill[(i + 1) % MillSize] ^ _mMill[(i + 4) % MillSize]; a[0] ^= 1; for (int i = 0; i < MillSize; i++) _mMill[i] = a[i]; for (int i = 0; i < BeltWidth; i++) _mMill[i + 13] ^= q[i]; } private void Finish() { int paddingSize = GetByteLength() - (((int) _processedBytes) % GetByteLength()); byte[] pad = new byte[paddingSize]; pad[0] = 0x01; BlockUpdate(pad, 0, paddingSize); for (int i = 0; i < NumberOfBlankIterations; i++) RoundFunction(); } private void ProcessBlock() { RoundFunction(); } // this takes a buffer of information and fills the block private void ProcessFilledBuffer() { int idx = 0; uint[] data = new uint[3]; for (int i = 0; i < 3; i++, idx++) { data[idx] = Pack.LE_To_UInt32(_buffer, i * 4); } for (int i = 0; i < BeltWidth; i++) { _mMill[i + 16] ^= data[i]; _mBelt[0][i] ^= data[i]; } ProcessBlock(); _bufferPos = 0; Array.Clear(_buffer, 0, _buffer.Length); } /** * Standard constructor */ public RadioGatun32Digest() { _mBelt = new uint[BeltLength][]; for (int i = 0; i < BeltLength; i++) _mBelt[i] = new uint[BeltWidth]; Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public RadioGatun32Digest(RadioGatun32Digest t) { Reset(t); } public string AlgorithmName { get { return "RadioGatun32"; } } public int GetDigestSize() { return DigestLengthBytes; } public int GetByteLength() { return ByteLength; } public void Update(byte input) { _buffer[_bufferPos] = input; _processedBytes++; _bufferPos++; if (_bufferPos == _buffer.Length) { ProcessFilledBuffer(); } } public void BlockUpdate(byte[] input, int inOff, int length) { while (length > 0) { Update(input[inOff]); ++inOff; --length; } } public int DoFinal(byte[] output, int outOff) { Finish(); uint[] temp = new uint[8]; for (int i = 0; i < 4; i++) { RoundFunction(); Array.Copy(_mMill, 1, temp, i * 2, 2); } Pack.UInt32_To_LE(temp, output, outOff); Reset(); return GetDigestSize(); } public void Reset() { Array.Clear(_mMill, 0, _mMill.Length); for (int i = 0; i < BeltLength; i++) Array.Clear(_mBelt[i], 0, _mBelt[i].Length); _bufferPos = 0; _processedBytes = 0; } public IMemoable Copy() { return new RadioGatun32Digest(this); } public void Reset(IMemoable other) { RadioGatun32Digest originalDigest = (RadioGatun32Digest) other; Array.Copy(originalDigest._mMill, 0, _mMill, 0, _mMill.Length); Array.Copy(originalDigest._buffer, 0, _buffer, 0, _buffer.Length); int outerSourceArrayLength = originalDigest._mBelt.Length; _mBelt = new uint[outerSourceArrayLength][]; for (var idx = 0; idx < outerSourceArrayLength; idx++) { uint[] innerSourceArray = originalDigest._mBelt[idx]; int innerSourceArrayLength = innerSourceArray.Length; _mBelt[idx] = new uint[innerSourceArrayLength]; Array.Copy(innerSourceArray, _mBelt[idx], innerSourceArrayLength); } _bufferPos = originalDigest._bufferPos; _processedBytes = originalDigest._processedBytes; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using System.Linq; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.IpMessaging.V2.Service { /// <summary> /// FetchChannelOptions /// </summary> public class FetchChannelOptions : IOptions<ChannelResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchChannelOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> public FetchChannelOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// DeleteChannelOptions /// </summary> public class DeleteChannelOptions : IOptions<ChannelResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public ChannelResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new DeleteChannelOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> public DeleteChannelOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// CreateChannelOptions /// </summary> public class CreateChannelOptions : IOptions<ChannelResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The friendly_name /// </summary> public string FriendlyName { get; set; } /// <summary> /// The unique_name /// </summary> public string UniqueName { get; set; } /// <summary> /// The attributes /// </summary> public string Attributes { get; set; } /// <summary> /// The type /// </summary> public ChannelResource.ChannelTypeEnum Type { get; set; } /// <summary> /// The date_created /// </summary> public DateTime? DateCreated { get; set; } /// <summary> /// The date_updated /// </summary> public DateTime? DateUpdated { get; set; } /// <summary> /// The created_by /// </summary> public string CreatedBy { get; set; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public ChannelResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new CreateChannelOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> public CreateChannelOptions(string pathServiceSid) { PathServiceSid = pathServiceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } if (Type != null) { p.Add(new KeyValuePair<string, string>("Type", Type.ToString())); } if (DateCreated != null) { p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated))); } if (DateUpdated != null) { p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated))); } if (CreatedBy != null) { p.Add(new KeyValuePair<string, string>("CreatedBy", CreatedBy)); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } /// <summary> /// ReadChannelOptions /// </summary> public class ReadChannelOptions : ReadOptions<ChannelResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The type /// </summary> public List<ChannelResource.ChannelTypeEnum> Type { get; set; } /// <summary> /// Construct a new ReadChannelOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> public ReadChannelOptions(string pathServiceSid) { PathServiceSid = pathServiceSid; Type = new List<ChannelResource.ChannelTypeEnum>(); } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Type != null) { p.AddRange(Type.Select(prop => new KeyValuePair<string, string>("Type", prop.ToString()))); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// UpdateChannelOptions /// </summary> public class UpdateChannelOptions : IOptions<ChannelResource> { /// <summary> /// The service_sid /// </summary> public string PathServiceSid { get; } /// <summary> /// The sid /// </summary> public string PathSid { get; } /// <summary> /// The friendly_name /// </summary> public string FriendlyName { get; set; } /// <summary> /// The unique_name /// </summary> public string UniqueName { get; set; } /// <summary> /// The attributes /// </summary> public string Attributes { get; set; } /// <summary> /// The date_created /// </summary> public DateTime? DateCreated { get; set; } /// <summary> /// The date_updated /// </summary> public DateTime? DateUpdated { get; set; } /// <summary> /// The created_by /// </summary> public string CreatedBy { get; set; } /// <summary> /// The X-Twilio-Webhook-Enabled HTTP request header /// </summary> public ChannelResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; } /// <summary> /// Construct a new UpdateChannelOptions /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathSid"> The sid </param> public UpdateChannelOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (Attributes != null) { p.Add(new KeyValuePair<string, string>("Attributes", Attributes)); } if (DateCreated != null) { p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated))); } if (DateUpdated != null) { p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated))); } if (CreatedBy != null) { p.Add(new KeyValuePair<string, string>("CreatedBy", CreatedBy)); } return p; } /// <summary> /// Generate the necessary header parameters /// </summary> public List<KeyValuePair<string, string>> GetHeaderParams() { var p = new List<KeyValuePair<string, string>>(); if (XTwilioWebhookEnabled != null) { p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString())); } return p; } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComSale.Order.DS { /// <summary> /// Summary description for SO_InvoiceDetailDS. /// </summary> public class SO_InvoiceDetailDS { private const string THIS = "PCSComSale.Order.DS.SO_ConfirmShipDetailDS"; public Object GetObjectVO(int pintID) { throw new NotImplementedException(); } public DataSet List() { throw new NotImplementedException(); } public void Delete(int pintID) { throw new NotImplementedException(); } public void Update(Object pobjObjecVO) { throw new NotImplementedException(); } public void Add(Object pobjObjectVO) { throw new NotImplementedException(); } public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + SO_InvoiceDetailTable.INVOICEDETAILID_FLD + "," + SO_InvoiceDetailTable.INVOICEMASTERID_FLD + "," + SO_InvoiceDetailTable.SALEORDERDETAILID_FLD + "," + SO_InvoiceDetailTable.DELIVERYSCHEDULEID_FLD + "," + SO_InvoiceDetailTable.PRICE_FLD + "," + SO_InvoiceDetailTable.INVOICEQTY_FLD + "," + SO_InvoiceDetailTable.NETAMOUNT_FLD + "," + SO_InvoiceDetailTable.VATAMOUNT_FLD + "," + SO_InvoiceDetailTable.VATPERCENT_FLD + "," + SO_InvoiceDetailTable.PRODUCTID_FLD + " FROM " + SO_InvoiceDetailTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,SO_InvoiceDetailTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } else throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet ListByMaster(int pintMasterID) { const string METHOD_NAME = THIS + ".ListByMaster()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql= "SELECT " + SO_InvoiceDetailTable.INVOICEDETAILID_FLD + "," + SO_InvoiceDetailTable.INVOICEMASTERID_FLD + "," + SO_InvoiceDetailTable.SALEORDERDETAILID_FLD + "," + SO_InvoiceDetailTable.DELIVERYSCHEDULEID_FLD + "," + SO_InvoiceDetailTable.PRICE_FLD + "," + SO_InvoiceDetailTable.INVOICEQTY_FLD + "," + SO_InvoiceDetailTable.NETAMOUNT_FLD + "," + SO_InvoiceDetailTable.VATPERCENT_FLD + "," + SO_InvoiceDetailTable.VATAMOUNT_FLD + "," + SO_InvoiceDetailTable.PRODUCTID_FLD + " FROM " + SO_InvoiceDetailTable.TABLE_NAME + " WHERE " + SO_InvoiceDetailTable.INVOICEMASTERID_FLD + "=?"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.Parameters.AddWithValue(SO_InvoiceDetailTable.INVOICEMASTERID_FLD, pintMasterID); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,SO_InvoiceDetailTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet ListForReview(int pintMasterID) { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { var strSql = " SELECT DISTINCT Bin.Code AS BCode, L.Code As LCode," + " CA.Code ITM_CategoryCode, G.Code PartNo, G.Description, G.Revision,H.Code UMCode, " + " C.SaleOrderDetailID, E.DeliveryScheduleID, G.ProductID, ISNULL(G.AllowNegativeQty,0) AllowNegativeQty," + " E.ScheduleDate, GA.Code SO_GateCode, E.DeliveryQuantity AS CommittedQuantity," + " A.InvoiceQty, A.InvoiceQty OldInvoiceQty, ISNULL(BC.OHQuantity,0) - ISNULL(BC.CommitQuantity,0) AvailableQty, " + " A.Price, A.NetAmount,A.VATPercent, A.VATAmount, A.InvoiceMasterID ," + " A.InvoiceDetailID, B.LocationID,B.BinID," + " C.SellingUMID, C.SaleOrderMasterID,D.Code, C.SaleOrderLine, E.Line" + " FROM SO_InvoiceDetail A INNER JOIN SO_InvoiceMaster B ON A.InvoiceMasterID = B.InvoiceMasterID" + " INNER JOIN SO_SaleOrderDetail C ON C.SaleOrderDetailID = A.SaleOrderDetailID" + " INNER JOIN SO_SaleOrderMaster D ON C.SaleOrderMasterID = D.SaleOrderMasterID" + " INNER JOIN SO_DeliverySchedule E ON E.DeliveryScheduleID = A.DeliveryScheduleID" + " LEFT JOIN SO_Gate GA ON E.GateID = GA.GateID" + " INNER JOIN ITM_Product G ON C.ProductID = G.ProductID" + " LEFT JOIN ITM_Category CA ON CA.CategoryID = G.CategoryID" + " LEFT JOIN MST_Location L ON L.LocationID= B.LocationID " + " LEFT JOIN MST_BIN Bin ON Bin.BinID = B.BinID " + " LEFT JOIN IV_BinCache BC ON B.BinID = BC.BinID" + " AND BC.ProductID = G.ProductID" + " INNER JOIN MST_UnitOfMeasure H ON C.SellingUMID = H.UnitOfMeasureID " + " WHERE B.InvoiceMasterID = ?"; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.Parameters.AddWithValue(SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD,pintMasterID); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,SO_InvoiceDetailTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
#region License /* * Copyright (C) 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Generic; using System.Text; #endregion namespace BitSharper.Collections.Generic { /// <summary> /// Serve as based class to be inherited by the classes that needs to /// implement both the <see cref="ICollection"/> and /// the <see cref="ICollection{T}"/> interfaces. /// </summary> /// <remarks> /// <para> /// By inheriting from this abstract class, subclass is only required /// to implement the <see cref="GetEnumerator()"/> to complete a concrete /// read only collection class. /// </para> /// <para> /// <see cref="AbstractCollection{T}"/> throws <see cref="NotSupportedException"/> /// for all access to the collection mutating members. /// </para> /// </remarks> /// <typeparam name="T">Element type of the collection</typeparam> /// <author>Kenneth Xu</author> [Serializable] internal abstract class AbstractCollection<T> : ICollection<T>, ICollection //NET_ONLY { #region ICollection<T> Members /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. This implementation /// always throw <see cref="NotSupportedException"/>. /// </summary> /// /// <param name="item"> /// The object to add to the <see cref="ICollection{T}"/>. /// </param> /// <exception cref="NotSupportedException"> /// The <see cref="ICollection{T}"/> is read-only. This implementation /// always throw this exception. /// </exception> public virtual void Add(T item) { throw new NotSupportedException(); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. This implementation /// always throw <see cref="NotSupportedException"/>. /// </summary> /// /// <exception cref="NotSupportedException"> /// The <see cref="ICollection{T}"/> is read-only. This implementation always /// throw exception. /// </exception> public virtual void Clear() { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific /// value. This implementation searches the element by iterating through the /// enumerator returned by <see cref="GetEnumerator()"/> method. /// </summary> /// /// <returns> /// true if item is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> /// /// <param name="item"> /// The object to locate in the <see cref="ICollection{T}"/>. /// </param> public virtual bool Contains(T item) { foreach (var t in this) { if (Equals(t, item)) return true; } return false; } /// <summary> /// Returns an array containing all of the elements in this collection, /// in proper sequence. /// </summary> /// <remarks> /// <para> /// The returned array will be "safe" in that no references to it are /// maintained by this collection. (In other words, this method must /// allocate a new array). The caller is thus free to modify the /// returned array. /// </para> /// <para> /// This method acts as bridge between array-based and collection-based /// APIs. /// </para> /// </remarks> /// <returns> /// An array containing all of the elements in this collection. /// </returns> public virtual T[] ToArray() { return DoCopyTo(null, 0, true); } /// <summary> /// Returns an array containing all of the elements in this collection, /// in proper sequence; the runtime type of the returned array is that /// of the specified array. If the collection fits in the specified /// array, it is returned therein. Otherwise, a new array is allocated /// with the runtime type of the specified array and the size of this /// collection. /// </summary> /// <remarks> /// <para> /// Like the <see cref="ToArray()"/> method, this method acts as bridge /// between array-based and collection-based APIs. Further, this /// method allows precise control over the runtime type of the output /// array, and may, under certain circumstances, be used to save /// allocation costs. /// </para> /// <para> /// Suppose <i>x</i> is a collection known to contain only strings. /// The following code can be used to dump the collection into a newly /// allocated array of <see cref="string"/>s: /// /// <code language="c#"> /// string[] y = (string[]) x.ToArray(new string[0]); /// </code> /// </para> /// <para> /// Note that <i>ToArray(new T[0])</i> is identical in function to /// <see cref="AbstractCollection{T}.ToArray()"/>. /// </para> /// </remarks> /// <param name="targetArray"> /// The array into which the elements of the collection are to be /// stored, if it is big enough; otherwise, a new array of the same /// runtime type is allocated for this purpose. /// </param> /// <returns> /// An array containing all of the elements in this collection. /// </returns> /// <exception cref="ArgumentNullException"> /// If the supplied <paramref name="targetArray"/> is /// <c>null</c>. /// </exception> /// <exception cref="ArrayTypeMismatchException"> /// If type of <paramref name="targetArray"/> is a derived type of /// <typeparamref name="T"/> and the collection contains element that /// is not that derived type. /// </exception> public virtual T[] ToArray(T[] targetArray) { if (targetArray == null) throw new ArgumentNullException("targetArray"); return DoCopyTo(targetArray, 0, true); } /// <summary> /// Copies the elements of the <see cref="ICollection{T}"/> to an /// <see cref="Array"/>, starting at a particular <see cref="Array"/> /// index. /// </summary> /// <remarks> /// This method is intentionally sealed. Subclass should override /// <see cref="DoCopyTo(T[], int, bool)"/> instead. /// </remarks> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the /// destination of the elements copied from <see cref="ICollection{T}"/>. /// The <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in array at which copying begins. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// arrayIndex is less than 0. /// </exception> /// <exception cref="ArgumentNullException"> /// array is null. /// </exception> /// <exception cref="ArgumentException"> /// array is multidimensional.<br/>-or-<br/> /// arrayIndex is equal to or greater than the length of array. <br/>-or-<br/> /// The number of elements in the source <see cref="ICollection{T}"/> /// is greater than the available space from arrayIndex to the end of /// the destination array. <br/>-or-<br/> /// Type T cannot be cast automatically to the type of the destination array. /// </exception> public void CopyTo(T[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < array.GetLowerBound(0)) { throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "arrayIndex must not be less then the lower bound of the array."); } try { DoCopyTo(array, arrayIndex, false); } catch (IndexOutOfRangeException e) { throw new ArgumentException("array is too small to fit the collection.", "array", e); } } /// <summary> /// Does the actual work of copying to array. Subclass is recommended to /// override this method instead of <see cref="CopyTo(T[], int)"/> method, which /// does all necessary parameter checking and raises proper exception /// before calling this method. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the /// destination of the elements copied from <see cref="ICollection{T}"/>. /// The <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in array at which copying begins. /// </param> /// <param name="ensureCapacity"> /// If is <c>true</c>, calls <see cref="EnsureCapacity"/> /// </param> /// <returns> /// A new array of same runtime type as <paramref name="array"/> if /// <paramref name="array"/> is too small to hold all elements and /// <paramref name="ensureCapacity"/> is <c>false</c>. Otherwise /// the <paramref name="array"/> instance itself. /// </returns> protected virtual T[] DoCopyTo(T[] array, int arrayIndex, bool ensureCapacity) { if (ensureCapacity) array = EnsureCapacity(array, Count); foreach (var e in this) array[arrayIndex++] = e; return array; } /// <summary> /// Ensures the returned array has capacity specified by <paramref name="length"/>. /// </summary> /// <remarks> /// If <typeparamref name="T"/> is <see cref="object"/> but array is /// actually <c>string[]</c>, the returned array is always <c>string[]</c>. /// </remarks> /// <param name="array"> /// The source array. /// </param> /// <param name="length"> /// Expected length of array. /// </param> /// <returns> /// <paramref name="array"/> itself if <c>array.Length >= length</c>. /// Otherwise a new array of same type of <paramref name="array"/> of given /// <paramref name="length"/>. /// </returns> protected static T[] EnsureCapacity(T[] array, int length) { if (array == null) return new T[length]; if (array.Length >= length) return array; // new T[size] won't work here when targetArray is subtype of T. return (T[]) Array.CreateInstance(array.GetType().GetElementType(), length); } /// <summary> /// Gets the number of elements contained in the <see cref="ICollection{T}"/>. /// This implementation counts the elements by iterating through the /// enumerator returned by <see cref="GetEnumerator()"/> method. /// </summary> /// /// <returns> /// The number of elements contained in the <see cref="ICollection{T}"/>. /// </returns> /// public virtual int Count { get { var count = 0; foreach (var item in this) count++; return count; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// This implementation always return true; /// </summary> /// /// <returns> /// true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// This implementation always return true; /// </returns> /// public virtual bool IsReadOnly { get { return true; } } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// This implementation always throw <see cref="NotSupportedException"/>. /// </summary> /// /// <returns> /// true if item was successfully removed from the <see cref="ICollection{T}"/>; /// otherwise, false. This method also returns false if item is not found in the /// original <see cref="ICollection{T}"/>. /// </returns> /// /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException"> /// When the <see cref="ICollection{T}"/> is read-only. This implementation always /// throw this exception. /// </exception> public virtual bool Remove(T item) { throw new NotSupportedException(); } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <remarks> /// Subclass must implement this method. /// </remarks> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate /// through the collection. /// </returns> /// <filterpriority>1</filterpriority> public abstract IEnumerator<T> GetEnumerator(); #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> /// object that can be used to iterate through the collection. /// </returns> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region ICollection Members /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> /// to an <see cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> /// that is the destination of the elements copied from /// <see cref="T:System.Collections.ICollection"/>. The /// <see cref="T:System.Array"/> must have zero-based indexing. </param> /// <param name="index">The zero-based index in array at which copying begins. </param> /// <exception cref="T:System.ArgumentNullException">array is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException">index is less than zero. </exception> /// <exception cref="T:System.ArgumentException"> /// array is multidimensional.-or- index is equal to or greater than /// the length of array.-or- The number of elements in the source /// <see cref="T:System.Collections.ICollection"/> is greater /// than the available space from index to the end of the destination /// array. </exception> /// <exception cref="T:System.InvalidCastException"> /// The type of the source <see cref="T:System.Collections.ICollection"/> /// cannot be cast automatically to the type of the destination array. </exception> /// <filterpriority>2</filterpriority> void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < array.GetLowerBound(0)) { throw new ArgumentOutOfRangeException("index", index, "index must not be less then lower bound of the array"); } try { CopyTo(array, index); } catch (RankException re) { throw new ArgumentException("array must not be multi-dimensional.", "array", re); } catch (IndexOutOfRangeException e) { throw new ArgumentException("array is too small to fit the collection.", "array", e); } } /// <summary> /// Gets a value indicating whether access to the /// <see cref="T:System.Collections.ICollection"/> /// is synchronized (thread safe). /// </summary> /// <returns> /// true if access to the <see cref="T:System.Collections.ICollection"/> /// is synchronized (thread safe); otherwise, false. /// </returns> /// <filterpriority>2</filterpriority> bool ICollection.IsSynchronized { get { return IsSynchronized; } } /// <summary> /// Gets an object that can be used to synchronize access to the /// <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <returns> /// An object that can be used to synchronize access to the /// <see cref="T:System.Collections.ICollection"/>. /// </returns> /// <filterpriority>2</filterpriority> object ICollection.SyncRoot { get { return SyncRoot; } } #endregion /// <summary> /// Returns a <see cref="string"/> that represents the current <see cref="object"/>. /// </summary> /// <remarks> /// This implementation list out all the elements separated by comma. /// </remarks> /// <returns> /// A <see cref="string"/> that represents the current <see cref="object"/>. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { var sb = new StringBuilder(); sb.Append(GetType().Name).Append("("); var first = true; foreach (var e in this) { if (!first) sb.Append(", "); sb.Append(e); first = false; } return sb.Append(")").ToString(); } /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an /// <see cref="Array"/>, starting at a particular <see cref="Array"/> /// index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the destination /// of the elements copied from <see cref="ICollection"/>. The /// <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="index"> /// The zero-based index in array at which copying begins. /// </param> /// <exception cref="ArgumentNullException">array is null. </exception> /// <exception cref="ArgumentOutOfRangeException"> /// index is less than zero. /// </exception> /// <exception cref="ArgumentException"> /// array is multidimensional.-or- index is equal to or greater than /// the length of array. /// -or- /// The number of elements in the source <see cref="ICollection"/> /// is greater than the available space from index to the end of the /// destination array. /// </exception> /// <exception cref="InvalidCastException"> /// The type of the source <see cref="ICollection"/> cannot be cast /// automatically to the type of the destination array. /// </exception> /// <filterpriority>2</filterpriority> protected virtual void CopyTo(Array array, int index) { foreach (var e in this) array.SetValue(e, index++); } /// <summary> /// Gets an object that can be used to synchronize access to the /// <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <remarks>This implementation returns <see langword="null"/>.</remarks> /// <returns> /// An object that can be used to synchronize access to the /// <see cref="T:System.Collections.ICollection"/>. /// </returns> /// <filterpriority>2</filterpriority> protected virtual object SyncRoot { get { return null; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> /// is synchronized (thread safe). /// </summary> /// <remarks>This implementation always return <see langword="false"/>.</remarks> /// <returns> /// true if access to the <see cref="ICollection"/> /// is synchronized (thread safe); otherwise, false. /// </returns> /// <filterpriority>2</filterpriority> protected virtual bool IsSynchronized { get { return false; } } /// <summary> /// Adds all of the elements in the supplied <paramref name="collection"/> /// to this collection. /// </summary> /// <remarks> /// <para> /// Attempts to <see cref="AddRange"/> of a collection to /// itself result in <see cref="ArgumentException"/>. Further, the /// behavior of this operation is undefined if the specified /// collection is modified while the operation is in progress. /// </para> /// <para> /// This implementation iterates over the specified collection, and /// adds each element returned by the iterator to this collection, in turn. /// An exception encountered while trying to add an element may result /// in only some of the elements having been successfully added when /// the associated exception is thrown. /// </para> /// </remarks> /// <param name="collection"> /// The collection containing the elements to be added to this collection. /// </param> /// <returns> /// <c>true</c> if this collection is modified, else <c>false</c>. /// </returns> /// <exception cref="System.ArgumentNullException"> /// If the supplied <paramref name="collection"/> is <see langword="null"/>. /// </exception> /// <exception cref="System.ArgumentException"> /// If the collection is the current collection. /// </exception> public virtual bool AddRange(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } if (collection == this) { throw new ArgumentException("Cannot add to itself.", "collection"); } return DoAddRange(collection); } /// <summary> /// Called by <see cref="AddRange"/> after the parameter is validated /// to be neither <c>null</c> nor this collection itself. /// </summary> /// <param name="collection">Collection of items to be added.</param> /// <returns> /// <c>true</c> if this collection is modified, else <c>false</c>. /// </returns> protected virtual bool DoAddRange(IEnumerable<T> collection) { var modified = false; foreach (var element in collection) { Add(element); modified = true; } return modified; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for RouteFilterRulesOperations. /// </summary> public static partial class RouteFilterRulesOperationsExtensions { /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> public static void Delete(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName) { operations.DeleteAsync(resourceGroupName, routeFilterName, ruleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified rule from a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> public static RouteFilterRule Get(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName) { return operations.GetAsync(resourceGroupName, routeFilterName, ruleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified rule from a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilterRule> GetAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> public static RouteFilterRule CreateOrUpdate(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilterRule> CreateOrUpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> public static RouteFilterRule Update(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters) { return operations.UpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilterRule> UpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> public static IPage<RouteFilterRule> ListByRouteFilter(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName) { return operations.ListByRouteFilterAsync(resourceGroupName, routeFilterName).GetAwaiter().GetResult(); } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilterRule>> ListByRouteFilterAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByRouteFilterWithHttpMessagesAsync(resourceGroupName, routeFilterName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> public static void BeginDelete(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName) { operations.BeginDeleteAsync(resourceGroupName, routeFilterName, ruleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified rule from a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> public static RouteFilterRule BeginCreateOrUpdate(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the create or update route filter rule operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilterRule> BeginCreateOrUpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> public static RouteFilterRule BeginUpdate(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters) { return operations.BeginUpdateAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a route in the specified route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='ruleName'> /// The name of the route filter rule. /// </param> /// <param name='routeFilterRuleParameters'> /// Parameters supplied to the update route filter rule operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RouteFilterRule> BeginUpdateAsync(this IRouteFilterRulesOperations operations, string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<RouteFilterRule> ListByRouteFilterNext(this IRouteFilterRulesOperations operations, string nextPageLink) { return operations.ListByRouteFilterNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all RouteFilterRules in a route filter. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RouteFilterRule>> ListByRouteFilterNextAsync(this IRouteFilterRulesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByRouteFilterNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* VRPhysicsConstraintPlanar * MiddleVR * (c) MiddleVR */ using UnityEngine; using System; using System.Collections; using MiddleVR_Unity3D; [AddComponentMenu("MiddleVR/Physics/Constraints/Planar")] [RequireComponent(typeof(VRPhysicsBody))] public class VRPhysicsConstraintPlanar : MonoBehaviour { #region Member Variables [SerializeField] private GameObject m_ConnectedBody = null; [SerializeField] private Vector3 m_Axis0 = new Vector3(1.0f, 0.0f, 0.0f); [SerializeField] private Vector3 m_Axis1 = new Vector3(0.0f, 1.0f, 0.0f); [SerializeField] private float m_GizmoLineLength = 1.0f; private vrPhysicsConstraintPlanar m_PhysicsConstraint = null; private string m_PhysicsConstraintName = ""; private vrEventListener m_MVREventListener = null; #endregion #region Member Properties public vrPhysicsConstraintPlanar PhysicsConstraint { get { return m_PhysicsConstraint; } } public string PhysicsConstraintName { get { return m_PhysicsConstraintName; } } public GameObject ConnectedBody { get { return m_ConnectedBody; } set { m_ConnectedBody = value; } } public Vector3 Axis0 { get { return m_Axis0; } set { m_Axis0 = value; } } public Vector3 Axis1 { get { return m_Axis1; } set { m_Axis1 = value; } } #endregion #region MonoBehaviour Member Functions protected void Start() { if (MiddleVR.VRClusterMgr.IsCluster() && !MiddleVR.VRClusterMgr.IsServer()) { enabled = false; return; } if (MiddleVR.VRPhysicsMgr == null) { MiddleVRTools.Log(0, "No PhysicsManager found when creating a planar constraint."); return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return; } if (m_PhysicsConstraint == null) { m_PhysicsConstraint = physicsEngine.CreateConstraintPlanarWithUniqueName(name); if (m_PhysicsConstraint == null) { MiddleVRTools.Log(0, "[X] Could not create a planar physics constraint '" + name + "'."); } else { GC.SuppressFinalize(m_PhysicsConstraint); m_MVREventListener = new vrEventListener(OnMVRNodeDestroy); m_PhysicsConstraint.AddEventListener(m_MVREventListener); m_PhysicsConstraintName = m_PhysicsConstraint.GetName(); AddConstraint(); } } } protected void OnDrawGizmosSelected() { if (enabled) { Vector3 origin = transform.TransformPoint(Vector3.zero); Gizmos.color = Color.yellow; Vector3 axis0Dir = transform.TransformDirection(m_Axis0); axis0Dir.Normalize(); Gizmos.DrawLine(origin, origin + m_GizmoLineLength * axis0Dir); Gizmos.color = Color.gray; Vector3 axis1Dir = transform.TransformDirection(m_Axis1); axis1Dir.Normalize(); Gizmos.DrawLine(origin, origin + m_GizmoLineLength * axis1Dir); } } protected void OnDestroy() { if (m_PhysicsConstraint == null) { return; } if (MiddleVR.VRPhysicsMgr == null) { return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return; } physicsEngine.DestroyConstraint(m_PhysicsConstraintName); m_PhysicsConstraint = null; m_PhysicsConstraintName = ""; } #endregion #region VRPhysicsConstraintPlanar Functions protected bool AddConstraint() { vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return false; } if (m_PhysicsConstraint == null) { return false; } bool addedToSimulation = false; // Cannot fail since we require this component. VRPhysicsBody body0 = GetComponent<VRPhysicsBody>(); VRPhysicsBody body1 = null; if (m_ConnectedBody != null) { body1 = m_ConnectedBody.GetComponent<VRPhysicsBody>(); } if (body0.PhysicsBody != null) { m_PhysicsConstraint.SetAxis0(MiddleVRTools.FromUnity(Axis0)); m_PhysicsConstraint.SetAxis1(MiddleVRTools.FromUnity(Axis1)); m_PhysicsConstraint.SetBody(0, body0.PhysicsBody); m_PhysicsConstraint.SetBody(1, body1 != null ? body1.PhysicsBody : null); addedToSimulation = physicsEngine.AddConstraint(m_PhysicsConstraint); if (addedToSimulation) { MiddleVRTools.Log(3, "[ ] The constraint '" + m_PhysicsConstraintName + "' was added to the physics simulation."); } else { MiddleVRTools.Log(3, "[X] Failed to add the constraint '" + m_PhysicsConstraintName + "' to the physics simulation."); } } else { MiddleVRTools.Log(0, "[X] The PhysicsBody of '" + name + "' for the planar physics constraint '" + m_PhysicsConstraintName + "' is null."); } return addedToSimulation; } private bool OnMVRNodeDestroy(vrEvent iBaseEvt) { vrObjectEvent e = vrObjectEvent.Cast(iBaseEvt); if (e != null) { if (e.ComesFrom(m_PhysicsConstraint)) { if (e.eventType == (int)VRObjectEventEnum.VRObjectEvent_Destroy) { // Killed in MiddleVR so delete it in C#. m_PhysicsConstraint.Dispose(); } } } return true; } #endregion }
using System; using System.Text; using System.IO; namespace CocosSharp { internal static partial class CCLabelUtilities { // The code for reading the TTF font file is based on TrueTypeSharp project originally // developed by Zer at http://www.zer7.com/software/truetypesharp. // The original code does not parse the name table to obtain the FontFamily so a rudimentary // implementation is here in GetFontFamily methods. #region Structure Definitions #pragma warning disable 0660, 0661 // This never goes into a collection... internal struct FakePtr<T> { public T[] Array; public int Offset; public T[] GetData(int length) { var t = new T[length]; if (Array != null) { global::System.Array.Copy(Array, Offset, t, 0, length); } return t; } public void MakeNull() { Array = null; Offset = 0; } public T this[int index] { get { try { return Array[Offset + index]; } catch (IndexOutOfRangeException) { return default(T); } // Sometimes accesses are made out of range, it appears. // In particular, to get all the way to char.MaxValue, this was needed. // Probably bad data in the font. Also, is bounds checking done? // I don't see it... Either way, it's not a problem for us here. } set { Array[Offset + index] = value; } } public T Value { get { return this[0]; } set { this[0] = value; } } public bool IsNull { get { return Array == null; } } public static FakePtr<T> operator +(FakePtr<T> p, int offset) { return new FakePtr<T>() { Array = p.Array, Offset = p.Offset + offset }; } public static FakePtr<T> operator -(FakePtr<T> p, int offset) { return p + -offset; } public static FakePtr<T> operator +(FakePtr<T> p, uint offset) { return p + (int)offset; } public static FakePtr<T> operator ++(FakePtr<T> p) { return p + 1; } public static bool operator ==(FakePtr<T> p1, FakePtr<T> p2) { return p1.Array == p2.Array && p1.Offset == p2.Offset; } public static bool operator !=(FakePtr<T> p1, FakePtr<T> p2) { return !(p1 == p2); } } internal struct stbtt_fontinfo { public FakePtr<byte> data; // pointer to .ttf file public int fontstart; // offset of start of font public uint name; // table locations as offset from start of .ttf public stbtt_name_record[] nameRecords; } internal struct stbtt_name_record { public ushort platformId; public ushort platformSpecificId; public ushort languageId; public ushort nameId; public ushort length; public uint offset; } static stbtt_fontinfo _info; #endregion #region GetFontFamily routines // // http://www.microsoft.com/typography/otspec/name.htm // and https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html // public static string GetFontFamily(string filename) { return GetFontFamily(File.ReadAllBytes(filename), 0); } // // http://www.microsoft.com/typography/otspec/name.htm // and https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html // public static string GetFontFamily(byte[] data, int offset) { CheckFontData(data, offset); if (0 == stbtt_InitFont(ref _info, new FakePtr<byte>() { Array = data }, offset)) { throw new BadImageFormatException("Couldn't load TrueType file."); } var name = new StringBuilder(); uint i; foreach (var nr in _info.nameRecords) { name.Clear(); //if (nr.nameId == 1 || nr.nameId == 2 || nr.nameId == 4) // We only want the Name Id code 1 for Font Family // Reference Name Identifiers in the links above if (nr.nameId == 1) { var nameBytes = new byte[nr.length]; var nameOffset = _info.data + nr.offset; for (i = 0; i < nr.length; i++) { nameBytes[i] = ttBYTE(nameOffset + i); } // reference http://www.microsoft.com/typography/otspec/name.htm // Note that OS/2 and Windows both require that all name strings be defined in Unicode. // Thus all 'name' table strings for platform ID = 3 (Windows) will require two bytes per character. // Macintosh fonts require single byte strings. if (nr.platformId == 1) // Mac name.Append(Encoding.UTF8.GetString(nameBytes)); else name.Append(Encoding.BigEndianUnicode.GetString(nameBytes)); // Microsoft return name.ToString(); } } return string.Empty; } #endregion #region TrueTypeSharp helper methods static void CheckFontData(byte[] data, int offset) { if (data == null) { throw new ArgumentNullException("data"); } if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException("offset"); } } static ushort ttUSHORT(FakePtr<byte> p) { return (ushort)(p[0] * 256 + p[1]); } static sbyte ttCHAR(FakePtr<byte> p) { return (sbyte)p.Value; } static uint ttULONG(FakePtr<byte> p) { return ((uint)p[0] << 24) + ((uint)p[1] << 16) + ((uint)p[2] << 8) + p[3]; } static byte ttBYTE(FakePtr<byte> p) { return p.Value; } static int stbtt_InitFont(ref stbtt_fontinfo info, FakePtr<byte> data2, int fontstart) { FakePtr<byte> data = (FakePtr<byte>)data2; uint i; info.data = data; info.fontstart = fontstart; info.name = stbtt__find_table(data, fontstart, "name"); // required if (info.name == 0) return 0; var format = ttUSHORT(data + info.name); var nameRecordCount = ttUSHORT(data + info.name + 2); var stringOffset = ttUSHORT(data + info.name + 4); var offset = info.name + stringOffset; var nameRecords = new stbtt_name_record[nameRecordCount]; for (i = 0; i < nameRecordCount; ++i) { uint name_record = info.name + 6 + 12 * i; var nr = nameRecords[i]; nr.platformId = ttUSHORT(data + name_record); nr.platformSpecificId = ttUSHORT(data + name_record + 2); nr.languageId = ttUSHORT(data + name_record + 4); nr.nameId = ttUSHORT(data + name_record + 6); nr.length = ttUSHORT(data + name_record + 8); nr.offset = ttUSHORT(data + name_record + 10) + offset; nameRecords[i] = nr; } info.nameRecords = nameRecords; return 1; } static uint stbtt__find_table(FakePtr<byte> data, int fontstart, string tag) { int num_tables = ttUSHORT(data + fontstart + 4); int tabledir = fontstart + 12; int i; for (i = 0; i < num_tables; ++i) { int loc = tabledir + 16 * i; if (stbtt_tag(data + loc + 0, tag)) return ttULONG(data + loc + 8); } return 0; } static bool stbtt_tag4(FakePtr<byte> p, byte c0, byte c1, byte c2, byte c3) { return ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)); } static bool stbtt_tag(FakePtr<byte> p, string str) { return stbtt_tag4(p, (byte)(str.Length >= 1 ? str[0] : 0), (byte)(str.Length >= 2 ? str[1] : 0), (byte)(str.Length >= 3 ? str[2] : 0), (byte)(str.Length >= 4 ? str[3] : 0)); } #endregion } }
using System; using System.IO; using System.Threading; using NServiceKit.Common.Web; using NServiceKit.Service; using NServiceKit.ServiceHost; using NServiceKit.Text; namespace NServiceKit.ServiceClient.Web { /// <summary>A JSON rest client asynchronous.</summary> [Obsolete("Use JsonServiceClient")] public class JsonRestClientAsync : IRestClientAsync { /// <summary>Type of the content.</summary> public const string ContentType = "application/json"; /// <summary>Initializes a new instance of the NServiceKit.ServiceClient.Web.JsonRestClientAsync class.</summary> /// /// <param name="baseUri">The base URI.</param> public JsonRestClientAsync(string baseUri) : this() { this.BaseUri = baseUri.WithTrailingSlash(); } /// <summary>Initializes a new instance of the NServiceKit.ServiceClient.Web.JsonRestClientAsync class.</summary> public JsonRestClientAsync() { this.client = new AsyncServiceClient { ContentType = ContentType, StreamSerializer = SerializeToStream, StreamDeserializer = JsonSerializer.DeserializeFromStream }; } /// <summary>Gets or sets the timeout.</summary> /// /// <value>The timeout.</value> public TimeSpan? Timeout { get { return this.client.Timeout; } set { this.client.Timeout = value; } } private static void SerializeToStream(IRequestContext requestContext, object dto, Stream stream) { JsonSerializer.SerializeToStream(dto, stream); } private readonly AsyncServiceClient client; /// <summary>Gets or sets URI of the base.</summary> /// /// <value>The base URI.</value> public string BaseUri { get; set; } /// <summary>Set the credentials to be used when making requests.</summary> /// /// <param name="userName">.</param> /// <param name="password">.</param> public void SetCredentials(string userName, string password) { this.client.SetCredentials(userName, password); } /// <summary>Gets the asynchronous.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="request"> The request.</param> /// <param name="onSuccess">The on success.</param> /// <param name="onError"> The on error.</param> public void GetAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } private string GetUrl(string relativeOrAbsoluteUrl) { return relativeOrAbsoluteUrl.StartsWith("http:") || relativeOrAbsoluteUrl.StartsWith("https:") ? relativeOrAbsoluteUrl : this.BaseUri + relativeOrAbsoluteUrl; } /// <summary>Gets the asynchronous.</summary> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param> /// <param name="onSuccess"> The on success.</param> /// <param name="onError"> The on error.</param> public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { this.client.SendAsync(HttpMethods.Get, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError); } /// <summary>Deletes the asynchronous.</summary> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param> /// <param name="onSuccess"> The on success.</param> /// <param name="onError"> The on error.</param> public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { this.client.SendAsync(HttpMethods.Delete, GetUrl(relativeOrAbsoluteUrl), null, onSuccess, onError); } /// <summary>Deletes the asynchronous.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="request"> The request.</param> /// <param name="onSuccess">The on success.</param> /// <param name="onError"> The on error.</param> public void DeleteAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } /// <summary>Posts the asynchronous.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="request"> The request.</param> /// <param name="onSuccess">The on success.</param> /// <param name="onError"> The on error.</param> public void PostAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } /// <summary>Posts the asynchronous.</summary> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param> /// <param name="request"> The request.</param> /// <param name="onSuccess"> The on success.</param> /// <param name="onError"> The on error.</param> public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { this.client.SendAsync(HttpMethods.Post, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError); } /// <summary>Puts the asynchronous.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="request"> The request.</param> /// <param name="onSuccess">The on success.</param> /// <param name="onError"> The on error.</param> public void PutAsync<TResponse>(IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } /// <summary>Puts the asynchronous.</summary> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="relativeOrAbsoluteUrl">URL of the relative or absolute.</param> /// <param name="request"> The request.</param> /// <param name="onSuccess"> The on success.</param> /// <param name="onError"> The on error.</param> public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { this.client.SendAsync(HttpMethods.Put, GetUrl(relativeOrAbsoluteUrl), request, onSuccess, onError); } /// <summary>Custom method asynchronous.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> /// /// <typeparam name="TResponse">Type of the response.</typeparam> /// <param name="httpVerb"> The HTTP verb.</param> /// <param name="request"> The request.</param> /// <param name="onSuccess">The on success.</param> /// <param name="onError"> The on error.</param> public void CustomMethodAsync<TResponse>(string httpVerb, IReturn<TResponse> request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { throw new NotImplementedException(); } /// <summary>Cancels pending async operations.</summary> /// /// <exception cref="NotImplementedException">Thrown when the requested operation is unimplemented.</exception> public void CancelAsync() { throw new NotImplementedException(); } /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> public void Dispose() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Internal.NativeFormat; namespace Internal.TypeSystem { public abstract partial class TypeSystemContext { public TypeSystemContext() : this(new TargetDetails(TargetArchitecture.Unknown, TargetOS.Unknown, TargetAbi.Unknown)) { } public TypeSystemContext(TargetDetails target) { Target = target; _instantiatedTypes = new InstantiatedTypeKey.InstantiatedTypeKeyHashtable(); _arrayTypes = new ArrayTypeKey.ArrayTypeKeyHashtable(); _byRefTypes = new ByRefHashtable(); _pointerTypes = new PointerHashtable(); _functionPointerTypes = new FunctionPointerHashtable(); _instantiatedMethods = new InstantiatedMethodKey.InstantiatedMethodKeyHashtable(); _methodForInstantiatedTypes = new MethodForInstantiatedTypeKey.MethodForInstantiatedTypeKeyHashtable(); _fieldForInstantiatedTypes = new FieldForInstantiatedTypeKey.FieldForInstantiatedTypeKeyHashtable(); _signatureVariables = new SignatureVariableHashtable(this); } public TargetDetails Target { get; } public ModuleDesc SystemModule { get; private set; } protected void InitializeSystemModule(ModuleDesc systemModule) { Debug.Assert(SystemModule == null); SystemModule = systemModule; } public abstract DefType GetWellKnownType(WellKnownType wellKnownType); public virtual ModuleDesc ResolveAssembly(AssemblyName name, bool throwIfNotFound = true) { if (throwIfNotFound) throw new NotSupportedException(); return null; } // // Array types // public ArrayType GetArrayType(TypeDesc elementType) { return GetArrayType(elementType, -1); } // // MDArray types // private struct ArrayTypeKey { private TypeDesc _elementType; private int _rank; public ArrayTypeKey(TypeDesc elementType, int rank) { _elementType = elementType; _rank = rank; } public TypeDesc ElementType { get { return _elementType; } } public int Rank { get { return _rank; } } public class ArrayTypeKeyHashtable : LockFreeReaderHashtable<ArrayTypeKey, ArrayType> { protected override int GetKeyHashCode(ArrayTypeKey key) { return TypeHashingAlgorithms.ComputeArrayTypeHashCode(key._elementType, key._rank); } protected override int GetValueHashCode(ArrayType value) { return TypeHashingAlgorithms.ComputeArrayTypeHashCode(value.ElementType, value.IsSzArray ? -1 : value.Rank); } protected override bool CompareKeyToValue(ArrayTypeKey key, ArrayType value) { if (key._elementType != value.ElementType) return false; if (value.IsSzArray) return key._rank == -1; return key._rank == value.Rank; } protected override bool CompareValueToValue(ArrayType value1, ArrayType value2) { return (value1.ElementType == value2.ElementType) && (value1.Rank == value2.Rank) && value1.IsSzArray == value2.IsSzArray; } protected override ArrayType CreateValueFromKey(ArrayTypeKey key) { return new ArrayType(key.ElementType, key.Rank); } } } private ArrayTypeKey.ArrayTypeKeyHashtable _arrayTypes; public ArrayType GetArrayType(TypeDesc elementType, int rank) { return _arrayTypes.GetOrCreateValue(new ArrayTypeKey(elementType, rank)); } // // ByRef types // public class ByRefHashtable : LockFreeReaderHashtable<TypeDesc, ByRefType> { protected override int GetKeyHashCode(TypeDesc key) { return key.GetHashCode(); } protected override int GetValueHashCode(ByRefType value) { return value.ParameterType.GetHashCode(); } protected override bool CompareKeyToValue(TypeDesc key, ByRefType value) { return key == value.ParameterType; } protected override bool CompareValueToValue(ByRefType value1, ByRefType value2) { return value1.ParameterType == value2.ParameterType; } protected override ByRefType CreateValueFromKey(TypeDesc key) { return new ByRefType(key); } } private ByRefHashtable _byRefTypes; public ByRefType GetByRefType(TypeDesc parameterType) { return _byRefTypes.GetOrCreateValue(parameterType); } // // Pointer types // public class PointerHashtable : LockFreeReaderHashtable<TypeDesc, PointerType> { protected override int GetKeyHashCode(TypeDesc key) { return key.GetHashCode(); } protected override int GetValueHashCode(PointerType value) { return value.ParameterType.GetHashCode(); } protected override bool CompareKeyToValue(TypeDesc key, PointerType value) { return key == value.ParameterType; } protected override bool CompareValueToValue(PointerType value1, PointerType value2) { return value1.ParameterType == value2.ParameterType; } protected override PointerType CreateValueFromKey(TypeDesc key) { return new PointerType(key); } } private PointerHashtable _pointerTypes; public PointerType GetPointerType(TypeDesc parameterType) { return _pointerTypes.GetOrCreateValue(parameterType); } // // Function pointer types // public class FunctionPointerHashtable : LockFreeReaderHashtable<MethodSignature, FunctionPointerType> { protected override int GetKeyHashCode(MethodSignature key) { return key.GetHashCode(); } protected override int GetValueHashCode(FunctionPointerType value) { return value.Signature.GetHashCode(); } protected override bool CompareKeyToValue(MethodSignature key, FunctionPointerType value) { return key.Equals(value.Signature); } protected override bool CompareValueToValue(FunctionPointerType value1, FunctionPointerType value2) { return value1.Signature.Equals(value2.Signature); } protected override FunctionPointerType CreateValueFromKey(MethodSignature key) { return new FunctionPointerType(key); } } private FunctionPointerHashtable _functionPointerTypes; public FunctionPointerType GetFunctionPointerType(MethodSignature signature) { return _functionPointerTypes.GetOrCreateValue(signature); } // // Instantiated types // private struct InstantiatedTypeKey { private TypeDesc _typeDef; private Instantiation _instantiation; public InstantiatedTypeKey(TypeDesc typeDef, Instantiation instantiation) { _typeDef = typeDef; _instantiation = instantiation; } public TypeDesc TypeDef { get { return _typeDef; } } public Instantiation Instantiation { get { return _instantiation; } } public class InstantiatedTypeKeyHashtable : LockFreeReaderHashtable<InstantiatedTypeKey, InstantiatedType> { protected override int GetKeyHashCode(InstantiatedTypeKey key) { return key._instantiation.ComputeGenericInstanceHashCode(key._typeDef.GetHashCode()); } protected override int GetValueHashCode(InstantiatedType value) { return value.Instantiation.ComputeGenericInstanceHashCode(value.GetTypeDefinition().GetHashCode()); } protected override bool CompareKeyToValue(InstantiatedTypeKey key, InstantiatedType value) { if (key._typeDef != value.GetTypeDefinition()) return false; Instantiation valueInstantiation = value.Instantiation; if (key._instantiation.Length != valueInstantiation.Length) return false; for (int i = 0; i < key._instantiation.Length; i++) { if (key._instantiation[i] != valueInstantiation[i]) return false; } return true; } protected override bool CompareValueToValue(InstantiatedType value1, InstantiatedType value2) { if (value1.GetTypeDefinition() != value2.GetTypeDefinition()) return false; Instantiation value1Instantiation = value1.Instantiation; Instantiation value2Instantiation = value2.Instantiation; if (value1Instantiation.Length != value2Instantiation.Length) return false; for (int i = 0; i < value1Instantiation.Length; i++) { if (value1Instantiation[i] != value2Instantiation[i]) return false; } return true; } protected override InstantiatedType CreateValueFromKey(InstantiatedTypeKey key) { return new InstantiatedType((MetadataType)key.TypeDef, key.Instantiation); } } } private InstantiatedTypeKey.InstantiatedTypeKeyHashtable _instantiatedTypes; public InstantiatedType GetInstantiatedType(MetadataType typeDef, Instantiation instantiation) { return _instantiatedTypes.GetOrCreateValue(new InstantiatedTypeKey(typeDef, instantiation)); } // // Instantiated methods // private struct InstantiatedMethodKey { private MethodDesc _methodDef; private Instantiation _instantiation; private int _hashcode; public InstantiatedMethodKey(MethodDesc methodDef, Instantiation instantiation) { _methodDef = methodDef; _instantiation = instantiation; _hashcode = TypeHashingAlgorithms.ComputeMethodHashCode(methodDef.OwningType.GetHashCode(), instantiation.ComputeGenericInstanceHashCode(TypeHashingAlgorithms.ComputeNameHashCode(methodDef.Name))); } public MethodDesc MethodDef { get { return _methodDef; } } public Instantiation Instantiation { get { return _instantiation; } } public class InstantiatedMethodKeyHashtable : LockFreeReaderHashtable<InstantiatedMethodKey, InstantiatedMethod> { protected override int GetKeyHashCode(InstantiatedMethodKey key) { return key._hashcode; } protected override int GetValueHashCode(InstantiatedMethod value) { return value.GetHashCode(); } protected override bool CompareKeyToValue(InstantiatedMethodKey key, InstantiatedMethod value) { if (key._methodDef != value.GetMethodDefinition()) return false; Instantiation valueInstantiation = value.Instantiation; if (key._instantiation.Length != valueInstantiation.Length) return false; for (int i = 0; i < key._instantiation.Length; i++) { if (key._instantiation[i] != valueInstantiation[i]) return false; } return true; } protected override bool CompareValueToValue(InstantiatedMethod value1, InstantiatedMethod value2) { if (value1.GetMethodDefinition() != value2.GetMethodDefinition()) return false; Instantiation value1Instantiation = value1.Instantiation; Instantiation value2Instantiation = value2.Instantiation; if (value1Instantiation.Length != value2Instantiation.Length) return false; for (int i = 0; i < value1Instantiation.Length; i++) { if (value1Instantiation[i] != value2Instantiation[i]) return false; } return true; } protected override InstantiatedMethod CreateValueFromKey(InstantiatedMethodKey key) { return new InstantiatedMethod(key.MethodDef, key.Instantiation, key._hashcode); } } } private InstantiatedMethodKey.InstantiatedMethodKeyHashtable _instantiatedMethods; public InstantiatedMethod GetInstantiatedMethod(MethodDesc methodDef, Instantiation instantiation) { Debug.Assert(!(methodDef is InstantiatedMethod)); return _instantiatedMethods.GetOrCreateValue(new InstantiatedMethodKey(methodDef, instantiation)); } // // Methods for instantiated type // private struct MethodForInstantiatedTypeKey { private MethodDesc _typicalMethodDef; private InstantiatedType _instantiatedType; private int _hashcode; public MethodForInstantiatedTypeKey(MethodDesc typicalMethodDef, InstantiatedType instantiatedType) { _typicalMethodDef = typicalMethodDef; _instantiatedType = instantiatedType; _hashcode = TypeHashingAlgorithms.ComputeMethodHashCode(instantiatedType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(typicalMethodDef.Name)); } public MethodDesc TypicalMethodDef { get { return _typicalMethodDef; } } public InstantiatedType InstantiatedType { get { return _instantiatedType; } } public class MethodForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable<MethodForInstantiatedTypeKey, MethodForInstantiatedType> { protected override int GetKeyHashCode(MethodForInstantiatedTypeKey key) { return key._hashcode; } protected override int GetValueHashCode(MethodForInstantiatedType value) { return value.GetHashCode(); } protected override bool CompareKeyToValue(MethodForInstantiatedTypeKey key, MethodForInstantiatedType value) { if (key._typicalMethodDef != value.GetTypicalMethodDefinition()) return false; return key._instantiatedType == value.OwningType; } protected override bool CompareValueToValue(MethodForInstantiatedType value1, MethodForInstantiatedType value2) { return (value1.GetTypicalMethodDefinition() == value2.GetTypicalMethodDefinition()) && (value1.OwningType == value2.OwningType); } protected override MethodForInstantiatedType CreateValueFromKey(MethodForInstantiatedTypeKey key) { return new MethodForInstantiatedType(key.TypicalMethodDef, key.InstantiatedType, key._hashcode); } } } private MethodForInstantiatedTypeKey.MethodForInstantiatedTypeKeyHashtable _methodForInstantiatedTypes; public MethodDesc GetMethodForInstantiatedType(MethodDesc typicalMethodDef, InstantiatedType instantiatedType) { Debug.Assert(!(typicalMethodDef is MethodForInstantiatedType)); Debug.Assert(!(typicalMethodDef is InstantiatedMethod)); return _methodForInstantiatedTypes.GetOrCreateValue(new MethodForInstantiatedTypeKey(typicalMethodDef, instantiatedType)); } // // Fields for instantiated type // private struct FieldForInstantiatedTypeKey { private FieldDesc _fieldDef; private InstantiatedType _instantiatedType; public FieldForInstantiatedTypeKey(FieldDesc fieldDef, InstantiatedType instantiatedType) { _fieldDef = fieldDef; _instantiatedType = instantiatedType; } public FieldDesc TypicalFieldDef { get { return _fieldDef; } } public InstantiatedType InstantiatedType { get { return _instantiatedType; } } public class FieldForInstantiatedTypeKeyHashtable : LockFreeReaderHashtable<FieldForInstantiatedTypeKey, FieldForInstantiatedType> { protected override int GetKeyHashCode(FieldForInstantiatedTypeKey key) { return key._fieldDef.GetHashCode() ^ key._instantiatedType.GetHashCode(); } protected override int GetValueHashCode(FieldForInstantiatedType value) { return value.GetTypicalFieldDefinition().GetHashCode() ^ value.OwningType.GetHashCode(); } protected override bool CompareKeyToValue(FieldForInstantiatedTypeKey key, FieldForInstantiatedType value) { if (key._fieldDef != value.GetTypicalFieldDefinition()) return false; return key._instantiatedType == value.OwningType; } protected override bool CompareValueToValue(FieldForInstantiatedType value1, FieldForInstantiatedType value2) { return (value1.GetTypicalFieldDefinition() == value2.GetTypicalFieldDefinition()) && (value1.OwningType == value2.OwningType); } protected override FieldForInstantiatedType CreateValueFromKey(FieldForInstantiatedTypeKey key) { return new FieldForInstantiatedType(key.TypicalFieldDef, key.InstantiatedType); } } } private FieldForInstantiatedTypeKey.FieldForInstantiatedTypeKeyHashtable _fieldForInstantiatedTypes; public FieldDesc GetFieldForInstantiatedType(FieldDesc fieldDef, InstantiatedType instantiatedType) { return _fieldForInstantiatedTypes.GetOrCreateValue(new FieldForInstantiatedTypeKey(fieldDef, instantiatedType)); } // // Signature variables // private class SignatureVariableHashtable : LockFreeReaderHashtable<uint, SignatureVariable> { private TypeSystemContext _context; public SignatureVariableHashtable(TypeSystemContext context) { _context = context; } protected override int GetKeyHashCode(uint key) { return (int)key; } protected override int GetValueHashCode(SignatureVariable value) { uint combinedIndex = value.IsMethodSignatureVariable ? ((uint)value.Index | 0x80000000) : (uint)value.Index; return (int)combinedIndex; } protected override bool CompareKeyToValue(uint key, SignatureVariable value) { uint combinedIndex = value.IsMethodSignatureVariable ? ((uint)value.Index | 0x80000000) : (uint)value.Index; return key == combinedIndex; } protected override bool CompareValueToValue(SignatureVariable value1, SignatureVariable value2) { uint combinedIndex1 = value1.IsMethodSignatureVariable ? ((uint)value1.Index | 0x80000000) : (uint)value1.Index; uint combinedIndex2 = value2.IsMethodSignatureVariable ? ((uint)value2.Index | 0x80000000) : (uint)value2.Index; return combinedIndex1 == combinedIndex2; } protected override SignatureVariable CreateValueFromKey(uint key) { bool method = ((key & 0x80000000) != 0); int index = (int)(key & 0x7FFFFFFF); if (method) return new SignatureMethodVariable(_context, index); else return new SignatureTypeVariable(_context, index); } } private SignatureVariableHashtable _signatureVariables; public TypeDesc GetSignatureVariable(int index, bool method) { if (index < 0) throw new BadImageFormatException(); uint combinedIndex = method ? ((uint)index | 0x80000000) : (uint)index; return _signatureVariables.GetOrCreateValue(combinedIndex); } protected internal virtual IEnumerable<MethodDesc> GetAllMethods(TypeDesc type) { return type.GetMethods(); } /// <summary> /// Abstraction to allow the type system context to affect the field layout /// algorithm used by types to lay themselves out. /// </summary> public virtual FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type) { // Type system contexts that support computing field layout need to override this. throw new NotSupportedException(); } /// <summary> /// Abstraction to allow the type system context to control the interfaces /// algorithm used by types. /// </summary> public RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForType(TypeDesc type) { if (type.IsDefType) { return GetRuntimeInterfacesAlgorithmForDefType((DefType)type); } else if (type.IsArray) { ArrayType arrType = (ArrayType)type; TypeDesc elementType = arrType.ElementType; if (arrType.IsSzArray && !elementType.IsPointer && !elementType.IsFunctionPointer) { return GetRuntimeInterfacesAlgorithmForNonPointerArrayType((ArrayType)type); } else { return BaseTypeRuntimeInterfacesAlgorithm.Instance; } } return null; } /// <summary> /// Abstraction to allow the type system context to control the interfaces /// algorithm used by types. /// </summary> protected virtual RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type) { // Type system contexts that support computing runtime interfaces need to override this. throw new NotSupportedException(); } /// <summary> /// Abstraction to allow the type system context to control the interfaces /// algorithm used by single dimensional array types. /// </summary> protected virtual RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type) { // Type system contexts that support computing runtime interfaces need to override this. throw new NotSupportedException(); } public virtual VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type) { // Type system contexts that support virtual method resolution need to override this. throw new NotSupportedException(); } // Abstraction to allow different runtimes to have different policy about which fields are // in the GC static region, and which are not protected internal virtual bool ComputeHasGCStaticBase(FieldDesc field) { // Type system contexts that support this need to override this. throw new NotSupportedException(); } /// <summary> /// TypeSystemContext controlled type flags computation. This allows computation of flags which depend /// on the particular TypeSystemContext in use /// </summary> internal TypeFlags ComputeTypeFlags(TypeDesc type, TypeFlags flags, TypeFlags mask) { // If we are looking to compute HasStaticConstructor, and we haven't yet assigned a value if ((mask & TypeFlags.HasStaticConstructorComputed) == TypeFlags.HasStaticConstructorComputed) { TypeDesc typeDefinition = type.GetTypeDefinition(); if (typeDefinition != type) { // If the type definition is different, the code was working with an instantiated generic or some such. // In that case, just query the HasStaticConstructor property, as it can cache the answer if (typeDefinition.HasStaticConstructor) flags |= TypeFlags.HasStaticConstructor; } else { if (ComputeHasStaticConstructor(typeDefinition)) { flags |= TypeFlags.HasStaticConstructor; } } flags |= TypeFlags.HasStaticConstructorComputed; } return flags; } /// <summary> /// Algorithm to control which types are considered to have static constructors /// </summary> protected internal abstract bool ComputeHasStaticConstructor(TypeDesc type); } }
using System; using Amazon.ElasticTranscoder.Model; using Amazon.RDS; using Amazon.RDS.Model; using NUnit.Framework; using CommonTests.Framework; namespace AWSSDK_DotNet.IntegrationTests.Tests.RDS { [TestFixture] public class BasicDescribes : TestBase<AmazonRDSClient> { [Test] [Category("RDS")] public void TestDescribeDBEngineVersions() { var response = Client.DescribeDBEngineVersionsAsync().Result; Assert.IsNotNull(response); string dbEngine = null; if (response.DBEngineVersions.Count > 0) { foreach (var dbev in response.DBEngineVersions) { Assert.IsFalse(string.IsNullOrEmpty(dbev.Engine)); if (dbEngine == null) dbEngine = dbev.Engine; Assert.IsFalse(string.IsNullOrEmpty(dbev.EngineVersion)); } } if (dbEngine != null) { // can perform a filtering test var specificEngineResponse = Client.DescribeDBEngineVersionsAsync(new DescribeDBEngineVersionsRequest {Engine = dbEngine}).Result; Assert.IsNotNull(specificEngineResponse); foreach (var dbev in specificEngineResponse.DBEngineVersions) { Assert.AreEqual(dbev.Engine, dbEngine); } } } [Test] [Category("RDS")] public void TestDescribeDBEngineVersionsForFamily() { var dbParamGroupFamily = Client.DescribeDBParameterGroupsAsync().Result.DBParameterGroups[0]; var response = Client.DescribeDBEngineVersionsAsync(new DescribeDBEngineVersionsRequest { DBParameterGroupFamily = dbParamGroupFamily.DBParameterGroupFamily }).Result; Assert.IsNotNull(response); if (response.DBEngineVersions.Count > 0) { foreach (var dbev in response.DBEngineVersions) { Assert.IsTrue(dbev.DBParameterGroupFamily.Equals(dbParamGroupFamily.DBParameterGroupFamily)); } } } [Test] [Category("RDS")] public void TestDescribeDBParameterGroups() { var response = Client.DescribeDBParameterGroupsAsync().Result; Assert.IsNotNull(response); if (response.DBParameterGroups.Count > 0) { foreach (var dbpg in response.DBParameterGroups) { Assert.IsFalse(string.IsNullOrEmpty(dbpg.DBParameterGroupFamily)); Assert.IsFalse(string.IsNullOrEmpty(dbpg.DBParameterGroupName)); } } } [Test] [Category("RDS")] public void TestDescribeDBInstances() { var response = Client.DescribeDBInstancesAsync().Result; Assert.IsNotNull(response); string dbInstanceIdentifier = null; if (response.DBInstances.Count > 0) { foreach (var dbi in response.DBInstances) { Assert.IsFalse(string.IsNullOrEmpty(dbi.DBInstanceIdentifier)); if (dbInstanceIdentifier == null) dbInstanceIdentifier = dbi.DBInstanceIdentifier; Assert.IsFalse(string.IsNullOrEmpty(dbi.Engine)); Assert.IsFalse(string.IsNullOrEmpty(dbi.EngineVersion)); if (dbi.DBParameterGroups.Count > 0) { foreach (var dbpg in dbi.DBParameterGroups) { Assert.IsFalse(string.IsNullOrEmpty(dbpg.DBParameterGroupName)); } } } } if (dbInstanceIdentifier != null) { // can do a further filtering test var specificIdResponse = Client.DescribeDBInstancesAsync(new DescribeDBInstancesRequest { DBInstanceIdentifier = dbInstanceIdentifier }).Result; Assert.IsNotNull(specificIdResponse); Assert.AreEqual(specificIdResponse.DBInstances.Count, 1); } } [Test] [Category("RDS")] public void DescribeDBSecurityGroups() { var response = Client.DescribeDBSecurityGroupsAsync().Result; Assert.IsNotNull(response); string dbSecurityGroupName = null; if (response.DBSecurityGroups.Count > 0) { foreach (var dbsg in response.DBSecurityGroups) { Assert.IsFalse(string.IsNullOrEmpty(dbsg.DBSecurityGroupName)); if (dbSecurityGroupName == null) dbSecurityGroupName = dbsg.DBSecurityGroupName; Assert.IsFalse(string.IsNullOrEmpty(dbsg.OwnerId)); } } if (dbSecurityGroupName != null) { // perform a filtering test var specificGroupResponse = Client.DescribeDBSecurityGroupsAsync(new DescribeDBSecurityGroupsRequest { DBSecurityGroupName = dbSecurityGroupName }).Result; Assert.IsNotNull(specificGroupResponse); Assert.AreEqual(specificGroupResponse.DBSecurityGroups.Count, 1); } } [Test] [Category("RDS")] public void DescribeDBSnapshots() { var response = Client.DescribeDBSnapshotsAsync().Result; Assert.IsNotNull(response); string dbInstanceIdentifier = null; string dbSnapshotIdentifier = null; if (response.DBSnapshots.Count > 0) { foreach (var dbss in response.DBSnapshots) { Assert.IsFalse(string.IsNullOrEmpty(dbss.DBInstanceIdentifier)); if (dbInstanceIdentifier == null) dbInstanceIdentifier = dbss.DBInstanceIdentifier; Assert.IsFalse(string.IsNullOrEmpty(dbss.DBSnapshotIdentifier)); if (dbSnapshotIdentifier == null) dbSnapshotIdentifier = dbss.DBSnapshotIdentifier; } } if (dbInstanceIdentifier != null) { var specificInstanceResponse = Client.DescribeDBSnapshotsAsync(new DescribeDBSnapshotsRequest { DBInstanceIdentifier = dbInstanceIdentifier }).Result; Assert.IsNotNull(specificInstanceResponse); Assert.IsTrue(specificInstanceResponse.DBSnapshots.Count > 0); } if (dbSnapshotIdentifier != null) { var specificSnapshotResponse = Client.DescribeDBSnapshotsAsync(new DescribeDBSnapshotsRequest { DBSnapshotIdentifier = dbSnapshotIdentifier }).Result; Assert.IsNotNull(specificSnapshotResponse); Assert.AreEqual(specificSnapshotResponse.DBSnapshots.Count, 1); } } [Test] [Category("RDS")] public void DescribeDBSubnetGroups() { var response = Client.DescribeDBSubnetGroupsAsync().Result; Assert.IsNotNull(response); string dbSubnetGroupName = null; if (response.DBSubnetGroups.Count > 0) { foreach (var dbsng in response.DBSubnetGroups) { Assert.IsFalse(string.IsNullOrEmpty(dbsng.DBSubnetGroupName)); if (dbSubnetGroupName == null) dbSubnetGroupName = dbsng.DBSubnetGroupName; if (dbsng.Subnets.Count > 0) { foreach (var s in dbsng.Subnets) { Assert.IsFalse(string.IsNullOrEmpty(s.SubnetIdentifier)); Assert.IsNotNull(s.SubnetAvailabilityZone); Assert.IsFalse(string.IsNullOrEmpty(s.SubnetAvailabilityZone.Name)); } } } } if (dbSubnetGroupName != null) { var specificSubnetResponse = Client.DescribeDBSubnetGroupsAsync(new DescribeDBSubnetGroupsRequest { DBSubnetGroupName = dbSubnetGroupName }).Result; Assert.IsNotNull(specificSubnetResponse); Assert.AreEqual(specificSubnetResponse.DBSubnetGroups.Count, 1); } } [Test] [Category("RDS")] public void DescribeEventCategories() { var response = Client.DescribeEventCategoriesAsync().Result; Assert.IsNotNull(response); string sourceType = null; if (response.EventCategoriesMapList.Count > 0) { foreach (var ec in response.EventCategoriesMapList) { Assert.IsFalse(string.IsNullOrEmpty(ec.SourceType)); if (sourceType == null) sourceType = ec.SourceType; if (ec.EventCategories.Count > 0) { foreach (var cat in ec.EventCategories) { Assert.IsFalse(string.IsNullOrEmpty(cat)); } } } } if (sourceType != null) { var specificSourceResponse = Client.DescribeEventCategoriesAsync(new DescribeEventCategoriesRequest { SourceType = sourceType }).Result; Assert.IsNotNull(specificSourceResponse); Assert.AreEqual(specificSourceResponse.EventCategoriesMapList.Count, 1); } } [Test] [Category("RDS")] public void DescribeEventSubscriptions() { // subscriptions depend on what account has set up, so simply verify we get a response var response = Client.DescribeEventSubscriptionsAsync().Result; Assert.IsNotNull(response); } [Test] [Category("RDS")] public void DescribeEvents() { var response = Client.DescribeEventsAsync().Result; Assert.IsNotNull(response); string sourceIdentifier = null; string sourceType = null; if (response.Events.Count > 0) { foreach (var e in response.Events) { Assert.IsFalse(string.IsNullOrEmpty(e.SourceType)); Assert.IsFalse(string.IsNullOrEmpty(e.SourceIdentifier)); if (sourceIdentifier == null) { sourceIdentifier = e.SourceIdentifier; sourceType = e.SourceType; } if (e.EventCategories.Count > 0) { foreach (var ec in e.EventCategories) { Assert.IsFalse(string.IsNullOrEmpty(ec)); } } } } if (sourceIdentifier != null) { var specificSourceResponse = Client.DescribeEventsAsync(new DescribeEventsRequest { SourceIdentifier = sourceIdentifier, SourceType = sourceType }).Result; Assert.IsNotNull(specificSourceResponse); } } [Test] [Category("RDS")] public void DescribeOptionGroups() { var response = Client.DescribeOptionGroupsAsync().Result; Assert.IsNotNull(response); string engineName = null; string optionGroupName = null; if (response.OptionGroupsList.Count > 0) { foreach (var og in response.OptionGroupsList) { Assert.IsFalse(string.IsNullOrEmpty(og.EngineName)); if (engineName == null) engineName = og.EngineName; Assert.IsFalse(string.IsNullOrEmpty(og.OptionGroupName)); if (optionGroupName == null) optionGroupName = og.OptionGroupName; if (og.Options.Count > 0) { foreach (var o in og.Options) { Assert.IsFalse(string.IsNullOrEmpty(o.OptionName)); if (o.OptionSettings.Count > 0) { foreach (var os in o.OptionSettings) { Assert.IsFalse(string.IsNullOrEmpty(os.Name)); } } } } } } if (engineName != null) { var specificEngineResponse = Client.DescribeOptionGroupsAsync(new DescribeOptionGroupsRequest { EngineName = engineName }).Result; Assert.IsNotNull(specificEngineResponse); Assert.IsTrue(specificEngineResponse.OptionGroupsList.Count > 0); } if (optionGroupName != null) { var specificGroupResponse = Client.DescribeOptionGroupsAsync(new DescribeOptionGroupsRequest { OptionGroupName = optionGroupName }).Result; Assert.IsNotNull(specificGroupResponse); Assert.AreEqual(specificGroupResponse.OptionGroupsList.Count, 1); } } [Test] [Category("RDS")] public void OptionGroupTests() { string ogNamePrefix = "simple-og"; var groups = Client.DescribeOptionGroupsAsync().Result.OptionGroupsList; foreach(var group in groups) { var groupName = group.OptionGroupName; if (groupName.IndexOf(ogNamePrefix, StringComparison.OrdinalIgnoreCase) >= 0) Client.DeleteOptionGroupAsync(new DeleteOptionGroupRequest { OptionGroupName = groupName }).Wait(); } var name = "simple-og" + DateTime.Now.Ticks; var optionGroup = Client.CreateOptionGroupAsync(new CreateOptionGroupRequest { EngineName = "mysql", MajorEngineVersion = "5.1", OptionGroupName = name, OptionGroupDescription = "Basic test OptionGroup" }).Result.OptionGroup; var optionGroupName = optionGroup.OptionGroupName; var copyOptionGroupName = optionGroupName + "copy"; Client.CopyOptionGroupAsync(new CopyOptionGroupRequest { SourceOptionGroupIdentifier = optionGroupName, TargetOptionGroupIdentifier = copyOptionGroupName, TargetOptionGroupDescription = "copy" }).Wait(); groups = Client.DescribeOptionGroupsAsync(new DescribeOptionGroupsRequest { OptionGroupName = copyOptionGroupName }).Result.OptionGroupsList; Assert.AreEqual(1, groups.Count); Client.DeleteOptionGroupAsync(new DeleteOptionGroupRequest { OptionGroupName = copyOptionGroupName }).Wait(); Client.DeleteOptionGroupAsync(new DeleteOptionGroupRequest { OptionGroupName = optionGroupName }).Wait(); } [Test] [Category("RDS")] public void DescribeReservedDBInstances() { var response = Client.DescribeReservedDBInstancesAsync().Result; Assert.IsNotNull(response); string reservedInstanceId = null; string dbInstanceClass = null; if (response.ReservedDBInstances.Count > 0) { foreach (var rdbi in response.ReservedDBInstances) { Assert.IsFalse(string.IsNullOrEmpty(rdbi.ReservedDBInstanceId)); if (reservedInstanceId == null) reservedInstanceId = rdbi.ReservedDBInstanceId; Assert.IsFalse(string.IsNullOrEmpty(rdbi.DBInstanceClass)); if (dbInstanceClass == null) dbInstanceClass = rdbi.DBInstanceClass; } } if (dbInstanceClass != null) { var specificClassResponse = Client.DescribeReservedDBInstancesAsync(new DescribeReservedDBInstancesRequest { DBInstanceClass = dbInstanceClass }).Result; Assert.IsNotNull(specificClassResponse); Assert.IsTrue(specificClassResponse.ReservedDBInstances.Count > 0); } if (reservedInstanceId != null) { var specificInstanceResponse = Client.DescribeReservedDBInstancesAsync(new DescribeReservedDBInstancesRequest { ReservedDBInstanceId = reservedInstanceId }).Result; Assert.IsNotNull(specificInstanceResponse); Assert.AreEqual(specificInstanceResponse.ReservedDBInstances.Count, 1); } } [Test] [Category("RDS")] public void DescribeReservedDBInstancesOfferings() { var response = Client.DescribeReservedDBInstancesOfferingsAsync().Result; Assert.IsNotNull(response); string offeringId = null; string offeringType = null; if (response.ReservedDBInstancesOfferings.Count > 0) { foreach (var ro in response.ReservedDBInstancesOfferings) { Assert.IsFalse(string.IsNullOrEmpty(ro.OfferingType)); if (offeringType == null) offeringType = ro.OfferingType; Assert.IsFalse(string.IsNullOrEmpty(ro.ReservedDBInstancesOfferingId)); if (offeringId == null) offeringId = ro.ReservedDBInstancesOfferingId; } } if (offeringType != null) { var specificTypeResponse = Client.DescribeReservedDBInstancesOfferingsAsync(new DescribeReservedDBInstancesOfferingsRequest { OfferingType = offeringType }).Result; Assert.IsNotNull(specificTypeResponse); Assert.IsTrue(specificTypeResponse.ReservedDBInstancesOfferings.Count > 0); } if (offeringId != null) { var specificIdResponse = Client.DescribeReservedDBInstancesOfferingsAsync(new DescribeReservedDBInstancesOfferingsRequest { ReservedDBInstancesOfferingId = offeringId }).Result; Assert.IsNotNull(specificIdResponse); Assert.AreEqual(specificIdResponse.ReservedDBInstancesOfferings.Count, 1); } } [Test] [Category("RDS")] public void TestDescribeAccountAttributes() { var result = Client.DescribeAccountAttributesAsync().Result; var quotas = result.AccountQuotas; Assert.IsNotNull(quotas); Assert.AreNotEqual(0, quotas.Count); foreach(var quota in quotas) { Assert.IsFalse(string.IsNullOrEmpty(quota.AccountQuotaName)); Assert.AreNotEqual(0, quota.Max); } } [Test] [Category("RDS")] public void TestDescribeCertificates() { var request = new DescribeCertificatesRequest(); do { var response = Client.DescribeCertificatesAsync(request).Result; var certificates = response.Certificates; Assert.IsNotNull(certificates); Assert.AreNotEqual(0, certificates.Count); foreach(var cert in certificates) { Assert.IsNotNull(cert); Assert.IsFalse(string.IsNullOrEmpty(cert.CertificateIdentifier)); Assert.IsFalse(string.IsNullOrEmpty(cert.CertificateType)); Assert.IsFalse(string.IsNullOrEmpty(cert.Thumbprint)); Assert.IsTrue(cert.ValidFrom > DateTime.MinValue); Assert.IsTrue(cert.ValidFrom < cert.ValidTill); } request.Marker = response.Marker; } while (!string.IsNullOrEmpty(request.Marker)); } [Test] [Category("RDS")] public void TestDescribeDBInstanceException() { var nfe = AssertExtensions.ExpectExceptionAsync<DBInstanceNotFoundException>( Client.DescribeDBInstancesAsync(new DescribeDBInstancesRequest { DBInstanceIdentifier = "fake-identifier" })).Result; Assert.IsFalse(string.IsNullOrEmpty(nfe.ErrorCode)); Assert.IsFalse(string.IsNullOrEmpty(nfe.Message)); Assert.IsFalse(string.IsNullOrEmpty(nfe.RequestId)); Assert.IsTrue((int)(nfe.StatusCode) >= 400); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class LambdaUnaryNotNullableTests { #region Test methods [Fact] public static void CheckLambdaUnaryNotNullableByteTest() { foreach (byte? value in new byte?[] { null, 0, 1, byte.MaxValue }) { VerifyUnaryNotNullableByte(value); } } [Fact] public static void CheckLambdaUnaryNotNullableIntTest() { foreach (int? value in new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }) { VerifyUnaryNotNullableInt(value); } } [Fact] public static void CheckLambdaUnaryNotNullableLongTest() { foreach (long? value in new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }) { VerifyUnaryNotNullableLong(value); } } [Fact] public static void CheckLambdaUnaryNotNullableSByteTest() { foreach (sbyte? value in new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }) { VerifyUnaryNotNullableSByte(value); } } [Fact] public static void CheckLambdaUnaryNotNullableShortTest() { foreach (short? value in new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }) { VerifyUnaryNotNullableShort(value); } } [Fact] public static void CheckLambdaUnaryNotNullableUIntTest() { foreach (uint? value in new uint?[] { null, 0, 1, uint.MaxValue }) { VerifyUnaryNotNullableUInt(value); } } [Fact] public static void CheckLambdaUnaryNotNullableULongTest() { foreach (ulong? value in new ulong?[] { null, 0, 1, ulong.MaxValue }) { VerifyUnaryNotNullableULong(value); } } [Fact] public static void CheckLambdaUnaryNotNullableUShortTest() { foreach (ushort? value in new ushort?[] { null, 0, 1, ushort.MaxValue }) { VerifyUnaryNotNullableUShort(value); } } #endregion #region Test verifiers private static void VerifyUnaryNotNullableByte(byte? value) { ParameterExpression p = Expression.Parameter(typeof(byte?), "p"); // parameter hard coded Expression<Func<byte?>> e1 = Expression.Lambda<Func<byte?>>( Expression.Invoke( Expression.Lambda<Func<byte?, byte?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(byte?)) }), Enumerable.Empty<ParameterExpression>()); Func<byte?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<byte?, Func<byte?>>> e2 = Expression.Lambda<Func<byte?, Func<byte?>>>( Expression.Lambda<Func<byte?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<byte?, Func<byte?>> f2 = e2.Compile(); // function generator Expression<Func<Func<byte?, byte?>>> e3 = Expression.Lambda<Func<Func<byte?, byte?>>>( Expression.Invoke( Expression.Lambda<Func<Func<byte?, byte?>>>( Expression.Lambda<Func<byte?, byte?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<byte?, byte?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<byte?, byte?>>> e4 = Expression.Lambda<Func<Func<byte?, byte?>>>( Expression.Lambda<Func<byte?, byte?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<byte?, byte?>> f4 = e4.Compile(); byte? expected = (byte?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableInt(int? value) { ParameterExpression p = Expression.Parameter(typeof(int?), "p"); // parameter hard coded Expression<Func<int?>> e1 = Expression.Lambda<Func<int?>>( Expression.Invoke( Expression.Lambda<Func<int?, int?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<int?, Func<int?>>> e2 = Expression.Lambda<Func<int?, Func<int?>>>( Expression.Lambda<Func<int?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<int?, Func<int?>> f2 = e2.Compile(); // function generator Expression<Func<Func<int?, int?>>> e3 = Expression.Lambda<Func<Func<int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int?, int?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<int?, int?>>> e4 = Expression.Lambda<Func<Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<int?, int?>> f4 = e4.Compile(); int? expected = (int?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableLong(long? value) { ParameterExpression p = Expression.Parameter(typeof(long?), "p"); // parameter hard coded Expression<Func<long?>> e1 = Expression.Lambda<Func<long?>>( Expression.Invoke( Expression.Lambda<Func<long?, long?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<long?, Func<long?>>> e2 = Expression.Lambda<Func<long?, Func<long?>>>( Expression.Lambda<Func<long?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<long?, Func<long?>> f2 = e2.Compile(); // function generator Expression<Func<Func<long?, long?>>> e3 = Expression.Lambda<Func<Func<long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<long?, long?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<long?, long?>>> e4 = Expression.Lambda<Func<Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<long?, long?>> f4 = e4.Compile(); long? expected = (long?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableSByte(sbyte? value) { ParameterExpression p = Expression.Parameter(typeof(sbyte?), "p"); // parameter hard coded Expression<Func<sbyte?>> e1 = Expression.Lambda<Func<sbyte?>>( Expression.Invoke( Expression.Lambda<Func<sbyte?, sbyte?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(sbyte?)) }), Enumerable.Empty<ParameterExpression>()); Func<sbyte?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<sbyte?, Func<sbyte?>>> e2 = Expression.Lambda<Func<sbyte?, Func<sbyte?>>>( Expression.Lambda<Func<sbyte?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<sbyte?, Func<sbyte?>> f2 = e2.Compile(); // function generator Expression<Func<Func<sbyte?, sbyte?>>> e3 = Expression.Lambda<Func<Func<sbyte?, sbyte?>>>( Expression.Invoke( Expression.Lambda<Func<Func<sbyte?, sbyte?>>>( Expression.Lambda<Func<sbyte?, sbyte?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<sbyte?, sbyte?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<sbyte?, sbyte?>>> e4 = Expression.Lambda<Func<Func<sbyte?, sbyte?>>>( Expression.Lambda<Func<sbyte?, sbyte?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<sbyte?, sbyte?>> f4 = e4.Compile(); sbyte? expected = (sbyte?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableShort(short? value) { ParameterExpression p = Expression.Parameter(typeof(short?), "p"); // parameter hard coded Expression<Func<short?>> e1 = Expression.Lambda<Func<short?>>( Expression.Invoke( Expression.Lambda<Func<short?, short?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<short?, Func<short?>>> e2 = Expression.Lambda<Func<short?, Func<short?>>>( Expression.Lambda<Func<short?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<short?, Func<short?>> f2 = e2.Compile(); // function generator Expression<Func<Func<short?, short?>>> e3 = Expression.Lambda<Func<Func<short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<short?, short?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<short?, short?>>> e4 = Expression.Lambda<Func<Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<short?, short?>> f4 = e4.Compile(); short? expected = (short?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableUInt(uint? value) { ParameterExpression p = Expression.Parameter(typeof(uint?), "p"); // parameter hard coded Expression<Func<uint?>> e1 = Expression.Lambda<Func<uint?>>( Expression.Invoke( Expression.Lambda<Func<uint?, uint?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<uint?, Func<uint?>>> e2 = Expression.Lambda<Func<uint?, Func<uint?>>>( Expression.Lambda<Func<uint?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<uint?, Func<uint?>> f2 = e2.Compile(); // function generator Expression<Func<Func<uint?, uint?>>> e3 = Expression.Lambda<Func<Func<uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<uint?, uint?>>> e4 = Expression.Lambda<Func<Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<uint?, uint?>> f4 = e4.Compile(); uint? expected = (uint?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableULong(ulong? value) { ParameterExpression p = Expression.Parameter(typeof(ulong?), "p"); // parameter hard coded Expression<Func<ulong?>> e1 = Expression.Lambda<Func<ulong?>>( Expression.Invoke( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<ulong?, Func<ulong?>>> e2 = Expression.Lambda<Func<ulong?, Func<ulong?>>>( Expression.Lambda<Func<ulong?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<ulong?, Func<ulong?>> f2 = e2.Compile(); // function generator Expression<Func<Func<ulong?, ulong?>>> e3 = Expression.Lambda<Func<Func<ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<ulong?, ulong?>>> e4 = Expression.Lambda<Func<Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<ulong?, ulong?>> f4 = e4.Compile(); ulong? expected = (ulong?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } private static void VerifyUnaryNotNullableUShort(ushort? value) { ParameterExpression p = Expression.Parameter(typeof(ushort?), "p"); // parameter hard coded Expression<Func<ushort?>> e1 = Expression.Lambda<Func<ushort?>>( Expression.Invoke( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Not(p), new ParameterExpression[] { p }), new Expression[] { Expression.Constant(value, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f1 = e1.Compile(); // function generator that takes a parameter Expression<Func<ushort?, Func<ushort?>>> e2 = Expression.Lambda<Func<ushort?, Func<ushort?>>>( Expression.Lambda<Func<ushort?>>( Expression.Not(p), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p }); Func<ushort?, Func<ushort?>> f2 = e2.Compile(); // function generator Expression<Func<Func<ushort?, ushort?>>> e3 = Expression.Lambda<Func<Func<ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?> f3 = e3.Compile()(); // parameter-taking function generator Expression<Func<Func<ushort?, ushort?>>> e4 = Expression.Lambda<Func<Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Not(p), new ParameterExpression[] { p }), Enumerable.Empty<ParameterExpression>()); Func<Func<ushort?, ushort?>> f4 = e4.Compile(); ushort? expected = (ushort?)~value; Assert.Equal(expected, f1()); Assert.Equal(expected, f2(value)()); Assert.Equal(expected, f3(value)); Assert.Equal(expected, f4()(value)); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Talent.V4Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTenantServiceClientTest { [xunit::FactAttribute] public void CreateTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request.Parent, request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request.Parent, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request.Parent, request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.CreateTenant(request.ParentAsProjectName, request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); CreateTenantRequest request = new CreateTenantRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.CreateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.CreateTenantAsync(request.ParentAsProjectName, request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.GetTenant(request.TenantName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); GetTenantRequest request = new GetTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.GetTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.GetTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.GetTenantAsync(request.TenantName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.UpdateTenant(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), UpdateMask = new wkt::FieldMask(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.UpdateTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.UpdateTenantAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant response = client.UpdateTenant(request.Tenant); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); UpdateTenantRequest request = new UpdateTenantRequest { Tenant = new Tenant(), }; Tenant expectedResponse = new Tenant { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), ExternalId = "external_id9442680e", UsageType = Tenant.Types.DataUsageType.Unspecified, KeywordSearchableProfileCustomAttributes = { "keyword_searchable_profile_custom_attributes9dbf9d03", }, }; mockGrpcClient.Setup(x => x.UpdateTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tenant>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); Tenant responseCallSettings = await client.UpdateTenantAsync(request.Tenant, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Tenant responseCancellationToken = await client.UpdateTenantAsync(request.Tenant, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenantRequestObject() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantRequestObjectAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenant() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTenantResourceNames() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenant(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); client.DeleteTenant(request.TenantName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTenantResourceNamesAsync() { moq::Mock<TenantService.TenantServiceClient> mockGrpcClient = new moq::Mock<TenantService.TenantServiceClient>(moq::MockBehavior.Strict); DeleteTenantRequest request = new DeleteTenantRequest { TenantName = TenantName.FromProjectTenant("[PROJECT]", "[TENANT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTenantAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TenantServiceClient client = new TenantServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteTenantAsync(request.TenantName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTenantAsync(request.TenantName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography.Pal.Native; using Microsoft.Win32.SafeHandles; using System; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Diagnostics; namespace Internal.Cryptography.Pal { internal sealed partial class StorePal : IDisposable, IStorePal, IExportPal, ILoaderPal { public static ILoaderPal FromBlob(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(rawData, null, password, keyStorageFlags); } public static ILoaderPal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(null, fileName, password, keyStorageFlags); } private static StorePal FromBlobOrFile(byte[] rawData, string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(password != null); bool fromFile = fileName != null; unsafe { fixed (byte* pRawData = rawData) { fixed (char* pFileName = fileName) { CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(fromFile ? 0 : rawData.Length, pRawData); bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet)); PfxCertStoreFlags certStoreFlags = MapKeyStorageFlags(keyStorageFlags); void* pvObject = fromFile ? (void*)pFileName : (void*)&blob; ContentType contentType; SafeCertStoreHandle certStore; if (!Interop.crypt32.CryptQueryObject( fromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB, pvObject, StoreExpectedContentFlags, ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL, 0, IntPtr.Zero, out contentType, IntPtr.Zero, out certStore, IntPtr.Zero, IntPtr.Zero )) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (contentType == ContentType.CERT_QUERY_CONTENT_PFX) { certStore.Dispose(); if (fromFile) { rawData = File.ReadAllBytes(fileName); } fixed (byte* pRawData2 = rawData) { CRYPTOAPI_BLOB blob2 = new CRYPTOAPI_BLOB(rawData.Length, pRawData2); certStore = Interop.crypt32.PFXImportCertStore(ref blob2, password, certStoreFlags); if (certStore == null || certStore.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (!persistKeySet) { // // If the user did not want us to persist private keys, then we should loop through all // the certificates in the collection and set our custom CERT_DELETE_KEYSET_PROP_ID property // so the key container will be deleted when the cert contexts will go away. // SafeCertContextHandle pCertContext = null; while (Interop.crypt32.CertEnumCertificatesInStore(certStore, ref pCertContext)) { CRYPTOAPI_BLOB nullBlob = new CRYPTOAPI_BLOB(0, null); if (!Interop.crypt32.CertSetCertificateContextProperty(pCertContext, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, CertSetPropertyFlags.CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, &nullBlob)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } } } return new StorePal(certStore); } } } } public static IExportPal FromCertificate(ICertificatePal cert) { CertificatePal certificatePal = (CertificatePal)cert; SafeCertStoreHandle certStore = Interop.crypt32.CertOpenStore( CertStoreProvider.CERT_STORE_PROV_MEMORY, CertEncodingType.All, IntPtr.Zero, CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG | CertStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, null); if (certStore.IsInvalid) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (!Interop.crypt32.CertAddCertificateLinkToStore(certStore, certificatePal.CertContext, CertStoreAddDisposition.CERT_STORE_ADD_ALWAYS, IntPtr.Zero)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return new StorePal(certStore); } /// <summary> /// Note: this factory method creates the store using links to the original certificates rather than copies. This means that any changes to certificate properties /// in the store changes the original. /// </summary> public static IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates) { // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation. // By default, Archived certificates will not be included. SafeCertStoreHandle certStore = Interop.crypt32.CertOpenStore( CertStoreProvider.CERT_STORE_PROV_MEMORY, CertEncodingType.All, IntPtr.Zero, CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG, null); if (certStore.IsInvalid) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; // // We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get // applied to the original store. This has a limit of 99 links per cert context however. // foreach (X509Certificate2 certificate in certificates) { SafeCertContextHandle certContext = ((CertificatePal)certificate.Pal).CertContext; if (!Interop.crypt32.CertAddCertificateLinkToStore(certStore, certContext, CertStoreAddDisposition.CERT_STORE_ADD_ALWAYS, IntPtr.Zero)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } return new StorePal(certStore); } public static IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags) { CertStoreFlags certStoreFlags = MapX509StoreFlags(storeLocation, openFlags); SafeCertStoreHandle certStore = Interop.crypt32.CertOpenStore(CertStoreProvider.CERT_STORE_PROV_SYSTEM_W, CertEncodingType.All, IntPtr.Zero, certStoreFlags, storeName); if (certStore.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); // // We want the store to auto-resync when requesting a snapshot so that // updates to the store will be taken into account. // // For compat with desktop, ignoring any failures from this call. (It is pretty unlikely to fail, in any case.) // bool ignore = Interop.crypt32.CertControlStore(certStore, CertControlStoreFlags.None, CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC, IntPtr.Zero); return new StorePal(certStore); } // this method maps a X509KeyStorageFlags enum to a combination of crypto API flags private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { PfxCertStoreFlags dwFlags = 0; if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet) dwFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET; else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet) dwFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET; if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable) dwFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE; if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected) dwFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED; if ((keyStorageFlags & X509KeyStorageFlags.EphemeralKeySet) == X509KeyStorageFlags.EphemeralKeySet) dwFlags |= PfxCertStoreFlags.PKCS12_NO_PERSIST_KEY | PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP; return dwFlags; } // this method maps X509Store OpenFlags to a combination of crypto API flags private static CertStoreFlags MapX509StoreFlags(StoreLocation storeLocation, OpenFlags flags) { CertStoreFlags dwFlags = 0; uint openMode = ((uint)flags) & 0x3; switch (openMode) { case (uint)OpenFlags.ReadOnly: dwFlags |= CertStoreFlags.CERT_STORE_READONLY_FLAG; break; case (uint)OpenFlags.MaxAllowed: dwFlags |= CertStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG; break; } if ((flags & OpenFlags.OpenExistingOnly) == OpenFlags.OpenExistingOnly) dwFlags |= CertStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG; if ((flags & OpenFlags.IncludeArchived) == OpenFlags.IncludeArchived) dwFlags |= CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG; if (storeLocation == StoreLocation.LocalMachine) dwFlags |= CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; else if (storeLocation == StoreLocation.CurrentUser) dwFlags |= CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; return dwFlags; } private const ExpectedContentTypeFlags StoreExpectedContentFlags = ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE; } }
#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 subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Configuration; using System.Data.SqlClient; using System.Text.RegularExpressions; using Subtext.Framework.Configuration; using Subtext.Framework.Exceptions; using Subtext.Framework.Properties; using Subtext.Framework.Providers; using Subtext.Framework.Security; namespace Subtext.Framework { /// <summary> /// Represents the system, and its settings, that hosts the blogs within this Subtext installation. /// </summary> public sealed class HostInfo { private static HostInfo _instance; /// <summary> /// Returns an instance of <see cref="HostInfo"/> used to /// describe this installation of Subtext. /// </summary> /// <returns></returns> public static HostInfo Instance { get { // no lock singleton. HostInfo instance = _instance; if(instance == null) { instance = LoadHost(true); // the next line might overwrite a HostInfo created by another thread, // but if it does, it'll only happen once and it's not so bad. I'll measure it to be sure. // -phil Jan 18, 2009 _instance = instance; } return _instance; } } /// <summary> /// Gets a value indicating whether the HostInfo table exists. /// </summary> /// <value> /// <c>true</c> if host info table exists; otherwise, <c>false</c>. /// </value> public static bool HostInfoTableExists { get { try { LoadHost(false); return true; } catch(HostDataDoesNotExistException) { return false; } } } /// <summary> /// Gets or sets the name of the host user. /// </summary> /// <value></value> public string HostUserName { get; set; } public string Email { get; set; } /// <summary> /// Gets or sets the host password. /// </summary> /// <value></value> public string Password { get; set; } /// <summary> /// Gets or sets the salt. /// </summary> /// <value></value> public string Salt { get; set; } /// <summary> /// Gets or sets the date this record was created. /// This is essentially the date that Subtext was /// installed. /// </summary> /// <value></value> public DateTime DateCreated { get; set; } public bool BlogAggregationEnabled { get; set; } public Blog AggregateBlog { get; set; } /// <summary> /// Loads the host from the Object Provider. This is provided for /// those cases when we really need to hit the data strore. Calling this /// method will also reload the HostInfo.Instance from the data store. /// </summary> /// <param name="suppressException">If true, won't throw an exception.</param> /// <returns></returns> public static HostInfo LoadHost(bool suppressException) { try { _instance = ObjectProvider.Instance().LoadHostInfo(new HostInfo()); if(_instance != null) { _instance.BlogAggregationEnabled = String.Equals(ConfigurationManager.AppSettings["AggregateEnabled"], "true", StringComparison.OrdinalIgnoreCase); if(_instance.BlogAggregationEnabled) { InitAggregateBlog(_instance); } } return _instance; } catch(SqlException e) { // LoadHostInfo now executes the stored proc subtext_GetHost, instead of checking the table subtext_Host if(e.Message.IndexOf("Invalid object name 'subtext_Host'") >= 0 || e.Message.IndexOf("Could not find stored procedure 'subtext_GetHost'") >= 0) { if(suppressException) { return null; } throw new HostDataDoesNotExistException(); } throw; } } /// <summary> /// Updates the host in the persistent store. /// </summary> /// <param name="host">Host.</param> /// <returns></returns> public static bool UpdateHost(HostInfo host) { if(ObjectProvider.Instance().UpdateHost(host)) { _instance = host; return true; } return false; } /// <summary> /// Creates the host in the persistent store. /// </summary> /// <returns></returns> public static bool CreateHost(string hostUserName, string hostPassword, string email) { if(Instance != null) { throw new InvalidOperationException(Resources.InvalidOperation_HostRecordAlreadyExists); } var host = new HostInfo {HostUserName = hostUserName, Email = email}; SetHostPassword(host, hostPassword); _instance = host; return UpdateHost(host); } public static void SetHostPassword(HostInfo host, string newPassword) { host.Salt = SecurityHelper.CreateRandomSalt(); if(Config.Settings.UseHashedPasswords) { string hashedPassword = SecurityHelper.HashPassword(newPassword, host.Salt); host.Password = hashedPassword; } else { host.Password = newPassword; } } private static void InitAggregateBlog(HostInfo hostInfo) { string aggregateHost = ConfigurationManager.AppSettings["AggregateUrl"]; if(aggregateHost == null) { return; } // validate host. var regex = new Regex(@"^(https?://)?(?<host>.+?)(/.*)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); Match match = regex.Match(aggregateHost); if(match.Success) { aggregateHost = match.Groups["host"].Value; } var blog = new Blog(true /*isAggregateBlog*/) { Title = ConfigurationManager.AppSettings["AggregateTitle"], Skin = SkinConfig.DefaultSkin, Host = aggregateHost, Subfolder = string.Empty, IsActive = true }; //TODO: blog.MobileSkin = ... if(hostInfo != null) { blog.UserName = hostInfo.HostUserName; hostInfo.AggregateBlog = blog; } } } }
#region Using using System; using System.Collections.Generic; using System.Drawing; using System.Xml; using System.Globalization; using TribalWars.Villages; using TribalWars.Villages.Buildings; using TribalWars.Villages.Resources; using TribalWars.Villages.Units; using TribalWars.Worlds; #endregion namespace TribalWars.Browsers.Reporting { /// <summary> /// Represents the current estimated situation of a village (DEFENDER) /// </summary> /// <remarks>The attacker side of the 'report' is empty</remarks> public class CurrentSituation { #region Fields private float _loyalty; private DateTime _villageDate; private DateTime _loyaltyDate; #endregion #region Properties /// <summary> /// Gets the defenses of the village /// </summary> public VillageDefense Defense { get; private set; } /// <summary> /// Gets the buildings in the village /// </summary> public VillageBuildings Buildings { get; private set; } /// <summary> /// Gets the village /// </summary> public Village Village { get; private set; } /// <summary> /// Gets the loyalty /// </summary> public string LoyaltyString { get { return _loyaltyDate == DateTime.MinValue ? "???" : _loyalty.ToString("0"); } } /// <summary> /// Gets the last time building levels were updated /// </summary> public DateTime BuildingsDate { get; internal set; } /// <summary> /// Gets the last time defense levels were updated /// </summary> public DateTime DefenseDate { get; internal set; } /// <summary> /// Gets the last known resource level /// </summary> public Resource Resources { get; private set; } /// <summary> /// Gets the last time resource levels were updated /// </summary> public DateTime ResourcesDate { private get; set; } /// <summary> /// Gets or sets the last known loyalty level /// </summary> public float Loyalty { get { return _loyalty; } set { _loyalty = value; _loyaltyDate = World.Default.Settings.ServerTime; } } /// <summary> /// Gets the last time loyalty info was gathered /// </summary> public DateTime LoyaltyDate { get { return _loyaltyDate; } } /// <summary> /// Gets the last time village info was gathered /// </summary> /// <remarks>This is usually the date of the last report</remarks> public DateTime VillageDate { get { return _villageDate; } } #endregion #region Constructors public CurrentSituation(Village village) { Village = village; Buildings = new VillageBuildings(); Defense = new VillageDefense(); Resources = new Resource(); } #endregion #region Public Methods /// <summary> /// Paints the report on a canvas /// </summary> public void Paint(Graphics g) { Update(); if (_villageDate == DateTime.MinValue) { var format = new StringFormat(); format.Alignment = StringAlignment.Center; g.DrawString("No estimated situation available.", SystemFonts.DefaultFont, Brushes.Black, new RectangleF(10, 10, g.VisibleClipBounds.Width - 10, 50), format); } else { g.TranslateTransform(10, 10); // resources float x = 5; const int resourceYOffset = 3; const int resourceXOffset = 5; const int imageXOffset = 20; var borderPen = new Pen(Color.Black, 2); const int imageYOffset = 20; const int imageYTextOffset = 5; if (ResourcesDate != DateTime.MinValue) { g.DrawImage(ResourceImages.wood, x, resourceYOffset); g.DrawString(Resources.WoodString, SystemFonts.DefaultFont, Brushes.Black, x + imageXOffset, resourceYOffset + imageYTextOffset); x += g.MeasureString(Resources.WoodString, SystemFonts.DefaultFont).Width; x += imageXOffset + resourceXOffset; g.DrawImage(ResourceImages.clay, x, resourceYOffset); g.DrawString(Resources.ClayString, SystemFonts.DefaultFont, Brushes.Black, x + imageXOffset, resourceYOffset + imageYTextOffset); x += g.MeasureString(Resources.ClayString, SystemFonts.DefaultFont).Width; x += imageXOffset + resourceXOffset; g.DrawImage(ResourceImages.iron, x, resourceYOffset); g.DrawString(Resources.IronString, SystemFonts.DefaultFont, Brushes.Black, x + imageXOffset, resourceYOffset + imageYTextOffset); x += g.MeasureString(Resources.IronString, SystemFonts.DefaultFont).Width; x += imageXOffset + resourceXOffset; g.DrawRectangle(borderPen, 0, 0, x, resourceYOffset + imageYOffset + 3); } // loyalty if (LoyaltyDate != DateTime.MinValue) { g.DrawString(LoyaltyString, SystemFonts.DefaultFont, Brushes.Black, x + 15, resourceYOffset + imageYTextOffset); float width = g.MeasureString(LoyaltyString, SystemFonts.DefaultFont).Width; g.DrawRectangle(borderPen, x + 10, 0, width + 10, resourceYOffset + imageYOffset + 3); } g.TranslateTransform(0, resourceYOffset + imageYOffset + 10); // buildings float y = 5; int column = 0; int xAdd = 0; if (BuildingsDate != DateTime.MinValue) { string dateString = string.Format("Date: {0}", Tools.Common.GetPrettyDate(BuildingsDate, true)); g.DrawString(dateString, SystemFonts.DefaultFont, Brushes.Black, 5, 5); y += g.MeasureString(dateString, SystemFonts.DefaultFont).Height + 5; foreach (KeyValuePair<Building, int> building in Buildings) { column++; g.DrawImage(building.Key.Image, 5 + xAdd, y); g.DrawString(building.Value.ToString(CultureInfo.InvariantCulture), SystemFonts.DefaultFont, Brushes.Black, 5 + imageXOffset + xAdd, y + 5); if (column % 2 == 0) { y += 20; xAdd = 0; } else { xAdd = 60; } } if (column % 2 == 1) y += 20; g.DrawRectangle(borderPen, 0, 0, 2 * 60 + 5, y); // 60 == xAdd g.TranslateTransform(2 * 60 + 12, 0); } // troops if (DefenseDate != DateTime.MinValue) { column = 0; xAdd = 0; y = 5; string dateString = string.Format("Date: {0}", Tools.Common.GetPrettyDate(DefenseDate, true)); g.DrawString(dateString, SystemFonts.DefaultFont, Brushes.Black, 5, 5); y += g.MeasureString(dateString, SystemFonts.DefaultFont).Height + 5; foreach (KeyValuePair<UnitTypes, int> unit in Defense.OwnTroops) { column++; g.DrawImage(WorldUnits.Default[unit.Key].Image, 5 + xAdd, y); g.DrawString(Tools.Common.GetPrettyNumber(unit.Value), SystemFonts.DefaultFont, Brushes.Black, 5 + imageXOffset + xAdd, y + 5); if (column % 2 == 0) { y += 20; xAdd = 0; } else { xAdd = 60; } } if (column % 2 == 1) y += 20; g.DrawRectangle(borderPen, 0, 0, 2 * xAdd + 5, y); } } } /// <summary> /// Updates the estimated report when a newer report is added /// </summary> public void UpdateDefender(Report report) { if (ResourcesDate < report.Date) { // Update resources if (report.ResourceHaulGot < report.ResourceHaulMax) { // All resources taken Resources = new Resource(); ResourcesDate = report.Date; } else if (report.ResourcesLeft.Set) { // Espionage resource Resources = report.ResourcesLeft.Clone(); ResourcesDate = report.Date; } else if (report.ResourcesHaul.Set && Resources.Set) { // Subtract haul from stock Update(); if (Resources.Wood < report.ResourcesHaul.Wood) { // If barbarian + we have building info // We need to inform the user that the buildings have been upgraded? } Resources.Wood -= report.ResourcesHaul.Wood; Resources.Clay -= report.ResourcesHaul.Clay; Resources.Iron -= report.ResourcesHaul.Iron; } } if (BuildingsDate < report.Date && report.Buildings.Count > 0) { // Update buildings foreach (ReportBuilding building in report.Buildings.Values) { Buildings[building.Building.Type] = building.Level; //if (_buildings[building.Building.Type] .ContainsKey(building.Building.Type)) _buildings[building.Building.Type].Level = building.Level; //else _buildings.Add(building.Building.Type, building.Clone()); } BuildingsDate = report.Date; } if (DefenseDate < report.Date && (report.ReportFlag & ReportFlags.SeenDefense) != 0) { // Update defenses foreach (ReportUnit unit in report.Defense.Values) { Defense.OwnTroops[unit.Unit.Type] = unit.AmountEnd; //if (_defense.ContainsKey(unit.Unit.Type)) _defense[unit.Unit.Type] = unit.Clone(); //else _defense.Add(unit.Unit.Type, unit.Clone()); //_defense[unit.Unit.Type].AmountStart -= _defense[unit.Unit.Type].AmountLost; } DefenseDate = report.Date; // Mark the village as a farm / to noble if ((report.ReportFlag & ReportFlags.Clear) > 0) { if (report.Defender.Village.Player == null) report.Defender.Village.Type |= VillageType.Farm; } } // loyalty changes if (_loyaltyDate < report.Date && report.LoyaltyBegin != report.LoyaltyEnd) { _loyalty = report.LoyaltyEnd; _loyaltyDate = report.Date; if (_loyalty <= 0) { Village.Nobled(report.Attacker.Village.Player); } } if (_villageDate < report.Date) _villageDate = report.Date; } /// <summary> /// Updates the estimated report when a newer report is added /// </summary> public void UpdateAttacker(Report report) { Update(); if (DefenseDate == DateTime.MinValue || DefenseDate < report.Date) { foreach (ReportUnit unit in report.Attack.Values) { if (Defense.OwnTroops[unit.Unit.Type] >= unit.AmountLost) Defense.OwnTroops[unit.Unit.Type] -= unit.AmountLost; else Defense.OwnTroops[unit.Unit.Type] = 0; } DefenseDate = report.Date; } if (_villageDate < report.Date) _villageDate = report.Date; } /// <summary> /// Makes assumptions about the village progress /// </summary> public void Update() { if (VillageDate != DateTime.MinValue && VillageDate < World.Default.Settings.ServerTime.AddMinutes(-30)) { if (Building.HasResourceInfo(Buildings)) { // Update resources TimeSpan elapsed = World.Default.Settings.ServerTime - VillageDate; //TimeSpan elapsed = new DateTime( 2008, 9, 7, 15, 29, 0) - VillageDate; Resources.Wood += (int)Math.Floor(elapsed.TotalSeconds * WorldBuildings.Default[BuildingTypes.TimberCamp].GetTotalProduction(Buildings[BuildingTypes.TimberCamp]) / 3600); Resources.Clay += (int)Math.Floor(elapsed.TotalSeconds * WorldBuildings.Default[BuildingTypes.ClayPit].GetTotalProduction(Buildings[BuildingTypes.ClayPit]) / 3600); Resources.Iron += (int)Math.Floor(elapsed.TotalSeconds * WorldBuildings.Default[BuildingTypes.IronMine].GetTotalProduction(Buildings[BuildingTypes.IronMine]) / 3600); int warehouse = WorldBuildings.Default[BuildingTypes.Warehouse].GetTotalProduction(Buildings[BuildingTypes.Warehouse]); if (Resources.Wood > warehouse) Resources.Wood = warehouse; if (Resources.Clay > warehouse) Resources.Clay = warehouse; if (Resources.Iron > warehouse) Resources.Iron = warehouse; } // Update loyalty if (_loyaltyDate != DateTime.MinValue && _loyalty < 100) { TimeSpan elapsed = World.Default.Settings.ServerTime - VillageDate; _loyalty += World.Default.Settings.Speed * elapsed.Hours; _loyaltyDate = _loyaltyDate.AddHours(elapsed.Hours); if (_loyalty > 100) _loyalty = 100; } _villageDate = World.Default.Settings.ServerTime; } } /// <summary> /// Sets the type of the village based on the troops /// inside the village /// </summary> public void GuessVillageType() { if (Village.Reports.CurrentSituation != null) { int def = 0; int off = 0; bool flagNoble = false; bool flagScout = false; CurrentSituation current = Village.Reports.CurrentSituation; foreach (KeyValuePair<UnitTypes, int> pair in current.Defense.OwnTroops) { Unit unit = WorldUnits.Default[pair.Key]; int value = pair.Value; if (value > 0) { if (unit.Offense) off += value * unit.Cost.People; else def += value * unit.Cost.People; if (unit.Type == UnitTypes.Snob) flagNoble = true; if (unit.Type == UnitTypes.Spy && value > 2000) flagScout = true; } } if (off + def < 200) { Village.Type = VillageType.Farm; } else { if (def > off * 1.2) Village.Type = VillageType.Defense; else if (off > def * 1.2) Village.Type = VillageType.Attack; else Village.Type = VillageType.Attack | VillageType.Defense; } if (flagNoble) Village.Type |= VillageType.Noble; if (flagScout) Village.Type |= VillageType.Scout; } } /// <summary> /// Updates the troop levels of the village /// </summary> /// <param name="ownForce">Your own troops home</param> /// <param name="thereForce">The total amount of troops in the village</param> /// <param name="awayForce">Your own troops in other villages</param> /// <param name="movingForce">Your own troops moving towards another village</param> public void UpdateTroops(Dictionary<UnitTypes, int> ownForce, Dictionary<UnitTypes, int> thereForce, Dictionary<UnitTypes, int> awayForce, Dictionary<UnitTypes, int> movingForce) { Defense.Clear(); foreach (UnitTypes key in awayForce.Keys) { Defense.OtherDefenses[key] = thereForce[key] - ownForce[key]; Defense.OwnTroops[key] = ownForce[key] + awayForce[key] + movingForce[key]; Defense.OutTroops[key] = awayForce[key] + movingForce[key]; } _villageDate = World.Default.Settings.ServerTime; DefenseDate = _villageDate; GuessVillageType(); } #endregion #region IXmlSerializable Members public void ReadXml(XmlReader r) { r.MoveToContent(); r.ReadStartElement(); // Info _villageDate = Convert.ToDateTime(r.GetAttribute(0), CultureInfo.InvariantCulture); r.ReadStartElement(); _loyalty = Convert.ToSingle(r.GetAttribute(0), CultureInfo.InvariantCulture); _loyaltyDate = Convert.ToDateTime(r.GetAttribute(1), CultureInfo.InvariantCulture); r.ReadStartElement(); // Comments if (r.IsStartElement("Comments")) { if (!r.IsEmptyElement) { Village.SetComments(r.ReadElementString("Comments")); } else { r.Read(); } } // resources DateTime? tempDate; Resources.ReadXml(r, out tempDate); if (tempDate.HasValue) ResourcesDate = tempDate.Value; // defense if (r.HasAttributes) DefenseDate = Convert.ToDateTime(r.GetAttribute(0), CultureInfo.InvariantCulture); r.Read(); if (r.IsStartElement("Unit")) { while (r.IsStartElement("Unit")) { string typeDesc = r.GetAttribute(0); if (Enum.IsDefined(typeof(UnitTypes), typeDesc)) { var type = (UnitTypes)Enum.Parse(typeof(UnitTypes), typeDesc); Defense.OwnTroops[type] = Convert.ToInt32(r.GetAttribute("OwnTroops")); Defense.OutTroops[type] = Convert.ToInt32(r.GetAttribute("OutTroops")); Defense.OtherDefenses[type] = Convert.ToInt32(r.GetAttribute("OtherDefenses")); } r.Read(); } r.ReadEndElement(); } // buildings Buildings.Clear(); if (r.HasAttributes) BuildingsDate = Convert.ToDateTime(r.GetAttribute(0), CultureInfo.InvariantCulture); r.Read(); if (r.IsStartElement("Building")) { while (r.IsStartElement("Building")) { string typeDesc = r.GetAttribute(0); if (Enum.IsDefined(typeof(BuildingTypes), typeDesc)) { var type = (BuildingTypes)Enum.Parse(typeof(BuildingTypes), typeDesc); int level = Convert.ToInt32(r.GetAttribute(1)); Buildings[type] = level; } r.Read(); } r.ReadEndElement(); } r.ReadEndElement(); // Info } public void WriteXml(XmlWriter w) { w.WriteStartElement("Village"); w.WriteAttributeString("X", Village.X.ToString(CultureInfo.InvariantCulture)); w.WriteAttributeString("Y", Village.Y.ToString(CultureInfo.InvariantCulture)); // Info w.WriteStartElement("Info"); w.WriteAttributeString("Date", _villageDate.ToString(CultureInfo.InvariantCulture)); w.WriteStartElement("Loyalty"); w.WriteAttributeString("Level", _loyalty.ToString(CultureInfo.InvariantCulture)); w.WriteAttributeString("Date", _loyaltyDate.ToString(CultureInfo.InvariantCulture)); w.WriteEndElement(); // Comments w.WriteElementString("Comments", Village.Comments); Resources.WriteXml(w, ResourcesDate); w.WriteStartElement("Defense"); if (DefenseDate != DateTime.MinValue) w.WriteAttributeString("Date", DefenseDate.ToString(CultureInfo.InvariantCulture)); foreach (UnitTypes key in Defense) { w.WriteStartElement("Unit"); w.WriteAttributeString("Type", key.ToString()); w.WriteAttributeString("OwnTroops", Defense.OwnTroops[key].ToString(CultureInfo.InvariantCulture)); w.WriteAttributeString("OutTroops", Defense.OutTroops[key].ToString(CultureInfo.InvariantCulture)); w.WriteAttributeString("OtherDefenses", Defense.OtherDefenses[key].ToString(CultureInfo.InvariantCulture)); w.WriteEndElement(); } w.WriteEndElement(); w.WriteStartElement("Buildings"); if (BuildingsDate != DateTime.MinValue) w.WriteAttributeString("Date", BuildingsDate.ToString(CultureInfo.InvariantCulture)); foreach (KeyValuePair<Building, int> build in Buildings) { w.WriteStartElement("Building"); w.WriteAttributeString("Type", build.Key.Type.ToString()); w.WriteAttributeString("Level", build.Value.ToString(CultureInfo.InvariantCulture)); w.WriteEndElement(); } w.WriteEndElement(); w.WriteEndElement(); // Info } #endregion #region Buildings /// <summary> /// Represents the building levels in a village /// </summary> public class VillageBuildings : IEnumerable<KeyValuePair<Building, int>> { #region Fields private readonly Dictionary<BuildingTypes, ReportBuilding> _buildings; #endregion #region Properties /// <summary> /// Gets or sets the building level /// </summary> public int this[BuildingTypes type] { get { if (!_buildings.ContainsKey(type)) return 0; return _buildings[type].Level; } set { if (!_buildings.ContainsKey(type)) _buildings.Add(type, new ReportBuilding(WorldBuildings.Default[type], value)); else _buildings[type].Level = value; } } #endregion #region Constructors public VillageBuildings() { _buildings = new Dictionary<BuildingTypes, ReportBuilding>(); foreach (Building build in WorldBuildings.Default) { _buildings.Add(build.Type, new ReportBuilding(build, 0)); } } #endregion #region Public Methods /// <summary> /// Clears the building information /// </summary> public void Clear() { foreach (ReportBuilding build in _buildings.Values) { build.Level = 0; } } #endregion #region IEnumerable<KeyValuePair<BuildingTypes,int>> Members public IEnumerator<KeyValuePair<Building, int>> GetEnumerator() { foreach (ReportBuilding build in _buildings.Values) { yield return new KeyValuePair<Building, int>(build.Building, build.Level); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #endregion #region Units /// <summary> /// Represents the building levels in a village /// </summary> public class VillageDefense : IEnumerable<UnitTypes> { #region Properties /// <summary> /// Gets the total own troops /// </summary> public Units OwnTroops { get; private set; } /// <summary> /// Gets the own troops not at home /// </summary> public Units OutTroops { get; private set; } /// <summary> /// Gets the own troops not at home /// </summary> public Units OtherDefenses { get; private set; } #endregion #region Constructors public VillageDefense() { OwnTroops = new Units(); OutTroops = new Units(); OtherDefenses = new Units(); } #endregion #region Public Methods /// <summary> /// Clears all unit information /// </summary> public void Clear() { OwnTroops = new Units(); OutTroops = new Units(); OtherDefenses = new Units(); } #endregion #region IEnumerable Members public IEnumerator<UnitTypes> GetEnumerator() { foreach (KeyValuePair<UnitTypes, int> pair in OwnTroops) yield return pair.Key; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Units /// <summary> /// Represents all the unit types with amounts /// </summary> public class Units : IEnumerable<KeyValuePair<UnitTypes, int>> { #region Fields private readonly Dictionary<UnitTypes, int> _troops; #endregion #region Properties /// <summary> /// Gets or sets the amount of units /// </summary> public int this[UnitTypes type] { get { if (!_troops.ContainsKey(type)) return 0; return _troops[type]; } set { if (!_troops.ContainsKey(type)) _troops.Add(type, value); else _troops[type] = value; } } #endregion #region Constructors public Units() { _troops = new Dictionary<UnitTypes, int>(); } #endregion #region IEnumerable Members public IEnumerator<KeyValuePair<UnitTypes, int>> GetEnumerator() { foreach (KeyValuePair<UnitTypes, int> pair in _troops) yield return pair; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; #pragma warning disable 618 namespace DefaultCluster.Tests.General { public class BasicActivationTests : HostedTestClusterEnsureDefaultStarted { [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")] public void BasicActivation_ActivateAndUpdate() { long g1Key = GetRandomGrainId(); long g2Key = GetRandomGrainId(); ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(g1Key); ITestGrain g2 = GrainClient.GrainFactory.GetGrain<ITestGrain>(g2Key); Assert.Equal(g1Key, g1.GetPrimaryKeyLong()); Assert.Equal(g1Key, g1.GetKey().Result); Assert.Equal(g1Key.ToString(), g1.GetLabel().Result); Assert.Equal(g2Key, g2.GetKey().Result); Assert.Equal(g2Key.ToString(), g2.GetLabel().Result); g1.SetLabel("one").Wait(); Assert.Equal("one", g1.GetLabel().Result); Assert.Equal(g2Key.ToString(), g2.GetLabel().Result); ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>(g1Key); Assert.Equal("one", g1a.GetLabel().Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")] public void BasicActivation_Guid_ActivateAndUpdate() { Guid guid1 = Guid.NewGuid(); Guid guid2 = Guid.NewGuid(); IGuidTestGrain g1 = GrainClient.GrainFactory.GetGrain<IGuidTestGrain>(guid1); IGuidTestGrain g2 = GrainClient.GrainFactory.GetGrain<IGuidTestGrain>(guid2); Assert.Equal(guid1, g1.GetPrimaryKey()); Assert.Equal(guid1, g1.GetKey().Result); Assert.Equal(guid1.ToString(), g1.GetLabel().Result); Assert.Equal(guid2, g2.GetKey().Result); Assert.Equal(guid2.ToString(), g2.GetLabel().Result); g1.SetLabel("one").Wait(); Assert.Equal("one", g1.GetLabel().Result); Assert.Equal(guid2.ToString(), g2.GetLabel().Result); IGuidTestGrain g1a = GrainClient.GrainFactory.GetGrain<IGuidTestGrain>(guid1); Assert.Equal("one", g1a.GetLabel().Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("ErrorHandling"), TestCategory("GetGrain")] public void BasicActivation_Fail() { bool failed; long key = 0; try { // Key values of -2 are not allowed in this case ITestGrain fail = GrainClient.GrainFactory.GetGrain<ITestGrain>(-2); key = fail.GetKey().Result; failed = false; } catch (Exception e) { Assert.IsAssignableFrom<OrleansException>(e.GetBaseException()) ; failed = true; } if (!failed) Assert.True(false, "Should have failed, but instead returned " + key); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")] public void BasicActivation_ULong_MaxValue() { ulong key1AsUlong = UInt64.MaxValue; // == -1L long key1 = (long)key1AsUlong; ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1); Assert.Equal(key1, g1.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong()); Assert.Equal(key1, g1.GetKey().Result); Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result); g1.SetLabel("MaxValue").Wait(); Assert.Equal("MaxValue", g1.GetLabel().Result); ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong); Assert.Equal("MaxValue", g1a.GetLabel().Result); Assert.Equal(key1, g1a.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1a.GetKey().Result); } [Fact, TestCategory("ActivateDeactivate"), TestCategory("GetGrain")] public void BasicActivation_ULong_MinValue() { ulong key1AsUlong = UInt64.MinValue; // == zero long key1 = (long)key1AsUlong; ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1); Assert.Equal(key1, g1.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong()); Assert.Equal(key1, g1.GetPrimaryKeyLong()); Assert.Equal(key1, g1.GetKey().Result); Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result); g1.SetLabel("MinValue").Wait(); Assert.Equal("MinValue", g1.GetLabel().Result); ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong); Assert.Equal("MinValue", g1a.GetLabel().Result); Assert.Equal(key1, g1a.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1a.GetKey().Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")] public void BasicActivation_Long_MaxValue() { long key1 = Int32.MaxValue; ulong key1AsUlong = (ulong)key1; ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1); Assert.Equal(key1, g1.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong()); Assert.Equal(key1, g1.GetKey().Result); Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result); g1.SetLabel("MaxValue").Wait(); Assert.Equal("MaxValue", g1.GetLabel().Result); ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong); Assert.Equal("MaxValue", g1a.GetLabel().Result); Assert.Equal(key1, g1a.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1a.GetKey().Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")] public void BasicActivation_Long_MinValue() { long key1 = Int64.MinValue; ulong key1AsUlong = (ulong)key1; ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1); Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong()); Assert.Equal(key1, g1.GetPrimaryKeyLong()); Assert.Equal(key1, g1.GetKey().Result); Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result); g1.SetLabel("MinValue").Wait(); Assert.Equal("MinValue", g1.GetLabel().Result); ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong); Assert.Equal("MinValue", g1a.GetLabel().Result); Assert.Equal(key1, g1a.GetPrimaryKeyLong()); Assert.Equal((long)key1AsUlong, g1a.GetKey().Result); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate")] public void BasicActivation_MultipleGrainInterfaces() { ITestGrain simple = GrainClient.GrainFactory.GetGrain<ITestGrain>(GetRandomGrainId()); simple.GetMultipleGrainInterfaces_List().Wait(); logger.Info("GetMultipleGrainInterfaces_List() worked"); simple.GetMultipleGrainInterfaces_Array().Wait(); logger.Info("GetMultipleGrainInterfaces_Array() worked"); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("Reentrancy")] public void BasicActivation_Reentrant_RecoveryAfterExpiredMessage() { List<Task> promises = new List<Task>(); TimeSpan prevTimeout = GrainClient.GetResponseTimeout(); // set short response time and ask to do long operation, to trigger expired msgs in the silo queues. TimeSpan shortTimeout = TimeSpan.FromMilliseconds(1000); GrainClient.SetResponseTimeout(shortTimeout); ITestGrain grain = GrainClient.GrainFactory.GetGrain<ITestGrain>(GetRandomGrainId()); int num = 10; for (long i = 0; i < num; i++) { Task task = grain.DoLongAction(TimeSpan.FromMilliseconds(shortTimeout.TotalMilliseconds * 3), "A_" + i); promises.Add(task); } try { Task.WhenAll(promises).Wait(); }catch(Exception) { logger.Info("Done with stress iteration."); } // wait a bit to make sure expired msgs in the silo is trigered. Thread.Sleep(TimeSpan.FromSeconds(10)); // set the regular response time back, expect msgs ot succeed. GrainClient.SetResponseTimeout(prevTimeout); logger.Info("About to send a next legit request that should succeed."); grain.DoLongAction(TimeSpan.FromMilliseconds(1), "B_" + 0).Wait(); logger.Info("The request succeeded."); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("RequestContext"), TestCategory("GetGrain")] public void BasicActivation_TestRequestContext() { ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(GetRandomGrainId()); Task<Tuple<string, string>> promise1 = g1.TestRequestContext(); Tuple<string, string> requstContext = promise1.Result; logger.Info("Request Context is: " + requstContext); Assert.NotNull(requstContext.Item2); Assert.NotNull(requstContext.Item1); } } } #pragma warning restore 618
#region License /* * HttpServer.cs * * A simple HTTP server that allows to accept the WebSocket connection requests. * * The MIT License * * Copyright (c) 2012-2013 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 Contributors /* * Contributors: * Juan Manuel Lallana <juan.manuel.lallana@gmail.com> */ #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Provides a simple HTTP server that allows to accept the WebSocket /// connection requests. /// </summary> /// <remarks> /// The HttpServer class can provide the multi WebSocket services. /// </remarks> public class HttpServer { #region Private Fields private HttpListener _listener; private Logger _logger; private int _port; private Thread _receiveRequestThread; private string _rootPath; private bool _secure; private WebSocketServiceHostManager _serviceHosts; private volatile ServerState _state; private object _sync; private bool _windows; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class that /// listens for incoming requests on port 80. /// </summary> public HttpServer () : this (80) { } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class that /// listens for incoming requests on the specified <paramref name="port"/>. /// </summary> /// <param name="port"> /// An <see cref="int"/> that contains a port number. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is not between 1 and 65535. /// </exception> public HttpServer (int port) : this (port, port == 443 ? true : false) { } /// <summary> /// Initializes a new instance of the <see cref="HttpServer"/> class that /// listens for incoming requests on the specified <paramref name="port"/> /// and <paramref name="secure"/>. /// </summary> /// <param name="port"> /// An <see cref="int"/> that contains a port number. /// </param> /// <param name="secure"> /// A <see cref="bool"/> that indicates providing a secure connection or not. /// (<c>true</c> indicates providing a secure connection.) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="port"/> is not between 1 and 65535. /// </exception> /// <exception cref="ArgumentException"> /// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid. /// </exception> public HttpServer (int port, bool secure) { if (!port.IsPortNumber ()) throw new ArgumentOutOfRangeException ( "port", "Must be between 1 and 65535: " + port); if ((port == 80 && secure) || (port == 443 && !secure)) throw new ArgumentException ( String.Format ( "Invalid pair of 'port' and 'secure': {0}, {1}", port, secure)); _port = port; _secure = secure; _listener = new HttpListener (); _logger = new Logger (); _serviceHosts = new WebSocketServiceHostManager (_logger); _state = ServerState.READY; _sync = new object (); var os = Environment.OSVersion; if (os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX) _windows = true; var prefix = String.Format ("http{0}://*:{1}/", _secure ? "s" : "", _port); _listener.Prefixes.Add (prefix); } #endregion #region Public Properties /// <summary> /// Gets or sets the scheme used to authenticate the clients. /// </summary> /// <value> /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> values /// that indicates the scheme used to authenticate the clients. The default /// value is <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// </value> public AuthenticationSchemes AuthenticationSchemes { get { return _listener.AuthenticationSchemes; } set { if (!canSet ("AuthenticationSchemes")) return; _listener.AuthenticationSchemes = value; } } /// <summary> /// Gets or sets the certificate used to authenticate the server on the /// secure connection. /// </summary> /// <value> /// A <see cref="X509Certificate2"/> used to authenticate the server. /// </value> public X509Certificate2 Certificate { get { return _listener.DefaultCertificate; } set { if (!canSet ("Certificate")) return; if (EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath)) _logger.Warn ( "The server certificate associated with the port number already exists."); _listener.DefaultCertificate = value; } } /// <summary> /// Gets a value indicating whether the server has been started. /// </summary> /// <value> /// <c>true</c> if the server has been started; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return _state == ServerState.START; } } /// <summary> /// Gets a value indicating whether the server provides secure connection. /// </summary> /// <value> /// <c>true</c> if the server provides secure connection; otherwise, /// <c>false</c>. /// </value> public bool IsSecure { get { return _secure; } } /// <summary> /// Gets or sets a value indicating whether the server cleans up the inactive /// WebSocket sessions periodically. /// </summary> /// <value> /// <c>true</c> if the server cleans up the inactive WebSocket sessions every /// 60 seconds; otherwise, <c>false</c>. The default value is <c>true</c>. /// </value> public bool KeepClean { get { return _serviceHosts.KeepClean; } set { _serviceHosts.KeepClean = value; } } /// <summary> /// Gets the logging functions. /// </summary> /// <remarks> /// The default logging level is the <see cref="LogLevel.ERROR"/>. If you /// change the current logging level, you set the <c>Log.Level</c> property /// to any of the <see cref="LogLevel"/> values. /// </remarks> /// <value> /// A <see cref="Logger"/> that provides the logging functions. /// </value> public Logger Log { get { return _logger; } } /// <summary> /// Gets the port on which to listen for incoming requests. /// </summary> /// <value> /// An <see cref="int"/> that contains a port number. /// </value> public int Port { get { return _port; } } /// <summary> /// Gets or sets the name of the realm associated with the /// <see cref="HttpServer"/>. /// </summary> /// <value> /// A <see cref="string"/> that contains the name of the realm. /// The default value is <c>SECRET AREA</c>. /// </value> public string Realm { get { return _listener.Realm; } set { if (!canSet ("Realm")) return; _listener.Realm = value; } } /// <summary> /// Gets or sets the document root path of server. /// </summary> /// <value> /// A <see cref="string"/> that contains the document root path of server. /// The default value is <c>./Public</c>. /// </value> public string RootPath { get { return _rootPath.IsNullOrEmpty () ? (_rootPath = "./Public") : _rootPath; } set { if (!canSet ("RootPath")) return; _rootPath = value; } } /// <summary> /// Gets or sets the delegate called to find the credentials for an identity /// used to authenticate a client. /// </summary> /// <value> /// A Func&lt;<see cref="IIdentity"/>, <see cref="NetworkCredential"/>&gt; /// delegate that references the method(s) used to find the credentials. The /// default value is a function that only returns <see langword="null"/>. /// </value> public Func<IIdentity, NetworkCredential> UserCredentialsFinder { get { return _listener.UserCredentialsFinder; } set { if (!canSet ("UserCredentialsFinder")) return; _listener.UserCredentialsFinder = value; } } /// <summary> /// Gets the functions for the WebSocket services provided by the /// <see cref="HttpServer"/>. /// </summary> /// <value> /// A <see cref="WebSocketServiceHostManager"/> that manages the WebSocket /// services. /// </value> public WebSocketServiceHostManager WebSocketServices { get { return _serviceHosts; } } #endregion #region Public Events /// <summary> /// Occurs when the server receives an HTTP CONNECT request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnConnect; /// <summary> /// Occurs when the server receives an HTTP DELETE request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnDelete; /// <summary> /// Occurs when the server receives an HTTP GET request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnGet; /// <summary> /// Occurs when the server receives an HTTP HEAD request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnHead; /// <summary> /// Occurs when the server receives an HTTP OPTIONS request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnOptions; /// <summary> /// Occurs when the server receives an HTTP PATCH request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnPatch; /// <summary> /// Occurs when the server receives an HTTP POST request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnPost; /// <summary> /// Occurs when the server receives an HTTP PUT request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnPut; /// <summary> /// Occurs when the server receives an HTTP TRACE request. /// </summary> public event EventHandler<HttpRequestEventArgs> OnTrace; #endregion #region Private Methods private void abort () { lock (_sync) { if (!IsListening) return; _state = ServerState.SHUTDOWN; } _serviceHosts.Stop ( ((ushort) CloseStatusCode.SERVER_ERROR).ToByteArrayInternally (ByteOrder.BIG), true); _listener.Abort (); _state = ServerState.STOP; } private void acceptHttpRequest (HttpListenerContext context) { var args = new HttpRequestEventArgs (context); var method = context.Request.HttpMethod; if (method == "GET" && OnGet != null) { OnGet (this, args); return; } if (method == "HEAD" && OnHead != null) { OnHead (this, args); return; } if (method == "POST" && OnPost != null) { OnPost (this, args); return; } if (method == "PUT" && OnPut != null) { OnPut (this, args); return; } if (method == "DELETE" && OnDelete != null) { OnDelete (this, args); return; } if (method == "OPTIONS" && OnOptions != null) { OnOptions (this, args); return; } if (method == "TRACE" && OnTrace != null) { OnTrace (this, args); return; } if (method == "CONNECT" && OnConnect != null) { OnConnect (this, args); return; } if (method == "PATCH" && OnPatch != null) { OnPatch (this, args); return; } context.Response.Close (HttpStatusCode.NotImplemented); } private void acceptRequestAsync (HttpListenerContext context) { ThreadPool.QueueUserWorkItem ( state => { try { var authScheme = _listener.SelectAuthenticationScheme (context); if (authScheme != AuthenticationSchemes.Anonymous && !authenticateRequest (authScheme, context)) return; if (context.Request.IsUpgradeTo ("websocket")) { acceptWebSocketRequest (context.AcceptWebSocket (_logger)); return; } acceptHttpRequest (context); context.Response.Close (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); context.Connection.Close (true); } }); } private void acceptWebSocketRequest (HttpListenerWebSocketContext context) { var path = context.Path; WebSocketServiceHost host; if (path == null || !_serviceHosts.TryGetServiceHostInternally (path, out host)) { context.Close (HttpStatusCode.NotImplemented); return; } host.StartSession (context); } private bool authenticateRequest ( AuthenticationSchemes scheme, HttpListenerContext context) { if (context.Request.IsAuthenticated) return true; if (scheme == AuthenticationSchemes.Basic) context.Response.CloseWithAuthChallenge ( HttpUtility.CreateBasicAuthChallenge (_listener.Realm)); else if (scheme == AuthenticationSchemes.Digest) context.Response.CloseWithAuthChallenge ( HttpUtility.CreateDigestAuthChallenge (_listener.Realm)); else context.Response.Close (HttpStatusCode.Forbidden); return false; } private bool canSet (string property) { if (_state == ServerState.START || _state == ServerState.SHUTDOWN) { _logger.Error ( String.Format ( "The '{0}' property cannot set a value because the server has already been started.", property)); return false; } return true; } private string checkIfCertExists () { return _secure && !EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath) && Certificate == null ? "The secure connection requires a server certificate." : null; } private void receiveRequest () { while (true) { try { acceptRequestAsync (_listener.GetContext ()); } catch (HttpListenerException ex) { _logger.Warn ( String.Format ( "Receiving has been stopped.\nreason: {0}.", ex.Message)); break; } catch (Exception ex) { _logger.Fatal (ex.ToString ()); break; } } if (IsListening) abort (); } private void startReceiving () { _receiveRequestThread = new Thread (new ThreadStart (receiveRequest)); _receiveRequestThread.IsBackground = true; _receiveRequestThread.Start (); } private void stopListener (int timeOut) { _listener.Close (); _receiveRequestThread.Join (timeOut); } #endregion #region Public Methods /// <summary> /// Adds the specified typed WebSocket service with the specified /// <paramref name="servicePath"/>. /// </summary> /// <remarks> /// This method converts <paramref name="servicePath"/> to URL-decoded string /// and removes <c>'/'</c> from tail end of <paramref name="servicePath"/>. /// </remarks> /// <param name="servicePath"> /// A <see cref="string"/> that contains an absolute path to the WebSocket /// service. /// </param> /// <typeparam name="TWithNew"> /// The type of the WebSocket service. The TWithNew must inherit the /// <see cref="WebSocketService"/> class and must have a public parameterless /// constructor. /// </typeparam> public void AddWebSocketService<TWithNew> (string servicePath) where TWithNew : WebSocketService, new () { AddWebSocketService<TWithNew> (servicePath, () => new TWithNew ()); } /// <summary> /// Adds the specified typed WebSocket service with the specified /// <paramref name="servicePath"/> and <paramref name="serviceConstructor"/>. /// </summary> /// <remarks> /// <para> /// This method converts <paramref name="servicePath"/> to URL-decoded /// string and removes <c>'/'</c> from tail end of /// <paramref name="servicePath"/>. /// </para> /// <para> /// <paramref name="serviceConstructor"/> returns a initialized specified /// typed WebSocket service instance. /// </para> /// </remarks> /// <param name="servicePath"> /// A <see cref="string"/> that contains an absolute path to the WebSocket /// service. /// </param> /// <param name="serviceConstructor"> /// A Func&lt;T&gt; delegate that references the method used to initialize /// a new WebSocket service instance (a new WebSocket session). /// </param> /// <typeparam name="T"> /// The type of the WebSocket service. The T must inherit the /// <see cref="WebSocketService"/> class. /// </typeparam> public void AddWebSocketService<T> (string servicePath, Func<T> serviceConstructor) where T : WebSocketService { var msg = servicePath.CheckIfValidServicePath () ?? (serviceConstructor == null ? "'serviceConstructor' must not be null." : null); if (msg != null) { _logger.Error ( String.Format ("{0}\nservice path: {1}", msg, servicePath ?? "")); return; } var host = new WebSocketServiceHost<T> ( servicePath, serviceConstructor, _logger); if (!KeepClean) host.KeepClean = false; _serviceHosts.Add (host.ServicePath, host); } /// <summary> /// Gets the contents of the file with the specified <paramref name="path"/>. /// </summary> /// <returns> /// An array of <see cref="byte"/> that contains the contents of the file if /// it exists; otherwise, <see langword="null"/>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that contains a virtual path to the file to get. /// </param> public byte[] GetFile (string path) { var filePath = RootPath + path; if (_windows) filePath = filePath.Replace ("/", "\\"); return File.Exists (filePath) ? File.ReadAllBytes (filePath) : null; } /// <summary> /// Removes the WebSocket service with the specified /// <paramref name="servicePath"/>. /// </summary> /// <remarks> /// This method converts <paramref name="servicePath"/> to URL-decoded string /// and removes <c>'/'</c> from tail end of <paramref name="servicePath"/>. /// </remarks> /// <returns> /// <c>true</c> if the WebSocket service is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="servicePath"> /// A <see cref="string"/> that contains an absolute path to the WebSocket /// service to find. /// </param> public bool RemoveWebSocketService (string servicePath) { var msg = servicePath.CheckIfValidServicePath (); if (msg != null) { _logger.Error ( String.Format ("{0}\nservice path: {1}", msg, servicePath)); return false; } return _serviceHosts.Remove (servicePath); } /// <summary> /// Starts receiving the HTTP requests. /// </summary> public void Start () { lock (_sync) { var msg = _state.CheckIfStopped () ?? checkIfCertExists (); if (msg != null) { _logger.Error ( String.Format ( "{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure)); return; } _serviceHosts.Start (); _listener.Start (); startReceiving (); _state = ServerState.START; } } /// <summary> /// Stops receiving the HTTP requests. /// </summary> public void Stop () { lock (_sync) { var msg = _state.CheckIfStarted (); if (msg != null) { _logger.Error (String.Format ("{0}\nstate: {1}", msg, _state)); return; } _state = ServerState.SHUTDOWN; } _serviceHosts.Stop (new byte [0], true); stopListener (5000); _state = ServerState.STOP; } /// <summary> /// Stops receiving the HTTP requests with the specified <see cref="ushort"/> /// and <see cref="string"/> used to stop the WebSocket services. /// </summary> /// <param name="code"> /// A <see cref="ushort"/> that contains a status code indicating the reason /// for stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that contains the reason for stop. /// </param> public void Stop (ushort code, string reason) { byte [] data = null; lock (_sync) { var msg = _state.CheckIfStarted () ?? code.CheckIfValidCloseStatusCode () ?? (data = code.Append (reason)).CheckIfValidCloseData (); if (msg != null) { _logger.Error ( String.Format ( "{0}\nstate: {1}\ncode: {2}\nreason: {3}", msg, _state, code, reason)); return; } _state = ServerState.SHUTDOWN; } _serviceHosts.Stop (data, !code.IsReserved ()); stopListener (5000); _state = ServerState.STOP; } /// <summary> /// Stops receiving the HTTP requests with the specified /// <see cref="CloseStatusCode"/> and <see cref="string"/> used to stop the /// WebSocket services. /// </summary> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> values that represent the status /// codes indicating the reasons for stop. /// </param> /// <param name="reason"> /// A <see cref="string"/> that contains the reason for stop. /// </param> public void Stop (CloseStatusCode code, string reason) { byte [] data = null; lock (_sync) { var msg = _state.CheckIfStarted () ?? (data = ((ushort) code).Append (reason)).CheckIfValidCloseData (); if (msg != null) { _logger.Error ( String.Format ("{0}\nstate: {1}\nreason: {2}", msg, _state, reason)); return; } _state = ServerState.SHUTDOWN; } _serviceHosts.Stop (data, !code.IsReserved ()); stopListener (5000); _state = ServerState.STOP; } #endregion } }
using System; using System.Collections; using System.Diagnostics; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Cms { /** * an expanded SignerInfo block from a CMS Signed message */ public class SignerInformation { private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance; private SignerID sid; private SignerInfo info; private AlgorithmIdentifier digestAlgorithm; private AlgorithmIdentifier encryptionAlgorithm; private readonly Asn1Set signedAttributeSet; private readonly Asn1Set unsignedAttributeSet; private CmsProcessable content; private byte[] signature; private DerObjectIdentifier contentType; private IDigestCalculator digestCalculator; private byte[] resultDigest; // Derived private Asn1.Cms.AttributeTable signedAttributeTable; private Asn1.Cms.AttributeTable unsignedAttributeTable; private readonly bool isCounterSignature; internal SignerInformation( SignerInfo info, DerObjectIdentifier contentType, CmsProcessable content, IDigestCalculator digestCalculator) { this.info = info; this.sid = new SignerID(); this.contentType = contentType; this.isCounterSignature = contentType == null; try { SignerIdentifier s = info.SignerID; if (s.IsTagged) { Asn1OctetString octs = Asn1OctetString.GetInstance(s.ID); sid.SubjectKeyIdentifier = octs.GetEncoded(); } else { Asn1.Cms.IssuerAndSerialNumber iAnds = Asn1.Cms.IssuerAndSerialNumber.GetInstance(s.ID); sid.Issuer = iAnds.Name; sid.SerialNumber = iAnds.SerialNumber.Value; } } catch (IOException) { throw new ArgumentException("invalid sid in SignerInfo"); } this.digestAlgorithm = info.DigestAlgorithm; this.signedAttributeSet = info.AuthenticatedAttributes; this.unsignedAttributeSet = info.UnauthenticatedAttributes; this.encryptionAlgorithm = info.DigestEncryptionAlgorithm; this.signature = info.EncryptedDigest.GetOctets(); this.content = content; this.digestCalculator = digestCalculator; } public bool IsCounterSignature { get { return isCounterSignature; } } public DerObjectIdentifier ContentType { get { return contentType; } } public SignerID SignerID { get { return sid; } } /** * return the version number for this objects underlying SignerInfo structure. */ public int Version { get { return info.Version.Value.IntValue; } } public AlgorithmIdentifier DigestAlgorithmID { get { return digestAlgorithm; } } /** * return the object identifier for the signature. */ public string DigestAlgOid { get { return digestAlgorithm.ObjectID.Id; } } /** * return the signature parameters, or null if there aren't any. */ public Asn1Object DigestAlgParams { get { Asn1Encodable ae = digestAlgorithm.Parameters; return ae == null ? null : ae.ToAsn1Object(); } } /** * return the content digest that was calculated during verification. */ public byte[] GetContentDigest() { if (resultDigest == null) { throw new InvalidOperationException("method can only be called after verify."); } return (byte[])resultDigest.Clone(); } public AlgorithmIdentifier EncryptionAlgorithmID { get { return encryptionAlgorithm; } } /** * return the object identifier for the signature. */ public string EncryptionAlgOid { get { return encryptionAlgorithm.ObjectID.Id; } } /** * return the signature/encryption algorithm parameters, or null if * there aren't any. */ public Asn1Object EncryptionAlgParams { get { Asn1Encodable ae = encryptionAlgorithm.Parameters; return ae == null ? null : ae.ToAsn1Object(); } } /** * return a table of the signed attributes - indexed by * the OID of the attribute. */ public Asn1.Cms.AttributeTable SignedAttributes { get { if (signedAttributeSet != null && signedAttributeTable == null) { signedAttributeTable = new Asn1.Cms.AttributeTable(signedAttributeSet); } return signedAttributeTable; } } /** * return a table of the unsigned attributes indexed by * the OID of the attribute. */ public Asn1.Cms.AttributeTable UnsignedAttributes { get { if (unsignedAttributeSet != null && unsignedAttributeTable == null) { unsignedAttributeTable = new Asn1.Cms.AttributeTable(unsignedAttributeSet); } return unsignedAttributeTable; } } /** * return the encoded signature */ public byte[] GetSignature() { return (byte[]) signature.Clone(); } /** * Return a SignerInformationStore containing the counter signatures attached to this * signer. If no counter signatures are present an empty store is returned. */ public SignerInformationStore GetCounterSignatures() { // TODO There are several checks implied by the RFC3852 comments that are missing /* The countersignature attribute MUST be an unsigned attribute; it MUST NOT be a signed attribute, an authenticated attribute, an unauthenticated attribute, or an unprotected attribute. */ Asn1.Cms.AttributeTable unsignedAttributeTable = UnsignedAttributes; if (unsignedAttributeTable == null) { return new SignerInformationStore(Platform.CreateArrayList(0)); } IList counterSignatures = Platform.CreateArrayList(); /* The UnsignedAttributes syntax is defined as a SET OF Attributes. The UnsignedAttributes in a signerInfo may include multiple instances of the countersignature attribute. */ Asn1EncodableVector allCSAttrs = unsignedAttributeTable.GetAll(CmsAttributes.CounterSignature); foreach (Asn1.Cms.Attribute counterSignatureAttribute in allCSAttrs) { /* A countersignature attribute can have multiple attribute values. The syntax is defined as a SET OF AttributeValue, and there MUST be one or more instances of AttributeValue present. */ Asn1Set values = counterSignatureAttribute.AttrValues; if (values.Count < 1) { // TODO Throw an appropriate exception? } foreach (Asn1Encodable asn1Obj in values) { /* Countersignature values have the same meaning as SignerInfo values for ordinary signatures, except that: 1. The signedAttributes field MUST NOT contain a content-type attribute; there is no content type for countersignatures. 2. The signedAttributes field MUST contain a message-digest attribute if it contains any other attributes. 3. The input to the message-digesting process is the contents octets of the DER encoding of the signatureValue field of the SignerInfo value with which the attribute is associated. */ SignerInfo si = SignerInfo.GetInstance(asn1Obj.ToAsn1Object()); string digestName = CmsSignedHelper.Instance.GetDigestAlgName(si.DigestAlgorithm.ObjectID.Id); counterSignatures.Add(new SignerInformation(si, null, null, new CounterSignatureDigestCalculator(digestName, GetSignature()))); } } return new SignerInformationStore(counterSignatures); } /** * return the DER encoding of the signed attributes. * @throws IOException if an encoding error occurs. */ public byte[] GetEncodedSignedAttributes() { return signedAttributeSet == null ? null : signedAttributeSet.GetEncoded(Asn1Encodable.Der); } private bool DoVerify( AsymmetricKeyParameter key) { string digestName = Helper.GetDigestAlgName(this.DigestAlgOid); IDigest digest = Helper.GetDigestInstance(digestName); DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID; Asn1Encodable sigParams = this.encryptionAlgorithm.Parameters; ISigner sig; if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss)) { // RFC 4056 2.2 // When the id-RSASSA-PSS algorithm identifier is used for a signature, // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params. if (sigParams == null) throw new CmsException("RSASSA-PSS signature must specify algorithm parameters"); try { // TODO Provide abstract configuration mechanism // (via alternate SignerUtilities.GetSigner method taking ASN.1 params) Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance( sigParams.ToAsn1Object()); if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID)) throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm"); if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1)) throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF"); IDigest pssDigest = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID); int saltLength = pss.SaltLength.Value.IntValue; byte trailerField = (byte) pss.TrailerField.Value.IntValue; // RFC 4055 3.1 // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC if (trailerField != 1) throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1"); sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength); } catch (Exception e) { throw new CmsException("failed to set RSASSA-PSS signature parameters", e); } } else { // TODO Probably too strong a check at the moment // if (sigParams != null) // throw new CmsException("unrecognised signature parameters provided"); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid); sig = Helper.GetSignatureInstance(signatureName); } try { if (digestCalculator != null) { resultDigest = digestCalculator.GetDigest(); } else { if (content != null) { content.Write(new DigOutputStream(digest)); } else if (signedAttributeSet == null) { // TODO Get rid of this exception and just treat content==null as empty not missing? throw new CmsException("data not encapsulated in signature - use detached constructor."); } resultDigest = DigestUtilities.DoFinal(digest); } } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } // RFC 3852 11.1 Check the content-type attribute is correct { Asn1Object validContentType = GetSingleValuedSignedAttribute( CmsAttributes.ContentType, "content-type"); if (validContentType == null) { if (!isCounterSignature && signedAttributeSet != null) throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); } else { if (isCounterSignature) throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); if (!(validContentType is DerObjectIdentifier)) throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'"); DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType; if (!signedContentType.Equals(contentType)) throw new CmsException("content-type attribute value does not match eContentType"); } } // RFC 3852 11.2 Check the message-digest attribute is correct { Asn1Object validMessageDigest = GetSingleValuedSignedAttribute( CmsAttributes.MessageDigest, "message-digest"); if (validMessageDigest == null) { if (signedAttributeSet != null) throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present"); } else { if (!(validMessageDigest is Asn1OctetString)) { throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'"); } Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest; if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets())) throw new CmsException("message-digest attribute value does not match calculated value"); } } // RFC 3852 11.4 Validate countersignature attribute(s) { Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes; if (signedAttrTable != null && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0) { throw new CmsException("A countersignature attribute MUST NOT be a signed attribute"); } Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes; if (unsignedAttrTable != null) { foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature)) { if (csAttr.AttrValues.Count < 1) throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue"); // Note: We don't recursively validate the countersignature value } } } try { sig.Init(false, key); if (signedAttributeSet == null) { if (digestCalculator != null) { // need to decrypt signature and check message bytes return VerifyDigest(resultDigest, key, this.GetSignature()); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(new SigOutputStream(sig)); } } else { byte[] tmp = this.GetEncodedSignedAttributes(); sig.BlockUpdate(tmp, 0, tmp.Length); } return sig.VerifySignature(this.GetSignature()); } catch (InvalidKeyException e) { throw new CmsException("key not appropriate to signature in message.", e); } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } catch (SignatureException e) { throw new CmsException("invalid signature format in message: " + e.Message, e); } } private bool IsNull( Asn1Encodable o) { return (o is Asn1Null) || (o == null); } private DigestInfo DerDecode( byte[] encoding) { if (encoding[0] != (int)(Asn1Tags.Constructed | Asn1Tags.Sequence)) { throw new IOException("not a digest info object"); } DigestInfo digInfo = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding)); // length check to avoid Bleichenbacher vulnerability if (digInfo.GetEncoded().Length != encoding.Length) { throw new CmsException("malformed RSA signature"); } return digInfo; } private bool VerifyDigest( byte[] digest, AsymmetricKeyParameter key, byte[] signature) { string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid); try { if (algorithm.Equals("RSA")) { IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding"); c.Init(false, key); byte[] decrypt = c.DoFinal(signature); DigestInfo digInfo = DerDecode(decrypt); if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID)) { return false; } if (!IsNull(digInfo.AlgorithmID.Parameters)) { return false; } byte[] sigHash = digInfo.GetDigest(); return Arrays.ConstantTimeAreEqual(digest, sigHash); } else if (algorithm.Equals("DSA")) { ISigner sig = SignerUtilities.GetSigner("NONEwithDSA"); sig.Init(false, key); sig.BlockUpdate(digest, 0, digest.Length); return sig.VerifySignature(signature); } else { throw new CmsException("algorithm: " + algorithm + " not supported in base signatures."); } } catch (SecurityUtilityException e) { throw e; } catch (GeneralSecurityException e) { throw new CmsException("Exception processing signature: " + e, e); } catch (IOException e) { throw new CmsException("Exception decoding signature: " + e, e); } } /** * verify that the given public key successfully handles and confirms the * signature associated with this signer. */ public bool Verify( AsymmetricKeyParameter pubKey) { if (pubKey.IsPrivate) throw new ArgumentException("Expected public key", "pubKey"); // Optional, but still need to validate if present GetSigningTime(); return DoVerify(pubKey); } /** * verify that the given certificate successfully handles and confirms * the signature associated with this signer and, if a signingTime * attribute is available, that the certificate was valid at the time the * signature was generated. */ public bool Verify( X509Certificate cert) { Asn1.Cms.Time signingTime = GetSigningTime(); if (signingTime != null) { cert.CheckValidity(signingTime.Date); } return DoVerify(cert.GetPublicKey()); } /** * Return the base ASN.1 CMS structure that this object contains. * * @return an object containing a CMS SignerInfo structure. */ public SignerInfo ToSignerInfo() { return info; } private Asn1Object GetSingleValuedSignedAttribute( DerObjectIdentifier attrOID, string printableName) { Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes; if (unsignedAttrTable != null && unsignedAttrTable.GetAll(attrOID).Count > 0) { throw new CmsException("The " + printableName + " attribute MUST NOT be an unsigned attribute"); } Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes; if (signedAttrTable == null) { return null; } Asn1EncodableVector v = signedAttrTable.GetAll(attrOID); switch (v.Count) { case 0: return null; case 1: Asn1.Cms.Attribute t = (Asn1.Cms.Attribute) v[0]; Asn1Set attrValues = t.AttrValues; if (attrValues.Count != 1) throw new CmsException("A " + printableName + " attribute MUST have a single attribute value"); return attrValues[0].ToAsn1Object(); default: throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the " + printableName + " attribute"); } } private Asn1.Cms.Time GetSigningTime() { Asn1Object validSigningTime = GetSingleValuedSignedAttribute( CmsAttributes.SigningTime, "signing-time"); if (validSigningTime == null) return null; try { return Asn1.Cms.Time.GetInstance(validSigningTime); } catch (ArgumentException) { throw new CmsException("signing-time attribute value not a valid 'Time' structure"); } } /** * Return a signer information object with the passed in unsigned * attributes replacing the ones that are current associated with * the object passed in. * * @param signerInformation the signerInfo to be used as the basis. * @param unsignedAttributes the unsigned attributes to add. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation ReplaceUnsignedAttributes( SignerInformation signerInformation, Asn1.Cms.AttributeTable unsignedAttributes) { SignerInfo sInfo = signerInformation.info; Asn1Set unsignedAttr = null; if (unsignedAttributes != null) { unsignedAttr = new DerSet(unsignedAttributes.ToAsn1EncodableVector()); } return new SignerInformation( new SignerInfo( sInfo.SignerID, sInfo.DigestAlgorithm, sInfo.AuthenticatedAttributes, sInfo.DigestEncryptionAlgorithm, sInfo.EncryptedDigest, unsignedAttr), signerInformation.contentType, signerInformation.content, null); } /** * Return a signer information object with passed in SignerInformationStore representing counter * signatures attached as an unsigned attribute. * * @param signerInformation the signerInfo to be used as the basis. * @param counterSigners signer info objects carrying counter signature. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation AddCounterSigners( SignerInformation signerInformation, SignerInformationStore counterSigners) { // TODO Perform checks from RFC 3852 11.4 SignerInfo sInfo = signerInformation.info; Asn1.Cms.AttributeTable unsignedAttr = signerInformation.UnsignedAttributes; Asn1EncodableVector v; if (unsignedAttr != null) { v = unsignedAttr.ToAsn1EncodableVector(); } else { v = new Asn1EncodableVector(); } Asn1EncodableVector sigs = new Asn1EncodableVector(); foreach (SignerInformation sigInf in counterSigners.GetSigners()) { sigs.Add(sigInf.ToSignerInfo()); } v.Add(new Asn1.Cms.Attribute(CmsAttributes.CounterSignature, new DerSet(sigs))); return new SignerInformation( new SignerInfo( sInfo.SignerID, sInfo.DigestAlgorithm, sInfo.AuthenticatedAttributes, sInfo.DigestEncryptionAlgorithm, sInfo.EncryptedDigest, new DerSet(v)), signerInformation.contentType, signerInformation.content, null); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, IControl>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; ; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.IO; using System.Management.Automation; using Microsoft.PowerShell.Commands; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Security; using System.Security.Principal; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using DWORD = System.UInt32; using BOOL = System.UInt32; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; namespace Microsoft.PowerShell { internal static class SecurityUtils { /// <summary> /// gets the size of a file /// </summary> /// /// <param name="filePath"> path to file </param> /// /// <returns> file size </returns> /// /// <remarks> </remarks> /// internal static long GetFileSize(string filePath) { long size = 0; using (FileStream fs = new FileStream(filePath, FileMode.Open)) { size = fs.Length; } return size; } #if false /// <summary> /// throw if file is smaller than 4 bytes in length /// </summary> /// /// <param name="filePath"> path to file </param> /// /// <returns> Does not return a value </returns> /// /// <remarks> </remarks> /// internal static void CheckIfFileSmallerThan4Bytes(string filePath) { if (GetFileSize(filePath) < 4) { string message = StringUtil.Format( UtilsStrings.FileSmallerThan4Bytes, new object[] { filePath } ); throw PSTraceSource.NewArgumentException(message, "path"); /* // 2004/10/22-JonN The above form of the constructor // no longer exists. This should probably be as below, // however I have not tested this. This method is not // used so I have removed it. throw PSTraceSource.NewArgumentException( "path", "Utils", "FileSmallerThan4Bytes", filePath ); */ } } #endif /// <summary> /// present a prompt for a SecureString data /// </summary> /// /// <param name="hostUI"> ref to host ui interface </param> /// /// <param name="prompt"> prompt text </param> /// /// <returns> user input as secure string </returns> /// /// <remarks> </remarks> /// internal static SecureString PromptForSecureString(PSHostUserInterface hostUI, string prompt) { SecureString ss = null; hostUI.Write(prompt); ss = hostUI.ReadLineAsSecureString(); hostUI.WriteLine(""); return ss; } #if !CORECLR /// <summary> /// get plain text string from a SecureString /// /// This function will not be required once all of the methods /// that we call accept a SecureString. The list below has /// classes/methods that will be changed to accept a SecureString /// after Whidbey beta1 /// /// -- X509Certificate2.Import (String, String, X509KeyStorageFlags) /// (DCR #33007 in the DevDiv Schedule db) /// /// -- NetworkCredential(string, string); /// /// </summary> /// /// <param name="ss"> input data </param> /// /// <returns> a string representing clear-text equivalent of ss </returns> /// /// <remarks> </remarks> /// [ArchitectureSensitive] internal static string GetStringFromSecureString(SecureString ss) { IntPtr p = Marshal.SecureStringToGlobalAllocUnicode(ss); string s = Marshal.PtrToStringUni(p); Marshal.ZeroFreeGlobalAllocUnicode(p); return s; } #endif /* /// <summary> /// display sec-desc of a file /// </summary> /// /// <param name="sd"> file security descriptor </param> /// /// <returns> Does not return a value </returns> /// /// <remarks> </remarks> /// internal static void ShowFileSd(FileSecurity sd) { string userName = null; FileSystemRights rights = 0; AccessControlType aceType = 0; rules = sd.GetAccessRules(true, false, typeof(NTAccount)); foreach (FileSystemAccessRule r in rules) { userName = r.IdentityReference.ToString(); aceType = r.AccessControlType; rights = r.FileSystemRights; Console.WriteLine("{0} : {1} : {2}", userName, aceType.ToString(), rights.ToString()); } } } */ /// <summary> /// /// </summary> /// /// <param name="resourceStr"> resource string </param> /// /// <param name="errorId"> error identifier </param> /// /// <param name="args"> replacement params for resource string formatting </param> /// /// <returns> </returns> /// /// <remarks> </remarks> /// internal static ErrorRecord CreateFileNotFoundErrorRecord(string resourceStr, string errorId, params object[] args) { string message = StringUtil.Format( resourceStr, args ); FileNotFoundException e = new FileNotFoundException(message); ErrorRecord er = new ErrorRecord(e, errorId, ErrorCategory.ObjectNotFound, null); return er; } /// <summary> /// /// </summary> /// /// <param name="path"> path that was not found </param> /// /// <param name="errorId"> error identifier </param> /// /// <returns> ErrorRecord instance </returns> /// /// <remarks> </remarks> /// internal static ErrorRecord CreatePathNotFoundErrorRecord(string path, string errorId) { ItemNotFoundException e = new ItemNotFoundException(path, "PathNotFound", SessionStateStrings.PathNotFound); ErrorRecord er = new ErrorRecord(e, errorId, ErrorCategory.ObjectNotFound, null); return er; } /// <summary> /// Create an error record for 'operation not supported' condition /// </summary> /// /// <param name="resourceStr"> resource string </param> /// /// <param name="errorId"> error identifier </param> /// /// <param name="args"> replacement params for resource string formatting </param> /// /// <returns> </returns> /// /// <remarks> </remarks> /// internal static ErrorRecord CreateNotSupportedErrorRecord(string resourceStr, string errorId, params object[] args) { string message = StringUtil.Format(resourceStr, args); NotSupportedException e = new NotSupportedException(message); ErrorRecord er = new ErrorRecord(e, errorId, ErrorCategory.NotImplemented, null); return er; } /// <summary> /// Create an error record for 'operation not supported' condition /// </summary> /// /// <param name="e"> exception to include in ErrorRecord </param> /// /// <param name="errorId"> error identifier </param> /// /// <returns> </returns> /// /// <remarks> </remarks> /// internal static ErrorRecord CreateInvalidArgumentErrorRecord(Exception e, string errorId) { ErrorRecord er = new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null); return er; } /// <summary> /// convert the specified provider path to a provider path /// and make sure that all of the following is true: /// -- it represents a FileSystem path /// -- it points to a file /// -- the file exists /// </summary> /// /// <param name="cmdlet"> cmdlet instance </param> /// /// <param name="path"> provider path </param> /// /// <returns> /// filesystem path if all conditions are true, /// null otherwise /// </returns> /// /// <remarks> </remarks> /// internal static string GetFilePathOfExistingFile(PSCmdlet cmdlet, string path) { string resolvedProviderPath = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); if (Utils.NativeFileExists(resolvedProviderPath)) { return resolvedProviderPath; } else { return null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Diagnostics; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; using Microsoft.Framework.Caching.Memory; using Microsoft.Framework.Configuration; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.Runtime; using PartsUnlimited.Areas.Admin; using PartsUnlimited.Models; using PartsUnlimited.Queries; using PartsUnlimited.Recommendations; using PartsUnlimited.Search; using PartsUnlimited.Security; using PartsUnlimited.Telemetry; using PartsUnlimited.WebsiteConfiguration; using System; namespace PartsUnlimited { public class Startup { public IConfiguration Configuration { get; private set; } public Startup(IApplicationEnvironment env) { //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var builder = new ConfigurationBuilder(env.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values. Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { //If this type is present - we're on mono var runningOnMono = Type.GetType("Mono.Runtime") != null; var sqlConnectionString = Configuration.Get("Data:DefaultConnection:ConnectionString"); var useInMemoryDatabase = string.IsNullOrWhiteSpace(sqlConnectionString); // Add EF services to the services container if (useInMemoryDatabase || runningOnMono) { services.AddEntityFramework() .AddInMemoryStore() .AddDbContext<PartsUnlimitedContext>(options => { options.UseInMemoryStore(); }); } else { services.AddEntityFramework() .AddSqlServer() .AddDbContext<PartsUnlimitedContext>(options => { options.UseSqlServer(sqlConnectionString); }); } // Add Identity services to the services container services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<PartsUnlimitedContext>() .AddDefaultTokenProviders(); // Configure admin policies services.ConfigureAuthorization(auth => { auth.AddPolicy(AdminConstants.Role, new AuthorizationPolicyBuilder() .RequireClaim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed) .Build()); }); // Add implementations services.AddSingleton<IMemoryCache, MemoryCache>(); services.AddScoped<IOrdersQuery, OrdersQuery>(); services.AddScoped<IRaincheckQuery, RaincheckQuery>(); services.AddSingleton<ITelemetryProvider, EmptyTelemetryProvider>(); services.AddScoped<IProductSearch, StringContainsProductSearch>(); SetupRecommendationService(services); services.AddScoped<IWebsiteOptions>(p => { var telemetry = p.GetRequiredService<ITelemetryProvider>(); return new ConfigurationWebsiteOptions(Configuration.GetConfigurationSection("WebsiteOptions"), telemetry); }); services.AddScoped<IApplicationInsightsSettings>(p => { return new ConfigurationApplicationInsightsSettings(Configuration.GetConfigurationSection("Keys:ApplicationInsights")); }); // Associate IPartsUnlimitedContext with context services.AddTransient<IPartsUnlimitedContext>(s => s.GetService<PartsUnlimitedContext>()); // We need access to these settings in a static extension method, so DI does not help us :( ContentDeliveryNetworkExtensions.Configuration = new ContentDeliveryNetworkConfiguration(Configuration.GetConfigurationSection("CDN")); // Add MVC services to the services container services.AddMvc(); //Add all SignalR related services to IoC. services.AddSignalR(); //Add InMemoryCache services.AddSingleton<IMemoryCache, MemoryCache>(); // Add session related services. services.AddCaching(); services.AddSession(); } private void SetupRecommendationService(IServiceCollection services) { var azureMlConfig = new AzureMLFrequentlyBoughtTogetherConfig(Configuration.GetConfigurationSection("Keys:AzureMLFrequentlyBoughtTogether")); // If keys are not available for Azure ML recommendation service, register an empty recommendation engine if (string.IsNullOrEmpty(azureMlConfig.AccountKey) || string.IsNullOrEmpty(azureMlConfig.ModelName)) { services.AddSingleton<IRecommendationEngine, EmptyRecommendationsEngine>(); } else { services.AddSingleton<IAzureMLAuthenticatedHttpClient, AzureMLAuthenticatedHttpClient>(); services.AddInstance<IAzureMLFrequentlyBoughtTogetherConfig>(azureMlConfig); services.AddScoped<IRecommendationEngine, AzureMLFrequentlyBoughtTogetherRecommendationEngine>(); } } //This method is invoked when KRE_ENV is 'Development' or is not defined //The allowed values are Development,Staging and Production public void ConfigureDevelopment(IApplicationBuilder app) { //Display custom error page in production when error occurs //During development use the ErrorPage middleware to display error information in the browser app.UseErrorPage(ErrorPageOptions.ShowAll); // Add the runtime information page that can be used by developers // to see what packages are used by the application // default path is: /runtimeinfo app.UseRuntimeInfoPage(); Configure(app); } //This method is invoked when KRE_ENV is 'Staging' //The allowed values are Development,Staging and Production public void ConfigureStaging(IApplicationBuilder app) { app.UseErrorHandler("/Home/Error"); Configure(app); } //This method is invoked when KRE_ENV is 'Production' //The allowed values are Development,Staging and Production public void ConfigureProduction(IApplicationBuilder app) { app.UseErrorHandler("/Home/Error"); Configure(app); } public void Configure(IApplicationBuilder app) { // Configure Session. app.UseSession(); //Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); // Add login providers (Microsoft/AzureAD/Google/etc). This must be done after `app.UseIdentity()` app.AddLoginProviders(new ConfigurationLoginProviders(Configuration.GetConfigurationSection("Authentication"))); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the PartsUnlimited sample data SampleData.InitializePartsUnlimitedDatabaseAsync( app.ApplicationServices.GetService<PartsUnlimitedContext>, app.ApplicationServices.GetService<UserManager<ApplicationUser>>(), Configuration.GetConfigurationSection("AdminRole") ).Wait(); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // PartitionedDataSource.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// Contiguous range chunk partitioning attempts to improve data locality by keeping /// data close together in the incoming data stream together in the outgoing partitions. /// There are really three types of partitions that are used internally: /// /// 1. If the data source is indexable--like an array or List_T--we can actually /// just compute the range indexes and avoid doing any copying whatsoever. Each /// "partition" is just an enumerator that will walk some subset of the data. /// 2. If the data source has an index (different than being indexable!), we can /// turn this into a range scan of the index. We can roughly estimate distribution /// and ensure an evenly balanced set of partitions. /// 3. If we can't use 1 or 2, we instead partition "on demand" by chunking the contents /// of the source enumerator as they are requested. The unfortunate thing is that /// this requires synchronization, since consumers may be running in parallel. We /// amortize the cost of this by giving chunks of items when requested instead of /// one element at a time. Note that this approach also works for infinite streams. /// /// In all cases, the caller can request that enumerators walk elements in striped /// contiguous chunks. If striping is requested, then each partition j will yield elements /// in the data source for which ((i / s)%p) == j, where i is the element's index, s is /// a chunk size calculated by the system with the intent of aligning on cache lines, and /// p is the number of partitions. If striping is not requested, we use the same algorithm, /// only, instead of aligning on cache lines, we use a chunk size of l / p, where l /// is the length of the input and p is the number of partitions. /// /// Notes: /// This is used as the default partitioning strategy by much of the PLINQ infrastructure. /// </summary> /// <typeparam name="T"></typeparam> internal class PartitionedDataSource<T> : PartitionedStream<T, int> { //--------------------------------------------------------------------------------------- // Just constructs a new partition stream. // internal PartitionedDataSource(IEnumerable<T> source, int partitionCount, bool useStriping) : base( partitionCount, Util.GetDefaultComparer<int>(), source is IList<T> ? OrdinalIndexState.Indexible : OrdinalIndexState.Correct) { InitializePartitions(source, partitionCount, useStriping); } //--------------------------------------------------------------------------------------- // This method just creates the individual partitions given a data source. // // Notes: // We check whether the data source is an IList<T> and, if so, we can partition // "in place" by calculating a set of indexes. Otherwise, we return an enumerator that // performs partitioning lazily. Depending on which case it is, the enumerator may // contain synchronization (i.e. the latter case), meaning callers may occasionally // block when enumerating it. // private void InitializePartitions(IEnumerable<T> source, int partitionCount, bool useStriping) { Debug.Assert(source != null); Debug.Assert(partitionCount > 0); // If this is a wrapper, grab the internal wrapped data source so we can uncover its real type. ParallelEnumerableWrapper<T> wrapper = source as ParallelEnumerableWrapper<T>; if (wrapper != null) { source = wrapper.WrappedEnumerable; Debug.Assert(source != null); } // Check whether we have an indexable data source. IList<T> sourceAsList = source as IList<T>; if (sourceAsList != null) { QueryOperatorEnumerator<T, int>[] partitions = new QueryOperatorEnumerator<T, int>[partitionCount]; // We use this below to specialize enumerators when possible. T[] sourceAsArray = source as T[]; // If range partitioning is used, chunk size will be unlimited, i.e. -1. int maxChunkSize = -1; if (useStriping) { maxChunkSize = Scheduling.GetDefaultChunkSize<T>(); // The minimum chunk size is 1. if (maxChunkSize < 1) { maxChunkSize = 1; } } // Calculate indexes and construct enumerators that walk a subset of the input. for (int i = 0; i < partitionCount; i++) { if (sourceAsArray != null) { // If the source is an array, we can use a fast path below to index using // 'ldelem' instructions rather than making interface method calls. if (useStriping) { partitions[i] = new ArrayIndexRangeEnumerator(sourceAsArray, partitionCount, i, maxChunkSize); } else { partitions[i] = new ArrayContiguousIndexRangeEnumerator(sourceAsArray, partitionCount, i); } TraceHelpers.TraceInfo("ContiguousRangePartitionExchangeStream::MakePartitions - (array) #{0} {1}", i, maxChunkSize); } else { // Create a general purpose list enumerator object. if (useStriping) { partitions[i] = new ListIndexRangeEnumerator(sourceAsList, partitionCount, i, maxChunkSize); } else { partitions[i] = new ListContiguousIndexRangeEnumerator(sourceAsList, partitionCount, i); } TraceHelpers.TraceInfo("ContiguousRangePartitionExchangeStream::MakePartitions - (list) #{0} {1})", i, maxChunkSize); } } Debug.Assert(partitions.Length == partitionCount); _partitions = partitions; } else { // We couldn't use an in-place partition. Shucks. Defer to the other overload which // accepts an enumerator as input instead. _partitions = MakePartitions(source.GetEnumerator(), partitionCount); } } //--------------------------------------------------------------------------------------- // This method just creates the individual partitions given a data source. See the base // class for more details on this method's contracts. This version takes an enumerator, // and so it can't actually do an in-place partition. We'll instead create enumerators // that coordinate with one another to lazily (on demand) grab chunks from the enumerator. // This clearly is much less efficient than the fast path above since it requires // synchronization. We try to amortize that cost by retrieving many elements at once // instead of just one-at-a-time. // private static QueryOperatorEnumerator<T, int>[] MakePartitions(IEnumerator<T> source, int partitionCount) { Debug.Assert(source != null); Debug.Assert(partitionCount > 0); // At this point we were unable to efficiently partition the data source. Instead, we // will return enumerators that lazily partition the data source. QueryOperatorEnumerator<T, int>[] partitions = new QueryOperatorEnumerator<T, int>[partitionCount]; // The following is used for synchronization between threads. object sharedSyncLock = new object(); Shared<int> sharedCurrentIndex = new Shared<int>(0); Shared<int> sharedPartitionCount = new Shared<int>(partitionCount); Shared<bool> sharedExceptionTracker = new Shared<bool>(false); // Create a new lazy chunking enumerator per partition, sharing the same lock. for (int i = 0; i < partitionCount; i++) { partitions[i] = new ContiguousChunkLazyEnumerator( source, sharedExceptionTracker, sharedSyncLock, sharedCurrentIndex, sharedPartitionCount); } return partitions; } //--------------------------------------------------------------------------------------- // This enumerator walks a range within an indexable data type. It's abstract. We assume // callers have validated that the ranges are legal given the data. IndexRangeEnumerator // handles both striped and range partitioning. // // PLINQ creates one IndexRangeEnumerator per partition. Together, the enumerators will // cover the entire list or array. // // In this context, the term "range" represents the entire array or list. The range is // split up into one or more "sections". Each section is split up into as many "chunks" as // we have partitions. i-th chunk in each section is assigned to partition i. // // All sections but the last one contain partitionCount * maxChunkSize elements, except // for the last section which may contain fewer. // // For example, if the input is an array with 2,101 elements, maxChunkSize is 128 // and partitionCount is 4, all sections except the last one will contain 128*4 = 512 // elements. The last section will contain 2,101 - 4*512 = 53 elements. // // All sections but the last one will be evenly divided among partitions: the first 128 // elements will go into partition 0, the next 128 elements into partition 1, etc. // // The last section is divided as evenly as possible. In the above example, the split would // be 14-13-13-13. // // A copy of the index enumerator specialized for array indexing. It uses 'ldelem' // instructions for element retrieval, rather than using a method call. internal sealed class ArrayIndexRangeEnumerator : QueryOperatorEnumerator<T, int> { private readonly T[] _data; // The elements to iterate over. private readonly int _elementCount; // The number of elements to iterate over. private readonly int _partitionCount; // The number of partitions. private readonly int _partitionIndex; // The index of the current partition. private readonly int _maxChunkSize; // The maximum size of a chunk. -1 if unlimited. private readonly int _sectionCount; // Precomputed in ctor: the number of sections the range is split into. private Mutables _mutables; // Lazily allocated mutable variables. class Mutables { internal Mutables() { // Place the enumerator just before the first element _currentSection = -1; } internal int _currentSection; // 0-based index of the current section. internal int _currentChunkSize; // The number of elements in the current chunk. internal int _currentPositionInChunk; // 0-based position within the current chunk. internal int _currentChunkOffset; // The offset of the current chunk from the beginning of the range. } internal ArrayIndexRangeEnumerator(T[] data, int partitionCount, int partitionIndex, int maxChunkSize) { Debug.Assert(data != null, "data musn't be null"); Debug.Assert(partitionCount > 0, "partitionCount must be positive"); Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative"); Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount"); Debug.Assert(maxChunkSize > 0, "maxChunkSize must be positive or -1"); _data = data; _elementCount = data.Length; _partitionCount = partitionCount; _partitionIndex = partitionIndex; _maxChunkSize = maxChunkSize; int sectionSize = maxChunkSize * partitionCount; Debug.Assert(sectionSize > 0); // Section count is ceiling(elementCount / sectionSize) _sectionCount = _elementCount / sectionSize + ((_elementCount % sectionSize) == 0 ? 0 : 1); } internal override bool MoveNext(ref T currentElement, ref int currentKey) { // Lazily allocate the mutable holder. Mutables mutables = _mutables; if (mutables == null) { mutables = _mutables = new Mutables(); } // If we are aren't within the chunk, we need to find another. if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath()) { currentKey = mutables._currentChunkOffset + mutables._currentPositionInChunk; currentElement = _data[currentKey]; return true; } return false; } private bool MoveNextSlowPath() { Mutables mutables = _mutables; Debug.Assert(mutables != null); Debug.Assert(mutables._currentPositionInChunk >= mutables._currentChunkSize); // Move on to the next section. int currentSection = ++mutables._currentSection; int sectionsRemaining = _sectionCount - currentSection; // If empty, return right away. if (sectionsRemaining <= 0) { return false; } // Compute the offset of the current section from the beginning of the range int currentSectionOffset = currentSection * _partitionCount * _maxChunkSize; mutables._currentPositionInChunk = 0; // Now do something different based on how many chunks remain. if (sectionsRemaining > 1) { // We are not on the last section. The size of this chunk is simply _maxChunkSize. mutables._currentChunkSize = _maxChunkSize; mutables._currentChunkOffset = currentSectionOffset + _partitionIndex * _maxChunkSize; } else { // We are on the last section. Compute the size of the chunk to ensure even distribution // of elements. int lastSectionElementCount = _elementCount - currentSectionOffset; int smallerChunkSize = lastSectionElementCount / _partitionCount; int biggerChunkCount = lastSectionElementCount % _partitionCount; mutables._currentChunkSize = smallerChunkSize; if (_partitionIndex < biggerChunkCount) { mutables._currentChunkSize++; } if (mutables._currentChunkSize == 0) { return false; } mutables._currentChunkOffset = currentSectionOffset // The beginning of this section + _partitionIndex * smallerChunkSize // + the start of this chunk if all chunks were "smaller" + (_partitionIndex < biggerChunkCount ? _partitionIndex : biggerChunkCount); // + the number of "bigger" chunks before this chunk } return true; } } // A contiguous index enumerator specialized for array indexing. It uses 'ldelem' // instructions for element retrieval, rather than using a method call. internal sealed class ArrayContiguousIndexRangeEnumerator : QueryOperatorEnumerator<T, int> { private readonly T[] _data; // The elements to iterate over. private readonly int _startIndex; // Where to begin iterating. private readonly int _maximumIndex; // The maximum index to iterate over. private Shared<int> _currentIndex; // The current index (lazily allocated). internal ArrayContiguousIndexRangeEnumerator(T[] data, int partitionCount, int partitionIndex) { Debug.Assert(data != null, "data must not be null"); Debug.Assert(partitionCount > 0, "partitionCount must be positive"); Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative"); Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount"); _data = data; // Compute the size of the chunk to ensure even distribution of elements. int smallerChunkSize = data.Length / partitionCount; int biggerChunkCount = data.Length % partitionCount; // Our start index is our index times the small chunk size, plus the number // of "bigger" chunks before this one. int startIndex = partitionIndex * smallerChunkSize + (partitionIndex < biggerChunkCount ? partitionIndex : biggerChunkCount); _startIndex = startIndex - 1; // Subtract one for the first call. _maximumIndex = startIndex + smallerChunkSize + // And add one if we're responsible for part of the (partitionIndex < biggerChunkCount ? 1 : 0); // leftover chunks. Debug.Assert(_currentIndex == null, "Expected deferred allocation to ensure it happens on correct thread"); } internal override bool MoveNext(ref T currentElement, ref int currentKey) { // Lazily allocate the current index if needed. if (_currentIndex == null) { _currentIndex = new Shared<int>(_startIndex); } // Now increment the current index, check bounds, and so on. int current = ++_currentIndex.Value; if (current < _maximumIndex) { currentKey = current; currentElement = _data[current]; return true; } return false; } } // A copy of the index enumerator specialized for IList<T> indexing. It calls through // the IList<T> interface for element retrieval. internal sealed class ListIndexRangeEnumerator : QueryOperatorEnumerator<T, int> { private readonly IList<T> _data; // The elements to iterate over. private readonly int _elementCount; // The number of elements to iterate over. private readonly int _partitionCount; // The number of partitions. private readonly int _partitionIndex; // The index of the current partition. private readonly int _maxChunkSize; // The maximum size of a chunk. -1 if unlimited. private readonly int _sectionCount; // Precomputed in ctor: the number of sections the range is split into. private Mutables _mutables; // Lazily allocated mutable variables. class Mutables { internal Mutables() { // Place the enumerator just before the first element _currentSection = -1; } internal int _currentSection; // 0-based index of the current section. internal int _currentChunkSize; // The number of elements in the current chunk. internal int _currentPositionInChunk; // 0-based position within the current chunk. internal int _currentChunkOffset; // The offset of the current chunk from the beginning of the range. } internal ListIndexRangeEnumerator(IList<T> data, int partitionCount, int partitionIndex, int maxChunkSize) { Debug.Assert(data != null, "data must not be null"); Debug.Assert(partitionCount > 0, "partitionCount must be positive"); Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative"); Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount"); Debug.Assert(maxChunkSize > 0, "maxChunkSize must be positive or -1"); _data = data; _elementCount = data.Count; _partitionCount = partitionCount; _partitionIndex = partitionIndex; _maxChunkSize = maxChunkSize; int sectionSize = maxChunkSize * partitionCount; Debug.Assert(sectionSize > 0); // Section count is ceiling(elementCount / sectionSize) _sectionCount = _elementCount / sectionSize + ((_elementCount % sectionSize) == 0 ? 0 : 1); } internal override bool MoveNext(ref T currentElement, ref int currentKey) { // Lazily allocate the mutable holder. Mutables mutables = _mutables; if (mutables == null) { mutables = _mutables = new Mutables(); } // If we are aren't within the chunk, we need to find another. if (++mutables._currentPositionInChunk < mutables._currentChunkSize || MoveNextSlowPath()) { currentKey = mutables._currentChunkOffset + mutables._currentPositionInChunk; currentElement = _data[currentKey]; return true; } return false; } private bool MoveNextSlowPath() { Mutables mutables = _mutables; Debug.Assert(mutables != null); Debug.Assert(mutables._currentPositionInChunk >= mutables._currentChunkSize); // Move on to the next section. int currentSection = ++mutables._currentSection; int sectionsRemaining = _sectionCount - currentSection; // If empty, return right away. if (sectionsRemaining <= 0) { return false; } // Compute the offset of the current section from the beginning of the range int currentSectionOffset = currentSection * _partitionCount * _maxChunkSize; mutables._currentPositionInChunk = 0; // Now do something different based on how many chunks remain. if (sectionsRemaining > 1) { // We are not on the last section. The size of this chunk is simply _maxChunkSize. mutables._currentChunkSize = _maxChunkSize; mutables._currentChunkOffset = currentSectionOffset + _partitionIndex * _maxChunkSize; } else { // We are on the last section. Compute the size of the chunk to ensure even distribution // of elements. int lastSectionElementCount = _elementCount - currentSectionOffset; int smallerChunkSize = lastSectionElementCount / _partitionCount; int biggerChunkCount = lastSectionElementCount % _partitionCount; mutables._currentChunkSize = smallerChunkSize; if (_partitionIndex < biggerChunkCount) { mutables._currentChunkSize++; } if (mutables._currentChunkSize == 0) { return false; } mutables._currentChunkOffset = currentSectionOffset // The beginning of this section + _partitionIndex * smallerChunkSize // + the start of this chunk if all chunks were "smaller" + (_partitionIndex < biggerChunkCount ? _partitionIndex : biggerChunkCount); // + the number of "bigger" chunks before this chunk } return true; } } // A contiguous index enumerator specialized for IList<T> indexing. It calls through // the IList<T> interface for element retrieval. internal sealed class ListContiguousIndexRangeEnumerator : QueryOperatorEnumerator<T, int> { private readonly IList<T> _data; // The elements to iterate over. private readonly int _startIndex; // Where to begin iterating. private readonly int _maximumIndex; // The maximum index to iterate over. private Shared<int> _currentIndex; // The current index (lazily allocated). internal ListContiguousIndexRangeEnumerator(IList<T> data, int partitionCount, int partitionIndex) { Debug.Assert(data != null, "data must not be null"); Debug.Assert(partitionCount > 0, "partitionCount must be positive"); Debug.Assert(partitionIndex >= 0, "partitionIndex can't be negative"); Debug.Assert(partitionIndex < partitionCount, "partitionIndex must be less than partitionCount"); _data = data; // Compute the size of the chunk to ensure even distribution of elements. int smallerChunkSize = data.Count / partitionCount; int biggerChunkCount = data.Count % partitionCount; // Our start index is our index times the small chunk size, plus the number // of "bigger" chunks before this one. int startIndex = partitionIndex * smallerChunkSize + (partitionIndex < biggerChunkCount ? partitionIndex : biggerChunkCount); _startIndex = startIndex - 1; // Subtract one for the first call. _maximumIndex = startIndex + smallerChunkSize + // And add one if we're responsible for part of the (partitionIndex < biggerChunkCount ? 1 : 0); // leftover chunks. Debug.Assert(_currentIndex == null, "Expected deferred allocation to ensure it happens on correct thread"); } internal override bool MoveNext(ref T currentElement, ref int currentKey) { // Lazily allocate the current index if needed. if (_currentIndex == null) { _currentIndex = new Shared<int>(_startIndex); } // Now increment the current index, check bounds, and so on. int current = ++_currentIndex.Value; if (current < _maximumIndex) { currentKey = current; currentElement = _data[current]; return true; } return false; } } //--------------------------------------------------------------------------------------- // This enumerator lazily grabs chunks of data from the underlying data source. It is // safe for this data source to be enumerated by multiple such enumerators, since it has // been written to perform proper synchronization. // private class ContiguousChunkLazyEnumerator : QueryOperatorEnumerator<T, int> { private const int chunksPerChunkSize = 7; // the rate at which to double the chunksize (double chunksize every 'r' chunks). MUST BE == (2^n)-1 for some n. private readonly IEnumerator<T> _source; // Data source to enumerate. private readonly object _sourceSyncLock; // Lock to use for all synchronization. private readonly Shared<int> _currentIndex; // The index shared by all. private readonly Shared<int> _activeEnumeratorsCount; // How many enumerators over the same source have not been disposed yet? private readonly Shared<bool> _exceptionTracker; private Mutables _mutables; // Any mutable fields on this enumerator. These mutables are local and persistent class Mutables { internal Mutables() { _nextChunkMaxSize = 1; // We start the chunk size at 1 and grow it later. _chunkBuffer = new T[Scheduling.GetDefaultChunkSize<T>()]; // Pre-allocate the array at the maximum size. _currentChunkSize = 0; // The chunk begins life begins empty. _currentChunkIndex = -1; _chunkBaseIndex = 0; _chunkCounter = 0; } internal readonly T[] _chunkBuffer; // Buffer array for the current chunk being enumerated. internal int _nextChunkMaxSize; // The max. chunk size to use for the next chunk. internal int _currentChunkSize; // The element count for our current chunk. internal int _currentChunkIndex; // Our current index within the temporary chunk. internal int _chunkBaseIndex; // The start index from which the current chunk was taken. internal int _chunkCounter; } //--------------------------------------------------------------------------------------- // Constructs a new enumerator that lazily retrieves chunks from the provided source. // internal ContiguousChunkLazyEnumerator( IEnumerator<T> source, Shared<bool> exceptionTracker, object sourceSyncLock, Shared<int> currentIndex, Shared<int> degreeOfParallelism) { Debug.Assert(source != null); Debug.Assert(sourceSyncLock != null); Debug.Assert(currentIndex != null); _source = source; _sourceSyncLock = sourceSyncLock; _currentIndex = currentIndex; _activeEnumeratorsCount = degreeOfParallelism; _exceptionTracker = exceptionTracker; } //--------------------------------------------------------------------------------------- // Just retrieves the current element from our current chunk. // internal override bool MoveNext(ref T currentElement, ref int currentKey) { Mutables mutables = _mutables; if (mutables == null) { mutables = _mutables = new Mutables(); } Debug.Assert(mutables._chunkBuffer != null); // Loop until we've exhausted our data source. while (true) { // If we have elements remaining in the current chunk, return right away. T[] chunkBuffer = mutables._chunkBuffer; int currentChunkIndex = ++mutables._currentChunkIndex; if (currentChunkIndex < mutables._currentChunkSize) { Debug.Assert(_source != null); Debug.Assert(chunkBuffer != null); Debug.Assert(mutables._currentChunkSize > 0); Debug.Assert(0 <= currentChunkIndex && currentChunkIndex < chunkBuffer.Length); currentElement = chunkBuffer[currentChunkIndex]; currentKey = mutables._chunkBaseIndex + currentChunkIndex; return true; } // Else, it could be the first time enumerating this object, or we may have // just reached the end of the current chunk and need to grab another one? In either // case, we will look for more data from the underlying enumerator. Because we // share the same enumerator object, we have to do this under a lock. lock (_sourceSyncLock) { Debug.Assert(0 <= mutables._nextChunkMaxSize && mutables._nextChunkMaxSize <= chunkBuffer.Length); // Accumulate a chunk of elements from the input. int i = 0; if (_exceptionTracker.Value) { return false; } try { for (; i < mutables._nextChunkMaxSize && _source.MoveNext(); i++) { // Read the current entry into our buffer. chunkBuffer[i] = _source.Current; } } catch { _exceptionTracker.Value = true; throw; } // Store the number of elements we fetched from the data source. mutables._currentChunkSize = i; // If we've emptied the enumerator, return immediately. if (i == 0) { return false; } // Increment the shared index for all to see. Throw an exception on overflow. mutables._chunkBaseIndex = _currentIndex.Value; checked { _currentIndex.Value += i; } } // Each time we access the data source, we grow the chunk size for the next go-round. // We grow the chunksize once per 'chunksPerChunkSize'. if (mutables._nextChunkMaxSize < chunkBuffer.Length) { if ((mutables._chunkCounter++ & chunksPerChunkSize) == chunksPerChunkSize) { mutables._nextChunkMaxSize = mutables._nextChunkMaxSize * 2; if (mutables._nextChunkMaxSize > chunkBuffer.Length) { mutables._nextChunkMaxSize = chunkBuffer.Length; } } } // Finally, reset our index to the beginning; loop around and we'll return the right values. mutables._currentChunkIndex = -1; } } protected override void Dispose(bool disposing) { if (Interlocked.Decrement(ref _activeEnumeratorsCount.Value) == 0) { _source.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; // This tests CompareExchange(object, object, object). // It just casts a bunch of different value types to object, // then makes sure CompareExchange works on those objects. public class InterlockedCompareExchange2 { private const int c_NUM_LOOPS = 100; private const int c_MIN_STRING_LEN = 5; private const int c_MAX_STRING_LEN = 128; public static int Main() { InterlockedCompareExchange2 test = new InterlockedCompareExchange2(); TestLibrary.TestFramework.BeginTestCase("InterlockedCompareExchange2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; return retVal; } // This particular test is for when the comparands are equal and the // switch should take place. public bool PosTest1() { bool retVal = true; object location; TestLibrary.TestFramework.BeginScenario("PosTest1: object Interlocked.CompareExchange(object&,object, object) where comparand is equal"); try { TestLibrary.TestFramework.BeginScenario("PosTest1: object == Byte"); location = (object)TestLibrary.Generator.GetByte(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetByte() ) && retVal; // Note that (&&) performs a logical-AND of // its bool operands, but only evaluates its second // operand if necessary. When ExchangeObjects is first // called (above), retVal (RHS) // is true, as it was initialized above. If ExchangeObjects // returns true, then it checks retVal (RHS), it is also true, // so retVal (LHS) gets set to true. This stays this // way so long as ExchangeObjects returns true in this and // subsequent calls. // If some time ExchangeObjects returns false (0), this // expression does not check retVal (RHS), and instead // retVal (LHS) becomes false. Next call to ExchangeObjects, // retVal (RHS) is false even if ExchangeObjects returns true, so // retVal (both RHS and LHS) remains false for all // subsequent calls to ExchangeObjects. As such, if any one of // the many calls to ExchangeObjects fails, retVal returns false TestLibrary.TestFramework.BeginScenario("PosTest1: object == Byte[]"); byte[] bArr1 = new Byte[5 + (TestLibrary.Generator.GetInt32() % 1024)]; byte[] bArr2 = new Byte[5 + (TestLibrary.Generator.GetInt32() % 1024)]; TestLibrary.Generator.GetBytes(bArr1); TestLibrary.Generator.GetBytes(bArr2); location = (object)bArr1; retVal = ExchangeObjects( true, location, location, (object)bArr2 ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int16"); location = (object)TestLibrary.Generator.GetInt16(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetInt16() ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int32"); location = (object)TestLibrary.Generator.GetInt32(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetInt32() ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int64"); location = (object)(object)TestLibrary.Generator.GetInt64(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetInt64() ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Single"); location = (object)(object)TestLibrary.Generator.GetSingle(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetSingle() ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Double"); location = (object)(object)TestLibrary.Generator.GetDouble(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetDouble() ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == string"); location = TestLibrary.Generator.GetString(false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetString(false, c_MIN_STRING_LEN, c_MAX_STRING_LEN) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == char"); location = TestLibrary.Generator.GetChar(); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetChar() ) && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } // This particular test is for when the comparands are not equal and the // switch should not take place. public bool PosTest2() { bool retVal = true; object location; object other; TestLibrary.TestFramework.BeginScenario("PosTest2: object Interlocked.CompareExchange(object&,object, object) where comparand are not equal"); try { TestLibrary.TestFramework.BeginScenario("PosTest2: object == Byte"); location = (object)TestLibrary.Generator.GetByte(); other = (object)TestLibrary.Generator.GetByte(); retVal = ExchangeObjects( false, location, (object)((byte)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Byte[]"); byte[] bArr1 = new Byte[5 + (TestLibrary.Generator.GetInt32() % 1024)]; byte[] bArr2 = new Byte[5 + (TestLibrary.Generator.GetInt32() % 1024)]; byte[] bArr3 = new Byte[5 + (TestLibrary.Generator.GetInt32() % 1024)]; TestLibrary.Generator.GetBytes(bArr1); TestLibrary.Generator.GetBytes(bArr2); TestLibrary.Generator.GetBytes(bArr3); location = (object)bArr1; retVal = ExchangeObjects( false, location, (object)bArr2, (object)bArr3 ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Int16"); location = (object)TestLibrary.Generator.GetInt16(); other = (object)TestLibrary.Generator.GetInt16(); retVal = ExchangeObjects( false, location, (object)((Int16)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Int32"); location = (object)TestLibrary.Generator.GetInt32(); other = (object)TestLibrary.Generator.GetInt32(); retVal = ExchangeObjects( false, location, (object)((Int32)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Int64"); location = (object)(object)TestLibrary.Generator.GetInt64(); other = (object)TestLibrary.Generator.GetInt64(); retVal = ExchangeObjects( false, location, (object)((Int64)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Single"); location = (object)(object)TestLibrary.Generator.GetSingle(); other = (object)TestLibrary.Generator.GetSingle(); retVal = ExchangeObjects( false, location, (object)((Single)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Double"); location = (object)(object)TestLibrary.Generator.GetDouble(); other = (object)TestLibrary.Generator.GetDouble(); retVal = ExchangeObjects( false, location, (object)((Double)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == string"); location = TestLibrary.Generator.GetString(false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); retVal = ExchangeObjects( false, location, (string)location+TestLibrary.Generator.GetChar(), (object)TestLibrary.Generator.GetDouble() ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == char"); location = TestLibrary.Generator.GetChar(); object comparand; do { comparand = TestLibrary.Generator.GetChar(); } while(comparand == location); retVal = ExchangeObjects( false, location, comparand, (object)TestLibrary.Generator.GetChar() ) && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool ExchangeObjects(bool exchange, object location, object comparand, object value) { bool retVal = true; object oldLocation; object originalLocation = location; if (!exchange && comparand == location) { TestLibrary.TestFramework.LogError("003", "Comparand and location are equal unexpectadly!!!!"); retVal = false; } if (exchange && comparand != location) { TestLibrary.TestFramework.LogError("004", "Comparand and location are not equal unexpectadly!!!!"); retVal = false; } // this is the only significant difference between this test // and InterlockedCompareExchange7.cs - here we use the // object overload directly. oldLocation = Interlocked.CompareExchange(ref location, value, comparand); // if exchange=true, then the exchange was supposed to take place. // as a result, assuming value did not equal comparand initially, // and location did equal comparand initially, then we should // expect the following: // oldLoc holds locations old value,oldLocation == comparand, because oldLocation equals what // location equaled before the exchange, and that // equaled comparand // location == value, because the exchange took place if (exchange) { if (!Object.ReferenceEquals(location,value)) { TestLibrary.TestFramework.LogError("005", "Interlocked.CompareExchange() did not do the exchange correctly: Expected location(" + location + ") to equal value(" + value + ")"); retVal = false; } if (!Object.ReferenceEquals(oldLocation,originalLocation)) { TestLibrary.TestFramework.LogError("006", "Interlocked.CompareExchange() did not return the expected value: Expected oldLocation(" + oldLocation + ") to equal originalLocation(" + originalLocation + ")"); retVal = false; } } // if exchange!=true, then the exchange was supposed to NOT take place. // expect the following: // location == originalLocation, because the exchange did not happen // oldLocation == originalLocation, because the exchange did not happen else { if (!Object.ReferenceEquals(location,originalLocation)) { TestLibrary.TestFramework.LogError("007", "Interlocked.CompareExchange() should not change the location: Expected location(" + location + ") to equal originalLocation(" + originalLocation + ")"); retVal = false; } if (!Object.ReferenceEquals(oldLocation,originalLocation)) { TestLibrary.TestFramework.LogError("008", "Interlocked.CompareExchange() did not return the expected value: Expected oldLocation(" + oldLocation + ") to equal originalLocation(" + originalLocation + ")"); retVal = false; } } return retVal; } }
using UnityEngine; using System.Collections; using DFHack; // Pretty tightly coupled to GameMap, ehhh. public class MapSelection : MonoBehaviour { GameMap gameMap; public GameObject cameraOrigin; public bool debugMode = false; public Vector3 dfCoord = new Vector3(); public Vector3 unityCoord = new Vector3(); //private Vector3 mouseWorldPosition = Vector3.zero; private Vector3 mouseWorldPositionPrevious = Vector3.zero; private float mouseWorldPlaneHeight = 0f; const int MAXIMUM_CHECKS = 5000; public Material highlightLineMaterial; void Awake() { gameMap = FindObjectOfType<GameMap>(); } //Handle mouse dragging here. void Update() { if (!DFConnection.Connected || !gameMap.enabled) return; //mouseWorldPosition = GetMouseWorldPosition(Input.mousePosition); UpdateCameraPan(); if(Input.GetMouseButton(0)) { Ray mouseRay = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); DFCoord currentTarget; Vector3 currentTargetCoords; if (DFConnection.Connected && gameMap.enabled && FindCurrentTarget(mouseRay, out currentTarget, out currentTargetCoords)) { gameMap.cursX = currentTarget.x; gameMap.cursY = currentTarget.y; gameMap.cursZ = currentTarget.z; } else { gameMap.cursX = -30000; gameMap.cursY = -30000; gameMap.cursZ = -30000; } } } private void UpdateCameraPan() { if (Input.GetMouseButtonDown(2)) { //Initialize mouse drag pan mouseWorldPositionPrevious = GetMouseWorldPosition(Input.mousePosition); mouseWorldPlaneHeight = mouseWorldPositionPrevious.y; } if (Input.GetMouseButton(2)) { //Mouse drag pan Vector3 mouseWorldPosition = GetMouseWorldPosition(Input.mousePosition, mouseWorldPlaneHeight); Vector3 current = new Vector3(mouseWorldPosition.x, 0f, mouseWorldPosition.z); Vector3 previous = new Vector3(mouseWorldPositionPrevious.x, 0f, mouseWorldPositionPrevious.z); cameraOrigin.transform.Translate(previous - current, Space.World); gameMap.UpdateCenter(cameraOrigin.transform.position); mouseWorldPositionPrevious = GetMouseWorldPosition(Input.mousePosition, mouseWorldPlaneHeight); } } private Vector3 GetMouseWorldPosition(Vector3 mousePosition, float planeHeight) { Plane plane = new Plane(Vector3.up, new Vector3(0f, planeHeight, 0f)); Ray ray = GetComponent<Camera>().ScreenPointToRay(mousePosition); float distance; if (plane.Raycast(ray, out distance)) { return ray.GetPoint(distance); } return this.mouseWorldPositionPrevious; } Vector3 GetMouseWorldPosition(Vector3 mousePosition) { DFCoord dfTarget; //dummy coord to hold things for now. Vector3 WorldPos; Ray mouseRay = GetComponent<Camera>().ScreenPointToRay(mousePosition); if (!FindCurrentTarget(mouseRay, out dfTarget, out WorldPos)) { Plane currentPlane = new Plane(Vector3.up, GameMap.DFtoUnityCoord(0, 0, gameMap.PosZ)); float distance; if (currentPlane.Raycast(mouseRay, out distance)) { WorldPos = mouseRay.GetPoint(distance); } else { WorldPos = Vector3.zero; } } return WorldPos; } // If we're attached to a camera, highlight the cube we're pointing at // (For now) void OnPostRender() { if (!DFConnection.Connected || !gameMap.enabled) return; Ray mouseRay = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); DFCoord currentTarget; Vector3 currentTargetCoords; if (FindCurrentTarget(mouseRay, out currentTarget, out currentTargetCoords)) { //DebugHighlightTile(currentTarget, Color.white); unityCoord = currentTargetCoords; dfCoord = new Vector3(currentTarget.x, currentTarget.y, currentTarget.z); } } // A big method, but pretty simple. // Walk through tiles (starting in current one); // in each tile, check if the ray is actively hitting something. // If it's not, find the wall of the tile the ray exits through, // go to that tile, and repeat. bool FindCurrentTarget(Ray ray, out DFCoord tileCoord, out Vector3 unityCoord) { if (!HitsMapCube(ray)) { tileCoord = default(DFCoord); unityCoord = default(Vector3); return false; } // In each tile, we find its bottom corner, and then add these // values to find the coordinates of the walls. // If the ray increases on this axis, the offset will be the // width of the tile along that axis; if the ray decreases, // the offset will be 0 (since we're already on that wall.) float xWallOffset, yWallOffset, zWallOffset; // When we pass through a tile and hit this wall, how do we increment // our DFCoord? DFCoord xHitIncrement, yHitIncrement, zHitIncrement; if (ray.direction.x > 0) { xWallOffset = GameMap.tileWidth; xHitIncrement = new DFCoord(1, 0, 0); } else { xWallOffset = 0; xHitIncrement = new DFCoord(-1, 0, 0); } if (ray.direction.z > 0) { zWallOffset = GameMap.tileWidth; zHitIncrement = new DFCoord(0, -1, 0); } else { zWallOffset = 0; zHitIncrement = new DFCoord(0, 1, 0); } if (ray.direction.y > 0) { yWallOffset = GameMap.tileHeight; yHitIncrement = new DFCoord(0, 0, 1); } else { yWallOffset = 0; yHitIncrement = new DFCoord(0, 0, -1); } // If this is true and we go onto a tile outside the map, // we stop iterating (since we can't hit anything.) bool haveHitMap = false; // The coordinate we start at. DFCoord currentCoord = GameMap.UnityToDFCoord(ray.origin); // The coordinate of the last tile wall intersection. Vector3 lastHit = ray.origin; // Cheap hack to keep from looping forever if we screw up somehow. for (int _insurance = 0; _insurance < MAXIMUM_CHECKS; _insurance++) { if (debugMode) { DebugHighlightTile(currentCoord, Color.blue); } // Make sure we don't move backwards somehow. if ((lastHit.x - ray.origin.x) / ray.direction.x < 0) { throw new UnityException("Negative distance multiplier?"); } // Get the corner of the current tile. Vector3 cornerCoord = GameMap.DFtoUnityBottomCorner(currentCoord); // Are we in the selectable area of the map? if (!MapDataStore.InMapBounds(currentCoord) || gameMap.PosZ <= currentCoord.z) { // No. if (haveHitMap) { // But we have been before; // we've entered and exited the map without hitting anything. tileCoord = default(DFCoord); unityCoord = default(Vector3); return false; } } else { // We are in the map. haveHitMap = true; MapDataStore.Tile? currentTile = MapDataStore.Main[currentCoord.x, currentCoord.y, currentCoord.z]; // Are we in a real tile? if (currentTile != null) { // Yes. switch (currentTile.Value.shape) { case RemoteFortressReader.TiletypeShape.EMPTY: case RemoteFortressReader.TiletypeShape.NO_SHAPE: // We're not hitting anything, though. break; //case RemoteFortressReader.TiletypeShape.SHRUB: //case RemoteFortressReader.TiletypeShape.SAPLING: case RemoteFortressReader.TiletypeShape.WALL: case RemoteFortressReader.TiletypeShape.FORTIFICATION: //case RemoteFortressReader.TiletypeShape.TRUNK_BRANCH: case RemoteFortressReader.TiletypeShape.TWIG: // We must be hitting things. // (maybe adjust shrub, saplings out of this group?) tileCoord = currentCoord; unityCoord = lastHit; return true; case RemoteFortressReader.TiletypeShape.RAMP: case RemoteFortressReader.TiletypeShape.FLOOR: case RemoteFortressReader.TiletypeShape.BOULDER: case RemoteFortressReader.TiletypeShape.PEBBLES: case RemoteFortressReader.TiletypeShape.BROOK_TOP: case RemoteFortressReader.TiletypeShape.SAPLING: case RemoteFortressReader.TiletypeShape.SHRUB: case RemoteFortressReader.TiletypeShape.BRANCH: case RemoteFortressReader.TiletypeShape.TRUNK_BRANCH: // Check if we're in the floor. // (that we're in the tile is implied.) if (Between(cornerCoord.y, lastHit.y, cornerCoord.y + GameMap.floorHeight)) { tileCoord = currentCoord; unityCoord = lastHit; return true; } // Check if we enter the floor; same way we check wall intersections. float floorY = cornerCoord.y + GameMap.floorHeight; float toFloorMult = (floorY - ray.origin.y) / ray.direction.y; Vector3 floorIntercept = ray.origin + ray.direction * toFloorMult; if (Between(cornerCoord.x, floorIntercept.x, cornerCoord.x + GameMap.tileWidth) && Between(cornerCoord.z, floorIntercept.z, cornerCoord.z + GameMap.tileWidth)) { tileCoord = currentCoord; unityCoord = lastHit; return true; } break; } } } // Didn't hit anything in the tile; figure out which wall we're hitting & walk to that tile. { float xMult = (cornerCoord.x + xWallOffset - ray.origin.x) / ray.direction.x; Vector3 xIntercept = ray.origin + ray.direction * xMult; if (Between(cornerCoord.z, xIntercept.z, cornerCoord.z + GameMap.tileWidth) && Between(cornerCoord.y, xIntercept.y, cornerCoord.y + GameMap.tileHeight)) { lastHit = xIntercept; currentCoord += xHitIncrement; continue; } } { float zMult = (cornerCoord.z + zWallOffset - ray.origin.z) / ray.direction.z; Vector3 zIntercept = ray.origin + ray.direction * zMult; if (Between(cornerCoord.x, zIntercept.x, cornerCoord.x + GameMap.tileWidth) && Between(cornerCoord.y, zIntercept.y, cornerCoord.y + GameMap.tileHeight)) { lastHit = zIntercept; currentCoord += zHitIncrement; continue; } } { float yMult = (cornerCoord.y + yWallOffset - ray.origin.y) / ray.direction.y; Vector3 yIntercept = ray.origin + ray.direction * yMult; if (cornerCoord.x <= yIntercept.x && yIntercept.x <= cornerCoord.x + GameMap.tileWidth && cornerCoord.z <= yIntercept.z && yIntercept.z <= cornerCoord.z + GameMap.tileWidth) { lastHit = yIntercept; currentCoord += yHitIncrement; continue; } } // We haven't found a wall to hit. // This shouldn't happen, but occasionally does. //throw new UnityException("Didn't hit any tile walls?"); } // We went the maximum amount of time without hitting anything tileCoord = default(DFCoord); unityCoord = default(Vector3); return false; } bool Between(float lower, float t, float upper) { return lower <= t && t <= upper; } // Check if a ray could possibly hit the game map at all bool HitsMapCube(Ray ray) { Vector3 lowerLimits = GameMap.DFtoUnityBottomCorner(new DFCoord(0, 0, 0)); Vector3 upperLimits = GameMap.DFtoUnityBottomCorner(new DFCoord( MapDataStore.MapSize.x - 1, MapDataStore.MapSize.y - 1, MapDataStore.MapSize.z - 1 )) + new Vector3(GameMap.tileWidth, GameMap.tileHeight, GameMap.tileWidth); // Multipliers to scale the ray to hit the different walls of the cube float tx1 = (lowerLimits.x - ray.origin.x) / ray.direction.x; float tx2 = (upperLimits.x - ray.origin.x) / ray.direction.x; float ty1 = (lowerLimits.y - ray.origin.y) / ray.direction.y; float ty2 = (upperLimits.y - ray.origin.y) / ray.direction.y; float tz1 = (lowerLimits.z - ray.origin.z) / ray.direction.z; float tz2 = (upperLimits.z - ray.origin.z) / ray.direction.z; float tMin = Mathf.Min(tx1, tx2, ty1, ty2, tz1, tz2); float tMax = Mathf.Max(tx1, tx2, ty1, ty2, tz1, tz2); // If tMax < 0, cube is entirely behind us; // if tMin > tMax, we don't intersect the cube at all return tMin < tMax && 0 < tMax; } void DebugHighlightTile(DFCoord tile, Color color) { DebugHighlightRegion(tile, tile, color); } void DebugHighlightRegion(DFCoord a, DFCoord b, Color color) { highlightLineMaterial.SetPass(0); Vector3 aVec = GameMap.DFtoUnityBottomCorner(a); Vector3 bVec = GameMap.DFtoUnityBottomCorner(b); Vector3 lowC = new Vector3( Mathf.Min(aVec.x, bVec.x), Mathf.Min(aVec.y, bVec.y), Mathf.Min(aVec.z, bVec.z) ); Vector3 upC = new Vector3( Mathf.Max(aVec.x, bVec.x) + GameMap.tileWidth, Mathf.Max(aVec.y, bVec.y) + GameMap.tileHeight, Mathf.Max(aVec.z, bVec.z) + GameMap.tileWidth ); // Bottom square GL.Begin(GL.LINES); GL.Color(color); GL.Vertex3(lowC.x, lowC.y, lowC.z); GL.Vertex3(lowC.x, lowC.y, upC.z); GL.Vertex3(lowC.x, lowC.y, upC.z); GL.Vertex3(upC.x, lowC.y, upC.z); GL.Vertex3(upC.x, lowC.y, upC.z); GL.Vertex3(upC.x, lowC.y, lowC.z); GL.Vertex3(upC.x, lowC.y, lowC.z); GL.Vertex3(lowC.x, lowC.y, lowC.z); // Vertical lines GL.Vertex3(lowC.x, lowC.y, lowC.z); GL.Vertex3(lowC.x, upC.y, lowC.z); GL.Vertex3(lowC.x, lowC.y, upC.z); GL.Vertex3(lowC.x, upC.y, upC.z); GL.Vertex3(upC.x, lowC.y, upC.z); GL.Vertex3(upC.x, upC.y, upC.z); GL.Vertex3(upC.x, lowC.y, lowC.z); GL.Vertex3(upC.x, upC.y, lowC.z); // Upper square GL.Vertex3(lowC.x, upC.y, lowC.z); GL.Vertex3(lowC.x, upC.y, upC.z); GL.Vertex3(lowC.x, upC.y, upC.z); GL.Vertex3(upC.x, upC.y, upC.z); GL.Vertex3(upC.x, upC.y, upC.z); GL.Vertex3(upC.x, upC.y, lowC.z); GL.Vertex3(upC.x, upC.y, lowC.z); GL.Vertex3(lowC.x, upC.y, lowC.z); GL.End(); } }
// // Extension.cs // // Author: // Lluis Sanchez Gual // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using System.Collections.Specialized; using Mono.Addins.Serialization; namespace Mono.Addins.Description { /// <summary> /// An extension definition. /// </summary> /// <remarks> /// An Extension is a collection of nodes which have to be registered in an extension point. /// The target extension point is specified in the <see cref="Mono.Addins.Description.Extension"/>.Path property. /// </remarks> public class Extension: ObjectDescription, IComparable { string path; ExtensionNodeDescriptionCollection nodes; /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.Description.Extension"/> class. /// </summary> public Extension () { } /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.Description.Extension"/> class. /// </summary> /// <param name='path'> /// Path that identifies the extension point being extended /// </param> public Extension (string path) { this.path = path; } /// <summary> /// Gets the object extended by this extension /// </summary> /// <returns> /// The extended object can be an <see cref="Mono.Addins.Description.ExtensionPoint"/> or /// an <see cref="Mono.Addins.Description.ExtensionNodeDescription"/>. /// </returns> /// <remarks> /// This method only works when the add-in description to which the extension belongs has been /// loaded from an add-in registry. /// </remarks> public ObjectDescription GetExtendedObject () { AddinDescription desc = ParentAddinDescription; if (desc == null) return null; ExtensionPoint ep = FindExtensionPoint (desc, path); if (ep == null && desc.OwnerDatabase != null) { foreach (Dependency dep in desc.MainModule.Dependencies) { AddinDependency adep = dep as AddinDependency; if (adep == null) continue; Addin ad = desc.OwnerDatabase.GetInstalledAddin (ParentAddinDescription.Domain, adep.FullAddinId); if (ad != null && ad.Description != null) { ep = FindExtensionPoint (ad.Description, path); if (ep != null) break; } } } if (ep != null) { string subp = path.Substring (ep.Path.Length).Trim ('/'); if (subp.Length == 0) return ep; // The extension is directly extending the extension point // The extension is extending a node of the extension point return desc.FindExtensionNode (path, true); } return null; } /// <summary> /// Gets the node types allowed in this extension. /// </summary> /// <returns> /// The allowed node types. /// </returns> /// <remarks> /// This method only works when the add-in description to which the extension belongs has been /// loaded from an add-in registry. /// </remarks> public ExtensionNodeTypeCollection GetAllowedNodeTypes () { ObjectDescription ob = GetExtendedObject (); ExtensionPoint ep = ob as ExtensionPoint; if (ep != null) return ep.NodeSet.GetAllowedNodeTypes (); ExtensionNodeDescription node = ob as ExtensionNodeDescription; if (node != null) { ExtensionNodeType nt = node.GetNodeType (); if (nt != null) return nt.GetAllowedNodeTypes (); } return new ExtensionNodeTypeCollection (); } ExtensionPoint FindExtensionPoint (AddinDescription desc, string path) { foreach (ExtensionPoint ep in desc.ExtensionPoints) { if (ep.Path == path || path.StartsWith (ep.Path + "/")) return ep; } return null; } internal override void Verify (string location, StringCollection errors) { VerifyNotEmpty (location + "Extension", errors, path, "path"); ExtensionNodes.Verify (location + "Extension (" + path + ")/", errors); foreach (ExtensionNodeDescription cnode in ExtensionNodes) VerifyNode (location, cnode, errors); } void VerifyNode (string location, ExtensionNodeDescription node, StringCollection errors) { string id = node.GetAttribute ("id"); if (id.Length > 0) id = "(" + id + ")"; if (node.NodeName == "Condition" && node.GetAttribute ("id").Length == 0) { errors.Add (location + node.NodeName + id + ": Missing 'id' attribute in Condition element."); } if (node.NodeName == "ComplexCondition") { if (node.ChildNodes.Count > 0) { VerifyConditionNode (location, node.ChildNodes[0], errors); for (int n=1; n<node.ChildNodes.Count; n++) VerifyNode (location + node.NodeName + id + "/", node.ChildNodes[n], errors); } else errors.Add (location + "ComplexCondition: Missing child condition in ComplexCondition element."); } foreach (ExtensionNodeDescription cnode in node.ChildNodes) VerifyNode (location + node.NodeName + id + "/", cnode, errors); } void VerifyConditionNode (string location, ExtensionNodeDescription node, StringCollection errors) { string nodeName = node.NodeName; if (nodeName != "Or" && nodeName != "And" && nodeName != "Not" && nodeName != "Condition") { errors.Add (location + "ComplexCondition: Invalid condition element: " + nodeName); return; } foreach (ExtensionNodeDescription cnode in node.ChildNodes) VerifyConditionNode (location, cnode, errors); } /// <summary> /// Initializes a new instance of the <see cref="Mono.Addins.Description.Extension"/> class. /// </summary> /// <param name='element'> /// XML that describes the extension. /// </param> public Extension (XmlElement element) { Element = element; path = element.GetAttribute ("path"); } /// <summary> /// Gets or sets the path that identifies the extension point being extended. /// </summary> /// <value> /// The path. /// </value> public string Path { get { return path; } set { path = value; } } internal override void SaveXml (XmlElement parent) { if (Element == null) { Element = parent.OwnerDocument.CreateElement ("Extension"); parent.AppendChild (Element); } Element.SetAttribute ("path", path); if (nodes != null) nodes.SaveXml (Element); } /// <summary> /// Gets the extension nodes. /// </summary> /// <value> /// The extension nodes. /// </value> public ExtensionNodeDescriptionCollection ExtensionNodes { get { if (nodes == null) { nodes = new ExtensionNodeDescriptionCollection (this); if (Element != null) { foreach (XmlNode node in Element.ChildNodes) { XmlElement e = node as XmlElement; if (e != null) nodes.Add (new ExtensionNodeDescription (e)); } } } return nodes; } } int IComparable.CompareTo (object obj) { Extension other = (Extension) obj; return Path.CompareTo (other.Path); } internal override void Write (BinaryXmlWriter writer) { writer.WriteValue ("path", path); writer.WriteValue ("Nodes", ExtensionNodes); } internal override void Read (BinaryXmlReader reader) { path = reader.ReadStringValue ("path"); nodes = (ExtensionNodeDescriptionCollection) reader.ReadValue ("Nodes", new ExtensionNodeDescriptionCollection (this)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Description { using System.Collections.Generic; using System.Runtime; using System.ServiceModel.Dispatcher; using Microsoft.Xml; using WsdlNS = System.Web.Services.Description; internal static class SoapHelper { private static object s_soapVersionStateKey = new object(); private static XmlDocument s_xmlDocument; private static XmlDocument Document { get { if (s_xmlDocument == null) s_xmlDocument = new XmlDocument(); return s_xmlDocument; } } private static XmlAttribute CreateLocalAttribute(string name, string value) { XmlAttribute attribute = Document.CreateAttribute(name); attribute.Value = value; return attribute; } // ----------------------------------------------------------------------------------------------------------------------- // Developers Note: We go through a little song an dance here to Get or Create an exsisting SoapBinding from the WSDL // Extensions for a number of reasons: // 1. Multiple Extensions may contribute to the settings in the soap binding and so to make this work without // relying on ordering, we need the GetOrCreate method. // 2. There are diffrent classes for diffrent SOAP versions and the extensions that determines the version is // also un-ordered so when we finally figure out the version we may need to recreate the BindingExtension and // clone it. internal static WsdlNS.SoapAddressBinding GetOrCreateSoapAddressBinding(WsdlNS.Binding wsdlBinding, WsdlNS.Port wsdlPort, WsdlExporter exporter) { if (GetSoapVersionState(wsdlBinding, exporter) == EnvelopeVersion.None) return null; WsdlNS.SoapAddressBinding existingSoapAddressBinding = GetSoapAddressBinding(wsdlPort); EnvelopeVersion version = GetSoapVersion(wsdlBinding); if (existingSoapAddressBinding != null) return existingSoapAddressBinding; WsdlNS.SoapAddressBinding soapAddressBinding = CreateSoapAddressBinding(version, wsdlPort); return soapAddressBinding; } internal static WsdlNS.SoapBinding GetOrCreateSoapBinding(WsdlEndpointConversionContext endpointContext, WsdlExporter exporter) { if (GetSoapVersionState(endpointContext.WsdlBinding, exporter) == EnvelopeVersion.None) return null; WsdlNS.SoapBinding existingSoapBinding = GetSoapBinding(endpointContext); if (existingSoapBinding != null) { return existingSoapBinding; } EnvelopeVersion version = GetSoapVersion(endpointContext.WsdlBinding); WsdlNS.SoapBinding soapBinding = CreateSoapBinding(version, endpointContext.WsdlBinding); return soapBinding; } internal static WsdlNS.SoapOperationBinding GetOrCreateSoapOperationBinding(WsdlEndpointConversionContext endpointContext, OperationDescription operation, WsdlExporter exporter) { if (GetSoapVersionState(endpointContext.WsdlBinding, exporter) == EnvelopeVersion.None) return null; WsdlNS.SoapOperationBinding existingSoapOperationBinding = GetSoapOperationBinding(endpointContext, operation); WsdlNS.OperationBinding wsdlOperationBinding = endpointContext.GetOperationBinding(operation); EnvelopeVersion version = GetSoapVersion(endpointContext.WsdlBinding); if (existingSoapOperationBinding != null) return existingSoapOperationBinding; WsdlNS.SoapOperationBinding soapOperationBinding = CreateSoapOperationBinding(version, wsdlOperationBinding); return soapOperationBinding; } internal static WsdlNS.SoapBodyBinding GetOrCreateSoapBodyBinding(WsdlEndpointConversionContext endpointContext, WsdlNS.MessageBinding wsdlMessageBinding, WsdlExporter exporter) { if (GetSoapVersionState(endpointContext.WsdlBinding, exporter) == EnvelopeVersion.None) return null; WsdlNS.SoapBodyBinding existingSoapBodyBinding = GetSoapBodyBinding(endpointContext, wsdlMessageBinding); EnvelopeVersion version = GetSoapVersion(endpointContext.WsdlBinding); if (existingSoapBodyBinding != null) return existingSoapBodyBinding; WsdlNS.SoapBodyBinding soapBodyBinding = CreateSoapBodyBinding(version, wsdlMessageBinding); return soapBodyBinding; } internal static WsdlNS.SoapHeaderBinding CreateSoapHeaderBinding(WsdlEndpointConversionContext endpointContext, WsdlNS.MessageBinding wsdlMessageBinding) { EnvelopeVersion version = GetSoapVersion(endpointContext.WsdlBinding); WsdlNS.SoapHeaderBinding soapHeaderBinding = CreateSoapHeaderBinding(version, wsdlMessageBinding); return soapHeaderBinding; } internal static void CreateSoapFaultBinding(string name, WsdlEndpointConversionContext endpointContext, WsdlNS.FaultBinding wsdlFaultBinding, bool isEncoded) { EnvelopeVersion version = GetSoapVersion(endpointContext.WsdlBinding); XmlElement fault = CreateSoapFaultBinding(version); fault.Attributes.Append(CreateLocalAttribute("name", name)); fault.Attributes.Append(CreateLocalAttribute("use", isEncoded ? "encoded" : "literal")); wsdlFaultBinding.Extensions.Add(fault); } internal static void SetSoapVersion(WsdlEndpointConversionContext endpointContext, WsdlExporter exporter, EnvelopeVersion version) { SetSoapVersionState(endpointContext.WsdlBinding, exporter, version); //Convert all SOAP extensions to the right version. if (endpointContext.WsdlPort != null) SoapConverter.ConvertExtensions(endpointContext.WsdlPort.Extensions, version, SoapConverter.ConvertSoapAddressBinding); SoapConverter.ConvertExtensions(endpointContext.WsdlBinding.Extensions, version, SoapConverter.ConvertSoapBinding); foreach (WsdlNS.OperationBinding operationBinding in endpointContext.WsdlBinding.Operations) { SoapConverter.ConvertExtensions(operationBinding.Extensions, version, SoapConverter.ConvertSoapOperationBinding); //Messages { if (operationBinding.Input != null) SoapConverter.ConvertExtensions(operationBinding.Input.Extensions, version, SoapConverter.ConvertSoapMessageBinding); if (operationBinding.Output != null) SoapConverter.ConvertExtensions(operationBinding.Output.Extensions, version, SoapConverter.ConvertSoapMessageBinding); foreach (WsdlNS.MessageBinding faultBinding in operationBinding.Faults) SoapConverter.ConvertExtensions(faultBinding.Extensions, version, SoapConverter.ConvertSoapMessageBinding); } } } internal static EnvelopeVersion GetSoapVersion(WsdlNS.Binding wsdlBinding) { foreach (object o in wsdlBinding.Extensions) { if (o is WsdlNS.SoapBinding) return o is WsdlNS.Soap12Binding ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11; } return EnvelopeVersion.Soap12; } private static void SetSoapVersionState(WsdlNS.Binding wsdlBinding, WsdlExporter exporter, EnvelopeVersion version) { object versions = null; if (!exporter.State.TryGetValue(s_soapVersionStateKey, out versions)) { versions = new Dictionary<WsdlNS.Binding, EnvelopeVersion>(); exporter.State[s_soapVersionStateKey] = versions; } ((Dictionary<WsdlNS.Binding, EnvelopeVersion>)versions)[wsdlBinding] = version; } private static EnvelopeVersion GetSoapVersionState(WsdlNS.Binding wsdlBinding, WsdlExporter exporter) { object versions = null; if (exporter.State.TryGetValue(s_soapVersionStateKey, out versions)) { if (versions != null && ((Dictionary<WsdlNS.Binding, EnvelopeVersion>)versions).ContainsKey(wsdlBinding)) { return ((Dictionary<WsdlNS.Binding, EnvelopeVersion>)versions)[wsdlBinding]; } } return null; } private static class SoapConverter { // hsomu, this could be simplified if we used generics. internal static void ConvertExtensions(WsdlNS.ServiceDescriptionFormatExtensionCollection extensions, EnvelopeVersion version, ConvertExtension conversionMethod) { bool foundOne = false; for (int i = extensions.Count - 1; i >= 0; i--) { object o = extensions[i]; if (conversionMethod(ref o, version)) { if (o == null) extensions.Remove(extensions[i]); else extensions[i] = o; foundOne = true; } } if (!foundOne) { object o = null; conversionMethod(ref o, version); if (o != null) extensions.Add(o); } } // This is the delegate implemented by the 4 methods below. It is expected to: // If given a null reference for src, a new instance of the extension can be set. internal delegate bool ConvertExtension(ref object src, EnvelopeVersion version); internal static bool ConvertSoapBinding(ref object src, EnvelopeVersion version) { WsdlNS.SoapBinding binding = src as WsdlNS.SoapBinding; if (src != null) { if (binding == null) return false; // not a soap object else if (GetBindingVersion<WsdlNS.Soap12Binding>(src) == version) return true; // matched but same version; no change } if (version == EnvelopeVersion.None) { src = null; return true; } WsdlNS.SoapBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12Binding() : new WsdlNS.SoapBinding(); if (binding != null) { dest.Required = binding.Required; dest.Style = binding.Style; dest.Transport = binding.Transport; } src = dest; return true; } internal static bool ConvertSoapAddressBinding(ref object src, EnvelopeVersion version) { WsdlNS.SoapAddressBinding binding = src as WsdlNS.SoapAddressBinding; if (src != null) { if (binding == null) return false; // no match else if (GetBindingVersion<WsdlNS.Soap12AddressBinding>(src) == version) return true; // matched but same version; no change } if (version == EnvelopeVersion.None) { src = null; return true; } WsdlNS.SoapAddressBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12AddressBinding() : new WsdlNS.SoapAddressBinding(); if (binding != null) { dest.Required = binding.Required; dest.Location = binding.Location; } src = dest; return true; } // returns true if src is an expected type; updates src in place; should handle null internal static bool ConvertSoapOperationBinding(ref object src, EnvelopeVersion version) { WsdlNS.SoapOperationBinding binding = src as WsdlNS.SoapOperationBinding; if (src != null) { if (binding == null) return false; // no match else if (GetBindingVersion<WsdlNS.Soap12OperationBinding>(src) == version) return true; // matched but same version } if (version == EnvelopeVersion.None) { src = null; return true; } WsdlNS.SoapOperationBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12OperationBinding() : new WsdlNS.SoapOperationBinding(); if (src != null) { dest.Required = binding.Required; dest.Style = binding.Style; dest.SoapAction = binding.SoapAction; } src = dest; return true; } internal static bool ConvertSoapMessageBinding(ref object src, EnvelopeVersion version) { WsdlNS.SoapBodyBinding body = src as WsdlNS.SoapBodyBinding; if (body != null) { src = ConvertSoapBodyBinding(body, version); return true; } WsdlNS.SoapHeaderBinding header = src as WsdlNS.SoapHeaderBinding; if (header != null) { src = ConvertSoapHeaderBinding(header, version); return true; } WsdlNS.SoapFaultBinding fault = src as WsdlNS.SoapFaultBinding; if (fault != null) { src = ConvertSoapFaultBinding(fault, version); return true; } XmlElement element = src as XmlElement; if (element != null) { if (IsSoapFaultBinding(element)) { src = ConvertSoapFaultBinding(element, version); return true; } } return src == null; // "match" only if nothing passed in } private static WsdlNS.SoapBodyBinding ConvertSoapBodyBinding(WsdlNS.SoapBodyBinding src, EnvelopeVersion version) { if (version == EnvelopeVersion.None) return null; EnvelopeVersion srcVersion = GetBindingVersion<WsdlNS.Soap12BodyBinding>(src); if (srcVersion == version) return src; WsdlNS.SoapBodyBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12BodyBinding() : new WsdlNS.SoapBodyBinding(); if (src != null) { if (XmlSerializerOperationFormatter.GetEncoding(srcVersion) == src.Encoding) dest.Encoding = XmlSerializerOperationFormatter.GetEncoding(version); dest.Encoding = XmlSerializerOperationFormatter.GetEncoding(version); dest.Namespace = src.Namespace; dest.Parts = src.Parts; dest.PartsString = src.PartsString; dest.Use = src.Use; dest.Required = src.Required; } return dest; } private static XmlElement ConvertSoapFaultBinding(XmlElement src, EnvelopeVersion version) { if (src == null) return null; if (version == EnvelopeVersion.Soap12) { if (src.NamespaceURI == WsdlNS.Soap12Binding.Namespace) return src; } else if (version == EnvelopeVersion.Soap11) { if (src.NamespaceURI == WsdlNS.SoapBinding.Namespace) return src; } else { return null; } XmlElement dest = CreateSoapFaultBinding(version); if (src.HasAttributes) { foreach (XmlAttribute attribute in src.Attributes) { dest.SetAttribute(attribute.Name, attribute.Value); } } return dest; } private static WsdlNS.SoapFaultBinding ConvertSoapFaultBinding(WsdlNS.SoapFaultBinding src, EnvelopeVersion version) { if (version == EnvelopeVersion.None) return null; if (GetBindingVersion<WsdlNS.Soap12FaultBinding>(src) == version) return src; WsdlNS.SoapFaultBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12FaultBinding() : new WsdlNS.SoapFaultBinding(); if (src != null) { dest.Encoding = src.Encoding; dest.Name = src.Name; dest.Namespace = src.Namespace; dest.Use = src.Use; dest.Required = src.Required; } return dest; } private static WsdlNS.SoapHeaderBinding ConvertSoapHeaderBinding(WsdlNS.SoapHeaderBinding src, EnvelopeVersion version) { if (version == EnvelopeVersion.None) return null; if (GetBindingVersion<WsdlNS.Soap12HeaderBinding>(src) == version) return src; WsdlNS.SoapHeaderBinding dest = version == EnvelopeVersion.Soap12 ? new WsdlNS.Soap12HeaderBinding() : new WsdlNS.SoapHeaderBinding(); if (src != null) { dest.Fault = src.Fault; dest.MapToProperty = src.MapToProperty; dest.Message = src.Message; dest.Part = src.Part; dest.Encoding = src.Encoding; dest.Namespace = src.Namespace; dest.Use = src.Use; dest.Required = src.Required; } return dest; } internal static EnvelopeVersion GetBindingVersion<T12>(object src) { return src is T12 ? EnvelopeVersion.Soap12 : EnvelopeVersion.Soap11; } } private static WsdlNS.SoapAddressBinding CreateSoapAddressBinding(EnvelopeVersion version, WsdlNS.Port wsdlPort) { WsdlNS.SoapAddressBinding soapAddressBinding = null; if (version == EnvelopeVersion.Soap12) { soapAddressBinding = new WsdlNS.Soap12AddressBinding(); } else if (version == EnvelopeVersion.Soap11) { soapAddressBinding = new WsdlNS.SoapAddressBinding(); } Fx.Assert(soapAddressBinding != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class"); wsdlPort.Extensions.Add(soapAddressBinding); return soapAddressBinding; } // REVIEW, alexdej: it's confusing that these methods add the binding to the target object. i'd prefer it if the caller did the adding or if you called them AddFoo private static WsdlNS.SoapBinding CreateSoapBinding(EnvelopeVersion version, WsdlNS.Binding wsdlBinding) { WsdlNS.SoapBinding soapBinding = null; if (version == EnvelopeVersion.Soap12) { soapBinding = new WsdlNS.Soap12Binding(); } else if (version == EnvelopeVersion.Soap11) { soapBinding = new WsdlNS.SoapBinding(); } Fx.Assert(soapBinding != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class"); wsdlBinding.Extensions.Add(soapBinding); return soapBinding; } private static WsdlNS.SoapOperationBinding CreateSoapOperationBinding(EnvelopeVersion version, WsdlNS.OperationBinding wsdlOperationBinding) { WsdlNS.SoapOperationBinding soapOperationBinding = null; if (version == EnvelopeVersion.Soap12) { soapOperationBinding = new WsdlNS.Soap12OperationBinding(); } else if (version == EnvelopeVersion.Soap11) { soapOperationBinding = new WsdlNS.SoapOperationBinding(); } Fx.Assert(soapOperationBinding != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class"); wsdlOperationBinding.Extensions.Add(soapOperationBinding); return soapOperationBinding; } private static WsdlNS.SoapBodyBinding CreateSoapBodyBinding(EnvelopeVersion version, WsdlNS.MessageBinding wsdlMessageBinding) { WsdlNS.SoapBodyBinding soapBodyBinding = null; if (version == EnvelopeVersion.Soap12) { soapBodyBinding = new WsdlNS.Soap12BodyBinding(); } else if (version == EnvelopeVersion.Soap11) { soapBodyBinding = new WsdlNS.SoapBodyBinding(); } Fx.Assert(soapBodyBinding != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class"); wsdlMessageBinding.Extensions.Add(soapBodyBinding); return soapBodyBinding; } private static WsdlNS.SoapHeaderBinding CreateSoapHeaderBinding(EnvelopeVersion version, WsdlNS.MessageBinding wsdlMessageBinding) { WsdlNS.SoapHeaderBinding soapHeaderBinding = null; if (version == EnvelopeVersion.Soap12) { soapHeaderBinding = new WsdlNS.Soap12HeaderBinding(); } else if (version == EnvelopeVersion.Soap11) { soapHeaderBinding = new WsdlNS.SoapHeaderBinding(); } Fx.Assert(soapHeaderBinding != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class"); wsdlMessageBinding.Extensions.Add(soapHeaderBinding); return soapHeaderBinding; } private static XmlElement CreateSoapFaultBinding(EnvelopeVersion version) { string prefix = null; string ns = null; if (version == EnvelopeVersion.Soap12) { ns = WsdlNS.Soap12Binding.Namespace; prefix = "soap12"; } else if (version == EnvelopeVersion.Soap11) { ns = WsdlNS.SoapBinding.Namespace; prefix = "soap"; } Fx.Assert(ns != null, "EnvelopeVersion is not recognized. Please update the SoapHelper class"); return Document.CreateElement(prefix, "fault", ns); } internal static WsdlNS.SoapAddressBinding GetSoapAddressBinding(WsdlNS.Port wsdlPort) { foreach (object o in wsdlPort.Extensions) { if (o is WsdlNS.SoapAddressBinding) return (WsdlNS.SoapAddressBinding)o; } return null; } private static WsdlNS.SoapBinding GetSoapBinding(WsdlEndpointConversionContext endpointContext) { foreach (object o in endpointContext.WsdlBinding.Extensions) { if (o is WsdlNS.SoapBinding) return (WsdlNS.SoapBinding)o; } return null; } private static WsdlNS.SoapOperationBinding GetSoapOperationBinding(WsdlEndpointConversionContext endpointContext, OperationDescription operation) { WsdlNS.OperationBinding wsdlOperationBinding = endpointContext.GetOperationBinding(operation); foreach (object o in wsdlOperationBinding.Extensions) { if (o is WsdlNS.SoapOperationBinding) return (WsdlNS.SoapOperationBinding)o; } return null; } private static WsdlNS.SoapBodyBinding GetSoapBodyBinding(WsdlEndpointConversionContext endpointContext, WsdlNS.MessageBinding wsdlMessageBinding) { foreach (object o in wsdlMessageBinding.Extensions) { if (o is WsdlNS.SoapBodyBinding) return (WsdlNS.SoapBodyBinding)o; } return null; } internal static string ReadSoapAction(WsdlNS.OperationBinding wsdlOperationBinding) { WsdlNS.SoapOperationBinding soapOperationBinding = (WsdlNS.SoapOperationBinding)wsdlOperationBinding.Extensions.Find(typeof(WsdlNS.SoapOperationBinding)); return soapOperationBinding != null ? soapOperationBinding.SoapAction : null; } internal static WsdlNS.SoapBindingStyle GetStyle(WsdlNS.Binding binding) { WsdlNS.SoapBindingStyle style = WsdlNS.SoapBindingStyle.Default; if (binding != null) { WsdlNS.SoapBinding soapBinding = binding.Extensions.Find(typeof(WsdlNS.SoapBinding)) as WsdlNS.SoapBinding; if (soapBinding != null) style = soapBinding.Style; } return style; } internal static WsdlNS.SoapBindingStyle GetStyle(WsdlNS.OperationBinding operationBinding, WsdlNS.SoapBindingStyle defaultBindingStyle) { WsdlNS.SoapBindingStyle style = defaultBindingStyle; if (operationBinding != null) { WsdlNS.SoapOperationBinding soapOperationBinding = operationBinding.Extensions.Find(typeof(WsdlNS.SoapOperationBinding)) as WsdlNS.SoapOperationBinding; if (soapOperationBinding != null) { if (soapOperationBinding.Style != WsdlNS.SoapBindingStyle.Default) style = soapOperationBinding.Style; } } return style; } internal static bool IsSoapFaultBinding(XmlElement element) { return (element != null && element.LocalName == "fault" && (element.NamespaceURI == WsdlNS.Soap12Binding.Namespace || element.NamespaceURI == WsdlNS.SoapBinding.Namespace)); } internal static bool IsEncoded(XmlElement element) { Fx.Assert(element != null, ""); XmlAttribute attribute = element.GetAttributeNode("use"); if (attribute == null) return false; return attribute.Value == "encoded"; } } }
using System; using System.IO; using System.Collections.Generic; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; using Discord; namespace KiteBot { public class KiteChat { public static Random RandomSeed; public static int RaeCounter; public static bool StartMarkovChain; private static string[] _greetings; private static string[] _mealResponses; private static string[] _bekGreetings; public static LivestreamChecker StreamChecker; public static GiantBombVideoChecker GbVideoChecker; public static MultiTextMarkovChainHelper MultiDeepMarkovChains; public static string ChatDirectory = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent?.Parent?.FullName; public static string GreetingFileLocation = ChatDirectory + "/Content/Greetings.txt"; public static string MealFileLocation = ChatDirectory + "/Content/Meals.txt"; public KiteChat(bool markovbool, string gBapi, int streamRefresh, int videoRefresh, int depth) : this(markovbool, depth,gBapi, streamRefresh, videoRefresh, File.ReadAllLines(GreetingFileLocation), File.ReadAllLines(MealFileLocation), new Random()) { } public KiteChat(bool markovbool, int depth, string gBapi,int streamRefresh, int videoRefresh, string[] arrayOfGreetings, string[] arrayOfMeals, Random randomSeed) { StartMarkovChain = markovbool; _greetings = arrayOfGreetings; _mealResponses = arrayOfMeals; RandomSeed = randomSeed; RaeCounter = 0; StreamChecker = new LivestreamChecker(gBapi, streamRefresh); GbVideoChecker = new GiantBombVideoChecker(gBapi, videoRefresh); MultiDeepMarkovChains = new MultiTextMarkovChainHelper(depth); } public async Task<bool> InitializeMarkovChain() { var bek = LoadBekGreetings(); if (StartMarkovChain) {await MultiDeepMarkovChains.Initialize();} return await bek; } public async Task AsyncParseChat(IMessage msg, IDiscordClient client) { Console.WriteLine("(" + msg.Author.Username + "/" + msg.Author.Id + ") - " + msg.Content); IsRaeTyping(msg); //add all messages to the Markov Chain list if (msg.Author.Id != client.CurrentUser.Id) { MultiDeepMarkovChains.Feed(msg); if (msg.Content.Contains("Mistake") && msg.Channel.Id == 96786127238725632) { await msg.Channel.SendMessageAsync("Anime is a mistake " + msg.Author.Mention +"."); } else if (msg.Content.Contains("GetDunked")) { await msg.Channel.SendMessageAsync("http://i.imgur.com/QhcNUWo.gif"); } else if (msg.Content.Contains(@"/saveJSON") && msg.Author.Id == 85817630560108544 && StartMarkovChain) { await MultiDeepMarkovChains.Save(); await msg.Channel.SendMessageAsync("Done."); } else if (msg.Content.Contains(@"/saveExit") && msg.Author.Id == 85817630560108544 && StartMarkovChain) { await MultiDeepMarkovChains.Save(); await msg.Channel.SendMessageAsync("Done."); Environment.Exit(1); } else if (msg.Content.Contains(@"/restart") && msg.Author.Id == 85817630560108544) { StreamChecker.Restart(); GbVideoChecker.Restart(); } else if ((msg.Content.Contains(@"/testMarkov") || msg.Content.StartsWith(@"@KiteBot /tm")) && StartMarkovChain) { try { await msg.Channel.SendMessageAsync(MultiDeepMarkovChains.GetSequence()); } catch (Exception) { await MultiDeepMarkovChains.Save(); throw; } finally { if (msg.Author.Id == 85817630560108544) { var userMessage = (IUserMessage) msg; await userMessage.DeleteAsync(); } } } else if (msg.Content.Contains(@"@KiteBot")) { if (msg.Content.StartsWith("@KiteBot #420") || msg.Content.ToLower().StartsWith("@KiteBot #blaze") || msg.Content.ToLower().Contains("waifu")) { await msg.Channel.SendMessageAsync("http://420.moe/"); } else if (msg.Content.ToLower().Contains("help")) { var nl = Environment.NewLine; await msg.Channel.SendMessageAsync("Current Commands are:" + nl + "#420"+ nl + "randomql" + nl + "google" + nl + "youtube" + nl + "/anime" + nl + "/manga" + nl + "!reminder" + nl + "/pizza" + nl + "Whats for dinner" + nl + "sandwich" + nl + "RaeCounter" + nl + "help"); } else if (msg.Content.ToLower().Contains("randomql")) { await msg.Channel.SendMessageAsync(GetResponseUriFromRandomQlCrew()); } else if (msg.Content.ToLower().Contains("raecounter")) { await msg.Channel.SendMessageAsync(@"Rae has ghost-typed " + RaeCounter); } else if (msg.Content.ToLower().Contains("google")) { await msg.Channel.SendMessageAsync("http://lmgtfy.com/?q=" + msg.Content.ToLower().Substring(16).Replace(' ', '+')); } else if (msg.Content.ToLower().Contains("fuck you") || msg.Content.ToLower().Contains("fuckyou")) { List<string> possibleResponses = new List<string> { "Hey fuck you too USER!", "I bet you'd like that wouldn't you USER?", "No, fuck you USER!", "Fuck you too USER!" }; await msg.Channel.SendMessageAsync( possibleResponses[RandomSeed.Next(0, possibleResponses.Count)].Replace("USER", msg.Author.Username)); } else if (msg.Content.ToLower().Contains("hi") || msg.Content.ToLower().Contains("hey") || msg.Content.ToLower().Contains("hello")) { await msg.Channel.SendMessageAsync(ParseGreeting(msg.Author.Username)); } else if (0 <= msg.Content.ToLower().IndexOf("/meal", 0, StringComparison.Ordinal) || msg.Content.ToLower().Contains("dinner") || msg.Content.ToLower().Contains("lunch")) { await msg.Channel.SendMessageAsync( _mealResponses[RandomSeed.Next(0, _mealResponses.Length)].Replace("USER", msg.Author.Username)); } else { await msg.Channel.SendMessageAsync("KiteBot ver. 2.0.3 \"Now with less...\""); } } } } public static string GetResponseUriFromRandomQlCrew() { string url = "http://qlcrew.com/main.php?anyone=anyone&inc%5B0%5D=&p=999&exc%5B0%5D=&per_page=15&random"; /*WebClient client = new WebClient(); client.Headers.Add("user-agent", "LassieMEKiteBot/0.9 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); client..OpenRead(url);*/ HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (request != null) { request.UserAgent = "LassieMEKiteBot/0.11 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); return response.ResponseUri.AbsoluteUri; } return "Couldn't load qlcrew's Random Link."; } //returns a greeting from the greetings.txt list on a per user or generic basis private string ParseGreeting(string userName) { if (userName.Equals("Bekenel") || userName.Equals("Pete")) { return (_bekGreetings[RandomSeed.Next(0, _bekGreetings.Length)]); } List<string> possibleResponses = new List<string>(); for (int i = 0; i < _greetings.Length - 2; i += 2) { if (userName.ToLower().Contains(_greetings[i])) { possibleResponses.Add(_greetings[i + 1]); } } if (possibleResponses.Count == 0) { for (int i = 0; i < _greetings.Length - 2; i += 2) { if (_greetings[i] == "generic") { possibleResponses.Add(_greetings[i + 1]); } } } //return a random response from the context provided, replacing the string "USER" with the appropriate username return (possibleResponses[RandomSeed.Next(0, possibleResponses.Count)].Replace("USER", userName)); } //grabs random greetings for user bekenel from a reddit profile private async Task<bool> LoadBekGreetings() { const string url = "https://www.reddit.com/user/UWotM8_SS"; string htmlCode = null; try { using (WebClient client = new WebClient()) { htmlCode = await client.DownloadStringTaskAsync(url); } } catch (Exception e) { Console.WriteLine("Could not load Bek greetings, server not found: " + e.Message); } finally { var regex1 = new Regex(@"<div class=""md""><p>(?<quote>.+)</p>"); if (htmlCode != null) { var matches = regex1.Matches(htmlCode); var stringArray = new string[matches.Count]; var i = 0; foreach (Match match in matches) { var s = match.Groups["quote"].Value.Replace("&#39;", "'").Replace("&quot;", "\""); stringArray[i] = s; i++; } _bekGreetings = stringArray; } } return true; } public void IsRaeTyping(IMessage msg) { if (msg.Author.Id == 85876755797139456) { RaeCounter += -1; } } public void IsRaeTyping(IUser user) { if (user.Id == 85876755797139456) { RaeCounter += 1; } } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] partial class AllReadyContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<int?>("EventId"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<int?>("OrganizationId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<int?>("OrganizationId"); b.Property<string>("PasswordHash"); b.Property<string>("PendingNewEmail"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<string>("TimeZoneId") .IsRequired(); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ExternalUrl"); b.Property<string>("ExternalUrlText"); b.Property<bool>("Featured"); b.Property<string>("FullDescription"); b.Property<string>("Headline") .HasAnnotation("MaxLength", 150); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<bool>("Locked"); b.Property<int>("ManagingOrganizationId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("OrganizationId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ClosestLocation", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<double>("Distance"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<int>("EventType"); b.Property<string>("Headline") .HasAnnotation("MaxLength", 150); b.Property<string>("ImageUrl"); b.Property<bool>("IsAllowWaitList"); b.Property<bool>("IsLimitVolunteers"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<int?>("EventId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.Property<int>("EventId"); b.Property<int>("SkillId"); b.HasKey("EventId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("Date"); b.Property<int>("EventId"); b.Property<string>("Name"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.Property<int>("ItineraryId"); b.Property<Guid>("RequestId"); b.Property<DateTime>("DateAssigned"); b.Property<int>("OrderIndex"); b.HasKey("ItineraryId", "RequestId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("DescriptionHtml"); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("PrivacyPolicy"); b.Property<string>("PrivacyPolicyUrl"); b.Property<string>("Summary") .HasAnnotation("MaxLength", 250); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.Property<int>("OrganizationId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("OrganizationId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeoCoordinate", b => { b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.HasKey("Latitude", "Longitude"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.Property<Guid>("RequestId") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<string>("City"); b.Property<DateTime>("DateAdded"); b.Property<string>("Email"); b.Property<int?>("EventId"); b.Property<double>("Latitude"); b.Property<double>("Longitude"); b.Property<string>("Name"); b.Property<string>("Phone"); b.Property<string>("ProviderData"); b.Property<string>("ProviderId"); b.Property<string>("State"); b.Property<int>("Status"); b.Property<string>("Zip"); b.HasKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AdditionalInfo"); b.Property<int?>("ItineraryId"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("ManagingOrganizationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Event", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.EventSignup", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.EventSkill", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.Itinerary", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.ItineraryRequest", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.Request") .WithMany() .HasForeignKey("RequestId"); }); modelBuilder.Entity("AllReady.Models.Organization", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.OrganizationContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OrganizationId"); }); modelBuilder.Entity("AllReady.Models.Request", b => { b.HasOne("AllReady.Models.Event") .WithMany() .HasForeignKey("EventId"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Organization") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.Itinerary") .WithMany() .HasForeignKey("ItineraryId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { /// <summary> /// The controller for navigation bars. /// </summary> /// <remarks> /// The threading model for this class is simple: all non-static members are affinitized to the /// UI thread. /// </remarks> internal partial class NavigationBarController : ForegroundThreadAffinitizedObject, INavigationBarController { private readonly INavigationBarPresenter _presenter; private readonly ITextBuffer _subjectBuffer; private readonly IWaitIndicator _waitIndicator; private readonly IAsynchronousOperationListener _asyncListener; private readonly WorkspaceRegistration _workspaceRegistration; /// <summary> /// If we have pushed a full list to the presenter in response to a focus event, this /// contains the version stamp of the list that was pushed. It is null if the last thing /// pushed to the list was due to a caret move or file change. /// </summary> private VersionStamp? _versionStampOfFullListPushedToPresenter = null; private bool _disconnected = false; private Workspace _workspace; public NavigationBarController( INavigationBarPresenter presenter, ITextBuffer subjectBuffer, IWaitIndicator waitIndicator, IAsynchronousOperationListener asyncListener) { _presenter = presenter; _subjectBuffer = subjectBuffer; _waitIndicator = waitIndicator; _asyncListener = asyncListener; _workspaceRegistration = Workspace.GetWorkspaceRegistration(subjectBuffer.AsTextContainer()); _workspaceRegistration.WorkspaceChanged += OnWorkspaceRegistrationChanged; presenter.CaretMoved += OnCaretMoved; presenter.ViewFocused += OnViewFocused; presenter.DropDownFocused += OnDropDownFocused; presenter.ItemSelected += OnItemSelected; subjectBuffer.PostChanged += OnSubjectBufferPostChanged; // Initialize the tasks to be an empty model so we never have to deal with a null case. _modelTask = Task.FromResult( new NavigationBarModel( SpecializedCollections.EmptyList<NavigationBarItem>(), default(VersionStamp), null)); _selectedItemInfoTask = Task.FromResult(new NavigationBarSelectedTypeAndMember(null, null)); if (_workspaceRegistration.Workspace != null) { ConnectToWorkspace(_workspaceRegistration.Workspace); } } private void OnWorkspaceRegistrationChanged(object sender, EventArgs e) { DisconnectFromWorkspace(); var newWorkspace = _workspaceRegistration.Workspace; if (newWorkspace != null) { ConnectToWorkspace(newWorkspace); } } private void ConnectToWorkspace(Workspace workspace) { AssertIsForeground(); // If we disconnected before the workspace ever connected, just disregard if (_disconnected) { return; } _workspace = workspace; _workspace.WorkspaceChanged += this.OnWorkspaceChanged; // For the first time you open the file, we'll start immediately StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true); } private void DisconnectFromWorkspace() { if (_workspace != null) { _workspace.WorkspaceChanged -= this.OnWorkspaceChanged; _workspace = null; } } public void Disconnect() { AssertIsForeground(); DisconnectFromWorkspace(); _subjectBuffer.PostChanged -= OnSubjectBufferPostChanged; _presenter.CaretMoved -= OnCaretMoved; _presenter.ViewFocused -= OnViewFocused; _presenter.DropDownFocused -= OnDropDownFocused; _presenter.ItemSelected -= OnItemSelected; _presenter.Disconnect(); _workspaceRegistration.WorkspaceChanged -= OnWorkspaceRegistrationChanged; _disconnected = true; // Cancel off any remaining background work _modelTaskCancellationSource.Cancel(); _selectedItemInfoTaskCancellationSource.Cancel(); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { // We're getting an event for a workspace we already disconnected from if (args.NewSolution.Workspace != _workspace) { return; } // If the displayed project is being renamed, retrigger the update if (args.Kind == WorkspaceChangeKind.ProjectChanged && args.ProjectId != null) { var oldProject = args.OldSolution.GetProject(args.ProjectId); var newProject = args.NewSolution.GetProject(args.ProjectId); if (oldProject.Name != newProject.Name) { var currentContextDocumentId = _workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer()); if (currentContextDocumentId != null && currentContextDocumentId.ProjectId == args.ProjectId) { StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true); } } } if (args.Kind == WorkspaceChangeKind.DocumentChanged && args.OldSolution == args.NewSolution) { var currentContextDocumentId = _workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer()); if (currentContextDocumentId != null && currentContextDocumentId == args.DocumentId) { // The context has changed, so update everything. StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: true); } } } private void OnSubjectBufferPostChanged(object sender, EventArgs e) { AssertIsForeground(); StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: TaggerConstants.MediumDelay, selectedItemUpdateDelay: 0, updateUIWhenDone: true); } private void OnCaretMoved(object sender, EventArgs e) { AssertIsForeground(); StartSelectedItemUpdateTask(delay: TaggerConstants.NearImmediateDelay, updateUIWhenDone: true); } private void OnViewFocused(object sender, EventArgs e) { AssertIsForeground(); StartSelectedItemUpdateTask(delay: TaggerConstants.ShortDelay, updateUIWhenDone: true); } private void OnDropDownFocused(object sender, EventArgs e) { AssertIsForeground(); // Refresh the drop downs to their full information _waitIndicator.Wait( EditorFeaturesResources.Navigation_Bars, EditorFeaturesResources.Refreshing_navigation_bars, allowCancel: true, action: context => UpdateDropDownsSynchronously(context.CancellationToken)); } private void UpdateDropDownsSynchronously(CancellationToken cancellationToken) { AssertIsForeground(); // If the presenter already has the full list and the model is already complete, then we // don't have to do any further computation nor push anything to the presenter if (PresenterAlreadyHaveUpToDateFullList(cancellationToken)) { return; } // We need to ensure that all the state computation is up to date, so cancel any // previous work and ensure the model is up to date StartModelUpdateAndSelectedItemUpdateTasks(modelUpdateDelay: 0, selectedItemUpdateDelay: 0, updateUIWhenDone: false); // Wait for the work to be complete. We'll wait with our cancellationToken, so if the // user hits cancel we won't block them, but the computation can still continue using (Logger.LogBlock(FunctionId.NavigationBar_UpdateDropDownsSynchronously_WaitForModel, cancellationToken)) { _modelTask.Wait(cancellationToken); } using (Logger.LogBlock(FunctionId.NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo, cancellationToken)) { _selectedItemInfoTask.Wait(cancellationToken); } IList<NavigationBarProjectItem> projectItems; NavigationBarProjectItem selectedProjectItem; GetProjectItems(out projectItems, out selectedProjectItem); _presenter.PresentItems( projectItems, selectedProjectItem, _modelTask.Result.Types, _selectedItemInfoTask.Result.TypeItem, _selectedItemInfoTask.Result.MemberItem); _versionStampOfFullListPushedToPresenter = _modelTask.Result.SemanticVersionStamp; } private void GetProjectItems(out IList<NavigationBarProjectItem> projectItems, out NavigationBarProjectItem selectedProjectItem) { var documents = _subjectBuffer.CurrentSnapshot.GetRelatedDocumentsWithChanges(); if (!documents.Any()) { projectItems = SpecializedCollections.EmptyList<NavigationBarProjectItem>(); selectedProjectItem = null; return; } projectItems = documents.Select(d => new NavigationBarProjectItem( d.Project.Name, d.Project.GetGlyph(), workspace: d.Project.Solution.Workspace, documentId: d.Id, language: d.Project.Language)).OrderBy(projectItem => projectItem.Text).ToList(); projectItems.Do(i => i.InitializeTrackingSpans(_subjectBuffer.CurrentSnapshot)); var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); selectedProjectItem = document != null ? projectItems.FirstOrDefault(p => p.Text == document.Project.Name) ?? projectItems.First() : projectItems.First(); } /// <summary> /// Check if the presenter has already been pushed the full model that corresponds to the /// current buffer's project version stamp. /// </summary> private bool PresenterAlreadyHaveUpToDateFullList(CancellationToken cancellationToken) { AssertIsForeground(); // If it doesn't have a full list pushed, then of course not if (_versionStampOfFullListPushedToPresenter == null) { return false; } var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return false; } return document.Project.GetDependentSemanticVersionAsync(cancellationToken).WaitAndGetResult(cancellationToken) == _versionStampOfFullListPushedToPresenter; } private void PushSelectedItemsToPresenter(NavigationBarSelectedTypeAndMember selectedItems) { AssertIsForeground(); var oldLeft = selectedItems.TypeItem; var oldRight = selectedItems.MemberItem; NavigationBarItem newLeft = null; NavigationBarItem newRight = null; var listOfLeft = new List<NavigationBarItem>(); var listOfRight = new List<NavigationBarItem>(); if (oldRight != null) { newRight = new NavigationBarPresentedItem(oldRight.Text, oldRight.Glyph, oldRight.Spans, oldRight.ChildItems, oldRight.Bolded, oldRight.Grayed || selectedItems.ShowMemberItemGrayed) { TrackingSpans = oldRight.TrackingSpans }; listOfRight.Add(newRight); } if (oldLeft != null) { newLeft = new NavigationBarPresentedItem(oldLeft.Text, oldLeft.Glyph, oldLeft.Spans, listOfRight, oldLeft.Bolded, oldLeft.Grayed || selectedItems.ShowTypeItemGrayed) { TrackingSpans = oldLeft.TrackingSpans }; listOfLeft.Add(newLeft); } IList<NavigationBarProjectItem> projectItems; NavigationBarProjectItem selectedProjectItem; GetProjectItems(out projectItems, out selectedProjectItem); _presenter.PresentItems( projectItems, selectedProjectItem, listOfLeft, newLeft, newRight); _versionStampOfFullListPushedToPresenter = null; } private void OnItemSelected(object sender, NavigationBarItemSelectedEventArgs e) { AssertIsForeground(); _waitIndicator.Wait( EditorFeaturesResources.Navigation_Bars, EditorFeaturesResources.Refreshing_navigation_bars, allowCancel: true, action: context => ProcessItemSelectionSynchronously(e.Item, context.CancellationToken)); } /// <summary> /// Process the selection of an item synchronously inside a wait context. /// </summary> /// <param name="item">The selected item.</param> /// <param name="cancellationToken">A cancellation token from the wait context.</param> private void ProcessItemSelectionSynchronously(NavigationBarItem item, CancellationToken cancellationToken) { AssertIsForeground(); var presentedItem = item as NavigationBarPresentedItem; if (presentedItem != null) { // Presented items are not navigable, but they may be selected due to a race // documented in Bug #1174848. Protect all INavigationBarItemService implementers // from this by ignoring these selections here. return; } var projectItem = item as NavigationBarProjectItem; if (projectItem != null) { projectItem.SwitchToContext(); // TODO: navigate to document / focus text view } else { var document = _subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var languageService = document.Project.LanguageServices.GetService<INavigationBarItemService>(); NavigateToItem(item, document, _subjectBuffer.CurrentSnapshot, languageService, cancellationToken); } } // Now that the edit has been done, refresh to make sure everything is up-to-date. At // this point, we now use CancellationToken.None to ensure we're properly refreshed. UpdateDropDownsSynchronously(CancellationToken.None); } private void NavigateToItem(NavigationBarItem item, Document document, ITextSnapshot snapshot, INavigationBarItemService languageService, CancellationToken cancellationToken) { item.Spans = item.TrackingSpans.Select(ts => ts.GetSpan(snapshot).Span.ToTextSpan()).ToList(); languageService.NavigateToItem(document, item, _presenter.TryGetCurrentView(), cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel { using System; using System.Text; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Net; using System.Net.Security; using System.Runtime.Serialization; using System.Security.Principal; using System.ServiceModel.Channels; using System.ServiceModel.Security; using System.ComponentModel; using Microsoft.Xml; public abstract class WSHttpBindingBase : Binding, IBindingRuntimePreferences { private WSMessageEncoding _messageEncoding; private OptionalReliableSession _reliableSession; // private BindingElements private HttpTransportBindingElement _httpTransport; private HttpsTransportBindingElement _httpsTransport; private TextMessageEncodingBindingElement _textEncoding; private MtomMessageEncodingBindingElement _mtomEncoding; private TransactionFlowBindingElement _txFlow; private ReliableSessionBindingElement _session; protected WSHttpBindingBase() : base() { Initialize(); } protected WSHttpBindingBase(bool reliableSessionEnabled) : this() { this.ReliableSession.Enabled = reliableSessionEnabled; } [DefaultValue(false)] public bool TransactionFlow { get { return _txFlow.Transactions; } set { _txFlow.Transactions = value; } } [DefaultValue(HttpTransportDefaults.HostNameComparisonMode)] public HostNameComparisonMode HostNameComparisonMode { get { return _httpTransport.HostNameComparisonMode; } set { _httpTransport.HostNameComparisonMode = value; _httpsTransport.HostNameComparisonMode = value; } } [DefaultValue(TransportDefaults.MaxBufferPoolSize)] public long MaxBufferPoolSize { get { return _httpTransport.MaxBufferPoolSize; } set { _httpTransport.MaxBufferPoolSize = value; _httpsTransport.MaxBufferPoolSize = value; } } [DefaultValue(TransportDefaults.MaxReceivedMessageSize)] public long MaxReceivedMessageSize { get { return _httpTransport.MaxReceivedMessageSize; } set { if (value > int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("value.MaxReceivedMessageSize", SRServiceModel.MaxReceivedMessageSizeMustBeInIntegerRange)); } _httpTransport.MaxReceivedMessageSize = value; _httpsTransport.MaxReceivedMessageSize = value; _mtomEncoding.MaxBufferSize = (int)value; } } [DefaultValue(WSHttpBindingDefaults.MessageEncoding)] public WSMessageEncoding MessageEncoding { get { return _messageEncoding; } set { _messageEncoding = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _textEncoding.ReaderQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(_textEncoding.ReaderQuotas); value.CopyTo(_mtomEncoding.ReaderQuotas); } } public OptionalReliableSession ReliableSession { get { return _reliableSession; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _reliableSession.CopySettings(value); } } public override string Scheme { get { return GetTransport().Scheme; } } public EnvelopeVersion EnvelopeVersion { get { return EnvelopeVersion.Soap12; } } // TODO: [TypeConverter(typeof(EncodingConverter))] public System.Text.Encoding TextEncoding { get { return _textEncoding.WriteEncoding; } set { _textEncoding.WriteEncoding = value; _mtomEncoding.WriteEncoding = value; } } bool IBindingRuntimePreferences.ReceiveSynchronously { get { return false; } } internal HttpTransportBindingElement HttpTransport { get { return _httpTransport; } } internal HttpsTransportBindingElement HttpsTransport { get { return _httpsTransport; } } internal ReliableSessionBindingElement ReliableSessionBindingElement { get { return _session; } } internal TransactionFlowBindingElement TransactionFlowBindingElement { get { return _txFlow; } } private static TransactionFlowBindingElement GetDefaultTransactionFlowBindingElement() { TransactionFlowBindingElement tfbe = new TransactionFlowBindingElement(false); tfbe.TransactionProtocol = TransactionProtocol.WSAtomicTransactionOctober2004; return tfbe; } private void Initialize() { _httpTransport = new HttpTransportBindingElement(); _httpsTransport = new HttpsTransportBindingElement(); _messageEncoding = WSHttpBindingDefaults.MessageEncoding; _txFlow = GetDefaultTransactionFlowBindingElement(); _session = new ReliableSessionBindingElement(true); _textEncoding = new TextMessageEncodingBindingElement(); _textEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; _mtomEncoding = new MtomMessageEncodingBindingElement(); _mtomEncoding.MessageVersion = MessageVersion.Soap12WSAddressing10; _reliableSession = new OptionalReliableSession(_session); } private void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, TransactionFlowBindingElement txFlow, ReliableSessionBindingElement session) { this.HostNameComparisonMode = transport.HostNameComparisonMode; this.MaxBufferPoolSize = transport.MaxBufferPoolSize; this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize; // this binding only supports Text and Mtom encoding if (encoding is TextMessageEncodingBindingElement) { this.MessageEncoding = WSMessageEncoding.Text; TextMessageEncodingBindingElement text = (TextMessageEncodingBindingElement)encoding; this.TextEncoding = text.WriteEncoding; this.ReaderQuotas = text.ReaderQuotas; } else if (encoding is MtomMessageEncodingBindingElement) { _messageEncoding = WSMessageEncoding.Mtom; MtomMessageEncodingBindingElement mtom = (MtomMessageEncodingBindingElement)encoding; this.TextEncoding = mtom.WriteEncoding; this.ReaderQuotas = mtom.ReaderQuotas; } this.TransactionFlow = txFlow.Transactions; _reliableSession.Enabled = session != null; //session if (session != null) { // only set properties that have standard binding manifestations _session.InactivityTimeout = session.InactivityTimeout; _session.Ordered = session.Ordered; } } // check that properties of the HttpTransportBindingElement and // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding // match default values of the binding elements private bool IsBindingElementsMatch(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, TransactionFlowBindingElement txFlow, ReliableSessionBindingElement session) { if (!this.GetTransport().IsMatch(transport)) return false; if (this.MessageEncoding == WSMessageEncoding.Text) { if (!_textEncoding.IsMatch(encoding)) return false; } else if (this.MessageEncoding == WSMessageEncoding.Mtom) { if (!_mtomEncoding.IsMatch(encoding)) return false; } if (!_txFlow.IsMatch(txFlow)) return false; if (_reliableSession.Enabled) { if (!_session.IsMatch(session)) return false; } else if (session != null) { return false; } return true; } public override BindingElementCollection CreateBindingElements() { // return collection of BindingElements BindingElementCollection bindingElements = new BindingElementCollection(); // order of BindingElements is important // context bindingElements.Add(_txFlow); // reliable if (_reliableSession.Enabled) { bindingElements.Add(_session); } // add security (*optional) SecurityBindingElement wsSecurity = this.CreateMessageSecurity(); if (wsSecurity != null) { bindingElements.Add(wsSecurity); } // add encoding (text or mtom) WSMessageEncodingHelper.SyncUpEncodingBindingElementProperties(_textEncoding, _mtomEncoding); if (this.MessageEncoding == WSMessageEncoding.Text) bindingElements.Add(_textEncoding); else if (this.MessageEncoding == WSMessageEncoding.Mtom) bindingElements.Add(_mtomEncoding); // add transport (http or https) bindingElements.Add(GetTransport()); return bindingElements.Clone(); } internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 6) return false; // collect all binding elements PrivacyNoticeBindingElement privacy = null; TransactionFlowBindingElement txFlow = null; ReliableSessionBindingElement session = null; SecurityBindingElement security = null; MessageEncodingBindingElement encoding = null; HttpTransportBindingElement transport = null; foreach (BindingElement element in elements) { if (element is SecurityBindingElement) security = element as SecurityBindingElement; else if (element is TransportBindingElement) transport = element as HttpTransportBindingElement; else if (element is MessageEncodingBindingElement) encoding = element as MessageEncodingBindingElement; else if (element is TransactionFlowBindingElement) txFlow = element as TransactionFlowBindingElement; else if (element is ReliableSessionBindingElement) session = element as ReliableSessionBindingElement; else if (element is PrivacyNoticeBindingElement) privacy = element as PrivacyNoticeBindingElement; else return false; } if (transport == null) return false; if (encoding == null) return false; if (!transport.AuthenticationScheme.IsSingleton()) { //multiple authentication schemes selected -- not supported in StandardBindings return false; } HttpsTransportBindingElement httpsTransport = transport as HttpsTransportBindingElement; if ((security != null) && (httpsTransport != null) && (httpsTransport.RequireClientCertificate != TransportDefaults.RequireClientCertificate)) { return false; } if (null != privacy || !WSHttpBinding.TryCreate(security, transport, session, txFlow, out binding)) if (!WSFederationHttpBinding.TryCreate(security, transport, privacy, session, txFlow, out binding)) if (!WS2007HttpBinding.TryCreate(security, transport, session, txFlow, out binding)) if (!WS2007FederationHttpBinding.TryCreate(security, transport, privacy, session, txFlow, out binding)) return false; if (txFlow == null) { txFlow = GetDefaultTransactionFlowBindingElement(); if ((binding is WS2007HttpBinding) || (binding is WS2007FederationHttpBinding)) { txFlow.TransactionProtocol = TransactionProtocol.WSAtomicTransaction11; } } WSHttpBindingBase wSHttpBindingBase = binding as WSHttpBindingBase; wSHttpBindingBase.InitializeFrom(transport, encoding, txFlow, session); if (!wSHttpBindingBase.IsBindingElementsMatch(transport, encoding, txFlow, session)) return false; return true; } protected abstract TransportBindingElement GetTransport(); protected abstract SecurityBindingElement CreateMessageSecurity(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using Xunit; namespace System.Tests { public static class Int32Tests { [Fact] public static void Ctor_Empty() { var i = new int(); Assert.Equal(0, i); } [Fact] public static void Ctor_Value() { int i = 41; Assert.Equal(41, i); } [Fact] public static void MaxValue() { Assert.Equal(0x7FFFFFFF, int.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(unchecked((int)0x80000000), int.MinValue); } [Theory] [InlineData(234, 234, 0)] [InlineData(234, int.MinValue, 1)] [InlineData(234, -123, 1)] [InlineData(234, 0, 1)] [InlineData(234, 123, 1)] [InlineData(234, 456, -1)] [InlineData(234, int.MaxValue, -1)] [InlineData(-234, -234, 0)] [InlineData(-234, 234, -1)] [InlineData(-234, -432, 1)] [InlineData(234, null, 1)] public static void CompareTo(int i, object value, int expected) { if (value is int) { Assert.Equal(expected, Math.Sign(i.CompareTo((int)value))); } IComparable comparable = i; Assert.Equal(expected, Math.Sign(comparable.CompareTo(value))); } [Fact] public static void CompareTo_ObjectNotInt_ThrowsArgumentException() { IComparable comparable = 234; Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not an int Assert.Throws<ArgumentException>(null, () => comparable.CompareTo((long)234)); // Obj is not an int } [Theory] [InlineData(789, 789, true)] [InlineData(789, -789, false)] [InlineData(789, 0, false)] [InlineData(0, 0, true)] [InlineData(-789, -789, true)] [InlineData(-789, 789, false)] [InlineData(789, null, false)] [InlineData(789, "789", false)] [InlineData(789, (long)789, false)] public static void Equals(int i1, object obj, bool expected) { if (obj is int) { int i2 = (int)obj; Assert.Equal(expected, i1.Equals(i2)); Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode())); } Assert.Equal(expected, i1.Equals(obj)); } public static IEnumerable<object[]> ToString_TestData() { NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo; yield return new object[] { int.MinValue, "G", emptyFormat, "-2147483648" }; yield return new object[] { -4567, "G", emptyFormat, "-4567" }; yield return new object[] { 0, "G", emptyFormat, "0" }; yield return new object[] { 4567, "G", emptyFormat, "4567" }; yield return new object[] { int.MaxValue, "G", emptyFormat, "2147483647" }; yield return new object[] { 0x2468, "x", emptyFormat, "2468" }; yield return new object[] { 2468, "N", emptyFormat, string.Format("{0:N}", 2468.00) }; NumberFormatInfo customFormat = new NumberFormatInfo(); customFormat.NegativeSign = "#"; customFormat.NumberDecimalSeparator = "~"; customFormat.NumberGroupSeparator = "*"; yield return new object[] { -2468, "N", customFormat, "#2*468~00" }; yield return new object[] { 2468, "N", customFormat, "2*468~00" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(int i, string format, IFormatProvider provider, string expected) { // Format is case insensitive string upperFormat = format.ToUpperInvariant(); string lowerFormat = format.ToLowerInvariant(); string upperExpected = expected.ToUpperInvariant(); string lowerExpected = expected.ToLowerInvariant(); bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo); if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G") { if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString()); Assert.Equal(upperExpected, i.ToString((IFormatProvider)null)); } Assert.Equal(upperExpected, i.ToString(provider)); } if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString(upperFormat)); Assert.Equal(lowerExpected, i.ToString(lowerFormat)); Assert.Equal(upperExpected, i.ToString(upperFormat, null)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, null)); } Assert.Equal(upperExpected, i.ToString(upperFormat, provider)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider)); } [Fact] public static void ToString_InvalidFormat_ThrowsFormatException() { int i = 123; Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format } public static IEnumerable<object[]> Parse_Valid_TestData() { NumberFormatInfo samePositiveNegativeFormat = new NumberFormatInfo() { PositiveSign = "|", NegativeSign = "|" }; NumberFormatInfo emptyPositiveFormat = new NumberFormatInfo() { PositiveSign = "" }; NumberFormatInfo emptyNegativeFormat = new NumberFormatInfo() { NegativeSign = "" }; // None yield return new object[] { "0", NumberStyles.None, null, 0 }; yield return new object[] { "123", NumberStyles.None, null, 123 }; yield return new object[] { "2147483647", NumberStyles.None, null, 2147483647 }; // HexNumber yield return new object[] { "123", NumberStyles.HexNumber, null, 0x123 }; yield return new object[] { "abc", NumberStyles.HexNumber, null, 0xabc }; yield return new object[] { "ABC", NumberStyles.HexNumber, null, 0xabc }; yield return new object[] { "12", NumberStyles.HexNumber, null, 0x12 }; // Currency NumberFormatInfo currencyFormat = new NumberFormatInfo() { CurrencySymbol = "$", CurrencyGroupSeparator = "|", NumberGroupSeparator = "/" }; yield return new object[] { "$1|000", NumberStyles.Currency, currencyFormat, 1000 }; yield return new object[] { "$1000", NumberStyles.Currency, currencyFormat, 1000 }; yield return new object[] { "$ 1000", NumberStyles.Currency, currencyFormat, 1000 }; yield return new object[] { "1000", NumberStyles.Currency, currencyFormat, 1000 }; yield return new object[] { "$(1000)", NumberStyles.Currency, currencyFormat, -1000}; yield return new object[] { "($1000)", NumberStyles.Currency, currencyFormat, -1000 }; yield return new object[] { "$-1000", NumberStyles.Currency, currencyFormat, -1000 }; yield return new object[] { "-$1000", NumberStyles.Currency, currencyFormat, -1000 }; NumberFormatInfo emptyCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "" }; yield return new object[] { "100", NumberStyles.Currency, emptyCurrencyFormat, 100 }; // If CurrencySymbol and Negative are the same, NegativeSign is preferred NumberFormatInfo sameCurrencyNegativeSignFormat = new NumberFormatInfo() { NegativeSign = "|", CurrencySymbol = "|" }; yield return new object[] { "|1000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowLeadingSign, sameCurrencyNegativeSignFormat, -1000 }; // Any yield return new object[] { "123", NumberStyles.Any, null, 123 }; // AllowLeadingSign yield return new object[] { "-2147483648", NumberStyles.AllowLeadingSign, null, -2147483648 }; yield return new object[] { "-123", NumberStyles.AllowLeadingSign, null, -123 }; yield return new object[] { "+0", NumberStyles.AllowLeadingSign, null, 0 }; yield return new object[] { "-0", NumberStyles.AllowLeadingSign, null, 0 }; yield return new object[] { "+123", NumberStyles.AllowLeadingSign, null, 123 }; // If PositiveSign and NegativeSign are the same, PositiveSign is preferred yield return new object[] { "|123", NumberStyles.AllowLeadingSign, samePositiveNegativeFormat, 123 }; // Empty PositiveSign or NegativeSign yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyPositiveFormat, 100 }; yield return new object[] { "100", NumberStyles.AllowLeadingSign, emptyNegativeFormat, 100 }; // AllowTrailingSign yield return new object[] { "123", NumberStyles.AllowTrailingSign, null, 123 }; yield return new object[] { "123+", NumberStyles.AllowTrailingSign, null, 123 }; yield return new object[] { "123-", NumberStyles.AllowTrailingSign, null, -123 }; // If PositiveSign and NegativeSign are the same, PositiveSign is preferred yield return new object[] { "123|", NumberStyles.AllowTrailingSign, samePositiveNegativeFormat, 123 }; // Empty PositiveSign or NegativeSign yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyPositiveFormat, 100 }; yield return new object[] { "100", NumberStyles.AllowTrailingSign, emptyNegativeFormat, 100 }; // AllowLeadingWhite and AllowTrailingWhite yield return new object[] { "123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 }; yield return new object[] { " 123", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 }; yield return new object[] { " 123 ", NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, null, 123 }; // AllowThousands NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" }; yield return new object[] { "1000", NumberStyles.AllowThousands, thousandsFormat, 1000 }; yield return new object[] { "1|0|0|0", NumberStyles.AllowThousands, thousandsFormat, 1000 }; yield return new object[] { "1|||", NumberStyles.AllowThousands, thousandsFormat, 1 }; NumberFormatInfo integerNumberSeparatorFormat = new NumberFormatInfo() { NumberGroupSeparator = "1" }; yield return new object[] { "1111", NumberStyles.AllowThousands, integerNumberSeparatorFormat, 1111 }; // AllowExponent yield return new object[] { "1E2", NumberStyles.AllowExponent, null, 100 }; yield return new object[] { "1E+2", NumberStyles.AllowExponent, null, 100 }; yield return new object[] { "1e2", NumberStyles.AllowExponent, null, 100 }; yield return new object[] { "1E0", NumberStyles.AllowExponent, null, 1 }; yield return new object[] { "(1E2)", NumberStyles.AllowExponent | NumberStyles.AllowParentheses, null, -100 }; yield return new object[] { "-1E2", NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign, null, -100 }; NumberFormatInfo negativeFormat = new NumberFormatInfo() { PositiveSign = "|" }; yield return new object[] { "1E|2", NumberStyles.AllowExponent, negativeFormat, 100 }; // AllowParentheses yield return new object[] { "123", NumberStyles.AllowParentheses, null, 123 }; yield return new object[] { "(123)", NumberStyles.AllowParentheses, null, -123 }; // AllowDecimalPoint NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "|" }; yield return new object[] { "67|", NumberStyles.AllowDecimalPoint, decimalFormat, 67 }; // NumberFormatInfo has a custom property with length > 1 NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" }; yield return new object[] { "123123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, 123 }; NumberFormatInfo integerPositiveSignFormat = new NumberFormatInfo() { PositiveSign = "123" }; yield return new object[] { "123123", NumberStyles.AllowLeadingSign, integerPositiveSignFormat, 123 }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse(string value, NumberStyles style, IFormatProvider provider, int expected) { bool isDefaultProvider = provider == null || provider == new NumberFormatInfo(); int result; if ((style & ~NumberStyles.Integer) == 0 && style != NumberStyles.None) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.True(int.TryParse(value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, int.Parse(value)); } Assert.Equal(expected, int.Parse(value, provider)); } // Use Parse(string, NumberStyles, IFormatProvider) Assert.True(int.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, int.Parse(value, style, provider)); if (isDefaultProvider) { // Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider) Assert.True(int.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(expected, result); Assert.Equal(expected, int.Parse(value, style)); Assert.Equal(expected, int.Parse(value, style, new NumberFormatInfo())); } } public static IEnumerable<object[]> Parse_Invalid_TestData() { // Garbage strings yield return new object[] { null, NumberStyles.Integer, null, typeof(ArgumentNullException) }; yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) }; yield return new object[] { "", NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) }; yield return new object[] { " \t \n \r ", NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { null, NumberStyles.Any, null, typeof(ArgumentNullException) }; yield return new object[] { "Garbage", NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { "Garbage", NumberStyles.Any, null, typeof(FormatException) }; // Integer doesn't allow hex, exponents, paretheses, currency, thousands, decimal yield return new object[] { "abc", NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { "1E23", NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { "(123)", NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { 1000.ToString("C0"), NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { 1000.ToString("N0"), NumberStyles.Integer, null, typeof(FormatException) }; yield return new object[] { 678.90.ToString("F2"), NumberStyles.Integer, null, typeof(FormatException) }; // HexNumber yield return new object[] { "0xabc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "&habc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "G1", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "g1", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "+abc", NumberStyles.HexNumber, null, typeof(FormatException) }; yield return new object[] { "-abc", NumberStyles.HexNumber, null, typeof(FormatException) }; // None doesn't allow hex or leading or trailing whitespace yield return new object[] { "abc", NumberStyles.None, null, typeof(FormatException) }; yield return new object[] { "123 ", NumberStyles.None, null, typeof(FormatException) }; yield return new object[] { " 123", NumberStyles.None, null, typeof(FormatException) }; yield return new object[] { " 123 ", NumberStyles.None, null, typeof(FormatException) }; // AllowLeadingSign yield return new object[] { "+", NumberStyles.AllowLeadingSign, null, typeof(FormatException) }; yield return new object[] { "-", NumberStyles.AllowLeadingSign, null, typeof(FormatException) }; yield return new object[] { "+-123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) }; yield return new object[] { "-+123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) }; yield return new object[] { "- 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) }; yield return new object[] { "+ 123", NumberStyles.AllowLeadingSign, null, typeof(FormatException) }; // AllowTrailingSign yield return new object[] { "123-+", NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; yield return new object[] { "123+-", NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; yield return new object[] { "123 -", NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; yield return new object[] { "123 +", NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; // Parentheses has priority over CurrencySymbol and PositiveSign NumberFormatInfo currencyNegativeParenthesesFormat = new NumberFormatInfo() { CurrencySymbol = "(", PositiveSign = "))" }; yield return new object[] { "(100))", NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingSign, currencyNegativeParenthesesFormat, typeof(FormatException) }; // AllowTrailingSign and AllowLeadingSign yield return new object[] { "+123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; yield return new object[] { "+123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; yield return new object[] { "-123+", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; yield return new object[] { "-123-", NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign, null, typeof(FormatException) }; // AllowLeadingSign and AllowParentheses yield return new object[] { "-(1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) }; yield return new object[] { "(-1000)", NumberStyles.AllowLeadingSign | NumberStyles.AllowParentheses, null, typeof(FormatException) }; // AllowLeadingWhite yield return new object[] { "1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) }; yield return new object[] { " 1 ", NumberStyles.AllowLeadingWhite, null, typeof(FormatException) }; // AllowTrailingWhite yield return new object[] { " 1 ", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) }; yield return new object[] { " 1", NumberStyles.AllowTrailingWhite, null, typeof(FormatException) }; // AllowThousands NumberFormatInfo thousandsFormat = new NumberFormatInfo() { NumberGroupSeparator = "|" }; yield return new object[] { "|||1", NumberStyles.AllowThousands, null, typeof(FormatException) }; // AllowExponent yield return new object[] { "65E", NumberStyles.AllowExponent, null, typeof(FormatException) }; yield return new object[] { "65E10", NumberStyles.AllowExponent, null, typeof(OverflowException) }; yield return new object[] { "65E+10", NumberStyles.AllowExponent, null, typeof(OverflowException) }; yield return new object[] { "65E-1", NumberStyles.AllowExponent, null, typeof(OverflowException) }; // AllowDecimalPoint NumberFormatInfo decimalFormat = new NumberFormatInfo() { NumberDecimalSeparator = "." }; yield return new object[] { "67.90", NumberStyles.AllowDecimalPoint, null, typeof(OverflowException) }; // Parsing integers doesn't allow NaN, PositiveInfinity or NegativeInfinity NumberFormatInfo doubleFormat = new NumberFormatInfo() { NaNSymbol = "NaN", PositiveInfinitySymbol = "Infinity", NegativeInfinitySymbol = "-Infinity" }; yield return new object[] { "NaN", NumberStyles.Any, doubleFormat, typeof(FormatException) }; yield return new object[] { "Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) }; yield return new object[] { "-Infinity", NumberStyles.Any, doubleFormat, typeof(FormatException) }; // NumberFormatInfo has a custom property with length > 1 NumberFormatInfo integerCurrencyFormat = new NumberFormatInfo() { CurrencySymbol = "123" }; yield return new object[] { "123", NumberStyles.AllowCurrencySymbol, integerCurrencyFormat, typeof(FormatException) }; NumberFormatInfo integerPositiveSignFormat = new NumberFormatInfo() { PositiveSign = "123" }; yield return new object[] { "123", NumberStyles.AllowLeadingSign, integerPositiveSignFormat, typeof(FormatException) }; // Not in range of Int32 yield return new object[] { "2147483648", NumberStyles.Any, null, typeof(OverflowException) }; yield return new object[] { "2147483648", NumberStyles.Integer, null, typeof(OverflowException) }; yield return new object[] { "-2147483649", NumberStyles.Any, null, typeof(OverflowException) }; yield return new object[] { "-2147483649", NumberStyles.Integer, null, typeof(OverflowException) }; yield return new object[] { "2147483649-", NumberStyles.AllowTrailingSign, null, typeof(OverflowException) }; yield return new object[] { "(2147483649)", NumberStyles.AllowParentheses, null, typeof(OverflowException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { bool isDefaultProvider = provider == null || provider == new NumberFormatInfo(); int result; if ((style & ~NumberStyles.Integer) == 0 && style != NumberStyles.None && (style & NumberStyles.AllowLeadingWhite) == (style & NumberStyles.AllowTrailingWhite)) { // Use Parse(string) or Parse(string, IFormatProvider) if (isDefaultProvider) { Assert.False(int.TryParse(value, out result)); Assert.Equal(default(int), result); Assert.Throws(exceptionType, () => int.Parse(value)); } Assert.Throws(exceptionType, () => int.Parse(value, provider)); } // Use Parse(string, NumberStyles, IFormatProvider) Assert.False(int.TryParse(value, style, provider, out result)); Assert.Equal(default(int), result); Assert.Throws(exceptionType, () => int.Parse(value, style, provider)); if (isDefaultProvider) { // Use Parse(string, NumberStyles) or Parse(string, NumberStyles, IFormatProvider) Assert.False(int.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(default(int), result); Assert.Throws(exceptionType, () => int.Parse(value, style)); Assert.Throws(exceptionType, () => int.Parse(value, style, new NumberFormatInfo())); } } [Theory] [InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses)] [InlineData(unchecked((NumberStyles)0xFFFFFC00))] public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style) { int result = 0; Assert.Throws<ArgumentException>(() => int.TryParse("1", style, null, out result)); Assert.Equal(default(int), result); Assert.Throws<ArgumentException>(() => int.Parse("1", style)); Assert.Throws<ArgumentException>(() => int.Parse("1", style, null)); } } }
using System; using System.Collections; using System.IO; using System.Globalization; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.IO.Pem; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.OpenSsl { /** * PEM generator for the original set of PEM objects used in Open SSL. */ public class MiscPemGenerator : PemObjectGenerator { private object obj; private string algorithm; private char[] password; private SecureRandom random; public MiscPemGenerator(object obj) { this.obj = obj; } public MiscPemGenerator( object obj, string algorithm, char[] password, SecureRandom random) { this.obj = obj; this.algorithm = algorithm; this.password = password; this.random = random; } private PemObject CreatePemObject(object o) { if (obj == null) throw new ArgumentNullException("obj"); if (obj is AsymmetricCipherKeyPair) { return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private); } string type; byte[] encoding; if (o is PemObject) return (PemObject)o; if (o is PemObjectGenerator) return ((PemObjectGenerator)o).Generate(); if (obj is X509Certificate) { // TODO Should we prefer "X509 CERTIFICATE" here? type = "CERTIFICATE"; try { encoding = ((X509Certificate)obj).GetEncoded(); } catch (CertificateEncodingException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } else if (obj is X509Crl) { type = "X509 CRL"; try { encoding = ((X509Crl)obj).GetEncoded(); } catch (CrlException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } else if (obj is AsymmetricKeyParameter) { AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj; if (akp.IsPrivate) { string keyType; encoding = EncodePrivateKey(akp, out keyType); type = keyType + " PRIVATE KEY"; } else { type = "PUBLIC KEY"; encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded(); } } else if (obj is IX509AttributeCertificate) { type = "ATTRIBUTE CERTIFICATE"; encoding = ((X509V2AttributeCertificate)obj).GetEncoded(); } else if (obj is Pkcs10CertificationRequest) { type = "CERTIFICATE REQUEST"; encoding = ((Pkcs10CertificationRequest)obj).GetEncoded(); } else if (obj is Asn1.Cms.ContentInfo) { type = "PKCS7"; encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded(); } else { throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); } return new PemObject(type, encoding); } // private string GetHexEncoded(byte[] bytes) // { // bytes = Hex.Encode(bytes); // // char[] chars = new char[bytes.Length]; // // for (int i = 0; i != bytes.Length; i++) // { // chars[i] = (char)bytes[i]; // } // // return new string(chars); // } private PemObject CreatePemObject( object obj, string algorithm, char[] password, SecureRandom random) { if (obj == null) throw new ArgumentNullException("obj"); if (algorithm == null) throw new ArgumentNullException("algorithm"); if (password == null) throw new ArgumentNullException("password"); if (random == null) throw new ArgumentNullException("random"); if (obj is AsymmetricCipherKeyPair) { return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random); } string type = null; byte[] keyData = null; if (obj is AsymmetricKeyParameter) { AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj; if (akp.IsPrivate) { string keyType; keyData = EncodePrivateKey(akp, out keyType); type = keyType + " PRIVATE KEY"; } } if (type == null || keyData == null) { // TODO Support other types? throw new PemGenerationException("Object type not supported: " + obj.GetType().FullName); } string dekAlgName = algorithm.ToUpper(CultureInfo.InvariantCulture); // Note: For backward compatibility if (dekAlgName == "DESEDE") { dekAlgName = "DES-EDE3-CBC"; } int ivLength = dekAlgName.StartsWith("AES-") ? 16 : 8; byte[] iv = new byte[ivLength]; random.NextBytes(iv); byte[] encData = PemUtilities.Crypt(true, keyData, password, dekAlgName, iv); IList headers = Platform.CreateArrayList(2); headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED")); headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv))); return new PemObject(type, headers, encData); } private byte[] EncodePrivateKey( AsymmetricKeyParameter akp, out string keyType) { PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp); DerObjectIdentifier oid = info.AlgorithmID.ObjectID; if (oid.Equals(X9ObjectIdentifiers.IdDsa)) { keyType = "DSA"; DsaParameter p = DsaParameter.GetInstance(info.AlgorithmID.Parameters); BigInteger x = ((DsaPrivateKeyParameters) akp).X; BigInteger y = p.G.ModPow(x, p.P); // TODO Create an ASN1 object somewhere for this? return new DerSequence( new DerInteger(0), new DerInteger(p.P), new DerInteger(p.Q), new DerInteger(p.G), new DerInteger(y), new DerInteger(x)).GetEncoded(); } if (oid.Equals(PkcsObjectIdentifiers.RsaEncryption)) { keyType = "RSA"; } else if (oid.Equals(CryptoProObjectIdentifiers.GostR3410x2001) || oid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { keyType = "EC"; } else { throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp"); } return info.PrivateKey.GetEncoded(); } public PemObject Generate() { try { if (algorithm != null) { return CreatePemObject(obj, algorithm, password, random); } return CreatePemObject(obj); } catch (IOException e) { throw new PemGenerationException("encoding exception", e); } } } }
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/> // <version>$Revision: 2743 $</version> // </file> using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace ICSharpCode.SharpDevelop.Dom { /// <summary> /// Class capable of loading xml documentation files. XmlDoc automatically creates a /// binary cache for big xml files to reduce memory usage. /// </summary> public sealed class XmlDoc : IDisposable { static readonly List<string> xmlDocLookupDirectories = new List<string> { System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() }; public static IList<string> XmlDocLookupDirectories { get { return xmlDocLookupDirectories; } } struct IndexEntry : IComparable<IndexEntry> { public int HashCode; public int FileLocation; public int CompareTo(IndexEntry other) { return HashCode.CompareTo(other.HashCode); } public IndexEntry(int HashCode, int FileLocation) { this.HashCode = HashCode; this.FileLocation = FileLocation; } } Dictionary<string, string> xmlDescription = new Dictionary<string, string>(); IndexEntry[] index; // SORTED array of index entries Queue<string> keyCacheQueue; const int cacheLength = 150; // number of strings to cache when working in file-mode void ReadMembersSection(XmlReader reader) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.EndElement: if (reader.LocalName == "members") { return; } break; case XmlNodeType.Element: if (reader.LocalName == "member") { string memberAttr = reader.GetAttribute(0); string innerXml = reader.ReadInnerXml(); xmlDescription[memberAttr] = innerXml; } break; } } } public string GetDocumentation(string key) { if (xmlDescription == null) throw new ObjectDisposedException("XmlDoc"); lock (xmlDescription) { string result; if (xmlDescription.TryGetValue(key, out result)) return result; if (index == null) return null; return LoadDocumentation(key); } } #region Save binary files // FILE FORMAT FOR BINARY DOCUMENTATION // long magic = 0x4244636f446c6d58 (identifies file type = 'XmlDocDB') const long magic = 0x4244636f446c6d58; // short version = 2 (file version) const short version = 2; // long fileDate (last change date of xml file in DateTime ticks) // int testHashCode = magicTestString.GetHashCode() // (check if hash-code implementation is compatible) // int entryCount (count of entries) // int indexPointer (points to location where index starts in the file) // { // string key (documentation key as length-prefixed string) // string docu (xml documentation as length-prefixed string) // } // indexPointer points to the start of the following section: // { // int hashcode // int index (index where the docu string starts in the file) // } void Save(string fileName, DateTime fileDate) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { using (BinaryWriter w = new BinaryWriter(fs)) { w.Write(magic); w.Write(version); w.Write(fileDate.Ticks); IndexEntry[] index = new IndexEntry[xmlDescription.Count]; w.Write(index.Length); int indexPointerPos = (int)fs.Position; w.Write(0); // skip 4 bytes int i = 0; foreach (KeyValuePair<string, string> p in xmlDescription) { index[i] = new IndexEntry(p.Key.GetHashCode(), (int)fs.Position); w.Write(p.Key); w.Write(p.Value.Trim()); i += 1; } Array.Sort(index); int indexStart = (int)fs.Position; foreach (IndexEntry entry in index) { w.Write(entry.HashCode); w.Write(entry.FileLocation); } w.Seek(indexPointerPos, SeekOrigin.Begin); w.Write(indexStart); } } } #endregion #region Load binary files BinaryReader loader; FileStream fs; bool LoadFromBinary(string fileName, DateTime fileDate) { keyCacheQueue = new Queue<string>(cacheLength); fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); int len = (int)fs.Length; loader = new BinaryReader(fs); try { if (loader.ReadInt64() != magic) { LoggingService.Warn("Cannot load XmlDoc: wrong magic"); return false; } if (loader.ReadInt16() != version) { LoggingService.Warn("Cannot load XmlDoc: wrong version"); return false; } if (loader.ReadInt64() != fileDate.Ticks) { LoggingService.Info("Not loading XmlDoc: file changed since cache was created"); return false; } int count = loader.ReadInt32(); int indexStartPosition = loader.ReadInt32(); // go to start of index if (indexStartPosition >= len) { LoggingService.Error("XmlDoc: Cannot find index, cache invalid!"); return false; } fs.Position = indexStartPosition; IndexEntry[] index = new IndexEntry[count]; for (int i = 0; i < index.Length; i++) { index[i] = new IndexEntry(loader.ReadInt32(), loader.ReadInt32()); } this.index = index; return true; } catch (Exception ex) { LoggingService.Error("Cannot load from cache", ex); return false; } } string LoadDocumentation(string key) { if (keyCacheQueue.Count > cacheLength - 1) { xmlDescription.Remove(keyCacheQueue.Dequeue()); } int hashcode = key.GetHashCode(); // use interpolation search to find the item string resultDocu = null; int m = Array.BinarySearch(index, new IndexEntry(hashcode, 0)); if (m >= 0) { // correct hash code found. // possibly there are multiple items with the same hash, so go to the first. while (--m >= 0 && index[m].HashCode == hashcode); // go through all items that have the correct hash while (++m < index.Length && index[m].HashCode == hashcode) { fs.Position = index[m].FileLocation; string keyInFile = loader.ReadString(); if (keyInFile == key) { resultDocu = loader.ReadString(); break; } else { LoggingService.Warn("Found " + keyInFile + " instead of " + key); } } } keyCacheQueue.Enqueue(key); xmlDescription.Add(key, resultDocu); return resultDocu; } public void Dispose() { if (loader != null) { loader.Close(); fs.Close(); } xmlDescription = null; index = null; keyCacheQueue = null; loader = null; fs = null; } #endregion public static XmlDoc Load(XmlReader reader) { XmlDoc newXmlDoc = new XmlDoc(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.LocalName) { case "members": newXmlDoc.ReadMembersSection(reader); break; } } } return newXmlDoc; } public static XmlDoc Load(string fileName, string cachePath) { return Load(fileName, cachePath, true); } static XmlDoc Load(string fileName, string cachePath, bool allowRedirect) { //LoggingService.Debug("Loading XmlDoc for " + fileName); XmlDoc doc; string cacheName = null; if (cachePath != null) { Directory.CreateDirectory(cachePath); cacheName = cachePath + "/" + Path.GetFileNameWithoutExtension(fileName) + "." + fileName.GetHashCode().ToString("x") + ".dat"; if (File.Exists(cacheName)) { doc = new XmlDoc(); if (doc.LoadFromBinary(cacheName, File.GetLastWriteTimeUtc(fileName))) { //LoggingService.Debug("XmlDoc: Load from cache successful"); return doc; } else { doc.Dispose(); try { File.Delete(cacheName); } catch {} } } } try { using (XmlTextReader xmlReader = new XmlTextReader(fileName)) { xmlReader.MoveToContent(); if (allowRedirect && !string.IsNullOrEmpty(xmlReader.GetAttribute("redirect"))) { string redirectionTarget = GetRedirectionTarget(xmlReader.GetAttribute("redirect")); if (redirectionTarget != null) { LoggingService.Info("XmlDoc " + fileName + " is redirecting to " + redirectionTarget); return Load(redirectionTarget, cachePath, false); } else { LoggingService.Warn("XmlDoc " + fileName + " is redirecting to " + xmlReader.GetAttribute("redirect") + ", but that file was not found."); return new XmlDoc(); } } doc = Load(xmlReader); } } catch (XmlException ex) { LoggingService.Warn("Error loading XmlDoc " + fileName, ex); return new XmlDoc(); } if (cachePath != null && doc.xmlDescription.Count > cacheLength * 2) { LoggingService.Debug("XmlDoc: Creating cache for " + fileName); DateTime date = File.GetLastWriteTimeUtc(fileName); try { doc.Save(cacheName, date); } catch (Exception ex) { LoggingService.Error("Cannot write to cache file " + cacheName, ex); return doc; } doc.Dispose(); doc = new XmlDoc(); doc.LoadFromBinary(cacheName, date); } return doc; } static string GetRedirectionTarget(string target) { string programFilesDir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (!programFilesDir.EndsWith("\\") && !programFilesDir.EndsWith("/")) programFilesDir += "\\"; string corSysDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); if (!corSysDir.EndsWith("\\") && !corSysDir.EndsWith("/")) corSysDir += "\\"; return LookupLocalizedXmlDoc(target.Replace("%PROGRAMFILESDIR%", programFilesDir) .Replace("%CORSYSDIR%", corSysDir)); } internal static string LookupLocalizedXmlDoc(string fileName) { string xmlFileName = Path.ChangeExtension(fileName, ".xml"); string currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName; string localizedXmlDocFile = GetLocalizedName(xmlFileName, currentCulture); LoggingService.Debug("Try find XMLDoc @" + localizedXmlDocFile); if (File.Exists(localizedXmlDocFile)) { return localizedXmlDocFile; } LoggingService.Debug("Try find XMLDoc @" + xmlFileName); if (File.Exists(xmlFileName)) { return xmlFileName; } if (currentCulture != "en") { string englishXmlDocFile = GetLocalizedName(xmlFileName, "en"); LoggingService.Debug("Try find XMLDoc @" + englishXmlDocFile); if (File.Exists(englishXmlDocFile)) { return englishXmlDocFile; } } return null; } static string GetLocalizedName(string fileName, string language) { string localizedXmlDocFile = Path.GetDirectoryName(fileName); localizedXmlDocFile = Path.Combine(localizedXmlDocFile, language); localizedXmlDocFile = Path.Combine(localizedXmlDocFile, Path.GetFileName(fileName)); return localizedXmlDocFile; } } }
using System; using System.Net; using System.Threading.Tasks; using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using Microsoft.WindowsAzure.Storage.Table.Protocol; using Orleans.AzureUtils; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using Xunit; namespace UnitTests.StorageTests { public class AzureTableDataManagerTests : IClassFixture<AzureStorageBasicTestFixture> { private string PartitionKey; private UnitTestAzureTableDataManager manager; private UnitTestAzureTableData GenerateNewData() { return new UnitTestAzureTableData("JustData", PartitionKey, "RK-" + Guid.NewGuid()); } public AzureTableDataManagerTests() { TestingUtils.ConfigureThreadPoolSettingsForStorageTests(); // Pre-create table, if required manager = new UnitTestAzureTableDataManager(StorageTestConstants.DataConnectionString); PartitionKey = "PK-AzureTableDataManagerTests-" + Guid.NewGuid(); } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_CreateTableEntryAsync() { var data = GenerateNewData(); await manager.CreateTableEntryAsync(data); try { var data2 = data.Clone(); data2.StringData = "NewData"; await manager.CreateTableEntryAsync(data2); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode, "Creating an already existing entry."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.Conflict, httpStatusCode); Assert.AreEqual("EntityAlreadyExists", restStatus); } var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.AreEqual(data.StringData, tuple.Item1.StringData); } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_UpsertTableEntryAsync() { var data = GenerateNewData(); await manager.UpsertTableEntryAsync(data); var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.AreEqual(data.StringData, tuple.Item1.StringData); var data2 = data.Clone(); data2.StringData = "NewData"; await manager.UpsertTableEntryAsync(data2); tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey); Assert.AreEqual(data2.StringData, tuple.Item1.StringData); } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_UpdateTableEntryAsync() { var data = GenerateNewData(); try { await manager.UpdateTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Update before insert."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } await manager.UpsertTableEntryAsync(data); var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.AreEqual(data.StringData, tuple.Item1.StringData); var data2 = data.Clone(); data2.StringData = "NewData"; string eTag1 = await manager.UpdateTableEntryAsync(data2, AzureStorageUtils.ANY_ETAG); tuple = await manager.ReadSingleTableEntryAsync(data2.PartitionKey, data2.RowKey); Assert.AreEqual(data2.StringData, tuple.Item1.StringData); var data3 = data.Clone(); data3.StringData = "EvenNewerData"; string ignoredETag = await manager.UpdateTableEntryAsync(data3, eTag1); tuple = await manager.ReadSingleTableEntryAsync(data3.PartitionKey, data3.RowKey); Assert.AreEqual(data3.StringData, tuple.Item1.StringData); try { string eTag3 = await manager.UpdateTableEntryAsync(data3.Clone(), eTag1); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode, "Wrong eTag"); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.PreconditionFailed, httpStatusCode); Assert.IsTrue(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied || restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus); } } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_DeleteTableAsync() { var data = GenerateNewData(); try { await manager.DeleteTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Delete before create."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } string eTag1 = await manager.UpsertTableEntryAsync(data); await manager.DeleteTableEntryAsync(data, eTag1); try { await manager.DeleteTableEntryAsync(data, eTag1); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Deleting an already deleted item."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.IsNull(tuple); } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_MergeTableAsync() { var data = GenerateNewData(); try { await manager.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Merge before create."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } string eTag1 = await manager.UpsertTableEntryAsync(data); var data2 = data.Clone(); data2.StringData = "NewData"; await manager.MergeTableEntryAsync(data2, eTag1); try { await manager.MergeTableEntryAsync(data, eTag1); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode, "Wrong eTag."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.PreconditionFailed, httpStatusCode); Assert.IsTrue(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied || restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus); } var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.AreEqual("NewData", tuple.Item1.StringData); } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_ReadSingleTableEntryAsync() { var data = GenerateNewData(); var tuple = await manager.ReadSingleTableEntryAsync(data.PartitionKey, data.RowKey); Assert.IsNull(tuple); } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_InsertTwoTableEntriesConditionallyAsync() { var data1 = GenerateNewData(); var data2 = GenerateNewData(); try { await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, AzureStorageUtils.ANY_ETAG); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Upadte item 2 before created it."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } string etag = await manager.CreateTableEntryAsync(data2.Clone()); var tuple = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag); try { await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), tuple.Item2); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode, "Inserting an already existing item 1."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.Conflict, httpStatusCode); Assert.AreEqual("EntityAlreadyExists", restStatus); } try { await manager.InsertTwoTableEntriesConditionallyAsync(data1.Clone(), data2.Clone(), AzureStorageUtils.ANY_ETAG); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.Conflict, exc.RequestInformation.HttpStatusCode, "Inserting an already existing item 1 AND wring eTag"); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.Conflict, httpStatusCode); Assert.AreEqual("EntityAlreadyExists", restStatus); }; } [Fact, TestCategory("Functional"), TestCategory("Azure"), TestCategory("Storage")] public async Task AzureTableDataManager_UpdateTwoTableEntriesConditionallyAsync() { var data1 = GenerateNewData(); var data2 = GenerateNewData(); try { await manager.UpdateTwoTableEntriesConditionallyAsync(data1, AzureStorageUtils.ANY_ETAG, data2, AzureStorageUtils.ANY_ETAG); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.NotFound, exc.RequestInformation.HttpStatusCode, "Update before insert."); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.NotFound, httpStatusCode); Assert.AreEqual(StorageErrorCodeStrings.ResourceNotFound, restStatus); } string etag = await manager.CreateTableEntryAsync(data2.Clone()); var tuple1 = await manager.InsertTwoTableEntriesConditionallyAsync(data1, data2, etag); var tuple2 = await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2); try { await manager.UpdateTwoTableEntriesConditionallyAsync(data1, tuple1.Item1, data2, tuple1.Item2); Assert.Fail("Should have thrown StorageException."); } catch(StorageException exc) { Assert.AreEqual((int)HttpStatusCode.PreconditionFailed, exc.RequestInformation.HttpStatusCode, "Wrong eTag"); HttpStatusCode httpStatusCode; string restStatus; AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus, true); Assert.AreEqual(HttpStatusCode.PreconditionFailed, httpStatusCode); Assert.IsTrue(restStatus == TableErrorCodeStrings.UpdateConditionNotSatisfied || restStatus == StorageErrorCodeStrings.ConditionNotMet, restStatus); } } } }
using System; /* Contains conversion support elements such as classes, interfaces and static methods. */ namespace zlib { class SupportClass { /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static long Identity(long literal) { return literal; } /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static ulong Identity(ulong literal) { return literal; } /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static float Identity(float literal) { return literal; } /// <summary> /// This method returns the literal value received /// </summary> /// <param name="literal">The literal to return</param> /// <returns>The received value</returns> public static double Identity(double literal) { return literal; } /*******************************/ /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { if ( number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, long bits) { return URShift(number, (int)bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { if ( number >= 0) return number >> bits; else return (number >> bits) + (2L << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, long bits) { return URShift(number, (int)bits); } /*******************************/ /// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary> /// <param name="sourceStream">The source Stream to read from.</param> /// <param name="target">Contains the array of characteres read from the source Stream.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source Stream.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.IO.Stream sourceStream, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; byte[] receiver = new byte[target.Length]; int bytesRead = sourceStream.Read(receiver, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for(int i = start; i < start + bytesRead; i++) target[i] = (byte)receiver[i]; return bytesRead; } /// <summary>Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.</summary> /// <param name="sourceTextReader">The source TextReader to read from</param> /// <param name="target">Contains the array of characteres read from the source TextReader.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source TextReader.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for(int index=start; index<start+bytesRead; index++) target[index] = (byte)charArray[index]; return bytesRead; } /// <summary> /// Converts a string to an array of bytes /// </summary> /// <param name="sourceString">The string to be converted</param> /// <returns>The new array of bytes</returns> public static byte[] ToByteArray(System.String sourceString) { return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); } /// <summary> /// Converts an array of bytes to an array of chars /// </summary> /// <param name="byteArray">The array of bytes to convert</param> /// <returns>The new array of chars</returns> public static char[] ToCharArray(byte[] byteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); } #if !RT /*******************************/ /// <summary> /// Writes an object to the specified Stream /// </summary> /// <param name="stream">The target Stream</param> /// <param name="objectToSend">The object to be sent</param> public static void Serialize(System.IO.Stream stream, System.Object objectToSend) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, objectToSend); } /// <summary> /// Writes an object to the specified BinaryWriter /// </summary> /// <param name="binaryWriter">The target BinaryWriter</param> /// <param name="objectToSend">The object to be sent</param> public static void Serialize(System.IO.BinaryWriter binaryWriter, System.Object objectToSend) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(binaryWriter.BaseStream, objectToSend); } /*******************************/ /// <summary> /// Deserializes an object, or an entire graph of connected objects, and returns the object intance /// </summary> /// <param name="binaryReader">Reader instance used to read the object</param> /// <returns>The object instance</returns> public static System.Object Deserialize(System.IO.BinaryReader binaryReader) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return formatter.Deserialize(binaryReader.BaseStream); } #endif /*******************************/ /// <summary> /// Writes the exception stack trace to the received stream /// </summary> /// <param name="throwable">Exception to obtain information from</param> /// <param name="stream">Output sream used to write to</param> public static void WriteStackTrace(System.Exception throwable, System.IO.TextWriter stream) { stream.Write(throwable.StackTrace); stream.Flush(); } } }
// 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.Immutable.Tests { public class ImmutableArrayExtensionsTest { private static readonly ImmutableArray<int> s_emptyDefault = default(ImmutableArray<int>); private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>(); private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1); private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3); private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1)); private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null); private static readonly ImmutableArray<int>.Builder s_emptyBuilder = ImmutableArray.Create<int>().ToBuilder(); private static readonly ImmutableArray<int>.Builder s_oneElementBuilder = ImmutableArray.Create<int>(1).ToBuilder(); private static readonly ImmutableArray<int>.Builder s_manyElementsBuilder = ImmutableArray.Create<int>(1, 2, 3).ToBuilder(); [Fact] public void Select() { Assert.Equal(new[] { 4, 5, 6 }, ImmutableArrayExtensions.Select(s_manyElements, n => n + 3)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(s_manyElements, null)); } [Fact] public void SelectEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select<int, bool>(s_emptyDefault, null)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select(s_emptyDefault, n => true)); } [Fact] public void SelectEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(s_empty, null)); Assert.False(ImmutableArrayExtensions.Select(s_empty, n => true).Any()); } [Fact] public void SelectMany() { Func<int, IEnumerable<int>> collectionSelector = i => Enumerable.Range(i, 10); Func<int, int, int> resultSelector = (i, e) => e * 2; foreach (var arr in new[] { s_empty, s_oneElement, s_manyElements }) { Assert.Equal( Enumerable.SelectMany(arr, collectionSelector, resultSelector), ImmutableArrayExtensions.SelectMany(arr, collectionSelector, resultSelector)); } Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SelectMany<int, int, int>(s_emptyDefault, null, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, null, (i, e) => e)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, i => new[] { i }, null)); } [Fact] public void Where() { Assert.Equal(new[] { 2, 3 }, ImmutableArrayExtensions.Where(s_manyElements, n => n > 1)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(s_manyElements, null)); } [Fact] public void WhereEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(s_emptyDefault, null)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(s_emptyDefault, n => true)); } [Fact] public void WhereEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(s_empty, null)); Assert.False(ImmutableArrayExtensions.Where(s_empty, n => true).Any()); } [Fact] public void Any() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(s_oneElement, null)); Assert.True(ImmutableArrayExtensions.Any(s_oneElement)); Assert.True(ImmutableArrayExtensions.Any(s_manyElements, n => n == 2)); Assert.False(ImmutableArrayExtensions.Any(s_manyElements, n => n == 4)); Assert.True(ImmutableArrayExtensions.Any(s_oneElementBuilder)); } [Fact] public void AnyEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault, n => true)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(s_emptyDefault, null)); } [Fact] public void AnyEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(s_empty, null)); Assert.False(ImmutableArrayExtensions.Any(s_empty)); Assert.False(ImmutableArrayExtensions.Any(s_empty, n => true)); } [Fact] public void All() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(s_oneElement, null)); Assert.False(ImmutableArrayExtensions.All(s_manyElements, n => n == 2)); Assert.True(ImmutableArrayExtensions.All(s_manyElements, n => n > 0)); } [Fact] public void AllEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(s_emptyDefault, n => true)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(s_emptyDefault, null)); } [Fact] public void AllEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(s_empty, null)); Assert.True(ImmutableArrayExtensions.All(s_empty, n => { throw new ShouldNotBeInvokedException(); })); // predicate should never be invoked. } [Fact] public void SequenceEqual() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, (IEnumerable<int>)null)); foreach (IEqualityComparer<int> comparer in new[] { null, EqualityComparer<int>.Default }) { Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, comparer)); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.ToArray(), comparer)); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_oneElement.ToArray(), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_oneElement.ToArray()), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.Add(1).ToArray(), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2).ToArray(), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), (IEnumerable<int>)s_manyElements.Add(2).ToArray(), comparer)); } Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, (a, b) => true)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, (a, b) => a == b)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2), (a, b) => a == b)); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(1), (a, b) => a == b)); Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), (a, b) => false)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_oneElement, (Func<int, int, bool>)null)); } [Fact] public void SequenceEqualEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_empty)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault, (Func<int, int, bool>)null)); } [Fact] public void SequenceEqualEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(s_empty, (IEnumerable<int>)null)); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty)); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty.ToArray())); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => true)); Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => false)); } [Fact] public void Aggregate() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(s_oneElement, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(s_oneElement, 1, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, null, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, (a, b) => a + b, null)); Assert.Equal(Enumerable.Aggregate(s_manyElements, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, (a, b) => a * b)); Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b)); Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a)); } [Fact] public void AggregateEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, (a, b) => a + b)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, 1, (a, b) => a + b)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_emptyDefault, 1, (a, b) => a + b, a => a)); } [Fact] public void AggregateEmpty() { Assert.Equal(0, ImmutableArrayExtensions.Aggregate(s_empty, (a, b) => a + b)); Assert.Equal(1, ImmutableArrayExtensions.Aggregate(s_empty, 1, (a, b) => a + b)); Assert.Equal(1, ImmutableArrayExtensions.Aggregate<int, int, int>(s_empty, 1, (a, b) => a + b, a => a)); } [Fact] public void ElementAt() { // Basis for some assertions that follow Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_empty, 0)); Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_manyElements, -1)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAt(s_emptyDefault, 0)); Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_empty, 0)); Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_manyElements, -1)); Assert.Equal(1, ImmutableArrayExtensions.ElementAt(s_oneElement, 0)); Assert.Equal(3, ImmutableArrayExtensions.ElementAt(s_manyElements, 2)); } [Fact] public void ElementAtOrDefault() { Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, -1), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, -1)); Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, 3), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 3)); Assert.Throws<InvalidOperationException>(() => Enumerable.ElementAtOrDefault(s_emptyDefault, 0)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAtOrDefault(s_emptyDefault, 0)); Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 0)); Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 1)); Assert.Equal(1, ImmutableArrayExtensions.ElementAtOrDefault(s_oneElement, 0)); Assert.Equal(3, ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 2)); } [Fact] public void First() { Assert.Equal(Enumerable.First(s_oneElement), ImmutableArrayExtensions.First(s_oneElement)); Assert.Equal(Enumerable.First(s_oneElement, i => true), ImmutableArrayExtensions.First(s_oneElement, i => true)); Assert.Equal(Enumerable.First(s_manyElements), ImmutableArrayExtensions.First(s_manyElements)); Assert.Equal(Enumerable.First(s_manyElements, i => true), ImmutableArrayExtensions.First(s_manyElements, i => true)); Assert.Equal(Enumerable.First(s_oneElementBuilder), ImmutableArrayExtensions.First(s_oneElementBuilder)); Assert.Equal(Enumerable.First(s_manyElementsBuilder), ImmutableArrayExtensions.First(s_manyElementsBuilder)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_manyElements, i => false)); } [Fact] public void FirstEmpty() { Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(s_empty, null)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_emptyBuilder)); } [Fact] public void FirstEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(s_emptyDefault, null)); } [Fact] public void FirstOrDefault() { Assert.Equal(Enumerable.FirstOrDefault(s_oneElement), ImmutableArrayExtensions.FirstOrDefault(s_oneElement)); Assert.Equal(Enumerable.FirstOrDefault(s_manyElements), ImmutableArrayExtensions.FirstOrDefault(s_manyElements)); foreach (bool result in new[] { true, false }) { Assert.Equal(Enumerable.FirstOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.FirstOrDefault(s_oneElement, i => result)); Assert.Equal(Enumerable.FirstOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.FirstOrDefault(s_manyElements, i => result)); } Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_oneElement, null)); Assert.Equal(Enumerable.FirstOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.FirstOrDefault(s_oneElementBuilder)); Assert.Equal(Enumerable.FirstOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.FirstOrDefault(s_manyElementsBuilder)); } [Fact] public void FirstOrDefaultEmpty() { Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty)); Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_empty, null)); Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_emptyBuilder)); } [Fact] public void FirstOrDefaultEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, null)); } [Fact] public void Last() { Assert.Equal(Enumerable.Last(s_oneElement), ImmutableArrayExtensions.Last(s_oneElement)); Assert.Equal(Enumerable.Last(s_oneElement, i => true), ImmutableArrayExtensions.Last(s_oneElement, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_oneElement, i => false)); Assert.Equal(Enumerable.Last(s_manyElements), ImmutableArrayExtensions.Last(s_manyElements)); Assert.Equal(Enumerable.Last(s_manyElements, i => true), ImmutableArrayExtensions.Last(s_manyElements, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_manyElements, i => false)); Assert.Equal(Enumerable.Last(s_oneElementBuilder), ImmutableArrayExtensions.Last(s_oneElementBuilder)); Assert.Equal(Enumerable.Last(s_manyElementsBuilder), ImmutableArrayExtensions.Last(s_manyElementsBuilder)); } [Fact] public void LastEmpty() { Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(s_empty, null)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_emptyBuilder)); } [Fact] public void LastEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(s_emptyDefault, null)); } [Fact] public void LastOrDefault() { Assert.Equal(Enumerable.LastOrDefault(s_oneElement), ImmutableArrayExtensions.LastOrDefault(s_oneElement)); Assert.Equal(Enumerable.LastOrDefault(s_manyElements), ImmutableArrayExtensions.LastOrDefault(s_manyElements)); foreach (bool result in new[] { true, false }) { Assert.Equal(Enumerable.LastOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.LastOrDefault(s_oneElement, i => result)); Assert.Equal(Enumerable.LastOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.LastOrDefault(s_manyElements, i => result)); } Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_oneElement, null)); Assert.Equal(Enumerable.LastOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.LastOrDefault(s_oneElementBuilder)); Assert.Equal(Enumerable.LastOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.LastOrDefault(s_manyElementsBuilder)); } [Fact] public void LastOrDefaultEmpty() { Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty)); Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_empty, null)); Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_emptyBuilder)); } [Fact] public void LastOrDefaultEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, null)); } [Fact] public void Single() { Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement)); Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => false)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_oneElement, i => false)); } [Fact] public void SingleEmpty() { Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(s_empty, null)); } [Fact] public void SingleEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(s_emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(s_emptyDefault, null)); } [Fact] public void SingleOrDefault() { Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement)); Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => true)); Assert.Equal(Enumerable.SingleOrDefault(s_oneElement, i => false), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => false)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements, i => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(s_oneElement, null)); } [Fact] public void SingleOrDefaultEmpty() { Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty)); Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(s_empty, null)); } [Fact] public void SingleOrDefaultEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, null)); } [Fact] public void ToDictionary() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null, EqualityComparer<int>.Default)); var stringToString = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString(), n => (n * 2).ToString()); Assert.Equal(stringToString.Count, s_manyElements.Length); Assert.Equal("2", stringToString["1"]); Assert.Equal("4", stringToString["2"]); Assert.Equal("6", stringToString["3"]); var stringToInt = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString()); Assert.Equal(stringToString.Count, s_manyElements.Length); Assert.Equal(1, stringToInt["1"]); Assert.Equal(2, stringToInt["2"]); Assert.Equal(3, stringToInt["3"]); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, EqualityComparer<int>.Default)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n, EqualityComparer<int>.Default)); } [Fact] public void ToArray() { Assert.Equal(0, ImmutableArrayExtensions.ToArray(s_empty).Length); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToArray(s_emptyDefault)); Assert.Equal(s_manyElements.ToArray(), ImmutableArrayExtensions.ToArray(s_manyElements)); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Common.IO; using Gallio.Common.Validation; using Gallio.Model.Schema; namespace Gallio.Runner.Projects.Schema { /// <summary> /// Describes a test project in a portable manner for serialization. /// </summary> [Serializable] [XmlRoot("testProject", Namespace = SchemaConstants.XmlNamespace)] [XmlType(Namespace = SchemaConstants.XmlNamespace)] public sealed class TestProjectData : IValidatable { private TestPackageData testPackage; private readonly List<FilterInfo> testFilters; private readonly List<string> testRunnerExtensions; private string reportNameFormat; private string reportDirectory; /// <summary> /// Creates an empty test project. /// </summary> public TestProjectData() { testPackage = new TestPackageData(); testFilters = new List<FilterInfo>(); testRunnerExtensions = new List<string>(); reportNameFormat = TestProject.DefaultReportNameFormat; reportDirectory = TestProject.DefaultReportDirectoryRelativePath; } /// <summary> /// Copies the contents of a test project. /// </summary> /// <param name="source">The source test project.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="source"/> is null.</exception> public TestProjectData(TestProject source) : this() { if (source == null) throw new ArgumentNullException("source"); testPackage = new TestPackageData(source.TestPackage); GenericCollectionUtils.ConvertAndAddAll(source.TestFilters, testFilters, x => x.Copy()); testRunnerExtensions.AddRange(source.TestRunnerExtensionSpecifications); reportNameFormat = source.ReportNameFormat; reportDirectory = source.ReportDirectory; } /// <summary> /// Gets or sets the test package. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> [XmlElement("testPackage", IsNullable = false)] public TestPackageData TestPackage { get { return testPackage; } set { if (value == null) throw new ArgumentNullException("value"); testPackage = value; } } /// <summary> /// Gets a mutable list of named test filters for the project. /// </summary> [XmlArray("testFilters", IsNullable = false)] [XmlArrayItem("testFilter", typeof(FilterInfo), IsNullable = false)] public List<FilterInfo> TestFilters { get { return testFilters; } } /// <summary> /// Gets a mutable list of test runner extensions used by the project. /// </summary> [XmlArray("extensionSpecifications", IsNullable = false)] [XmlArrayItem("extensionSpecification", typeof(string), IsNullable = false)] public List<string> TestRunnerExtensions { get { return testRunnerExtensions; } } /// <summary> /// Gets or sets the folder to save generated reports to. /// </summary> /// <remarks> /// <para> /// Relative to project location, if not absolute. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> [XmlElement("reportDirectory")] public string ReportDirectory { get { return reportDirectory; } set { if (value == null) throw new ArgumentNullException("value"); reportDirectory = value; } } /// <summary> /// Gets or sets the format for the filename of generated reports. /// </summary> /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception> [XmlElement("reportNameFormat")] public string ReportNameFormat { get { return reportNameFormat; } set { if (value == null) throw new ArgumentNullException("value"); reportNameFormat = value; } } /// <summary> /// Initializes a test project with the contents of this structure. /// </summary> /// <param name="testProject">The test project to populate.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="testProject"/> is null.</exception> public void InitializeTestProject(TestProject testProject) { if (testProject == null) throw new ArgumentNullException("testProject"); testPackage.InitializeTestPackage(testProject.TestPackage); GenericCollectionUtils.ForEach(testFilters, x => testProject.AddTestFilter(x)); GenericCollectionUtils.ForEach(testRunnerExtensions, x => testProject.AddTestRunnerExtensionSpecification(x)); testProject.ReportNameFormat = reportNameFormat; testProject.ReportDirectory = reportDirectory; } /// <summary> /// Creates a test project with the contents of this structure. /// </summary> /// <returns>The test project.</returns> public TestProject ToTestProject() { var testProject = new TestProject(); InitializeTestProject(testProject); return testProject; } /// <summary> /// Makes the test project paths relative to the specified base path. /// </summary> /// <param name="basePath">The base path.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="basePath"/> is null.</exception> public void MakeRelativePaths(string basePath) { ApplyPathConversion(basePath, FileUtils.MakeRelativePath); if (TestPackage != null) TestPackage.MakeRelativePaths(basePath); } /// <summary> /// Makes the test project paths absolute given the specified base path. /// </summary> /// <param name="basePath">The base path.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="basePath"/> is null.</exception> public void MakeAbsolutePaths(string basePath) { ApplyPathConversion(basePath, FileUtils.MakeAbsolutePath); if (TestPackage != null) TestPackage.MakeAbsolutePaths(basePath); } private void ApplyPathConversion(string basePath, Func<string, string, string> converter) { if (basePath == null) throw new ArgumentNullException("basePath"); if (reportDirectory != null) reportDirectory = converter(reportDirectory, basePath); } /// <inheritdoc /> public void Validate() { ValidationUtils.ValidateNotNull("testPackage", testPackage); testPackage.Validate(); ValidationUtils.ValidateElementsAreNotNull("testFilters", testFilters); ValidationUtils.ValidateAll(testFilters); ValidationUtils.ValidateElementsAreNotNull("testRunnerExtensions", testRunnerExtensions); ValidationUtils.ValidateNotNull("reportNameFormat", reportNameFormat); ValidationUtils.ValidateNotNull("reportDirectory", reportDirectory); } } }
using System; using UnityEngine; namespace MLAPI.Serialization { public sealed class NetworkSerializer { private readonly NetworkReader m_Reader; private readonly NetworkWriter m_Writer; public NetworkReader Reader => m_Reader; public NetworkWriter Writer => m_Writer; public bool IsReading { get; } public NetworkSerializer(NetworkReader reader) { m_Reader = reader; IsReading = true; } public NetworkSerializer(NetworkWriter writer) { m_Writer = writer; IsReading = false; } public void Serialize(ref bool value) { if (IsReading) value = m_Reader.ReadBool(); else m_Writer.WriteBool(value); } public void Serialize(ref char value) { if (IsReading) value = m_Reader.ReadCharPacked(); else m_Writer.WriteCharPacked(value); } public void Serialize(ref sbyte value) { if (IsReading) value = m_Reader.ReadSByte(); else m_Writer.WriteSByte(value); } public void Serialize(ref byte value) { if (IsReading) value = m_Reader.ReadByteDirect(); else m_Writer.WriteByte(value); } public void Serialize(ref short value) { if (IsReading) value = m_Reader.ReadInt16Packed(); else m_Writer.WriteInt16Packed(value); } public void Serialize(ref ushort value) { if (IsReading) value = m_Reader.ReadUInt16Packed(); else m_Writer.WriteUInt16Packed(value); } public void Serialize(ref int value) { if (IsReading) value = m_Reader.ReadInt32Packed(); else m_Writer.WriteInt32Packed(value); } public void Serialize(ref uint value) { if (IsReading) value = m_Reader.ReadUInt32Packed(); else m_Writer.WriteUInt32Packed(value); } public void Serialize(ref long value) { if (IsReading) value = m_Reader.ReadInt64Packed(); else m_Writer.WriteInt64Packed(value); } public void Serialize(ref ulong value) { if (IsReading) value = m_Reader.ReadUInt64Packed(); else m_Writer.WriteUInt64Packed(value); } public void Serialize(ref float value) { if (IsReading) value = m_Reader.ReadSinglePacked(); else m_Writer.WriteSinglePacked(value); } public void Serialize(ref double value) { if (IsReading) value = m_Reader.ReadDoublePacked(); else m_Writer.WriteDoublePacked(value); } public void Serialize(ref string value) { if (IsReading) { var isSet = m_Reader.ReadBool(); value = isSet ? m_Reader.ReadStringPacked() : null; } else { var isSet = value != null; m_Writer.WriteBool(isSet); if (isSet) { m_Writer.WriteStringPacked(value); } } } public void Serialize(ref Color value) { if (IsReading) value = m_Reader.ReadColorPacked(); else m_Writer.WriteColorPacked(value); } public void Serialize(ref Color32 value) { if (IsReading) value = m_Reader.ReadColor32(); else m_Writer.WriteColor32(value); } public void Serialize(ref Vector2 value) { if (IsReading) value = m_Reader.ReadVector2Packed(); else m_Writer.WriteVector2Packed(value); } public void Serialize(ref Vector3 value) { if (IsReading) value = m_Reader.ReadVector3Packed(); else m_Writer.WriteVector3Packed(value); } public void Serialize(ref Vector4 value) { if (IsReading) value = m_Reader.ReadVector4Packed(); else m_Writer.WriteVector4Packed(value); } public void Serialize(ref Quaternion value) { if (IsReading) value = m_Reader.ReadRotationPacked(); else m_Writer.WriteRotationPacked(value); } public void Serialize(ref Ray value) { if (IsReading) value = m_Reader.ReadRayPacked(); else m_Writer.WriteRayPacked(value); } public void Serialize(ref Ray2D value) { if (IsReading) value = m_Reader.ReadRay2DPacked(); else m_Writer.WriteRay2DPacked(value); } public unsafe void Serialize<TEnum>(ref TEnum value) where TEnum : unmanaged, Enum { if (sizeof(TEnum) == sizeof(int)) { if (IsReading) { int intValue = m_Reader.ReadInt32Packed(); value = *(TEnum*)&intValue; } else { TEnum enumValue = value; m_Writer.WriteInt32Packed(*(int*)&enumValue); } } else if (sizeof(TEnum) == sizeof(byte)) { if (IsReading) { byte intValue = m_Reader.ReadByteDirect(); value = *(TEnum*)&intValue; } else { TEnum enumValue = value; m_Writer.WriteByte(*(byte*)&enumValue); } } else if (sizeof(TEnum) == sizeof(short)) { if (IsReading) { short intValue = m_Reader.ReadInt16Packed(); value = *(TEnum*)&intValue; } else { TEnum enumValue = value; m_Writer.WriteInt16Packed(*(short*)&enumValue); } } else if (sizeof(TEnum) == sizeof(long)) { if (IsReading) { long intValue = m_Reader.ReadInt64Packed(); value = *(TEnum*)&intValue; } else { TEnum enumValue = value; m_Writer.WriteInt64Packed(*(long*)&enumValue); } } else if (IsReading) { value = default; } } public void Serialize(ref bool[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new bool[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadBool(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteBool(array[i]); } } } public void Serialize(ref char[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new char[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadCharPacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteCharPacked(array[i]); } } } public void Serialize(ref sbyte[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new sbyte[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadSByte(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteSByte(array[i]); } } } public void Serialize(ref byte[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new byte[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadByteDirect(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteByte(array[i]); } } } public void Serialize(ref short[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new short[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadInt16Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteInt16Packed(array[i]); } } } public void Serialize(ref ushort[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new ushort[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadUInt16Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteUInt16Packed(array[i]); } } } public void Serialize(ref int[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new int[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadInt32Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteInt32Packed(array[i]); } } } public void Serialize(ref uint[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new uint[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadUInt32Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteUInt32Packed(array[i]); } } } public void Serialize(ref long[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new long[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadInt64Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteInt64Packed(array[i]); } } } public void Serialize(ref ulong[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new ulong[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadUInt64Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteUInt64Packed(array[i]); } } } public void Serialize(ref float[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new float[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadSinglePacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteSinglePacked(array[i]); } } } public void Serialize(ref double[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new double[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadDoublePacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteDoublePacked(array[i]); } } } public void Serialize(ref string[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new string[length] : null; for (var i = 0; i < length; ++i) { var isSet = m_Reader.ReadBool(); array[i] = isSet ? m_Reader.ReadStringPacked() : null; } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { var isSet = array[i] != null; m_Writer.WriteBool(isSet); if (isSet) { m_Writer.WriteStringPacked(array[i]); } } } } public void Serialize(ref Color[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Color[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadColorPacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteColorPacked(array[i]); } } } public void Serialize(ref Color32[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Color32[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadColor32(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteColor32(array[i]); } } } public void Serialize(ref Vector2[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Vector2[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadVector2Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteVector2Packed(array[i]); } } } public void Serialize(ref Vector3[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Vector3[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadVector3Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteVector3Packed(array[i]); } } } public void Serialize(ref Vector4[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Vector4[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadVector4Packed(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteVector4Packed(array[i]); } } } public void Serialize(ref Quaternion[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Quaternion[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadRotationPacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteRotationPacked(array[i]); } } } public void Serialize(ref Ray[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Ray[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadRayPacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteRayPacked(array[i]); } } } public void Serialize(ref Ray2D[] array) { if (IsReading) { var length = m_Reader.ReadInt32Packed(); array = length > -1 ? new Ray2D[length] : null; for (var i = 0; i < length; ++i) { array[i] = m_Reader.ReadRay2DPacked(); } } else { var length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); for (var i = 0; i < length; ++i) { m_Writer.WriteRay2DPacked(array[i]); } } } public unsafe void Serialize<TEnum>(ref TEnum[] array) where TEnum : unmanaged, Enum { int length; if (IsReading) { length = m_Reader.ReadInt32Packed(); array = length > -1 ? new TEnum[length] : null; } else { length = array?.Length ?? -1; m_Writer.WriteInt32Packed(length); } if (sizeof(TEnum) == sizeof(int)) { if (IsReading) { for (var i = 0; i < length; ++i) { int intValue = m_Reader.ReadInt32Packed(); array[i] = *(TEnum*)&intValue; } } else { for (var i = 0; i < length; ++i) { TEnum enumValue = array[i]; m_Writer.WriteInt32Packed(*(int*)&enumValue); } } } else if (sizeof(TEnum) == sizeof(byte)) { if (IsReading) { for (var i = 0; i < length; ++i) { byte intValue = m_Reader.ReadByteDirect(); array[i] = *(TEnum*)&intValue; } } else { for (var i = 0; i < length; ++i) { TEnum enumValue = array[i]; m_Writer.WriteByte(*(byte*)&enumValue); } } } else if (sizeof(TEnum) == sizeof(short)) { if (IsReading) { for (var i = 0; i < length; ++i) { short intValue = m_Reader.ReadInt16Packed(); array[i] = *(TEnum*)&intValue; } } else { for (var i = 0; i < length; ++i) { TEnum enumValue = array[i]; m_Writer.WriteInt16Packed(*(short*)&enumValue); } } } else if (sizeof(TEnum) == sizeof(long)) { if (IsReading) { for (var i = 0; i < length; ++i) { long intValue = m_Reader.ReadInt64Packed(); array[i] = *(TEnum*)&intValue; } } else { for (var i = 0; i < length; ++i) { TEnum enumValue = array[i]; m_Writer.WriteInt64Packed(*(long*)&enumValue); } } } else if (IsReading) { array = default; } } } }
using UnityEngine; //using Windows.Kinect; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System; using System.IO; using ICSharpCode.SharpZipLib.Zip; public class KinectInterop { // constants public static class Constants { // public const int BodyCount = 6; public const int JointCount = 25; public const float MinTimeBetweenSameGestures = 0.0f; public const float PoseCompleteDuration = 1.0f; public const float ClickMaxDistance = 0.05f; public const float ClickStayDuration = 1.5f; } /// Data structures for interfacing C# with the native wrapper [Flags] public enum FrameSource : uint { TypeNone = 0x0, TypeColor = 0x1, TypeInfrared = 0x2, TypeDepth = 0x8, TypeBodyIndex = 0x10, TypeBody = 0x20, TypeAudio = 0x40 } public enum JointType : int { SpineBase = 0, SpineMid = 1, Neck = 2, Head = 3, ShoulderLeft = 4, ElbowLeft = 5, WristLeft = 6, HandLeft = 7, ShoulderRight = 8, ElbowRight = 9, WristRight = 10, HandRight = 11, HipLeft = 12, KneeLeft = 13, AnkleLeft = 14, FootLeft = 15, HipRight = 16, KneeRight = 17, AnkleRight = 18, FootRight = 19, SpineShoulder = 20, HandTipLeft = 21, ThumbLeft = 22, HandTipRight = 23, ThumbRight = 24 //Count = 25 } public static readonly Vector3[] JointBaseDir = { Vector3.zero, Vector3.up, Vector3.up, Vector3.up, Vector3.left, Vector3.left, Vector3.left, Vector3.left, Vector3.right, Vector3.right, Vector3.right, Vector3.right, Vector3.down, Vector3.down, Vector3.down, Vector3.forward, Vector3.down, Vector3.down, Vector3.down, Vector3.forward, Vector3.up, Vector3.left, Vector3.forward, Vector3.right, Vector3.forward }; public enum TrackingState { NotTracked = 0, Inferred = 1, Tracked = 2 } public enum HandState { Unknown = 0, NotTracked = 1, Open = 2, Closed = 3, Lasso = 4 } public enum TrackingConfidence { Low = 0, High = 1 } // [Flags] // public enum ClippedEdges // { // None = 0, // Right = 1, // Left = 2, // Top = 4, // Bottom = 8 // } public enum FaceShapeAnimations : int { JawOpen =0, LipPucker =1, JawSlideRight =2, LipStretcherRight =3, LipStretcherLeft =4, LipCornerPullerLeft =5, LipCornerPullerRight =6, LipCornerDepressorLeft =7, LipCornerDepressorRight =8, LeftcheekPuff =9, RightcheekPuff =10, LefteyeClosed =11, RighteyeClosed =12, RighteyebrowLowerer =13, LefteyebrowLowerer =14, LowerlipDepressorLeft =15, LowerlipDepressorRight =16, } public enum FaceShapeDeformations : int { PCA01 =0, PCA02 =1, PCA03 =2, PCA04 =3, PCA05 =4, PCA06 =5, PCA07 =6, PCA08 =7, PCA09 =8, PCA10 =9, Chin03 =10, Forehead00 =11, Cheeks02 =12, Cheeks01 =13, MouthBag01 =14, MouthBag02 =15, Eyes02 =16, MouthBag03 =17, Forehead04 =18, Nose00 =19, Nose01 =20, Nose02 =21, MouthBag06 =22, MouthBag05 =23, Cheeks00 =24, Mask03 =25, Eyes03 =26, Nose03 =27, Eyes08 =28, MouthBag07 =29, Eyes00 =30, Nose04 =31, Mask04 =32, Chin04 =33, Forehead05 =34, Eyes06 =35, Eyes11 =36, Nose05 =37, Mouth07 =38, Cheeks08 =39, Eyes09 =40, Mask10 =41, Mouth09 =42, Nose07 =43, Nose08 =44, Cheeks07 =45, Mask07 =46, MouthBag09 =47, Nose06 =48, Chin02 =49, Eyes07 =50, Cheeks10 =51, Rim20 =52, Mask22 =53, MouthBag15 =54, Chin01 =55, Cheeks04 =56, Eyes17 =57, Cheeks13 =58, Mouth02 =59, MouthBag12 =60, Mask19 =61, Mask20 =62, Forehead06 =63, Mouth13 =64, Mask25 =65, Chin05 =66, Cheeks20 =67, Nose09 =68, Nose10 =69, MouthBag27 =70, Mouth11 =71, Cheeks14 =72, Eyes16 =73, Mask29 =74, Nose15 =75, Cheeks11 =76, Mouth16 =77, Eyes19 =78, Mouth17 =79, MouthBag36 =80, Mouth15 =81, Cheeks25 =82, Cheeks16 =83, Cheeks18 =84, Rim07 =85, Nose13 =86, Mouth18 =87, Cheeks19 =88, Rim21 =89, Mouth22 =90, Nose18 =91, Nose16 =92, Rim22 =93, } public class SensorData { public DepthSensorInterface sensorInterface; public int bodyCount; public int jointCount; public int colorImageWidth; public int colorImageHeight; public byte[] colorImage; public long lastColorFrameTime = 0; public int depthImageWidth; public int depthImageHeight; public ushort[] depthImage; public long lastDepthFrameTime = 0; public ushort[] infraredImage; public long lastInfraredFrameTime = 0; public byte[] bodyIndexImage; public long lastBodyIndexFrameTime = 0; } public struct SmoothParameters { public float smoothing; public float correction; public float prediction; public float jitterRadius; public float maxDeviationRadius; } public struct JointData { // parameters filled in by the sensor interface public JointType jointType; public TrackingState trackingState; public Vector3 kinectPos; public Vector3 position; public Quaternion orientation; // deprecated // KM calculated parameters public Vector3 direction; public Quaternion normalRotation; public Quaternion mirroredRotation; } public struct BodyData { // parameters filled in by the sensor interface public Int64 liTrackingID; public Vector3 position; public Quaternion orientation; // deprecated public JointData[] joint; // KM calculated parameters public Quaternion normalRotation; public Quaternion mirroredRotation; public Vector3 hipsDirection; public Vector3 shouldersDirection; public float bodyTurnAngle; public Vector3 leftThumbDirection; public Vector3 leftArmDirection; public Vector3 leftThumbForward; //public float leftThumbAngle; public Vector3 rightThumbDirection; public Vector3 rightArmDirection; public Vector3 rightThumbForward; //public float rightThumbAngle; //public Vector3 leftLegDirection; //public Vector3 leftFootDirection; //public Vector3 rightLegDirection; //public Vector3 rightFootDirection; public HandState leftHandState; public TrackingConfidence leftHandConfidence; public HandState rightHandState; public TrackingConfidence rightHandConfidence; public uint dwClippedEdges; public short bIsTracked; public short bIsRestricted; } public struct BodyFrameData { public Int64 liRelativeTime; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.Struct)] public BodyData[] bodyData; public UnityEngine.Vector4 floorClipPlane; public BodyFrameData(int bodyCount, int jointCount) { liRelativeTime = 0; floorClipPlane = UnityEngine.Vector4.zero; bodyData = new BodyData[bodyCount]; for(int i = 0; i < bodyCount; i++) { bodyData[i].joint = new JointData[jointCount]; } } } // initializes the available sensor interfaces public static List<DepthSensorInterface> InitSensorInterfaces(ref bool bNeedRestart) { List<DepthSensorInterface> listInterfaces = new List<DepthSensorInterface>(); var typeInterface = typeof(DepthSensorInterface); Type[] typesAvailable = typeInterface.Assembly.GetTypes(); foreach(Type type in typesAvailable) { if(typeInterface.IsAssignableFrom(type) && type != typeInterface) { DepthSensorInterface sensorInt = null; try { sensorInt = (DepthSensorInterface)Activator.CreateInstance(type); bool bIntNeedRestart = false; if(sensorInt.InitSensorInterface(ref bIntNeedRestart)) { bNeedRestart |= bIntNeedRestart; } else { sensorInt.FreeSensorInterface(); sensorInt = null; continue; } if(sensorInt.GetSensorsCount() <= 0) { sensorInt.FreeSensorInterface(); sensorInt = null; } } catch (Exception) { if(sensorInt != null) { try { sensorInt.FreeSensorInterface(); } catch (Exception) { // do nothing } finally { sensorInt = null; } } } if(sensorInt != null) { listInterfaces.Add(sensorInt); } } } return listInterfaces; } // opens the default sensor and needed readers public static SensorData OpenDefaultSensor(List<DepthSensorInterface> listInterfaces, FrameSource dwFlags, float sensorAngle, bool bUseMultiSource) { SensorData sensorData = null; if(listInterfaces == null) return sensorData; foreach(DepthSensorInterface sensorInt in listInterfaces) { try { if(sensorData == null) { sensorData = sensorInt.OpenDefaultSensor(dwFlags, sensorAngle, bUseMultiSource); if(sensorData != null) { sensorData.sensorInterface = sensorInt; Debug.Log("Interface used: " + sensorInt.GetType().Name); } } else { sensorInt.FreeSensorInterface(); } } catch (Exception ex) { Debug.LogError("Initialization of sensor failed."); Debug.LogError(ex.ToString()); try { sensorInt.FreeSensorInterface(); } catch (Exception) { // do nothing } } } return sensorData; } // closes opened readers and closes the sensor public static void CloseSensor(SensorData sensorData) { if(sensorData != null && sensorData.sensorInterface != null) { sensorData.sensorInterface.CloseSensor(sensorData); } } // invoked periodically to update sensor data, if needed public static bool UpdateSensorData(SensorData sensorData) { bool bResult = false; if(sensorData.sensorInterface != null) { bResult = sensorData.sensorInterface.UpdateSensorData(sensorData); } return bResult; } // returns the mirror joint of the given joint public static JointType GetMirrorJoint(JointType joint) { switch(joint) { case JointType.ShoulderLeft: return JointType.ShoulderRight; case JointType.ElbowLeft: return JointType.ElbowRight; case JointType.WristLeft: return JointType.WristRight; case JointType.HandLeft: return JointType.HandRight; case JointType.ShoulderRight: return JointType.ShoulderLeft; case JointType.ElbowRight: return JointType.ElbowLeft; case JointType.WristRight: return JointType.WristLeft; case JointType.HandRight: return JointType.HandLeft; case JointType.HipLeft: return JointType.HipRight; case JointType.KneeLeft: return JointType.KneeRight; case JointType.AnkleLeft: return JointType.AnkleRight; case JointType.FootLeft: return JointType.FootRight; case JointType.HipRight: return JointType.HipLeft; case JointType.KneeRight: return JointType.KneeLeft; case JointType.AnkleRight: return JointType.AnkleLeft; case JointType.FootRight: return JointType.FootLeft; case JointType.HandTipLeft: return JointType.HandTipRight; case JointType.ThumbLeft: return JointType.ThumbRight; case JointType.HandTipRight: return JointType.HandTipLeft; case JointType.ThumbRight: return JointType.ThumbLeft; } return joint; } // gets new multi source frame public static bool GetMultiSourceFrame(SensorData sensorData) { bool bResult = false; if(sensorData.sensorInterface != null) { bResult = sensorData.sensorInterface.GetMultiSourceFrame(sensorData); } return bResult; } // frees last multi source frame public static void FreeMultiSourceFrame(SensorData sensorData) { if(sensorData.sensorInterface != null) { sensorData.sensorInterface.FreeMultiSourceFrame(sensorData); } } // Polls for new skeleton data public static bool PollBodyFrame(SensorData sensorData, ref BodyFrameData bodyFrame, ref Matrix4x4 kinectToWorld) { bool bNewFrame = false; if(sensorData.sensorInterface != null) { bNewFrame = sensorData.sensorInterface.PollBodyFrame(sensorData, ref bodyFrame, ref kinectToWorld); if(bNewFrame) { for(int i = 0; i < sensorData.bodyCount; i++) { if(bodyFrame.bodyData[i].bIsTracked != 0) { // calculate joint directions for(int j = 0; j < sensorData.jointCount; j++) { if(j == 0) { bodyFrame.bodyData[i].joint[j].direction = Vector3.zero; } else { int jParent = (int)sensorData.sensorInterface.GetParentJoint(bodyFrame.bodyData[i].joint[j].jointType); if(bodyFrame.bodyData[i].joint[j].trackingState != TrackingState.NotTracked && bodyFrame.bodyData[i].joint[jParent].trackingState != TrackingState.NotTracked) { bodyFrame.bodyData[i].joint[j].direction = bodyFrame.bodyData[i].joint[j].position - bodyFrame.bodyData[i].joint[jParent].position; } } } } } } } return bNewFrame; } // Polls for new color frame data public static bool PollColorFrame(SensorData sensorData) { bool bNewFrame = false; if(sensorData.sensorInterface != null) { bNewFrame = sensorData.sensorInterface.PollColorFrame(sensorData); } return bNewFrame; } // Polls for new depth frame data public static bool PollDepthFrame(SensorData sensorData) { bool bNewFrame = false; if(sensorData.sensorInterface != null) { bNewFrame = sensorData.sensorInterface.PollDepthFrame(sensorData); } return bNewFrame; } // Polls for new infrared frame data public static bool PollInfraredFrame(SensorData sensorData) { bool bNewFrame = false; if(sensorData.sensorInterface != null) { bNewFrame = sensorData.sensorInterface.PollInfraredFrame(sensorData); } return bNewFrame; } // returns depth frame coordinates for the given 3d Kinect-space point public static Vector2 MapSpacePointToDepthCoords(SensorData sensorData, Vector3 kinectPos) { Vector2 vPoint = Vector2.zero; if(sensorData.sensorInterface != null) { vPoint = sensorData.sensorInterface.MapSpacePointToDepthCoords(sensorData, kinectPos); } return vPoint; } // returns 3d coordinates for the given depth-map point public static Vector3 MapDepthPointToSpaceCoords(SensorData sensorData, Vector2 depthPos, ushort depthVal) { Vector3 vPoint = Vector3.zero; if(sensorData.sensorInterface != null) { vPoint = sensorData.sensorInterface.MapDepthPointToSpaceCoords(sensorData, depthPos, depthVal); } return vPoint; } // returns color-map coordinates for the given depth point public static Vector2 MapDepthPointToColorCoords(SensorData sensorData, Vector2 depthPos, ushort depthVal) { Vector2 vPoint = Vector2.zero; if(sensorData.sensorInterface != null) { vPoint = sensorData.sensorInterface.MapDepthPointToColorCoords(sensorData, depthPos, depthVal); } return vPoint; } // estimates color-map coordinates for the current depth frame public static bool MapDepthFrameToColorCoords(SensorData sensorData, ref Vector2[] vColorCoords) { bool bResult = false; if(sensorData.sensorInterface != null) { bResult = sensorData.sensorInterface.MapDepthFrameToColorCoords(sensorData, ref vColorCoords); } return bResult; } // draws a line in a texture public static void DrawLine(Texture2D a_Texture, int x1, int y1, int x2, int y2, Color a_Color) { int width = a_Texture.width; int height = a_Texture.height; int dy = y2 - y1; int dx = x2 - x1; int stepy = 1; if (dy < 0) { dy = -dy; stepy = -1; } int stepx = 1; if (dx < 0) { dx = -dx; stepx = -1; } dy <<= 1; dx <<= 1; if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height) for(int x = -1; x <= 1; x++) for(int y = -1; y <= 1; y++) a_Texture.SetPixel(x1 + x, y1 + y, a_Color); if (dx > dy) { int fraction = dy - (dx >> 1); while (x1 != x2) { if (fraction >= 0) { y1 += stepy; fraction -= dx; } x1 += stepx; fraction += dy; if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height) for(int x = -1; x <= 1; x++) for(int y = -1; y <= 1; y++) a_Texture.SetPixel(x1 + x, y1 + y, a_Color); } } else { int fraction = dx - (dy >> 1); while (y1 != y2) { if (fraction >= 0) { x1 += stepx; fraction -= dy; } y1 += stepy; fraction += dx; if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height) for(int x = -1; x <= 1; x++) for(int y = -1; y <= 1; y++) a_Texture.SetPixel(x1 + x, y1 + y, a_Color); } } } // Copy a resource file to the target public static bool CopyResourceFile(string targetFilePath, string resFileName, ref bool bOneCopied, ref bool bAllCopied) { TextAsset textRes = Resources.Load(resFileName, typeof(TextAsset)) as TextAsset; if(textRes == null) { bOneCopied = false; bAllCopied = false; return false; } FileInfo targetFile = new FileInfo(targetFilePath); if(!targetFile.Directory.Exists) { targetFile.Directory.Create(); } if(!targetFile.Exists || targetFile.Length != textRes.bytes.Length) { if(textRes != null) { using (FileStream fileStream = new FileStream (targetFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)) { fileStream.Write(textRes.bytes, 0, textRes.bytes.Length); } bool bFileCopied = File.Exists(targetFilePath); bOneCopied = bOneCopied || bFileCopied; bAllCopied = bAllCopied && bFileCopied; return bFileCopied; } } return false; } // Unzips resource file to the target path public static bool UnzipResourceDirectory(string targetFilePath, string resFileName, string checkForDir) { if(checkForDir != string.Empty && Directory.Exists(checkForDir)) { return false; } TextAsset textRes = Resources.Load(resFileName, typeof(TextAsset)) as TextAsset; if(textRes == null || textRes.bytes.Length == 0) { return false; } // get the resource steam MemoryStream memStream = new MemoryStream(textRes.bytes); using(ZipInputStream s = new ZipInputStream(memStream)) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { //Debug.Log(theEntry.Name); string directoryName = targetFilePath + "/" + Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if(!Directory.Exists(directoryName)) { // create directory Directory.CreateDirectory(directoryName); } if (fileName != string.Empty && !fileName.EndsWith(".meta")) { using (FileStream streamWriter = File.Create(theEntry.Name)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } } // close the resource stream memStream.Close(); return true; } // returns true if the project is running on 64-bit architecture, false if 32-bit public static bool Is64bitArchitecture() { int sizeOfPtr = Marshal.SizeOf(typeof(IntPtr)); return (sizeOfPtr > 4); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; using System.Threading; namespace Microsoft.Build.BuildEngine { internal class Introspector { #region Constructors internal Introspector(Engine parentEngine, ProjectManager projectManager, NodeManager nodeManager) { this.parentEngine = parentEngine; this.projectManager = projectManager; this.nodeManager = nodeManager; this.ignoreTimeout = 0; } #endregion #region Methods /// <summary> /// This method is called when the parent engine doesn't see activity for a preset time period to /// determine if the whole system is making forward progress. In order to that, status is collected /// from every node in the system. If no node is making forward progress then the graph of all the /// inprogress targets is analyzed for cycles. If a cycle is found the appropriate node is instructed /// to break it. If no cause for deadlock can be determined the system is shutdown. /// </summary> /// <returns>New inactivity timeout</returns> internal int DetectDeadlock( int queueCounts, long lastLoopActivity, int currentTimeout) { // Don't try to detect deadlock in single threaded mode or on a child node if (parentEngine.Router.ChildMode || parentEngine.Router.SingleThreadedMode) { return Timeout.Infinite; } // Calculate time since last loop activity TimeSpan timeSinceLastLoopActivity = new TimeSpan(DateTime.Now.Ticks - lastLoopActivity); // If there are items in the queue waiting to be processed or there was loop activity // not so long ago - continue if (queueCounts > 0 || timeSinceLastLoopActivity.TotalMilliseconds < currentTimeout) { return currentTimeout; } if (nodeManager.TaskExecutionModule == null) { return currentTimeout; } // Calculate the time since the last task activity TimeSpan timeSinceLastTEMActivity = new TimeSpan(DateTime.Now.Ticks - nodeManager.TaskExecutionModule.LastTaskActivity()); // If there was not task activity for the whole time period - check with individual nodes // to see if there was activity there if (timeSinceLastTEMActivity.TotalMilliseconds < currentTimeout) { // Increase the timeout since tasks are taking a long time return calculateNewLoopTimeout(currentTimeout); } // Check if we are waiting on an outcome of an operation if ((ignoreTimeout - DateTime.Now.Ticks) > 0) { return currentTimeout; } long requestStartTime = DateTime.Now.Ticks; NodeStatus[] nodeStatus = nodeManager.RequestStatusForNodes(nodeStatusReplyTimeout); long requestDurationTime = DateTime.Now.Ticks - requestStartTime; for (int i = 0; i < nodeStatus.Length; i++) { if (nodeStatus[i] == null) { // A node failed to respond to the request for status. The only option is to shutdown // the build and error out LogOrDumpError("FailedToReceiveChildStatus", i + 1, nodeStatusReplyTimeout); SystemShutdown(); return currentTimeout; } else if (nodeStatus[i].HasExited) { // A node has exited prematurely. The only option is to shutdown LogOrDumpError("ChildExitedPrematurely", i + 1); SystemShutdown(); return currentTimeout; } else if (nodeStatus[i].IsActive) { // Calculate the time since last node activity TimeSpan timeSinceLastNodeTaskActivity = new TimeSpan(nodeStatus[i].TimeSinceLastTaskActivity); TimeSpan timeSinceLastNodeLoopActivity = new TimeSpan(nodeStatus[i].TimeSinceLastLoopActivity); // Check if there was activity on the node within the timeout if (nodeStatus[i].QueueDepth > 0 || timeSinceLastNodeTaskActivity.TotalMilliseconds < currentTimeout || timeSinceLastNodeLoopActivity.TotalMilliseconds < currentTimeout) { // If the time out has been exceeded while one of the nodes was // active lets increase the timeout return calculateNewLoopTimeout(currentTimeout); } } else if (nodeStatus[i].IsLaunchInProgress) { // If there is a node in process of being launched, only the NodeProvider // knows how long that should take so the decision to error out can // only be made by the node provider. return currentTimeout; } } // There was no detected activity within the system for the whole time period. Check // if there is a cycle in the in progress targets TargetCycleDetector cycleDetector = new TargetCycleDetector(parentEngine.LoggingServices, parentEngine.EngineCallback); AddTargetStatesToCycleDetector(nodeStatus, cycleDetector); NodeStatus localStatus = parentEngine.RequestStatus(0); cycleDetector.AddTargetsToGraph(localStatus.StateOfInProgressTargets); if (cycleDetector.FindCycles()) { if (Engine.debugMode) { Console.WriteLine("Breaking cycle between " + cycleDetector.CycleEdgeChild.TargetId.name + " and " + cycleDetector.CycleEdgeParent.TargetId.name); } // A cycle has been detected - it needs to be broken for the build to continue nodeManager.PostCycleNotification(cycleDetector.CycleEdgeChild.TargetId.nodeId, cycleDetector.CycleEdgeChild, cycleDetector.CycleEdgeParent); // Use the amount of time it took us to receive the NodeStatus and buffer it a little because node status is sent via a faster code path ignoreTimeout = DateTime.Now.Ticks + requestDurationTime + (cycleBreakTimeout * TimeSpan.TicksPerMillisecond); return currentTimeout; } // The system doesn't appear to be making progress. Switch to a largest sampling interval. if (currentTimeout != maxLoopTimeout) { return maxLoopTimeout; } // Should make at least two observations before assuming that no forward progress is being made if (previousStatus == null || previousLocalStatus == null || nodeStatus.Length != previousStatus.Length) { previousStatus = nodeStatus; previousLocalStatus = localStatus; return currentTimeout; } // There was some activity between previous and current status checks on the local node if (localStatus.LastLoopActivity != previousLocalStatus.LastLoopActivity || localStatus.LastTaskActivity != previousLocalStatus.LastTaskActivity ) { previousStatus = nodeStatus; previousLocalStatus = localStatus; return currentTimeout; } for (int i = 0; i < nodeStatus.Length; i++) { // There was some activity between previous and current status checks on the child node if (nodeStatus[i].LastTaskActivity != previousStatus[i].LastTaskActivity || nodeStatus[i].LastLoopActivity != previousStatus[i].LastLoopActivity) { previousStatus = nodeStatus; previousLocalStatus = localStatus; return currentTimeout; } } // The system is not making forward progress for an unknown reason. The // only recourse to is to collect as much data as possible and shutdown with // an error message // UNDONE - using logging and resource string to output the state dump GatherNodeInformationForShutdown(nodeStatus, localStatus); SystemShutdown(); return currentTimeout; } /// <summary> /// Logs an error, or if the loggers are not available, writes it to the console /// </summary> private void LogOrDumpError(string resourceName, params object[] args) { if (parentEngine.LoggingServices != null) { parentEngine.LoggingServices.LogError(BuildEventContext.Invalid, new BuildEventFileInfo(String.Empty) /* no project file */, resourceName, args); } else { // Can't log it -- we can only log to the console instead string message = ResourceUtilities.FormatResourceString(resourceName, args); Console.WriteLine(message); } } /// <summary> /// Adds a set of nodeStatus's to the cycle graph /// </summary> private void AddTargetStatesToCycleDetector(NodeStatus[] nodeStatus, TargetCycleDetector cycleDetector) { for (int i = 0; i < nodeStatus.Length; i++) { cycleDetector.AddTargetsToGraph(nodeStatus[i].StateOfInProgressTargets); } } /// <summary> /// The system is not making forward progress for an unknown reason. The /// only recourse to is to collect as much data as possible and shutdown with /// an error message /// </summary> private void GatherNodeInformationForShutdown(NodeStatus[] nodeStatus, NodeStatus localStatus) { for (int i = 0; i < nodeStatus.Length; i++) { TimeSpan timeSinceLastNodeTaskActivity = new TimeSpan(nodeStatus[i].TimeSinceLastTaskActivity); TimeSpan timeSinceLastNodeLoopActivity = new TimeSpan(nodeStatus[i].TimeSinceLastLoopActivity); Console.WriteLine("Status: " + i + " Task Activity " + timeSinceLastNodeTaskActivity.TotalMilliseconds + " Loop Activity " + timeSinceLastNodeLoopActivity.TotalMilliseconds + " Queue depth " + nodeStatus[i].QueueDepth); for (int j = 0; j < nodeStatus[i].StateOfInProgressTargets.Length; j++) { Console.WriteLine(nodeStatus[i].StateOfInProgressTargets[j].ProjectName + ":" + nodeStatus[i].StateOfInProgressTargets[j].TargetId.name); } } Console.WriteLine("Status: LocalNode Task Activity " + localStatus.TimeSinceLastTaskActivity + " Loop Activity " + localStatus.TimeSinceLastLoopActivity + " Queue depth " + localStatus.QueueDepth); for (int j = 0; j < localStatus.StateOfInProgressTargets.Length; j++) { Console.WriteLine(localStatus.StateOfInProgressTargets[j].ProjectName + ":" + localStatus.StateOfInProgressTargets[j].TargetId.name); } parentEngine.Scheduler.DumpState(); } /// <summary> /// This method is called to shutdown the system in case of fatal error /// </summary> internal void SystemShutdown() { ErrorUtilities.LaunchMsBuildDebuggerOnFatalError(); nodeManager.ShutdownNodes(Node.NodeShutdownLevel.ErrorShutdown); } /// <summary> /// This function is called to break the link between two targets that creates a cycle. The link could be /// due to depends/onerror relationship between parent and child. In that case both parent and child are /// on the same node and within the same project. Or the link could be formed by an IBuildEngine callback /// (made such by tasks such as MSBuild or CallTarget) in which case there maybe multiple requests forming /// same link between parent and child. Also in that case parent and child maybe on different nodes and/or in /// different projects. In either case the break is forced by finding the correct builds states and causing /// them to fail. /// </summary> internal void BreakCycle(TargetInProgessState child, TargetInProgessState parent) { ErrorUtilities.VerifyThrow( child.TargetId.nodeId == parentEngine.NodeId, "Expect the child target to be on the node"); Project parentProject = projectManager.GetProject(child.TargetId.projectId); ErrorUtilities.VerifyThrow(parentProject != null, "Expect the parent project to be on the node"); Target childTarget = parentProject.Targets[child.TargetId.name]; List<ProjectBuildState> parentStates = FindConnectingContexts(child, parent, childTarget, childTarget.ExecutionState.GetWaitingBuildContexts(), childTarget.ExecutionState.InitiatingBuildContext); ErrorUtilities.VerifyThrow(parentStates.Count > 0, "Must find at least one matching context"); for (int i = 0; i < parentStates.Count; i++) { parentStates[i].CurrentBuildContextState = ProjectBuildState.BuildContextState.CycleDetected; TaskExecutionContext taskExecutionContext = new TaskExecutionContext(parentProject, childTarget, null, parentStates[i], EngineCallback.invalidEngineHandle, EngineCallback.inProcNode, null); parentEngine.PostTaskOutputUpdates(taskExecutionContext); } } /// <summary> /// Find all the build contexts that connects child to parent. The only time multiple contexts are possible /// is if the connection is formed by an IBuildEngine callback which requests the same target in the /// same project to be build in parallel multiple times. /// </summary> internal List<ProjectBuildState> FindConnectingContexts ( TargetInProgessState child, TargetInProgessState parent, Target childTarget, List<ProjectBuildState> waitingStates, ProjectBuildState initiatingBuildContext ) { List<ProjectBuildState> connectingContexts = new List<ProjectBuildState>(); // Since the there is a cycle formed at the child there must be at least two requests // since the edge between the parent and the child is a backward edge ErrorUtilities.VerifyThrow(waitingStates != null, "There must be a at least two requests at the child"); for (int i = 0; i < waitingStates.Count; i++) { if (child.CheckBuildContextForParentMatch(parentEngine.EngineCallback, parent.TargetId, childTarget, waitingStates[i])) { connectingContexts.Add(waitingStates[i]); } } if (child.CheckBuildContextForParentMatch(parentEngine.EngineCallback, parent.TargetId, childTarget, initiatingBuildContext)) { connectingContexts.Add(initiatingBuildContext); } return connectingContexts; } /// <summary> /// Increase the inactivity time out /// </summary> /// <param name="currentTimeout">current inactivity timeout</param> /// <returns>new inactivity timeout</returns> private int calculateNewLoopTimeout(int currentTimeout) { if (currentTimeout < maxLoopTimeout) { currentTimeout = 2*currentTimeout; } return currentTimeout; } #endregion #region Data private Engine parentEngine; private ProjectManager projectManager; private NodeManager nodeManager; private NodeStatus[] previousStatus; private NodeStatus previousLocalStatus; private long ignoreTimeout; internal const int initialLoopTimeout = 1000; // Start with a 1 sec of inactivity delay before asking for status internal const int cycleBreakTimeout = 5000; // Allow 5 seconds for the cycle break to reach the child node internal const int maxLoopTimeout = 50000; // Allow at most 50 sec of inactivity before asking for status internal const int nodeStatusReplyTimeout = 300000; // Give the node 5 minutes to reply to a status request #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Runtime; using Orleans.Runtime.GrainDirectory; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { public class TestGrain : Grain, ITestGrain { private string label; private ILogger logger; private IDisposable timer; public TestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { if (this.GetPrimaryKeyLong() == -2) throw new ArgumentException("Primary key cannot be -2 for this test case"); label = this.GetPrimaryKeyLong().ToString(); logger.Info("OnActivateAsync"); return base.OnActivateAsync(); } public override Task OnDeactivateAsync() { logger.Info("!!! OnDeactivateAsync"); return base.OnDeactivateAsync(); } public Task<long> GetKey() { return Task.FromResult(this.GetPrimaryKeyLong()); } public Task<string> GetLabel() { return Task.FromResult(label); } public async Task DoLongAction(TimeSpan timespan, string str) { logger.Info("DoLongAction {0} received", str); await Task.Delay(timespan); } public Task SetLabel(string label) { this.label = label; logger.Info("SetLabel {0} received", label); return Task.CompletedTask; } public Task StartTimer() { logger.Info("StartTimer."); timer = base.RegisterTimer(TimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(10)); return Task.CompletedTask; } private Task TimerTick(object data) { logger.Info("TimerTick."); return Task.CompletedTask; } public async Task<Tuple<string, string>> TestRequestContext() { string bar1 = null; RequestContext.Set("jarjar", "binks"); var task = Task.Factory.StartNew(() => { bar1 = (string) RequestContext.Get("jarjar"); logger.Info("bar = {0}.", bar1); }); string bar2 = null; var ac = Task.Factory.StartNew(() => { bar2 = (string) RequestContext.Get("jarjar"); logger.Info("bar = {0}.", bar2); }); await Task.WhenAll(task, ac); return new Tuple<string, string>(bar1, bar2); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<string> GetActivationId() { return Task.FromResult(Data.ActivationId.ToString()); } public Task<ITestGrain> GetGrainReference() { return Task.FromResult(this.AsReference<ITestGrain>()); } public Task<IGrain[]> GetMultipleGrainInterfaces_Array() { var grains = new IGrain[5]; for (var i = 0; i < grains.Length; i++) { grains[i] = GrainFactory.GetGrain<ITestGrain>(i); } return Task.FromResult(grains); } public Task<List<IGrain>> GetMultipleGrainInterfaces_List() { var grains = new IGrain[5]; for (var i = 0; i < grains.Length; i++) { grains[i] = GrainFactory.GetGrain<ITestGrain>(i); } return Task.FromResult(grains.ToList()); } } internal class GuidTestGrain : Grain, IGuidTestGrain { private string label; private ILogger logger; public GuidTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync() { //if (this.GetPrimaryKeyLong() == -2) // throw new ArgumentException("Primary key cannot be -2 for this test case"); label = this.GetPrimaryKey().ToString(); logger.Info("OnActivateAsync"); return Task.CompletedTask; } public Task<Guid> GetKey() { return Task.FromResult(this.GetPrimaryKey()); } public Task<string> GetLabel() { return Task.FromResult(label); } public Task SetLabel(string label) { this.label = label; return Task.CompletedTask; } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<string> GetActivationId() { return Task.FromResult(Data.ActivationId.ToString()); } } internal class OneWayGrain : Grain, IOneWayGrain, ISimpleGrainObserver { private int count; private TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(); private IOneWayGrain other; private Catalog catalog; public OneWayGrain(Catalog catalog) { this.catalog = catalog; } private ILocalGrainDirectory LocalGrainDirectory => this.ServiceProvider.GetRequiredService<ILocalGrainDirectory>(); private ILocalSiloDetails LocalSiloDetails => this.ServiceProvider.GetRequiredService<ILocalSiloDetails>(); public Task Notify() { this.count++; return Task.CompletedTask; } public Task Notify(ISimpleGrainObserver observer) { this.count++; observer.StateChanged(this.count - 1, this.count); return Task.CompletedTask; } public async Task<bool> NotifyOtherGrain(IOneWayGrain otherGrain, ISimpleGrainObserver observer) { var task = otherGrain.Notify(observer); var completedSynchronously = task.Status == TaskStatus.RanToCompletion; await task; return completedSynchronously; } public async Task<IOneWayGrain> GetOtherGrain() { return this.other ?? (this.other = await GetGrainOnOtherSilo()); async Task<IOneWayGrain> GetGrainOnOtherSilo() { while (true) { var candidate = this.GrainFactory.GetGrain<IOneWayGrain>(Guid.NewGuid()); var directorySilo = await candidate.GetPrimaryForGrain(); var thisSilo = await this.GetSiloAddress(); var candidateSilo = await candidate.GetSiloAddress(); if (!directorySilo.Equals(candidateSilo) && !directorySilo.Equals(thisSilo) && !candidateSilo.Equals(thisSilo)) { return candidate; } } } } public Task<string> GetActivationAddress(IGrain grain) { var grainId = ((GrainReference)grain).GrainId; if (this.catalog.FastLookup(grainId, out var addresses)) { return Task.FromResult(addresses.Addresses.Single().ToString()); } return Task.FromResult<string>(null); } public Task NotifyOtherGrain() => this.other.Notify(this.AsReference<ISimpleGrainObserver>()); public Task<int> GetCount() => Task.FromResult(this.count); public Task Deactivate() { this.DeactivateOnIdle(); return Task.CompletedTask; } public Task ThrowsOneWay() { throw new Exception("GET OUT!"); } public Task<SiloAddress> GetSiloAddress() { return Task.FromResult(this.LocalSiloDetails.SiloAddress); } public Task<SiloAddress> GetPrimaryForGrain() { var grainId = (GrainId)this.Identity; var primaryForGrain = this.LocalGrainDirectory.GetPrimaryForGrain(grainId); return Task.FromResult(primaryForGrain); } public void StateChanged(int a, int b) { this.tcs.TrySetResult(0); } } public class CanBeOneWayGrain : Grain, ICanBeOneWayGrain { private int count; public Task Notify() { this.count++; return Task.CompletedTask; } public Task Notify(ISimpleGrainObserver observer) { this.count++; observer.StateChanged(this.count - 1, this.count); return Task.CompletedTask; } public Task<int> GetCount() => Task.FromResult(this.count); public Task Throws() { throw new Exception("GET OUT!"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Provides support for EventSource activities by marking the start and /// end of a particular operation. /// </summary> internal sealed class EventSourceActivity : IDisposable { /// <summary> /// Initializes a new instance of the EventSourceActivity class that /// is attached to the specified event source. The new activity will /// not be attached to any related (parent) activity. /// The activity is created in the Initialized state. /// </summary> /// <param name="eventSource"> /// The event source to which the activity information is written. /// </param> public EventSourceActivity(EventSource eventSource) { if (eventSource == null) throw new ArgumentNullException(nameof(eventSource)); this.eventSource = eventSource; } /// <summary> /// You can make an activity out of just an EventSource. /// </summary> public static implicit operator EventSourceActivity(EventSource eventSource) { return new EventSourceActivity(eventSource); } /* Properties */ /// <summary> /// Gets the event source to which this activity writes events. /// </summary> public EventSource EventSource { get { return this.eventSource; } } /// <summary> /// Gets this activity's unique identifier, or the default Guid if the /// event source was disabled when the activity was initialized. /// </summary> public Guid Id { get { return this.activityId; } } #if false // don't expose RelatedActivityId unless there is a need. /// <summary> /// Gets the unique identifier of this activity's related (parent) /// activity. /// </summary> public Guid RelatedId { get { return this.relatedActivityId; } } #endif /// <summary> /// Writes a Start event with the specified name and data. If the start event is not active (because the provider /// is not on or keyword-level indicates the event is off, then the returned activity is simply the 'this' pointer /// and it is effectively like start did not get called. /// /// A new activityID GUID is generated and the returned /// EventSourceActivity remembers this activity and will mark every event (including the start stop and any writes) /// with this activityID. In addition the Start activity will log a 'relatedActivityID' that was the activity /// ID before the start event. This way event processors can form a linked list of all the activities that /// caused this one (directly or indirectly). /// </summary> /// <param name="eventName"> /// The name to use for the event. It is strongly suggested that this name end in 'Start' (e.g. DownloadStart). /// If you do this, then the Stop() method will automatically replace the 'Start' suffix with a 'Stop' suffix. /// </param> /// <param name="options">Allow options (keywords, level) to be set for the write associated with this start /// These will also be used for the stop event.</param> /// <param name="data">The data to include in the event.</param> public EventSourceActivity Start<T>(string? eventName, EventSourceOptions options, T data) { return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) Data payload is empty. /// </summary> public EventSourceActivity Start(string? eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data). Data payload is empty. /// </summary> public EventSourceActivity Start(string? eventName, EventSourceOptions options) { var data = new EmptyStruct(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords /// and level==Info) /// </summary> public EventSourceActivity Start<T>(string? eventName, T data) { var options = new EventSourceOptions(); return this.Start(eventName, ref options, ref data); } /// <summary> /// Writes a Stop event with the specified data, and sets the activity /// to the Stopped state. The name is determined by the eventName used in Start. /// If that Start event name is suffixed with 'Start' that is removed, and regardless /// 'Stop' is appended to the result to form the Stop event name. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="data">The data to include in the event.</param> public void Stop<T>(T data) { this.Stop(null, ref data); } /// <summary> /// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop') /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// </summary> public void Stop<T>(string? eventName) { var data = new EmptyStruct(); this.Stop(eventName, ref data); } /// <summary> /// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop') /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that /// you start with the same prefix used for the start event and you end with the 'Stop' suffix. /// </summary> public void Stop<T>(string? eventName, T data) { this.Stop(eventName, ref data); } /// <summary> /// Writes an event associated with this activity to the eventSource associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. If null, the name is determined from /// data's type. /// </param> /// <param name="options"> /// The options to use for the event. /// </param> /// <param name="data">The data to include in the event.</param> public void Write<T>(string? eventName, EventSourceOptions options, T data) { this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes an event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. If null, the name is determined from /// data's type. /// </param> /// <param name="data">The data to include in the event.</param> public void Write<T>(string? eventName, T data) { var options = new EventSourceOptions(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes a trivial event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. Must not be null. /// </param> /// <param name="options"> /// The options to use for the event. /// </param> public void Write(string? eventName, EventSourceOptions options) { var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes a trivial event associated with this activity. /// May only be called when the activity is in the Started state. /// </summary> /// <param name="eventName"> /// The name to use for the event. Must not be null. /// </param> public void Write(string? eventName) { var options = new EventSourceOptions(); var data = new EmptyStruct(); this.Write(this.eventSource, eventName, ref options, ref data); } /// <summary> /// Writes an event to a arbitrary eventSource stamped with the activity ID of this activity. /// </summary> public void Write<T>(EventSource source, string? eventName, EventSourceOptions options, T data) { this.Write(source, eventName, ref options, ref data); } /// <summary> /// Releases any unmanaged resources associated with this object. /// If the activity is in the Started state, calls Stop(). /// </summary> public void Dispose() { if (this.state == State.Started) { var data = new EmptyStruct(); this.Stop(null, ref data); } } #region private private EventSourceActivity Start<T>(string? eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // If the source is not on at all, then we don't need to do anything and we can simply return ourselves. if (!this.eventSource.IsEnabled()) return this; var newActivity = new EventSourceActivity(eventSource); if (!this.eventSource.IsEnabled(options.Level, options.Keywords)) { // newActivity.relatedActivityId = this.Id; Guid relatedActivityId = this.Id; newActivity.activityId = Guid.NewGuid(); newActivity.startStopOptions = options; newActivity.eventName = eventName; newActivity.startStopOptions.Opcode = EventOpcode.Start; this.eventSource.Write(eventName, ref newActivity.startStopOptions, ref newActivity.activityId, ref relatedActivityId, ref data); } else { // If we are not active, we don't set the eventName, which basically also turns off the Stop event as well. newActivity.activityId = this.Id; } return newActivity; } private void Write<T>(EventSource eventSource, string? eventName, ref EventSourceOptions options, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // Write after stop. if (eventName == null) throw new ArgumentNullException(); eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data); } private void Stop<T>(string? eventName, ref T data) { if (this.state != State.Started) throw new InvalidOperationException(); // If start was not fired, then stop isn't as well. if (!StartEventWasFired) return; Debug.Assert(this.eventName != null); this.state = State.Stopped; if (eventName == null) { eventName = this.eventName; if (eventName.EndsWith("Start")) eventName = eventName.Substring(0, eventName.Length - 5); eventName = eventName + "Stop"; } this.startStopOptions.Opcode = EventOpcode.Stop; this.eventSource.Write(eventName, ref this.startStopOptions, ref this.activityId, ref s_empty, ref data); } private enum State { Started, Stopped } /// <summary> /// If eventName is non-null then we logged a start event /// </summary> private bool StartEventWasFired { get { return eventName != null; } } private readonly EventSource eventSource; private EventSourceOptions startStopOptions; internal Guid activityId; // internal Guid relatedActivityId; private State state; private string? eventName; internal static Guid s_empty; #endregion } }
using Akka.TestKit.Xunit2; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.UnitTests.Extensions; using Neo.VM; using Neo.VM.Types; using System.Linq; using Array = System.Array; namespace Neo.UnitTests.SmartContract { [TestClass] public partial class UT_Syscalls : TestKit { [TestMethod] public void System_Blockchain_GetBlock() { var tx = new Transaction() { Script = new byte[] { 0x01 }, Attributes = Array.Empty<TransactionAttribute>(), Signers = Array.Empty<Signer>(), NetworkFee = 0x02, SystemFee = 0x03, Nonce = 0x04, ValidUntilBlock = 0x05, Version = 0x06, Witnesses = new Witness[] { new Witness() { VerificationScript = new byte[] { 0x07 } } }, }; var block = new TrimmedBlock() { Header = new Header { Index = 0, Timestamp = 2, Witness = new Witness() { InvocationScript = Array.Empty<byte>(), VerificationScript = Array.Empty<byte>() }, PrevHash = UInt256.Zero, MerkleRoot = UInt256.Zero, PrimaryIndex = 1, NextConsensus = UInt160.Zero, }, Hashes = new[] { tx.Hash } }; var snapshot = TestBlockchain.GetTestSnapshot(); using ScriptBuilder script = new(); script.EmitDynamicCall(NativeContract.Ledger.Hash, "getBlock", block.Hash.ToArray()); // Without block var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, settings: TestBlockchain.TheNeoSystem.Settings); engine.LoadScript(script.ToArray()); Assert.AreEqual(engine.Execute(), VMState.HALT); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Peek().IsNull); // Not traceable block const byte Prefix_Transaction = 11; const byte Prefix_CurrentBlock = 12; var height = snapshot[NativeContract.Ledger.CreateStorageKey(Prefix_CurrentBlock)].GetInteroperable<HashIndexState>(); height.Index = block.Index + ProtocolSettings.Default.MaxTraceableBlocks; UT_SmartContractHelper.BlocksAdd(snapshot, block.Hash, block); snapshot.Add(NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, tx.Hash), new StorageItem(new TransactionState { BlockIndex = block.Index, Transaction = tx })); engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, settings: TestBlockchain.TheNeoSystem.Settings); engine.LoadScript(script.ToArray()); Assert.AreEqual(engine.Execute(), VMState.HALT); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsTrue(engine.ResultStack.Peek().IsNull); // With block height.Index = block.Index; engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, settings: TestBlockchain.TheNeoSystem.Settings); engine.LoadScript(script.ToArray()); Assert.AreEqual(engine.Execute(), VMState.HALT); Assert.AreEqual(1, engine.ResultStack.Count); var array = engine.ResultStack.Pop<VM.Types.Array>(); Assert.AreEqual(block.Hash, new UInt256(array[0].GetSpan())); } [TestMethod] public void System_ExecutionEngine_GetScriptContainer() { var snapshot = TestBlockchain.GetTestSnapshot(); using ScriptBuilder script = new(); script.EmitSysCall(ApplicationEngine.System_Runtime_GetScriptContainer); // Without tx var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); engine.LoadScript(script.ToArray()); Assert.AreEqual(engine.Execute(), VMState.FAULT); Assert.AreEqual(0, engine.ResultStack.Count); // With tx var tx = new Transaction() { Script = new byte[] { 0x01 }, Signers = new Signer[] { new Signer() { Account = UInt160.Zero, Scopes = WitnessScope.None } }, Attributes = Array.Empty<TransactionAttribute>(), NetworkFee = 0x02, SystemFee = 0x03, Nonce = 0x04, ValidUntilBlock = 0x05, Version = 0x06, Witnesses = new Witness[] { new Witness() { VerificationScript = new byte[] { 0x07 } } }, }; engine = ApplicationEngine.Create(TriggerType.Application, tx, snapshot); engine.LoadScript(script.ToArray()); Assert.AreEqual(engine.Execute(), VMState.HALT); Assert.AreEqual(1, engine.ResultStack.Count); var array = engine.ResultStack.Pop<VM.Types.Array>(); Assert.AreEqual(tx.Hash, new UInt256(array[0].GetSpan())); } [TestMethod] public void System_Runtime_GasLeft() { var snapshot = TestBlockchain.GetTestSnapshot(); using (var script = new ScriptBuilder()) { script.Emit(OpCode.NOP); script.EmitSysCall(ApplicationEngine.System_Runtime_GasLeft); script.Emit(OpCode.NOP); script.EmitSysCall(ApplicationEngine.System_Runtime_GasLeft); script.Emit(OpCode.NOP); script.Emit(OpCode.NOP); script.Emit(OpCode.NOP); script.EmitSysCall(ApplicationEngine.System_Runtime_GasLeft); // Execute var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, gas: 100_000_000); engine.LoadScript(script.ToArray()); Assert.AreEqual(engine.Execute(), VMState.HALT); // Check the results CollectionAssert.AreEqual ( engine.ResultStack.Select(u => (int)u.GetInteger()).ToArray(), new int[] { 99_999_490, 99_998_980, 99_998_410 } ); } // Check test mode using (var script = new ScriptBuilder()) { script.EmitSysCall(ApplicationEngine.System_Runtime_GasLeft); // Execute var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); engine.LoadScript(script.ToArray()); // Check the results Assert.AreEqual(engine.Execute(), VMState.HALT); Assert.AreEqual(1, engine.ResultStack.Count); Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(Integer)); Assert.AreEqual(1999999520, engine.ResultStack.Pop().GetInteger()); } } [TestMethod] public void System_Runtime_GetInvocationCounter() { ContractState contractA, contractB, contractC; var snapshot = TestBlockchain.GetTestSnapshot(); // Create dummy contracts using (var script = new ScriptBuilder()) { script.EmitSysCall(ApplicationEngine.System_Runtime_GetInvocationCounter); contractA = new ContractState() { Nef = new NefFile { Script = new byte[] { (byte)OpCode.DROP, (byte)OpCode.DROP }.Concat(script.ToArray()).ToArray() } }; contractB = new ContractState() { Nef = new NefFile { Script = new byte[] { (byte)OpCode.DROP, (byte)OpCode.DROP, (byte)OpCode.NOP }.Concat(script.ToArray()).ToArray() } }; contractC = new ContractState() { Nef = new NefFile { Script = new byte[] { (byte)OpCode.DROP, (byte)OpCode.DROP, (byte)OpCode.NOP, (byte)OpCode.NOP }.Concat(script.ToArray()).ToArray() } }; contractA.Hash = contractA.Script.ToScriptHash(); contractB.Hash = contractB.Script.ToScriptHash(); contractC.Hash = contractC.Script.ToScriptHash(); // Init A,B,C contracts // First two drops is for drop method and arguments snapshot.DeleteContract(contractA.Hash); snapshot.DeleteContract(contractB.Hash); snapshot.DeleteContract(contractC.Hash); contractA.Manifest = TestUtils.CreateManifest("dummyMain", ContractParameterType.Any, ContractParameterType.String, ContractParameterType.Integer); contractB.Manifest = TestUtils.CreateManifest("dummyMain", ContractParameterType.Any, ContractParameterType.String, ContractParameterType.Integer); contractC.Manifest = TestUtils.CreateManifest("dummyMain", ContractParameterType.Any, ContractParameterType.String, ContractParameterType.Integer); snapshot.AddContract(contractA.Hash, contractA); snapshot.AddContract(contractB.Hash, contractB); snapshot.AddContract(contractC.Hash, contractC); } // Call A,B,B,C using (var script = new ScriptBuilder()) { script.EmitDynamicCall(contractA.Hash, "dummyMain", "0", 1); script.EmitDynamicCall(contractB.Hash, "dummyMain", "0", 1); script.EmitDynamicCall(contractB.Hash, "dummyMain", "0", 1); script.EmitDynamicCall(contractC.Hash, "dummyMain", "0", 1); // Execute var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot); engine.LoadScript(script.ToArray()); Assert.AreEqual(VMState.HALT, engine.Execute()); // Check the results CollectionAssert.AreEqual ( engine.ResultStack.Select(u => (int)u.GetInteger()).ToArray(), new int[] { 1, /* A */ 1, /* B */ 2, /* B */ 1 /* C */ } ); } } } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Drawing; using System.Windows.Forms; namespace Sce.Sled.Shared.Controls { /// <summary> /// Collapsible GroupBox Control /// </summary> public class SledCollapsibleGroupBox : GroupBox { /// <summary> /// Constructor /// </summary> public SledCollapsibleGroupBox() { m_btn = new Button { Location = new Point(0, 0), Size = new Size(BtnWidth, BtnHeight) }; m_btn.Paint += BtnPaint; m_btn.Click += BtnClick; m_btnFormat = new StringFormat {Alignment = StringAlignment.Center}; Controls.Add(m_btn); } /// <summary> /// Get or set Text property /// </summary> public override string Text { get { return base.Text; } set { // In DesignMode don't add the extra padding. It messes up things // when the app is run live (ie. it will have extra padding). base.Text = DesignMode ? value : value.Insert(0, PaddingString); } } /// <summary> /// Expand the GroupBox /// </summary> public void Expand() { if (IsExpanded) return; // Resize GroupBox Height = m_iSavedHeight; // Show all controls in the GroupBox foreach (Control ctrl in Controls) { if (ctrl == m_btn) continue; ctrl.Visible = true; } // Fire expanded event var handler = ExpandedEvent; if (handler != null) handler(this, EventArgs.Empty); // Toggle state & force redraw m_bExpanded = !m_bExpanded; m_btn.Invalidate(); } /// <summary> /// Collapse the GroupBox /// </summary> public void Collapse() { if (IsCollapsed) return; // Hide all controls in the GroupBox foreach (Control ctrl in Controls) { if (ctrl == m_btn) continue; ctrl.Visible = false; } // Resize GroupBox m_iSavedHeight = Height; m_iLastHeight = m_iSavedHeight - CollapseHeight; Height = CollapseHeight; // Fire collapsed event var handler = CollapsedEvent; if (handler != null) handler(this, EventArgs.Empty); // Toggle state & force redraw m_bExpanded = !m_bExpanded; m_btn.Invalidate(); } /// <summary> /// Gets whether the control is collapsed or not /// </summary> public bool IsCollapsed { get { return !m_bExpanded; } } /// <summary> /// Get whether the control is expanded or not /// </summary> public bool IsExpanded { get { return m_bExpanded; } } /// <summary> /// Get the last height of the form /// </summary> public int LastHeight { get { return m_iLastHeight; } } /// <summary> /// Event triggered when control is collapsed /// </summary> public event EventHandler CollapsedEvent; /// <summary> /// Event triggered when control is expanded /// </summary> public event EventHandler ExpandedEvent; /// <summary> /// Disposes resources</summary> /// <param name="disposing">If true, then Dispose() called this method and managed resources should /// be released in addition to unmanaged resources. If false, then the finalizer called this method /// and no managed objects should be called and only unmanaged resources should be released.</param> protected override void Dispose(bool disposing) { if (disposing) { if (m_btn != null) { m_btn.Dispose(); m_btn = null; } if (m_btnFormat != null) { m_btnFormat.Dispose(); m_btnFormat = null; } } base.Dispose(disposing); } /// <summary> /// Draw plus or minus on button /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Paint event arguments</param> private void BtnPaint(object sender, PaintEventArgs e) { using (var brush = new SolidBrush(ForeColor)) { e.Graphics.DrawString( m_bExpanded ? "-" : "+", Font, brush, new RectangleF(0.0f, 0.0f, m_btn.Width, m_btn.Height), m_btnFormat); } } /// <summary> /// Collapse or expand the GroupBox /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event arguments</param> private void BtnClick(object sender, EventArgs e) { if (IsExpanded) Collapse(); else Expand(); } private Button m_btn; private StringFormat m_btnFormat; private bool m_bExpanded = true; private int m_iSavedHeight; private int m_iLastHeight; private const string PaddingString = " "; private const int CollapseHeight = 24; private const int BtnWidth = 16; private const int BtnHeight = 16; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Microsoft.WSMan.Management { /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsLifecycle.Invoke, "WSManAction", DefaultParameterSetName = "URI", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141446")] public class InvokeWSManActionCommand : AuthenticatingWSManCommand, IDisposable { /// <summary> /// The following is the definition of the input parameter "Action". /// Indicates the method which needs to be executed on the management object /// specified by the ResourceURI and selectors. /// </summary> [Parameter(Mandatory = true, Position = 1)] [ValidateNotNullOrEmpty] public string Action { get { return action; } set { action = value; } } private string action; /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public string ApplicationName { get { return applicationname; } set { applicationname = value; } } private string applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public string ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) { computername = "localhost"; } } } private string computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] [Alias("CURI", "CU")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "FilePath". /// Updates the management resource specified by the ResourceURI and SelectorSet /// via this input file. /// </summary> [Parameter] [Alias("Path")] [ValidateNotNullOrEmpty] public string FilePath { get { return filepath; } set { filepath = value; } } private string filepath; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hashtable and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are are more than 1 instance of the resource /// class. /// </summary> [Parameter(Position = 2, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This hashtable can /// be created using New-WSManSessionOption. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; /// <summary> /// The following is the definition of the input parameter "ValueSet". /// ValueSet is a hahs table which helps to modify resource represented by the /// ResourceURI and SelectorSet. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable ValueSet { get { return valueset; } set { valueset = value; } } private Hashtable valueset; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Alias("ruri")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; private WSManHelper helper; IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); IWSManSession m_session = null; string connectionStr = string.Empty; /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { helper = new WSManHelper(this); helper.WSManOp = "invoke"; // create the connection string connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { // create the resourcelocator object IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); // create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, action); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); string resultXml = m_session.Invoke(action, m_resource, input, 0); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); } finally { if (!string.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!string.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } } #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { // CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void EndProcessing() { // WSManHelper helper = new WSManHelper(); helper.CleanUp(); } } }
#if DNX451 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using OmniSharp.Models; using OmniSharp.Roslyn.CSharp.Services.CodeActions; using OmniSharp.Services; namespace OmniSharp { public class FixUsingsWorker { private OmnisharpWorkspace _workspace; private Document _document; private SemanticModel _semanticModel; public async Task<FixUsingsResponse> FixUsings(OmnisharpWorkspace workspace, IEnumerable<ICodeActionProvider> codeActionProviders, Document document) { _workspace = workspace; _document = document; _semanticModel = await document.GetSemanticModelAsync(); await AddMissingUsings(codeActionProviders); await RemoveUsings(codeActionProviders); await SortUsings(); await TryAddLinqQuerySyntax(); var ambiguous = await GetAmbiguousUsings(codeActionProviders); var response = new FixUsingsResponse(); response.AmbiguousResults = ambiguous; return response; } private async Task<List<QuickFix>> GetAmbiguousUsings(IEnumerable<ICodeActionProvider> codeActionProviders) { var ambiguousNodes = new List<SimpleNameSyntax>(); var ambiguous = new List<QuickFix>(); var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot(); var nodes = syntaxNode.DescendantNodes() .OfType<SimpleNameSyntax>() .Where(x => _semanticModel.GetSymbolInfo(x).Symbol == null && !ambiguousNodes.Contains(x)).ToList(); foreach (var node in nodes) { var pointDiagnostics = await GetPointDiagnostics(node.Identifier.Span, new List<string>() { "CS0246", "CS1061", "CS0103" }); if (pointDiagnostics.Any()) { var pointdiagfirst = pointDiagnostics.First().Location.SourceSpan; if (pointDiagnostics.Any(d => d.Location.SourceSpan != pointdiagfirst)) { continue; } var usingOperations = await GetUsingActions(codeActionProviders, pointDiagnostics, "using"); if (usingOperations.Count() > 1) { //More than one operation - ambiguous ambiguousNodes.Add(node); var unresolvedText = node.Identifier.ValueText; var unresolvedLocation = node.GetLocation().GetLineSpan().StartLinePosition; ambiguous.Add(new QuickFix { Line = unresolvedLocation.Line + 1, Column = unresolvedLocation.Character + 1, FileName = _document.FilePath, Text = "`" + unresolvedText + "`" + " is ambiguous" }); } } } return ambiguous; } private async Task AddMissingUsings(IEnumerable<ICodeActionProvider> codeActionProviders) { bool processMore = true; while (processMore) { bool updated = false; var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot(); var nodes = syntaxNode.DescendantNodes() .OfType<SimpleNameSyntax>() .Where(x => _semanticModel.GetSymbolInfo(x).Symbol == null).ToList(); foreach (var node in nodes) { var pointDiagnostics = await GetPointDiagnostics(node.Identifier.Span, new List<string>() { "CS0246", "CS1061", "CS0103" }); if (pointDiagnostics.Any()) { var pointdiagfirst = pointDiagnostics.First().Location.SourceSpan; if (pointDiagnostics.Any(d => d.Location.SourceSpan != pointdiagfirst)) { continue; } var usingOperations = await GetUsingActions(codeActionProviders, pointDiagnostics, "using"); if (usingOperations.Count() == 1) { //Only one operation - apply it usingOperations.Single().Apply(_workspace, CancellationToken.None); updated = true; } } } processMore = updated; } return; } private async Task RemoveUsings(IEnumerable<ICodeActionProvider> codeActionProviders) { //Remove unneccessary usings var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot(); var nodes = syntaxNode.DescendantNodes().Where(x => x is UsingDirectiveSyntax); foreach (var node in nodes) { var sourceText = (await _document.GetTextAsync()); var actions = new List<CodeAction>(); var pointDiagnostics = await GetPointDiagnostics(node.Span, new List<string>() { "CS0105", "CS8019" }); if (pointDiagnostics.Any()) { var pointdiagfirst = pointDiagnostics.First().Location.SourceSpan; if (pointDiagnostics.Any(d => d.Location.SourceSpan != pointdiagfirst)) { continue; } var usingActions = await GetUsingActions(codeActionProviders, pointDiagnostics, "Remove Unnecessary Usings"); foreach (var codeOperation in usingActions) { if (codeOperation != null) { codeOperation.Apply(_workspace, CancellationToken.None); } } } } return; } private async Task SortUsings() { //Sort usings var nRefactoryProvider = new NRefactoryCodeActionProvider(); var sortActions = new List<CodeAction>(); var refactoringContext = await GetRefactoringContext(_document, sortActions); if (refactoringContext != null) { var sortUsingsAction = nRefactoryProvider.Refactorings .First(r => r is ICSharpCode.NRefactory6.CSharp.Refactoring.SortUsingsAction); await sortUsingsAction.ComputeRefactoringsAsync(refactoringContext.Value); foreach (var action in sortActions) { var operations = await action.GetOperationsAsync(CancellationToken.None).ConfigureAwait(false); if (operations != null) { foreach (var codeOperation in operations) { if (codeOperation != null) { codeOperation.Apply(_workspace, CancellationToken.None); } } } } } } private async Task TryAddLinqQuerySyntax() { var fileName = _document.FilePath; var syntaxNode = (await _document.GetSyntaxTreeAsync()).GetRoot(); var compilationUnitSyntax = (CompilationUnitSyntax)syntaxNode; var usings = GetUsings(syntaxNode); if (HasLinqQuerySyntax(_semanticModel, syntaxNode) && !usings.Contains("using System.Linq;")) { var linqName = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Linq")); var linq = SyntaxFactory.UsingDirective(linqName).NormalizeWhitespace() .WithTrailingTrivia(SyntaxFactory.Whitespace(Environment.NewLine)); var oldSolution = _workspace.CurrentSolution; _document = _document.WithSyntaxRoot(compilationUnitSyntax.AddUsings(linq)); var newDocText = await _document.GetTextAsync(); var newSolution = oldSolution.WithDocumentText(_document.Id, newDocText); _workspace.TryApplyChanges(newSolution); _semanticModel = await _document.GetSemanticModelAsync(); } } private static async Task<CodeRefactoringContext?> GetRefactoringContext(Document document, List<CodeAction> actionsDestination) { var firstUsing = (await document.GetSyntaxTreeAsync()).GetRoot().DescendantNodes().FirstOrDefault(n => n is UsingDirectiveSyntax); if (firstUsing == null) { return null; } var location = firstUsing.GetLocation().SourceSpan; return new CodeRefactoringContext(document, location, (a) => actionsDestination.Add(a), CancellationToken.None); } private async Task<IEnumerable<CodeActionOperation>> GetUsingActions(IEnumerable<ICodeActionProvider> codeActionProviders, ImmutableArray<Diagnostic> pointDiagnostics, string actionPrefix) { var actions = new List<CodeAction>(); var context = new CodeFixContext(_document, pointDiagnostics.First().Location.SourceSpan, pointDiagnostics, (a, d) => actions.Add(a), CancellationToken.None); var providers = codeActionProviders.SelectMany(x => x.CodeFixes); //Disable await warning since we dont need the result of the call. Else we need to use a throwaway variable. #pragma warning disable 4014 foreach (var provider in providers) { provider.RegisterCodeFixesAsync(context); } #pragma warning restore 4014 var tasks = actions.Where(a => a.Title.StartsWith(actionPrefix)) .Select(async a => await a.GetOperationsAsync(CancellationToken.None)).ToList(); return (await Task.WhenAll(tasks)).SelectMany(x => x); } private static HashSet<string> GetUsings(SyntaxNode root) { var usings = root.DescendantNodes().OfType<UsingDirectiveSyntax>().Select(u => u.ToString().Trim()); return new HashSet<string>(usings); } private async Task<ImmutableArray<Diagnostic>> GetPointDiagnostics(TextSpan location, List<string> diagnosticIds) { _document = _workspace.GetDocument(_document.FilePath); _semanticModel = await _document.GetSemanticModelAsync(); var diagnostics = _semanticModel.GetDiagnostics(); //Restrict diagnostics only to missing usings return diagnostics.Where(d => d.Location.SourceSpan.Contains(location) && diagnosticIds.Contains(d.Id)).ToImmutableArray(); } private bool HasLinqQuerySyntax(SemanticModel semanticModel, SyntaxNode syntaxNode) { return syntaxNode.DescendantNodes() .Any(x => x.Kind() == SyntaxKind.QueryExpression || x.Kind() == SyntaxKind.QueryBody || x.Kind() == SyntaxKind.FromClause || x.Kind() == SyntaxKind.LetClause || x.Kind() == SyntaxKind.JoinClause || x.Kind() == SyntaxKind.JoinClause || x.Kind() == SyntaxKind.JoinIntoClause || x.Kind() == SyntaxKind.WhereClause || x.Kind() == SyntaxKind.OrderByClause || x.Kind() == SyntaxKind.AscendingOrdering || x.Kind() == SyntaxKind.DescendingOrdering || x.Kind() == SyntaxKind.SelectClause || x.Kind() == SyntaxKind.GroupClause || x.Kind() == SyntaxKind.QueryContinuation ); } } } #endif
--- src/System.Net.Http/src/SR.cs.orig 2016-04-26 19:33:55.922338000 -0400 +++ src/System.Net.Http/src/SR.cs 2016-04-26 19:34:36.495649000 -0400 @@ -0,0 +1,766 @@ +using System; +using System.Resources; + +namespace FxResources.System.Net.Http +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.Net.Http.SR"; + + internal static string net_http_unix_handler_disposed + { + get + { + return GetResourceString("net_http_unix_handler_disposed", null); + } + } + + internal static string net_http_unix_invalid_certcallback_option + { + get + { + return GetResourceString("net_http_unix_invalid_certcallback_option", null); + } + } + + internal static string net_http_response_headers_exceeded_length + { + get + { + return GetResourceString("net_http_response_headers_exceeded_length", null); + } + } + + internal static String net_http_buffer_insufficient_length + { + get + { + return SR.GetResourceString("net_http_buffer_insufficient_length", null); + } + } + + internal static String ArgumentOutOfRange_FileLengthTooBig + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_FileLengthTooBig", null); + } + } + + internal static String event_ClientSendCompleted + { + get + { + return SR.GetResourceString("event_ClientSendCompleted", null); + } + } + + internal static String event_ContentNull + { + get + { + return SR.GetResourceString("event_ContentNull", null); + } + } + + internal static String event_HeadersInvalidValue + { + get + { + return SR.GetResourceString("event_HeadersInvalidValue", null); + } + } + + internal static String InvalidHeaderName + { + get + { + return SR.GetResourceString("InvalidHeaderName", null); + } + } + + internal static String IO_FileExists_Name + { + get + { + return SR.GetResourceString("IO_FileExists_Name", null); + } + } + + internal static String IO_FileNotFound + { + get + { + return SR.GetResourceString("IO_FileNotFound", null); + } + } + + internal static String IO_FileNotFound_FileName + { + get + { + return SR.GetResourceString("IO_FileNotFound_FileName", null); + } + } + + internal static String IO_PathNotFound_NoPathName + { + get + { + return SR.GetResourceString("IO_PathNotFound_NoPathName", null); + } + } + + internal static String IO_PathNotFound_Path + { + get + { + return SR.GetResourceString("IO_PathNotFound_Path", null); + } + } + + internal static String IO_PathTooLong + { + get + { + return SR.GetResourceString("IO_PathTooLong", null); + } + } + + internal static String IO_SharingViolation_File + { + get + { + return SR.GetResourceString("IO_SharingViolation_File", null); + } + } + + internal static String IO_SharingViolation_NoFileName + { + get + { + return SR.GetResourceString("IO_SharingViolation_NoFileName", null); + } + } + + internal static String MailAddressInvalidFormat + { + get + { + return SR.GetResourceString("MailAddressInvalidFormat", null); + } + } + + internal static String MailHeaderFieldInvalidCharacter + { + get + { + return SR.GetResourceString("MailHeaderFieldInvalidCharacter", null); + } + } + + internal static String MailHeaderFieldMalformedHeader + { + get + { + return SR.GetResourceString("MailHeaderFieldMalformedHeader", null); + } + } + + internal static String net_cookie_attribute + { + get + { + return SR.GetResourceString("net_cookie_attribute", null); + } + } + + internal static String net_http_argument_empty_string + { + get + { + return SR.GetResourceString("net_http_argument_empty_string", null); + } + } + + internal static String net_http_chunked_not_allowed_with_content_length + { + get + { + return SR.GetResourceString("net_http_chunked_not_allowed_with_content_length", null); + } + } + + internal static String net_http_chunked_not_allowed_with_empty_content + { + get + { + return SR.GetResourceString("net_http_chunked_not_allowed_with_empty_content", null); + } + } + + internal static String net_http_client_absolute_baseaddress_required + { + get + { + return SR.GetResourceString("net_http_client_absolute_baseaddress_required", null); + } + } + + internal static String net_http_client_execution_error + { + get + { + return SR.GetResourceString("net_http_client_execution_error", null); + } + } + + internal static String net_http_client_http_baseaddress_required + { + get + { + return SR.GetResourceString("net_http_client_http_baseaddress_required", null); + } + } + + internal static String net_http_client_invalid_requesturi + { + get + { + return SR.GetResourceString("net_http_client_invalid_requesturi", null); + } + } + + internal static String net_http_client_request_already_sent + { + get + { + return SR.GetResourceString("net_http_client_request_already_sent", null); + } + } + + internal static String net_http_client_send_canceled + { + get + { + return SR.GetResourceString("net_http_client_send_canceled", null); + } + } + + internal static String net_http_client_send_error + { + get + { + return SR.GetResourceString("net_http_client_send_error", null); + } + } + + internal static String net_http_content_buffersize_exceeded + { + get + { + return SR.GetResourceString("net_http_content_buffersize_exceeded", null); + } + } + + internal static String net_http_content_buffersize_limit + { + get + { + return SR.GetResourceString("net_http_content_buffersize_limit", null); + } + } + + internal static String net_http_content_field_too_long + { + get + { + return SR.GetResourceString("net_http_content_field_too_long", null); + } + } + + internal static String net_http_content_invalid_charset + { + get + { + return SR.GetResourceString("net_http_content_invalid_charset", null); + } + } + + internal static String net_http_content_no_concurrent_reads + { + get + { + return SR.GetResourceString("net_http_content_no_concurrent_reads", null); + } + } + + internal static String net_http_content_no_task_returned + { + get + { + return SR.GetResourceString("net_http_content_no_task_returned", null); + } + } + + internal static String net_http_content_readonly_stream + { + get + { + return SR.GetResourceString("net_http_content_readonly_stream", null); + } + } + + internal static String net_http_content_stream_already_read + { + get + { + return SR.GetResourceString("net_http_content_stream_already_read", null); + } + } + + internal static String net_http_content_stream_copy_error + { + get + { + return SR.GetResourceString("net_http_content_stream_copy_error", null); + } + } + + internal static String net_http_copyto_array_too_small + { + get + { + return SR.GetResourceString("net_http_copyto_array_too_small", null); + } + } + + internal static String net_http_handler_norequest + { + get + { + return SR.GetResourceString("net_http_handler_norequest", null); + } + } + + internal static String net_http_handler_noresponse + { + get + { + return SR.GetResourceString("net_http_handler_noresponse", null); + } + } + + internal static String net_http_handler_not_assigned + { + get + { + return SR.GetResourceString("net_http_handler_not_assigned", null); + } + } + + internal static String net_http_headers_invalid_etag_name + { + get + { + return SR.GetResourceString("net_http_headers_invalid_etag_name", null); + } + } + + internal static String net_http_headers_invalid_from_header + { + get + { + return SR.GetResourceString("net_http_headers_invalid_from_header", null); + } + } + + internal static String net_http_headers_invalid_header_name + { + get + { + return SR.GetResourceString("net_http_headers_invalid_header_name", null); + } + } + + internal static String net_http_headers_invalid_host_header + { + get + { + return SR.GetResourceString("net_http_headers_invalid_host_header", null); + } + } + + internal static String net_http_headers_invalid_range + { + get + { + return SR.GetResourceString("net_http_headers_invalid_range", null); + } + } + + internal static String net_http_headers_invalid_value + { + get + { + return SR.GetResourceString("net_http_headers_invalid_value", null); + } + } + + internal static String net_http_headers_no_newlines + { + get + { + return SR.GetResourceString("net_http_headers_no_newlines", null); + } + } + + internal static String net_http_headers_not_allowed_header_name + { + get + { + return SR.GetResourceString("net_http_headers_not_allowed_header_name", null); + } + } + + internal static String net_http_headers_not_found + { + get + { + return SR.GetResourceString("net_http_headers_not_found", null); + } + } + + internal static String net_http_headers_single_value_header + { + get + { + return SR.GetResourceString("net_http_headers_single_value_header", null); + } + } + + internal static String net_http_httpmethod_format_error + { + get + { + return SR.GetResourceString("net_http_httpmethod_format_error", null); + } + } + + internal static String net_http_invalid_cookiecontainer + { + get + { + return SR.GetResourceString("net_http_invalid_cookiecontainer", null); + } + } + + internal static String net_http_invalid_cookiecontainer_unix + { + get + { + return SR.GetResourceString("net_http_invalid_cookiecontainer_unix", null); + } + } + + internal static String net_http_invalid_enable_first + { + get + { + return SR.GetResourceString("net_http_invalid_enable_first", null); + } + } + + internal static String net_http_invalid_proxy + { + get + { + return SR.GetResourceString("net_http_invalid_proxy", null); + } + } + + internal static String net_http_invalid_proxyusepolicy + { + get + { + return SR.GetResourceString("net_http_invalid_proxyusepolicy", null); + } + } + + internal static String net_http_io_read + { + get + { + return SR.GetResourceString("net_http_io_read", null); + } + } + + internal static String net_http_io_write + { + get + { + return SR.GetResourceString("net_http_io_write", null); + } + } + + internal static String net_http_log_content_no_task_returned_copytoasync + { + get + { + return SR.GetResourceString("net_http_log_content_no_task_returned_copytoasync", null); + } + } + + internal static String net_http_log_headers_invalid_quality + { + get + { + return SR.GetResourceString("net_http_log_headers_invalid_quality", null); + } + } + + internal static String net_http_log_headers_no_newlines + { + get + { + return SR.GetResourceString("net_http_log_headers_no_newlines", null); + } + } + + internal static String net_http_log_headers_wrong_email_format + { + get + { + return SR.GetResourceString("net_http_log_headers_wrong_email_format", null); + } + } + + internal static String net_http_message_not_success_statuscode + { + get + { + return SR.GetResourceString("net_http_message_not_success_statuscode", null); + } + } + + internal static String net_http_no_concurrent_io_allowed + { + get + { + return SR.GetResourceString("net_http_no_concurrent_io_allowed", null); + } + } + + internal static String net_http_operation_started + { + get + { + return SR.GetResourceString("net_http_operation_started", null); + } + } + + internal static String net_http_parser_invalid_base64_string + { + get + { + return SR.GetResourceString("net_http_parser_invalid_base64_string", null); + } + } + + internal static String net_http_reasonphrase_format_error + { + get + { + return SR.GetResourceString("net_http_reasonphrase_format_error", null); + } + } + + internal static String net_http_unix_https_libcurl_no_versioninfo + { + get + { + return SR.GetResourceString("net_http_unix_https_libcurl_no_versioninfo", null); + } + } + + internal static String net_http_unix_https_libcurl_too_old + { + get + { + return SR.GetResourceString("net_http_unix_https_libcurl_too_old", null); + } + } + + internal static String net_http_unix_https_support_unavailable_libcurl + { + get + { + return SR.GetResourceString("net_http_unix_https_support_unavailable_libcurl", null); + } + } + + internal static String net_http_unix_invalid_client_cert_option + { + get + { + return SR.GetResourceString("net_http_unix_invalid_client_cert_option", null); + } + } + + internal static String net_http_unix_invalid_credential + { + get + { + return SR.GetResourceString("net_http_unix_invalid_credential", null); + } + } + + internal static String net_http_unix_invalid_response + { + get + { + return SR.GetResourceString("net_http_unix_invalid_response", null); + } + } + + internal static String net_http_username_empty_string + { + get + { + return SR.GetResourceString("net_http_username_empty_string", null); + } + } + + internal static String net_http_value_must_be_greater_than + { + get + { + return SR.GetResourceString("net_http_value_must_be_greater_than", null); + } + } + + internal static String net_http_value_not_supported + { + get + { + return SR.GetResourceString("net_http_value_not_supported", null); + } + } + + internal static String net_securityprotocolnotsupported + { + get + { + return SR.GetResourceString("net_securityprotocolnotsupported", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Net.Http.SR); + } + } + + internal static String UnauthorizedAccess_IODenied_NoPathName + { + get + { + return SR.GetResourceString("UnauthorizedAccess_IODenied_NoPathName", null); + } + } + + internal static String UnauthorizedAccess_IODenied_Path + { + get + { + return SR.GetResourceString("UnauthorizedAccess_IODenied_Path", null); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2, p3); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Check the give namespace name availability. /// </summary> /// <param name='parameters'> /// Parameters to check availability of the given namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityMethodWithHttpMessagesAsync(CheckNameAvailability parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the available namespaces within the subscription, /// irrespective of the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBNamespace>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBNamespace>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBNamespace>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, SBNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a description for the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBNamespace>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to update a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBNamespace>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, SBNamespaceUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBAuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an authorization rule for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639410.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBAuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SBAuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a namespace authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639417.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an authorization rule for a namespace by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639392.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBAuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the /// namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639398.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the primary or secondary connection strings for the /// namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt718977.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SBNamespace>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, SBNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the available namespaces within the subscription, /// irrespective of the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBNamespace>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBNamespace>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SBAuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
namespace gView.DataSources.Fdb.UI.MSSql { partial class SqlFDBImageDatasetExplorerTabPage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SqlFDBImageDatasetExplorerTabPage)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripButtonAdd = new System.Windows.Forms.ToolStripButton(); this.btnImportDirectory = new System.Windows.Forms.ToolStripButton(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.StatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.listView = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.removeImageFromDatasetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.updateImageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openImageFiles = new System.Windows.Forms.OpenFileDialog(); this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStrip1.SuspendLayout(); this.statusStrip.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripButtonAdd, this.btnImportDirectory, this.toolStripSeparator1}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(513, 25); this.toolStrip1.TabIndex = 0; this.toolStrip1.Text = "toolStrip1"; // // toolStripButtonAdd // this.toolStripButtonAdd.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButtonAdd.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButtonAdd.Image"))); this.toolStripButtonAdd.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButtonAdd.Name = "toolStripButtonAdd"; this.toolStripButtonAdd.Size = new System.Drawing.Size(23, 22); this.toolStripButtonAdd.Text = "toolStripButton1"; this.toolStripButtonAdd.Click += new System.EventHandler(this.toolStripButtonAdd_Click); // // btnImportDirectory // this.btnImportDirectory.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnImportDirectory.Image = global::gView.DataSources.Fdb.UI.Properties.Resources.addfolder; this.btnImportDirectory.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnImportDirectory.Name = "btnImportDirectory"; this.btnImportDirectory.Size = new System.Drawing.Size(23, 22); this.btnImportDirectory.Text = "Import directory and subdirectories"; this.btnImportDirectory.Click += new System.EventHandler(this.btnImportDirectory_Click); // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.StatusLabel1}); this.statusStrip.Location = new System.Drawing.Point(0, 393); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(513, 22); this.statusStrip.TabIndex = 1; this.statusStrip.Text = "statusStrip1"; // // StatusLabel1 // this.StatusLabel1.Name = "StatusLabel1"; this.StatusLabel1.Size = new System.Drawing.Size(118, 17); this.StatusLabel1.Text = " "; // // listView // this.listView.AllowDrop = true; this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.listView.Dock = System.Windows.Forms.DockStyle.Fill; this.listView.Location = new System.Drawing.Point(0, 25); this.listView.Name = "listView"; this.listView.Size = new System.Drawing.Size(513, 368); this.listView.SmallImageList = this.imageList1; this.listView.TabIndex = 2; this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.Details; this.listView.DragEnter += new System.Windows.Forms.DragEventHandler(this.listView_DragEnter); this.listView.DragDrop += new System.Windows.Forms.DragEventHandler(this.listView_DragDrop); this.listView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Key_pressed); this.listView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.listView_MouseMove); this.listView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.listView_MouseDown); // // columnHeader1 // this.columnHeader1.Text = "Filename"; this.columnHeader1.Width = 387; // // columnHeader2 // this.columnHeader2.Text = "Type"; // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.White; this.imageList1.Images.SetKeyName(0, "ok.png"); this.imageList1.Images.SetKeyName(1, "old.png"); this.imageList1.Images.SetKeyName(2, "new.png"); this.imageList1.Images.SetKeyName(3, "deleted.png"); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.removeImageFromDatasetToolStripMenuItem, this.updateImageToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(226, 48); // // removeImageFromDatasetToolStripMenuItem // this.removeImageFromDatasetToolStripMenuItem.Name = "removeImageFromDatasetToolStripMenuItem"; this.removeImageFromDatasetToolStripMenuItem.Size = new System.Drawing.Size(225, 22); this.removeImageFromDatasetToolStripMenuItem.Text = "Remove Image From Dataset"; this.removeImageFromDatasetToolStripMenuItem.Click += new System.EventHandler(this.removeImageFromDatasetToolStripMenuItem_Click); // // updateImageToolStripMenuItem // this.updateImageToolStripMenuItem.Name = "updateImageToolStripMenuItem"; this.updateImageToolStripMenuItem.Size = new System.Drawing.Size(225, 22); this.updateImageToolStripMenuItem.Text = "Update Image"; this.updateImageToolStripMenuItem.Click += new System.EventHandler(this.updateImageToolStripMenuItem_Click); // // openImageFiles // this.openImageFiles.Filter = "All Image Files|*.jpg;*.jpeg;*.png;*.jp2;*.tif;*.tiff;*.sid|Jpg Files (*.jpg)|*.j" + "pg;*.jpeg|PNG Files (*.png)|*.png|Jpeg 2000 (*.jp2)|*.jp2|TIFF Files (*.tif)|*.t" + "if;*.tiff|MrSid (*.sid)|*.sid"; this.openImageFiles.Multiselect = true; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // SqlFDBImageDatasetExplorerTabPage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.listView); this.Controls.Add(this.statusStrip); this.Controls.Add(this.toolStrip1); this.Name = "SqlFDBImageDatasetExplorerTabPage"; this.Size = new System.Drawing.Size(513, 415); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.contextMenuStrip1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ListView listView; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem removeImageFromDatasetToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel StatusLabel1; private System.Windows.Forms.ToolStripMenuItem updateImageToolStripMenuItem; private System.Windows.Forms.ToolStripButton toolStripButtonAdd; private System.Windows.Forms.OpenFileDialog openImageFiles; private System.Windows.Forms.ToolStripButton btnImportDirectory; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Collections; using System.IO; using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class CollectionTests { [Fact] public static void X509CertificateCollectionsProperties() { IList ilist = new X509CertificateCollection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); ilist = new X509Certificate2Collection(); Assert.False(ilist.IsSynchronized); Assert.False(ilist.IsFixedSize); Assert.False(ilist.IsReadOnly); } [Fact] public static void X509CertificateCollectionConstructors() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509CertificateCollection cc2 = new X509CertificateCollection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection(new X509Certificate[] { c1, c2, null, c3 })); } } [Fact] public static void X509Certificate2CollectionConstructors() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); X509Certificate2Collection cc2 = new X509Certificate2Collection(cc); Assert.Equal(3, cc2.Count); Assert.Same(c1, cc2[0]); Assert.Same(c2, cc2[1]); Assert.Same(c3, cc2[2]); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection(new X509Certificate2[] { c1, c2, null, c3 })); using (X509Certificate c4 = new X509Certificate()) { X509Certificate2Collection collection = new X509Certificate2Collection { c1, c2, c3 }; ((IList)collection).Add(c4); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => new X509Certificate2Collection(collection)); } } } [Fact] public static void X509Certificate2CollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); object ignored; X509Certificate2Enumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } [Fact] public static void X509CertificateCollectionEnumerator() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); object ignored; X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } IEnumerator e2 = cc.GetEnumerator(); TestNonGenericEnumerator(e2, c1, c2, c3); IEnumerator e3 = ((IEnumerable)cc).GetEnumerator(); TestNonGenericEnumerator(e3, c1, c2, c3); } } private static void TestNonGenericEnumerator(IEnumerator e, object c1, object c2, object c3) { object ignored; for (int i = 0; i < 2; i++) { // Not started Assert.Throws<InvalidOperationException>(() => ignored = e.Current); Assert.True(e.MoveNext()); Assert.Same(c1, e.Current); Assert.True(e.MoveNext()); Assert.Same(c2, e.Current); Assert.True(e.MoveNext()); Assert.Same(c3, e.Current); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); Assert.False(e.MoveNext()); // Ended Assert.Throws<InvalidOperationException>(() => ignored = e.Current); e.Reset(); } } [Fact] public static void X509CertificateCollectionThrowsArgumentNullException() { using (X509Certificate certificate = new X509Certificate()) { Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection((X509CertificateCollection)null)); X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add(null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => collection.Remove(null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } Assert.Throws<ArgumentNullException>(() => new X509CertificateCollection.X509CertificateEnumerator(null)); } [Fact] public static void X509Certificate2CollectionThrowsArgumentNullException() { using (X509Certificate2 certificate = new X509Certificate2()) { Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => new X509Certificate2Collection((X509Certificate2Collection)null)); X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentNullException>(() => collection[0] = null); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Add((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509CertificateCollection)null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.AddRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Insert(0, (X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate)null)); Assert.Throws<ArgumentNullException>(() => collection.Remove((X509Certificate2)null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2[])null)); Assert.Throws<ArgumentNullException>(() => collection.RemoveRange((X509Certificate2Collection)null)); Assert.Throws<ArgumentNullException>(() => collection.Import((byte[])null)); Assert.Throws<ArgumentNullException>(() => collection.Import((string)null)); IList ilist = (IList)collection; Assert.Throws<ArgumentNullException>(() => ilist[0] = null); Assert.Throws<ArgumentNullException>(() => ilist.Add(null)); Assert.Throws<ArgumentNullException>(() => ilist.CopyTo(null, 0)); Assert.Throws<ArgumentNullException>(() => ilist.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => ilist.Remove(null)); } } [Fact] public static void X509CertificateCollectionThrowsArgumentOutOfRangeException() { using (X509Certificate certificate = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509Certificate2CollectionThrowsArgumentOutOfRangeException() { using (X509Certificate2 certificate = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection { certificate }; Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(collection.Count)); IList ilist = (IList)collection; Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count]); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[-1] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist[collection.Count] = certificate); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(-1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.Insert(collection.Count + 1, certificate)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => ilist.RemoveAt(collection.Count)); } } [Fact] public static void X509CertificateCollectionContains() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection collection = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509Certificate2CollectionContains() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection collection = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); Assert.True(collection.Contains(c1)); Assert.True(collection.Contains(c2)); Assert.True(collection.Contains(c3)); // Note: X509Certificate2Collection.Contains used to throw ArgumentNullException, but it // has been deliberately changed to no longer throw to match the behavior of // X509CertificateCollection.Contains and the IList.Contains implementation, which do not // throw. Assert.False(collection.Contains(null)); IList ilist = (IList)collection; Assert.True(ilist.Contains(c1)); Assert.True(ilist.Contains(c2)); Assert.True(ilist.Contains(c3)); Assert.False(ilist.Contains(null)); Assert.False(ilist.Contains("Bogus")); } } [Fact] public static void X509CertificateCollectionEnumeratorModification() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509CertificateCollection.X509CertificateEnumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509Certificate2CollectionEnumeratorModification() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2Enumerator e = cc.GetEnumerator(); cc.Add(c1); // Collection changed. Assert.Throws<InvalidOperationException>(() => e.MoveNext()); Assert.Throws<InvalidOperationException>(() => e.Reset()); } } [Fact] public static void X509CertificateCollectionAdd() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { X509CertificateCollection cc = new X509CertificateCollection(); int idx = cc.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, cc[0]); idx = cc.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, cc[1]); Assert.Throws<ArgumentNullException>(() => cc.Add(null)); IList il = new X509CertificateCollection(); idx = il.Add(c1); Assert.Equal(0, idx); Assert.Same(c1, il[0]); idx = il.Add(c2); Assert.Equal(1, idx); Assert.Same(c2, il[1]); Assert.Throws<ArgumentNullException>(() => il.Add(null)); } } [Fact] public static void X509CertificateCollectionAsIList() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) { IList il = new X509CertificateCollection(); il.Add(c1); il.Add(c2); Assert.Throws<ArgumentNullException>(() => il[0] = null); string bogus = "Bogus"; Assert.Throws<ArgumentException>(() => il[0] = bogus); Assert.Throws<ArgumentException>(() => il.Add(bogus)); Assert.Throws<ArgumentException>(() => il.Insert(0, bogus)); } } [Fact] public static void AddDoesNotClone() { using (X509Certificate2 c1 = new X509Certificate2()) { X509Certificate2Collection coll = new X509Certificate2Collection(); coll.Add(c1); Assert.Same(c1, coll[0]); } } [Fact] public static void ImportStoreSavedAsCerData() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ImportStoreSavedAsSerializedCerData_Windows() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedCerData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ImportStoreSavedAsSerializedCerData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedCerData)); Assert.Equal(0, cc2.Count); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ImportStoreSavedAsSerializedStoreData_Windows() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsSerializedStoreData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ImportStoreSavedAsSerializedStoreData_Unix() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(TestData.StoreSavedAsSerializedStoreData)); Assert.Equal(0, cc2.Count); } [Fact] public static void ImportStoreSavedAsPfxData() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) using (ImportedCollection ic = Cert.Import(TestData.StoreSavedAsPfxData)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); Assert.NotSame(msCer, cs[0]); Assert.Equal(msCer, cs[0]); Assert.Equal(msCer.Thumbprint, cs[0].Thumbprint); Assert.NotSame(pfxCer, cs[1]); Assert.Equal(pfxCer, cs[1]); Assert.Equal(pfxCer.Thumbprint, cs[1].Thumbprint); } } [Fact] public static void ImportInvalidData() { X509Certificate2Collection cc2 = new X509Certificate2Collection(); Assert.ThrowsAny<CryptographicException>(() => cc2.Import(new byte[] { 0, 1, 1, 2, 3, 5, 8, 13, 21 })); } [Fact] public static void ImportFromFileTests() { using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "My.pfx"), TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { // pfxCer was loaded directly, cc2[0] was Imported, two distinct copies. Assert.NotSame(pfxCer, c); Assert.Equal(pfxCer, c); Assert.Equal(pfxCer.Thumbprint, c.Thumbprint); } } } } [Fact] [ActiveIssue(2745, PlatformID.AnyUnix)] public static void ImportMultiplePrivateKeysPfx() { using (ImportedCollection ic = Cert.Import(TestData.MultiPrivateKeyPfx)) { X509Certificate2Collection collection = ic.Collection; Assert.Equal(2, collection.Count); foreach (X509Certificate2 cert in collection) { Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey"); } } } [Fact] public static void ExportCert() { TestExportSingleCert(X509ContentType.Cert); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ExportSerializedCert_Windows() { TestExportSingleCert(X509ContentType.SerializedCert); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ExportSerializedCert_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedCert)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void ExportSerializedStore_Windows() { TestExportStore(X509ContentType.SerializedStore); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void ExportSerializedStore_Unix() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var ecdsa256Cer = new X509Certificate2(TestData.ECDsa256Certificate)) { X509Certificate2Collection cc = new X509Certificate2Collection(new[] { msCer, ecdsa256Cer }); Assert.Throws<PlatformNotSupportedException>(() => cc.Export(X509ContentType.SerializedStore)); } } [Fact] public static void ExportPkcs7() { TestExportStore(X509ContentType.Pkcs7); } [Fact] public static void X509CertificateCollectionSyncRoot() { var cc = new X509CertificateCollection(); Assert.NotNull(((ICollection)cc).SyncRoot); Assert.Same(((ICollection)cc).SyncRoot, ((ICollection)cc).SyncRoot); } [Fact] public static void ExportEmpty_Cert() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Cert); Assert.Null(exported); } [Fact] [ActiveIssue(2746, PlatformID.AnyUnix)] public static void ExportEmpty_Pkcs12() { var collection = new X509Certificate2Collection(); byte[] exported = collection.Export(X509ContentType.Pkcs12); // The empty PFX is legal, the answer won't be null. Assert.NotNull(exported); } [Fact] public static void ExportUnrelatedPfx() { // Export multiple certificates which are not part of any kind of certificate chain. // Nothing in the PKCS12 structure requires they're related, but it might be an underlying // assumption of the provider. using (var cert1 = new X509Certificate2(TestData.MsCertificate)) using (var cert2 = new X509Certificate2(TestData.ComplexNameInfoCert)) using (var cert3 = new X509Certificate2(TestData.CertWithPolicies)) { var collection = new X509Certificate2Collection { cert1, cert2, cert3, }; byte[] exported = collection.Export(X509ContentType.Pkcs12); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; // Verify that the two collections contain the same certificates, // but the order isn't really a factor. Assert.Equal(collection.Count, importedCollection.Count); // Compare just the subject names first, because it's the easiest thing to read out of the failure message. string[] subjects = new string[collection.Count]; string[] importedSubjects = new string[collection.Count]; for (int i = 0; i < collection.Count; i++) { subjects[i] = collection[i].GetNameInfo(X509NameType.SimpleName, false); importedSubjects[i] = importedCollection[i].GetNameInfo(X509NameType.SimpleName, false); } Assert.Equal(subjects, importedSubjects); // But, really, the collections should be equivalent // (after being coerced to IEnumerable<X509Certificate2>) Assert.Equal(collection.OfType<X509Certificate2>(), importedCollection.OfType<X509Certificate2>()); } } } [Fact] public static void MultipleImport() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), null, default(X509KeyStorageFlags)); collection.Import(TestData.PfxData, TestData.PfxDataPassword, default(X509KeyStorageFlags)); Assert.Equal(3, collection.Count); } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] [ActiveIssue(2743, PlatformID.AnyUnix)] public static void ExportMultiplePrivateKeys() { var collection = new X509Certificate2Collection(); try { collection.Import(Path.Combine("TestData", "DummyTcpServer.pfx"), null, X509KeyStorageFlags.Exportable); collection.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable); // Pre-condition, we have multiple private keys int originalPrivateKeyCount = collection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(2, originalPrivateKeyCount); // Export, re-import. byte[] exported; try { exported = collection.Export(X509ContentType.Pkcs12); } catch (PlatformNotSupportedException) { // [ActiveIssue(2743, PlatformID.AnyUnix)] // Our Unix builds can't export more than one private key in a single PFX, so this is // their exit point. // // If Windows gets here, or any exception other than PlatformNotSupportedException is raised, // let that fail the test. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw; } return; } // As the other half of issue 2743, if we make it this far we better be Windows (or remove the catch // above) Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "RuntimeInformation.IsOSPlatform(OSPlatform.Windows)"); using (ImportedCollection ic = Cert.Import(exported)) { X509Certificate2Collection importedCollection = ic.Collection; Assert.Equal(collection.Count, importedCollection.Count); int importedPrivateKeyCount = importedCollection.OfType<X509Certificate2>().Count(c => c.HasPrivateKey); Assert.Equal(originalPrivateKeyCount, importedPrivateKeyCount); } } finally { foreach (X509Certificate2 cert in collection) { cert.Dispose(); } } } [Fact] public static void X509CertificateCollectionCopyTo() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); X509Certificate[] array1 = new X509Certificate[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate[] array2 = new X509Certificate[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } public static void X509ChainElementCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (X509Chain chain = new X509Chain()) { chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; chain.Build(microsoftDotCom); ICollection collection = chain.ChainElements; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509ExtensionCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException() { using (X509Certificate2 cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { ICollection collection = cert.Extensions; Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => collection.CopyTo(array, 0)); } } [Fact] public static void X509CertificateCollectionIndexOf() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); Assert.Equal(0, cc.IndexOf(c1)); Assert.Equal(1, cc.IndexOf(c2)); IList il = cc; Assert.Equal(0, il.IndexOf(c1)); Assert.Equal(1, il.IndexOf(c2)); } } [Fact] public static void X509CertificateCollectionRemove() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); cc.Remove(c1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.Remove(c2); Assert.Equal(0, cc.Count); Assert.Throws<ArgumentException>(() => cc.Remove(c2)); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2 }); il.Remove(c1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.Remove(c2); Assert.Equal(0, il.Count); Assert.Throws<ArgumentException>(() => il.Remove(c2)); } } [Fact] public static void X509CertificateCollectionRemoveAt() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc.RemoveAt(0); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c3, cc[1]); cc.RemoveAt(1); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc.RemoveAt(0); Assert.Equal(0, cc.Count); IList il = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); il.RemoveAt(0); Assert.Equal(2, il.Count); Assert.Same(c2, il[0]); Assert.Same(c3, il[1]); il.RemoveAt(1); Assert.Equal(1, il.Count); Assert.Same(c2, il[0]); il.RemoveAt(0); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionRemoveRangeArray() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(array); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2[] { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, c2, null })); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentNullException>(() => cc.RemoveRange(new X509Certificate2[] { c1, null, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); Assert.Throws<ArgumentException>(() => cc.RemoveRange(new X509Certificate2[] { c1Clone, c1, c2 })); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509Certificate2CollectionRemoveRangeCollection() { using (X509Certificate2 c1 = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate2 c2 = new X509Certificate2(TestData.DssCer)) using (X509Certificate2 c1Clone = new X509Certificate2(TestData.MsCertificate)) using (X509Certificate c3 = new X509Certificate()) { X509Certificate2[] array = new X509Certificate2[] { c1, c2 }; X509Certificate2Collection cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1, c2 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c2, c1 }); Assert.Equal(0, cc.Count); cc = new X509Certificate2Collection(array); cc.RemoveRange(new X509Certificate2Collection { c1 }); Assert.Equal(1, cc.Count); Assert.Same(c2, cc[0]); cc = new X509Certificate2Collection(array); X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(c1); collection.Add(c2); ((IList)collection).Add(c3); // Add non-X509Certificate2 object Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection(); collection.Add(c1); ((IList)collection).Add(c3); // Add non-X509Certificate2 object collection.Add(c2); Assert.Throws<InvalidCastException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1, cc[1]); // Remove c1Clone (success) // Remove c1 (exception) // Add c1Clone back // End state: { c1, c2 } => { c2, c1Clone } cc = new X509Certificate2Collection(array); collection = new X509Certificate2Collection { c1Clone, c1, c2, }; Assert.Throws<ArgumentException>(() => cc.RemoveRange(collection)); Assert.Equal(2, cc.Count); Assert.Same(c2, cc[0]); Assert.Same(c1Clone, cc[1]); } } [Fact] public static void X509CertificateCollectionIndexer() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509Certificate2CollectionIndexer() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); cc[0] = c3; cc[1] = c2; cc[2] = c1; Assert.Same(c3, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c1, cc[2]); IList il = cc; il[0] = c1; il[1] = c2; il[2] = c3; Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); } } [Fact] public static void X509CertificateCollectionInsertAndClear() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(); cc.Insert(0, c1); cc.Insert(1, c2); cc.Insert(2, c3); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); cc.Add(c1); cc.Add(c3); Assert.Equal(2, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c3, cc[1]); cc.Insert(1, c2); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); cc.Clear(); Assert.Equal(0, cc.Count); IList il = cc; il.Insert(0, c1); il.Insert(1, c2); il.Insert(2, c3); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); il.Add(c1); il.Add(c3); Assert.Equal(2, il.Count); Assert.Same(c1, il[0]); Assert.Same(c3, il[1]); il.Insert(1, c2); Assert.Equal(3, il.Count); Assert.Same(c1, il[0]); Assert.Same(c2, il[1]); Assert.Same(c3, il[2]); il.Clear(); Assert.Equal(0, il.Count); } } [Fact] public static void X509Certificate2CollectionInsert() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(); cc.Insert(0, c3); cc.Insert(0, c2); cc.Insert(0, c1); Assert.Equal(3, cc.Count); Assert.Same(c1, cc[0]); Assert.Same(c2, cc[1]); Assert.Same(c3, cc[2]); } } [Fact] public static void X509Certificate2CollectionCopyTo() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); X509Certificate2[] array1 = new X509Certificate2[cc.Count]; cc.CopyTo(array1, 0); Assert.Same(c1, array1[0]); Assert.Same(c2, array1[1]); Assert.Same(c3, array1[2]); X509Certificate2[] array2 = new X509Certificate2[cc.Count]; ((ICollection)cc).CopyTo(array2, 0); Assert.Same(c1, array2[0]); Assert.Same(c2, array2[1]); Assert.Same(c3, array2[2]); } } [Fact] public static void X509CertificateCollectionGetHashCode() { using (X509Certificate c1 = new X509Certificate()) using (X509Certificate c2 = new X509Certificate()) using (X509Certificate c3 = new X509Certificate()) { X509CertificateCollection cc = new X509CertificateCollection(new X509Certificate[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509Certificate2CollectionGetHashCode() { using (X509Certificate2 c1 = new X509Certificate2()) using (X509Certificate2 c2 = new X509Certificate2()) using (X509Certificate2 c3 = new X509Certificate2()) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { c1, c2, c3 }); int expected = c1.GetHashCode() + c2.GetHashCode() + c3.GetHashCode(); Assert.Equal(expected, cc.GetHashCode()); } } [Fact] public static void X509ChainElementCollection_IndexerVsEnumerator() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (X509Chain chain = new X509Chain()) { chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; // Halfway between microsoftDotCom's NotBefore and NotAfter // This isn't a boundary condition test. chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(microsoftDotCom); Assert.True(valid, "Precondition: Chain built validly"); int position = 0; foreach (X509ChainElement chainElement in chain.ChainElements) { X509ChainElement indexerElement = chain.ChainElements[position]; Assert.NotNull(chainElement); Assert.NotNull(indexerElement); Assert.Same(indexerElement, chainElement); position++; } } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidValue() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); X509Extension byValue = extensions[SubjectKeyIdentifierOidValue]; Assert.Same(skidExtension, byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_ByOidFriendlyName() { const string SubjectKeyIdentifierOidValue = "2.5.29.14"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // Stable index can be counted on by ExtensionsTests.ReadExtensions(). X509Extension skidExtension = extensions[1]; // Precondition: We've found the SKID extension. Assert.Equal(SubjectKeyIdentifierOidValue, skidExtension.Oid.Value); // The friendly name of "Subject Key Identifier" is localized, but // we can use the invariant form to ask for the friendly name to ask // for the extension by friendly name. X509Extension byFriendlyName = extensions[new Oid(SubjectKeyIdentifierOidValue).FriendlyName]; Assert.Same(skidExtension, byFriendlyName); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByValue() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; X509Extension byValue = extensions[RsaOidValue]; Assert.Null(byValue); } } [Fact] public static void X509ExtensionCollection_OidIndexer_NoMatchByFriendlyName() { const string RsaOidValue = "1.2.840.113549.1.1.1"; using (var cert = new X509Certificate2(TestData.MsCertificate)) { X509ExtensionCollection extensions = cert.Extensions; // While "RSA" is actually invariant, this just guarantees that we're doing // the system-preferred lookup. X509Extension byFriendlyName = extensions[new Oid(RsaOidValue).FriendlyName]; Assert.Null(byFriendlyName); } } private static void TestExportSingleCert(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(1, count); using (X509Certificate2 c = cc2[0]) { Assert.NotSame(msCer, c); Assert.NotSame(pfxCer, c); Assert.True(msCer.Equals(c) || pfxCer.Equals(c)); } } } } private static void TestExportStore(X509ContentType ct) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection cc = new X509Certificate2Collection(new X509Certificate2[] { msCer, pfxCer }); byte[] blob = cc.Export(ct); Assert.Equal(ct, X509Certificate2.GetCertContentType(blob)); using (ImportedCollection ic = Cert.Import(blob)) { X509Certificate2Collection cc2 = ic.Collection; int count = cc2.Count; Assert.Equal(2, count); X509Certificate2[] cs = cc2.ToArray().OrderBy(c => c.Subject).ToArray(); using (X509Certificate2 first = cs[0]) { Assert.NotSame(msCer, first); Assert.Equal(msCer, first); } using (X509Certificate2 second = cs[1]) { Assert.NotSame(pfxCer, second); Assert.Equal(pfxCer, second); } } } } private static X509Certificate2[] ToArray(this X509Certificate2Collection col) { X509Certificate2[] array = new X509Certificate2[col.Count]; for (int i = 0; i < col.Count; i++) { array[i] = col[i]; } return array; } } }
// // ExportedType.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace Mono.Cecil { public class ExportedType : IMetadataTokenProvider { string @namespace; string name; uint attributes; IMetadataScope scope; int identifier; ExportedType declaring_type; internal MetadataToken token; public string Namespace { get { return @namespace; } set { @namespace = value; } } public string Name { get { return name; } set { name = value; } } public TypeAttributes Attributes { get { return (TypeAttributes) attributes; } set { attributes = (uint) value; } } public IMetadataScope Scope { get { if (declaring_type != null) return declaring_type.Scope; return scope; } } public ExportedType DeclaringType { get { return declaring_type; } set { declaring_type = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } public int Identifier { get { return identifier; } set { identifier = value; } } #region TypeAttributes public bool IsNotPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); } } public bool IsNestedPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); } } public bool IsNestedPrivate { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); } } public bool IsNestedFamily { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); } } public bool IsNestedAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); } } public bool IsNestedFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); } } public bool IsNestedFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); } } public bool IsAutoLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); } } public bool IsSequentialLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); } } public bool IsExplicitLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); } } public bool IsClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); } } public bool IsInterface { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); } } public bool IsSealed { get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); } } public bool IsImport { get { return attributes.GetAttributes ((uint) TypeAttributes.Import); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); } } public bool IsSerializable { get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); } } public bool IsAnsiClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); } } public bool IsUnicodeClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); } } public bool IsAutoClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); } } public bool IsBeforeFieldInit { get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); } } #endregion public bool IsForwarder { get { return attributes.GetAttributes ((uint) TypeAttributes.Forwarder); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Forwarder, value); } } public string FullName { get { if (declaring_type != null) return declaring_type.FullName + "/" + name; if (string.IsNullOrEmpty (@namespace)) return name; return @namespace + "." + name; } } public ExportedType (string @namespace, string name, IMetadataScope scope) { this.@namespace = @namespace; this.name = name; this.scope = scope; } public override string ToString () { return FullName; } } }
using Serilog.Capturing; using Serilog.Core; using Serilog.Events; using Serilog.Parsing; using Serilog.Tests.Support; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; // ReSharper disable UnusedAutoPropertyAccessor.Global, UnusedParameter.Local namespace Serilog.Tests.Capturing { public class PropertyValueConverterTests { readonly PropertyValueConverter _converter = new(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); [Fact] public async Task MaximumDepthIsEffectiveAndThreadSafe() { var converter = new PropertyValueConverter(3, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false); var barrier = new Barrier(participantCount: 3); var t1 = Task.Run(() => DoThreadTest(new { Root = new { B = new { C = new { D = new { E = "F" } } } } }, result => { Assert.Contains("B", result); Assert.Contains("C", result); Assert.DoesNotContain("D", result); Assert.DoesNotContain("E", result); })); var t2 = Task.Run(() => DoThreadTest(new { Root = new { Y = new { Z = "5" } } }, result => { Assert.Contains("Y", result); Assert.Contains("Z", result); })); var t3 = Task.Run(() => DoThreadTest(new { Root = new { M = new { N = new { V = 8 } } } }, result => { Assert.Contains("M", result); Assert.Contains("N", result); Assert.DoesNotContain("V", result); })); await Task.WhenAll(t1, t2, t3); void DoThreadTest(object logObject, Action<string?> assertAction) { for (var i = 0; i < 100; ++i) { barrier.SignalAndWait(); var propValue = converter.CreatePropertyValue(logObject, true); Assert.IsType<StructureValue>(propValue); var result = ((StructureValue)propValue).Properties.SingleOrDefault(p => p.Name == "Root")?.Value?.ToString(); assertAction.Invoke(result); } } } [Fact] public void UnderDestructuringAByteArrayIsAScalarValue() { var pv = _converter.CreatePropertyValue(new byte[0], Destructuring.Destructure); Assert.IsType<ScalarValue>(pv); Assert.IsType<string>(((ScalarValue)pv).Value); } [Fact] public void UnderDestructuringABooleanIsAScalarValue() { var pv = _converter.CreatePropertyValue(true, Destructuring.Destructure); Assert.IsType<ScalarValue>(pv); Assert.IsType<bool>(((ScalarValue)pv).Value); } [Fact] public void UnderDestructuringAnIntegerArrayIsASequenceValue() { var pv = _converter.CreatePropertyValue(new int[0], Destructuring.Destructure); Assert.IsType<SequenceValue>(pv); } [Fact] public void ByDefaultADestructuredNullNullableIsAScalarNull() { var pv = _converter.CreatePropertyValue(default(int?), Destructuring.Destructure); Assert.Null(((ScalarValue)pv).Value); } [Fact] public void ByDefaultADestructuredNonNullNullableIsItsValue() { // ReSharper disable RedundantExplicitNullableCreation var pv = _converter.CreatePropertyValue(new int?(2), Destructuring.Destructure); // ReSharper restore RedundantExplicitNullableCreation Assert.Equal(2, ((ScalarValue)pv).Value); } class A { public B? B { get; set; } } class B { // ReSharper disable UnusedAutoPropertyAccessor.Local public A? A { get; set; } // ReSharper restore UnusedAutoPropertyAccessor.Local } [Fact] public void DestructuringACyclicStructureDoesNotStackOverflow() { var ab = new A { B = new B() }; ab.B.A = ab; var pv = _converter.CreatePropertyValue(ab, true); Assert.IsType<StructureValue>(pv); } struct C { public D D { get; set; } } class D { // ReSharper disable once MemberHidesStaticFromOuterClass // ReSharper disable once UnusedAutoPropertyAccessor.Local public IList<C?>? C { get; set; } } [Fact] public void CollectionsAndCustomPoliciesInCyclesDoNotStackOverflow() { var cd = new C { D = new D() }; cd.D.C = new List<C?> { cd }; var pv = _converter.CreatePropertyValue(cd, true); Assert.IsType<StructureValue>(pv); } [Fact] public void ByDefaultAScalarDictionaryIsADictionaryValue() { var pv = _converter.CreatePropertyValue(new Dictionary<int, string> { { 1, "hello" } }, Destructuring.Default); Assert.IsType<DictionaryValue>(pv); var dv = (DictionaryValue)pv; Assert.Equal(1, dv.Elements.Count); } [Fact] public void ByDefaultANonScalarDictionaryIsASequenceValue() { var pv = _converter.CreatePropertyValue(new Dictionary<A, string> { { new A(), "hello" } }, Destructuring.Default); Assert.IsType<SequenceValue>(pv); var sv = (SequenceValue)pv; Assert.Equal(1, sv.Elements.Count); } [Fact] public void DelegatesAreConvertedToScalarStringsWhenDestructuring() { Action del = DelegatesAreConvertedToScalarStringsWhenDestructuring; var pv = _converter.CreatePropertyValue(del, Destructuring.Destructure); Assert.IsType<ScalarValue>(pv); Assert.IsType<string>(pv.LiteralValue()); } [Fact] public void ByteArraysAreConvertedToStrings() { var bytes = Enumerable.Range(0, 10).Select(b => (byte)b).ToArray(); var pv = _converter.CreatePropertyValue(bytes); var lv = (string)pv.LiteralValue(); Assert.Equal("00010203040506070809", lv); } [Fact] public void ByteArraysLargerThan1kAreLimitedAndConvertedToStrings() { var bytes = Enumerable.Range(0, 1025).Select(b => (byte)b).ToArray(); var pv = _converter.CreatePropertyValue(bytes); var lv = (string)pv.LiteralValue(); Assert.EndsWith("(1025 bytes)", lv); } #if FEATURE_SPAN [Fact] public void ByteSpansAreConvertedToStrings() { var bytes = Enumerable.Range(0, 10).Select(b => (byte)b).ToArray().AsMemory(); var pv = _converter.CreatePropertyValue(bytes); var lv = (string)pv.LiteralValue(); Assert.Equal("00010203040506070809", lv); } [Fact] public void ByteSpansLargerThan1kAreLimitedAndConvertedToStrings() { var bytes = Enumerable.Range(0, 1025).Select(b => (byte)b).ToArray().AsMemory(); var pv = _converter.CreatePropertyValue(bytes); var lv = (string)pv.LiteralValue(); Assert.EndsWith("(1025 bytes)", lv); } [Theory] [InlineData(10)] [InlineData(1000)] [InlineData(10000)] public void ByteSpansAreConvertedToTheSameStringsAsArrays(int length) { var bytes = Enumerable.Range(0, length).Select(b => (byte)b).ToArray(); var bytesSpan = bytes.AsMemory(); var bytesResult = _converter.CreatePropertyValue(bytes).LiteralValue(); var bytesSpanResult = _converter.CreatePropertyValue(bytesSpan).LiteralValue(); Assert.Equal(bytesResult, bytesSpanResult); } [Fact] public void FailsGracefullyWhenAccessingPropertiesViaReflectionThrows() { var thrower = new int[] { 1, 2, 3 }.AsMemory(); var pv = _converter.CreatePropertyValue(thrower, Destructuring.Destructure); var sv = (StructureValue)pv; Assert.Equal(3, sv.Properties.Count); var t = sv.Properties.Single(m => m.Name == "Span"); Assert.Equal("Accessing this property is not supported via Reflection API", t.Value.LiteralValue()); var l = sv.Properties.Single(m => m.Name == "Length"); Assert.Equal(3, l.Value.LiteralValue()); var k = sv.Properties.Single(m => m.Name == "IsEmpty"); Assert.False((bool)k.Value.LiteralValue()); var s = sv.Properties.Single(m => m.Name == "Span"); } #endif public class Thrower { public string Throws => throw new NotSupportedException(); public string Doesnt => "Hello"; } [Fact] public void FailsGracefullyWhenGettersThrow() { var pv = _converter.CreatePropertyValue(new Thrower(), Destructuring.Destructure); var sv = (StructureValue)pv; Assert.Equal(2, sv.Properties.Count); var t = sv.Properties.Single(m => m.Name == "Throws"); Assert.Equal("The property accessor threw an exception: NotSupportedException", t.Value.LiteralValue()); var d = sv.Properties.Single(m => m.Name == "Doesnt"); Assert.Equal("Hello", d.Value.LiteralValue()); } [Fact] public void SurvivesDestructuringASystemType() { var pv = _converter.CreatePropertyValue(typeof(string), Destructuring.Destructure); Assert.Equal(typeof(string), pv.LiteralValue()); } #if GETCURRENTMETHOD [Fact] public void SurvivesDestructuringMethodBase() { var theMethod = System.Reflection.MethodBase.GetCurrentMethod(); var pv = _converter.CreatePropertyValue(theMethod, Destructuring.Destructure); Assert.Equal(theMethod, pv.LiteralValue()); } #endif public class BaseWithProps { public string? PropA { get; set; } public virtual string? PropB { get; set; } public string? PropC { get; set; } } public class DerivedWithOverrides : BaseWithProps { public new string? PropA { get; set; } public override string? PropB { get; set; } public string? PropD { get; set; } } [Fact] public void NewAndInheritedPropertiesAppearOnlyOnce() { var valAsDerived = new DerivedWithOverrides { PropA = "A", PropB = "B", PropC = "C", PropD = "D" }; var valAsBase = (BaseWithProps)valAsDerived; valAsBase.PropA = "BA"; var pv = (StructureValue)_converter.CreatePropertyValue(valAsDerived, true); Assert.Equal(4, pv.Properties.Count); Assert.Equal("A", pv.Properties.Single(pp => pp.Name == "PropA").Value.LiteralValue()); Assert.Equal("B", pv.Properties.Single(pp => pp.Name == "PropB").Value.LiteralValue()); } class HasIndexer { public string this[int index] => "Indexer"; } [Fact] public void IndexerPropertiesAreIgnoredWhenDestructuring() { var indexed = new HasIndexer(); var pv = (StructureValue)_converter.CreatePropertyValue(indexed, true); Assert.Equal(0, pv.Properties.Count); } // Important because we use "Item" to short cut indexer checking // (reducing garbage). class HasItem { public string Item => "Item"; } [Fact] public void ItemPropertiesNotAreIgnoredWhenDestructuring() { var indexed = new HasItem(); var pv = (StructureValue)_converter.CreatePropertyValue(indexed, true); Assert.Equal(1, pv.Properties.Count); var item = pv.Properties.Single(); Assert.Equal("Item", item.Name); } [Fact] public void CSharpAnonymousTypesAreRecognizedWhenDestructuring() { var o = new { Foo = "Bar" }; var result = _converter.CreatePropertyValue(o, true); Assert.Equal(typeof(StructureValue), result.GetType()); var structuredValue = (StructureValue)result; Assert.Null(structuredValue.TypeTag); } [Fact] public void ValueTuplesAreRecognizedWhenDestructuring() { var o = (1, "A", new[] { "B" }); var result = _converter.CreatePropertyValue(o); var sequenceValue = Assert.IsType<SequenceValue>(result); Assert.Equal(3, sequenceValue.Elements.Count); Assert.Equal(new ScalarValue(1), sequenceValue.Elements[0]); Assert.Equal(new ScalarValue("A"), sequenceValue.Elements[1]); var nested = Assert.IsType<SequenceValue>(sequenceValue.Elements[2]); Assert.Equal(1, nested.Elements.Count); Assert.Equal(new ScalarValue("B"), nested.Elements[0]); } [Fact] public void AllTupleLengthsUpToSevenAreSupportedForCapturing() { var tuples = new object[] { ValueTuple.Create(1), (1, 2), (1, 2, 3), (1, 2, 3, 4), (1, 2, 3, 4, 5), (1, 2, 3, 4, 5, 6), (1, 2, 3, 4, 5, 6, 7) }; foreach (var t in tuples) Assert.IsType<SequenceValue>(_converter.CreatePropertyValue(t)); } [Fact] public void EightPlusValueTupleElementsAreIgnoredByCapturing() { var scalar = _converter.CreatePropertyValue((1, 2, 3, 4, 5, 6, 7, 8)); Assert.IsType<ScalarValue>(scalar); } [Fact] public void ValueTupleDestructuringIsTransitivelyApplied() { var tuple = _converter.CreatePropertyValue(ValueTuple.Create(new { A = 1 }), true); var sequence = Assert.IsType<SequenceValue>(tuple); Assert.IsType<StructureValue>(sequence.Elements[0]); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace StudyServer.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections.Generic; using System.Reflection; using Debug = System.Diagnostics.Debug; using ConditionalAttribute = System.Diagnostics.ConditionalAttribute; using HandleType = Internal.Metadata.NativeFormat.HandleType; using Internal.LowLevelLinq; using Internal.NativeFormat; namespace Internal.Metadata.NativeFormat.Writer { using Graph = AdjacencyGraph; internal class Edge { public MetadataRecord Source; public MetadataRecord Target; public Edge(MetadataRecord source, MetadataRecord target) { Source = source; Target = target; } }; internal class AdjacencyGraph { private HashSet<MetadataRecord> _vertices = new HashSet<MetadataRecord>(); // private Dictionary<MetadataRecord, HashSet<Edge>> _edges = new Dictionary<MetadataRecord, HashSet<Edge>>(); public void AddVertex(MetadataRecord v) { _vertices.Add(v); } #if false public void AddEdge(Edge e) { HashSet<Edge> vedges; if (!_edges.TryGetValue(e.Source, out vedges)) { vedges = new HashSet<Edge>(); _edges.Add(e.Source, vedges); } vedges.Add(e); } #endif public bool ContainsVertex(MetadataRecord v) { return _vertices.Contains(v); } public IEnumerable<MetadataRecord> Vertices { get { return _vertices; } } } internal partial interface IRecordVisitor { // Adds edge DstT Visit<SrcT, DstT>(SrcT src, DstT dst) where SrcT : MetadataRecord where DstT : MetadataRecord; // Adds grouped edges Dictionary<string, DstT> Visit<SrcT, DstT>(SrcT src, IEnumerable<KeyValuePair<string, DstT>> dst) where SrcT : MetadataRecord where DstT : MetadataRecord; // Adds grouped edges List<DstT> Visit<SrcT, DstT>(SrcT src, List<DstT> dst) where SrcT : MetadataRecord where DstT : MetadataRecord; } internal class SourceVertex : MetadataRecord { public override HandleType HandleType { get { throw new NotImplementedException(); } } internal override void Save(NativeWriter writer) { throw new NotImplementedException(); } internal override void Visit(IRecordVisitor visitor) { throw new NotImplementedException(); } } internal abstract class RecordVisitorBase : IRecordVisitor { #if false private class SequenceComparer<T> : IEqualityComparer<IEnumerable<T>> { public bool Equals(IEnumerable<T> x, IEnumerable<T> y) { return Object.ReferenceEquals(x, y) || (x != null && y != null && x.GetType() == y.GetType() && x.SequenceEqual(y)); } public static int GetHashCode(T o) { if (o == null) return 0; return o.GetHashCode(); } public int GetHashCode(IEnumerable<T> obj) { if (obj == null) return 0; return obj.Aggregate(0, (h, o) => h ^ GetHashCode(o)); } } Dictionary<IEnumerable<MetadataRecord>, object> _listPool = new Dictionary<IEnumerable<MetadataRecord>, object>(new SequenceComparer<MetadataRecord>()); private List<T> GetPooledArray<T>(List<T> rec) where T : MetadataRecord { if (rec == null || rec.Count() == 0) return rec; object pooledRecord; if (_listPool.TryGetValue(rec, out pooledRecord) && pooledRecord != rec) { if (rec.GetType().GetElementType() == typeof(MetadataRecord)) _stats.ArraySizeSavings += rec.Count() * sizeof(int) - 3; else _stats.ArraySizeSavings += rec.Count() * 3 - 3; Debug.Assert(rec.GetType() == pooledRecord.GetType()); rec = (List<T>)pooledRecord; } else { _listPool[rec] = rec; } return rec; } private struct Stats { public int ArraySizeSavings; } private Stats _stats = new Stats(); #endif private Dictionary<MetadataRecord, MetadataRecord> _recordPool = new Dictionary<MetadataRecord, MetadataRecord>(); public RecordVisitorBase() { _graph.AddVertex(MetaSourceVertex); } internal T MapToPooledRecord<T>(T rec) where T : MetadataRecord { return (T)_recordPool[rec]; } private T GetPooledRecord<T>(T rec) where T : MetadataRecord { if (rec == null) return rec; MetadataRecord pooledRecord; if (_recordPool.TryGetValue(rec, out pooledRecord) && pooledRecord != rec) { Debug.Assert(rec.GetType() == pooledRecord.GetType()); rec = (T)pooledRecord; } else { _recordPool[rec] = rec; } return rec; } // Adds a Vertex public T Visit<T>(T rec) where T : MetadataRecord { rec = GetPooledRecord(rec); if (rec == null) return rec; if (_graph.ContainsVertex(rec)) return rec; _graph.AddVertex(rec); _queue.Enqueue(rec); return rec; } // Adds Edges public Dictionary<string, DstT> Visit<SrcT, DstT>(SrcT src, IEnumerable<KeyValuePair<string, DstT>> dst) where SrcT : MetadataRecord where DstT : MetadataRecord { var res = new Dictionary<string, DstT>(); foreach (var kv in dst) { res.Add(kv.Key, Visit(src, kv.Value, true)); } return res; } public void Run(IEnumerable<MetadataRecord> records) { foreach (var rec in records) { Visit((MetadataRecord)null, rec); } while (_queue.Count != 0) { _queue.Dequeue().Visit(this); } } // Adds Edges public List<DstT> Visit<SrcT, DstT>(SrcT src, List<DstT> dst) where SrcT : MetadataRecord where DstT : MetadataRecord { #if false return GetPooledArray(dst.Select(d => Visit(src, d, true)).ToList()); #else var result = new List<DstT>(dst.Count); foreach (var destNode in dst) result.Add(Visit(src, destNode, true)); return result; #endif } // Adds Edge public DstT Visit<SrcT, DstT>(SrcT src, DstT dst) where SrcT : MetadataRecord where DstT : MetadataRecord { return Visit(src, dst, src == null); } // Adds Edge internal DstT Visit<SrcT, DstT>(SrcT src, DstT dst, bool isChild) where SrcT : MetadataRecord where DstT : MetadataRecord { var res = Visit(dst); #if false if (res != null) { _graph.AddEdge(new Edge(src ?? MetaSourceVertex, res)); } #endif return res; } protected Queue<MetadataRecord> _queue = new Queue<MetadataRecord>(); protected Graph _graph = new Graph(); public Graph Graph { get { return _graph; } } public readonly MetadataRecord MetaSourceVertex = new SourceVertex(); } internal class RecordVisitor : RecordVisitorBase { } internal partial class MetadataHeader : MetadataRecord { public const uint Signature = 0xDEADDFFD; public List<ScopeDefinition> ScopeDefinitions = new List<ScopeDefinition>(); internal override void Save(NativeWriter writer) { writer.WriteUInt32(Signature); writer.Write(ScopeDefinitions); } public override HandleType HandleType { get { throw new NotImplementedException(); } } internal override void Visit(IRecordVisitor visitor) { ScopeDefinitions = visitor.Visit(this, ScopeDefinitions); } } public partial class MetadataWriter { internal MetadataHeader _metadataHeader = new MetadataHeader(); public List<MetadataRecord> AdditionalRootRecords { get; private set; } public List<ScopeDefinition> ScopeDefinitions { get { return _metadataHeader.ScopeDefinitions; } } private RecordVisitor _visitor = null; public MetadataWriter() { AdditionalRootRecords = new List<MetadataRecord>(); } public int GetRecordHandle(MetadataRecord rec) { var realRec = _visitor.MapToPooledRecord(rec); Debug.Assert(realRec.Handle.Offset != 0); return realRec.Handle._value; } public void Write(Stream stream) { _visitor = new RecordVisitor(); _visitor.Run(ScopeDefinitions.AsEnumerable()); _visitor.Run(AdditionalRootRecords.AsEnumerable()); IEnumerable<MetadataRecord> records = _visitor.Graph.Vertices.Where(v => v != _visitor.MetaSourceVertex); var writer = new NativeWriter(); var section = writer.NewSection(); _metadataHeader.ScopeDefinitions = ScopeDefinitions; section.Place(_metadataHeader); foreach (var rec in records) { section.Place(rec); } writer.Save(stream); if (LogWriter != null) { // Create a CSV file, one line per meta-data record. LogWriter.WriteLine("Handle, Kind, Name, Children"); // needed to enumerate children of a meta-data record var childVisitor = new WriteChildrenVisitor(LogWriter); foreach (var rec in records) { // First the metadata handle LogWriter.Write(rec.Handle._value.ToString("x8")); LogWriter.Write(", "); // Next the handle type LogWriter.Write(rec.HandleType.ToString()); LogWriter.Write(", "); // 3rd, the name, Quote the string if not already quoted string asString = rec.ToString(false); bool alreadyQuoted = asString.StartsWith("\"") && asString.EndsWith("\""); if (!alreadyQuoted) { LogWriter.Write("\""); asString = asString.Replace("\\", "\\\\").Replace("\"", "\\\""); // Quote " and \ } // TODO we assume that a quoted string is escaped properly LogWriter.Write(asString); if (!alreadyQuoted) LogWriter.Write("\""); LogWriter.Write(", "); // Finally write out the handle IDs for my children LogWriter.Write("\""); childVisitor.Reset(); rec.Visit(childVisitor); LogWriter.Write("\""); LogWriter.WriteLine(); } LogWriter.Flush(); } } // WriteChildrenVisitor is a helper class needed to write out the list of the // handles (as space separated hex numbers) of all children of a given node // to the 'logWriter' text stream. It simply implementes the IRecordVisitor // interface to hook the callbacks needed for the MetadataRecord.Visit API. // It is only used in the Write() method above. private class WriteChildrenVisitor : IRecordVisitor { public WriteChildrenVisitor(TextWriter logWriter) { _logWriter = logWriter; } // Resets the state back to what is was just after the constructor is called. public void Reset() { _notFirst = false; } // All visits come to here for every child. Here we simply print the handle as hex. public void Log(MetadataRecord rec) { if (rec == null) return; if (_notFirst) _logWriter.Write(" "); else _notFirst = true; _logWriter.Write(rec.Handle._value.ToString("x")); } public DstT Visit<SrcT, DstT>(SrcT src, DstT dst) where SrcT : MetadataRecord where DstT : MetadataRecord { Log(dst); return dst; } public Dictionary<string, DstT> Visit<SrcT, DstT>(SrcT src, IEnumerable<KeyValuePair<string, DstT>> dst) where SrcT : MetadataRecord where DstT : MetadataRecord { foreach (var keyValue in dst) Log(keyValue.Value); return dst as Dictionary<string, DstT>; } public List<DstT> Visit<SrcT, DstT>(SrcT src, List<DstT> dst) where SrcT : MetadataRecord where DstT : MetadataRecord { foreach (var elem in dst) Log(elem); return dst.ToList(); } private bool _notFirst; // The first child should not have a space before it. This tracks this private TextWriter _logWriter; // Where we write output to } public TextWriter LogWriter = null; } internal class ReentrancyGuardStack { private MetadataRecord[] _array; private int _size; public ReentrancyGuardStack() { // Start with a non-zero initial size. With a bit of luck this will prevent memory allocations // when Push() is used. _array = new MetadataRecord[8]; _size = 0; } public bool Contains(MetadataRecord item) { int count = _size; while (count-- > 0) { // Important: we use ReferenceEquals because this method will be called from Equals() // on 'record'. This is also why we can't use System.Collections.Generic.Stack. if (Object.ReferenceEquals(item, _array[count])) return true; } return false; } public MetadataRecord Pop() { if (_size == 0) throw new InvalidOperationException(); MetadataRecord record = _array[--_size]; _array[_size] = null; return record; } public void Push(MetadataRecord item) { if (_size == _array.Length) Array.Resize(ref _array, 2 * _array.Length); _array[_size++] = item; } } public abstract class MetadataRecord : Vertex { protected int _hash = 0; // debug-only guard against reentrancy in GetHashCode() private bool _gettingHashCode = false; [Conditional("DEBUG")] protected void EnterGetHashCode() { Debug.Assert(!_gettingHashCode); _gettingHashCode = true; } [Conditional("DEBUG")] protected void LeaveGetHashCode() { Debug.Assert(_gettingHashCode); _gettingHashCode = false; } public abstract HandleType HandleType { get; } internal int HandleOffset { get { return _offset & 0x00FFFFFF; } } internal Handle Handle { get { return new Handle(HandleType, HandleOffset); } } internal abstract void Visit(IRecordVisitor visitor); public override string ToString() { return "[@TODO:" + this.GetType().ToString() + "]"; } public virtual string ToString(bool includeHandleValue) { return ToString(); } protected static string ToString<T>(IEnumerable<T> arr, string sep = ", ", bool includeHandleValue = false) where T : MetadataRecord { return String.Join(sep, arr.Select(v => v.ToString(includeHandleValue))); } } public interface ICustomAttributeMetadataRecord { IList<CustomAttribute> GetCustomAttributes(); } public abstract partial class Blob : MetadataRecord { } /// <summary> /// Supplements generated class with convenient coversion operators /// </summary> public partial class ConstantStringValue { public static explicit operator string(ConstantStringValue value) { if (value == null) return null; else return value.Value; } public static explicit operator ConstantStringValue(string value) { return new ConstantStringValue() { Value = value }; } } public partial class ScopeDefinition { public override string ToString() { return ToString(true); } public override string ToString(bool includeHandleValue) { return Name.ToString() + (includeHandleValue ? String.Format(" ({0:x})", Handle._value) : ""); } } public partial class ScopeReference { public override string ToString() { return ToString(true); } public override string ToString(bool includeHandleValue) { return Name.ToString() + (includeHandleValue ? String.Format(" ({0:x})", Handle._value) : ""); } } public partial class NamespaceDefinition { public override string ToString() { return ToString(true); } public override string ToString(bool includeHandleValue) { string str; if (Name != null && !String.IsNullOrEmpty(Name.Value)) { str = Name.Value; } else { str = string.Empty; } if (includeHandleValue) str += String.Format("({0})", Handle.ToString()); if (this.ParentScopeOrNamespace != null) { var pns = this.ParentScopeOrNamespace as NamespaceDefinition; if (pns != null) { if (!String.IsNullOrEmpty(pns.ToString(false))) str = pns.ToString(false) + '.' + str; } } return str; } } public partial class NamespaceReference { public override string ToString() { return ToString(true); } public override string ToString(bool includeHandleValue) { string str; if (Name != null && !String.IsNullOrEmpty(Name.Value)) { str = Name.Value; } else { str = string.Empty; } if (includeHandleValue) str += String.Format("({0})", Handle.ToString()); if (this.ParentScopeOrNamespace != null) { var pns = this.ParentScopeOrNamespace as NamespaceReference; if (pns != null) { if (!String.IsNullOrEmpty(pns.ToString(false))) str = pns.ToString(false) + '.' + str; } else { //str = ParentScopeOrNamespace.ToString() + " : " + str; } } return str; } } public partial class TypeDefinition { public override string ToString() { return ToString(false); } public override string ToString(bool includeHandleValue) { string str = null; if (this.EnclosingType != null) { str = this.EnclosingType.ToString(false) + "+" + Name.Value; if (includeHandleValue) str += String.Format(" ({0:x})", Handle._value); return str; } else if (this.NamespaceDefinition != null && this.NamespaceDefinition.Name != null) { str = this.NamespaceDefinition.ToString(false) + "." + Name.Value; if (includeHandleValue) str += String.Format(" ({0:x})", Handle._value); return str; } str = Name.Value + String.Format(" ({0:x})", Handle._value); if (includeHandleValue) str += String.Format(" ({0:x})", Handle._value); return str; } } public partial class TypeReference { public override string ToString() { return ToString(false); } public override string ToString(bool includeHandleValue) { String s = ""; if (ParentNamespaceOrType is NamespaceReference) s += ParentNamespaceOrType.ToString(false) + "."; if (ParentNamespaceOrType is TypeReference) s += ParentNamespaceOrType.ToString(false) + "+"; s += TypeName.Value; if (includeHandleValue) s += String.Format(" ({0:x})", Handle._value); return s; } } public partial class TypeForwarder { public override string ToString() { return this.Name.Value + " -> " + this.Scope.Name.Value; } } public partial class GenericParameter { public override string ToString() { return Kind.FlagsToString() + " " + Name.Value + "(" + Number.ToString() + ")"; } } public partial class Field { public override string ToString() { return Name.Value; } } public partial class Method { public override string ToString() { return Signature.ToString(Name.Value); } } public partial class QualifiedMethod { public override string ToString() { return EnclosingType.ToString(false) + "." + Method.ToString(); } } public partial class Property { public override string ToString() { return Name.Value; } } public partial class Event { public override string ToString() { return Name.Value; } } public partial class SZArraySignature { public override string ToString() { return ElementType.ToString() + "[]"; } } public partial class ArraySignature { public override string ToString() { return ElementType.ToString() + "[" + new String(',', Rank - 1) + "]"; } } public partial class TypeSpecification { public override string ToString() { return Signature.ToString(); } } public partial class TypeInstantiationSignature { public override string ToString() { return this.GenericType.ToString() + "<" + String.Join(", ", this.GenericTypeArguments.Select(ga => ga.ToString())) + ">"; } } public partial class MethodImpl { public override string ToString() { return this.MethodDeclaration.ToString(); } } public partial class MethodInstantiation { public override string ToString() { return Method.ToString() + "(Arguments: " + "<" + String.Join(", ", this.GenericTypeArguments.Select(ga => ga.ToString())) + ">"; } } public partial class ByReferenceSignature { public override string ToString() { return "ref " + Type.ToString(); } } public partial class CustomAttribute { public override string ToString() { string str = Constructor.ToString(); str += "(" + String.Join(", ", FixedArguments.Select(fa => fa.ToString())) + String.Join(", ", NamedArguments.Select(na => na.ToString())) + ")"; str += "(ctor: " + Constructor.Handle.ToString(); return str; } } public partial class FixedArgument { private static bool IsConstantArray(MetadataRecord rec) { switch (rec.HandleType) { case HandleType.ConstantBooleanArray: case HandleType.ConstantCharArray: case HandleType.ConstantStringArray: case HandleType.ConstantByteArray: case HandleType.ConstantSByteArray: case HandleType.ConstantInt16Array: case HandleType.ConstantUInt16Array: case HandleType.ConstantInt32Array: case HandleType.ConstantUInt32Array: case HandleType.ConstantInt64Array: case HandleType.ConstantUInt64Array: case HandleType.ConstantSingleArray: case HandleType.ConstantDoubleArray: return true; default: return false; } } public override string ToString() { return Flags.FlagsToString() + (Type != null ? " (" + Type.ToString() + ")" : "") + (Value != null ? " " + Value.ToString() : ""); } } public partial class NamedArgument { public override string ToString() { return Name + " = " + Value.ToString(); } } public partial class MemberReference { public override string ToString() { return Parent.ToString() + "." + Name.Value + " (Signature: " + Signature.ToString() + ")"; } } public partial class MethodSemantics { public override string ToString() { string str = Enum.GetName(typeof(MethodSemanticsAttributes), Attributes); return str + " : " + Method.ToString(); } } public partial class MethodSignature { public override string ToString() { return ToString(" "); } public string ToString(string name) { return String.Join(" ", new string[] { CallingConvention.FlagsToString(), ReturnType.ToString(false), name + (GenericParameterCount == 0 ? "" : "`" + GenericParameterCount.ToString()) + "(" + String.Join(", ", Parameters.Select(p => p.ToString(false))) + String.Join(", ", VarArgParameters.Select(p => p.ToString(false))) + ")"}.Where(e => !String.IsNullOrWhiteSpace(e))); } } public partial class PropertySignature { public override string ToString() { return String.Join(" ", Enum.GetName(typeof(CallingConventions), CallingConvention), Type.ToString()) + "(" + ToString(Parameters) + ")"; } } public partial class FieldSignature { public override string ToString() { return Type.ToString(); } } public partial class ModifiedType { public override string ToString() { return "[" + (IsOptional ? "opt : " : "req : ") + ModifierType.ToString() + "] " + Type.ToString(); } } public partial class TypeVariableSignature { public override string ToString() { return "!" + Number; } } public partial class MethodTypeVariableSignature { public override string ToString() { return "!!" + Number; } } public partial class Parameter { public override string ToString() { string flags = Flags.FlagsToString(); return String.Format("{0}{1} (Seq:{2}) {3}", flags, Name.ToString(), Sequence, (DefaultValue == null ? "" : " = " + DefaultValue.ToString())); } } public partial class PointerSignature { public override string ToString() { return Type.ToString() + "*"; } } public static class EnumHelpers { public static string FlagsToString<T>(this T value) where T : IConvertible { if (!(value is Enum)) throw new ArgumentException(); var eType = value.GetType(); var flags = ((T[])Enum.GetValues(eType)).Where( eVal => (((IConvertible)eVal).ToInt32(null) != 0) && ((((IConvertible)value).ToInt32(null) & ((IConvertible)eVal).ToInt32(null)) == ((IConvertible)eVal).ToInt32(null))); if (flags.Count() == 0) return ""; else return "[" + String.Join(" | ", flags.Select(eVal => Enum.GetName(eType, eVal))) + "] "; } } public static class ListExtensions { public static T FirstOrDefault<T>(this List<T> list) { if (list.Count != 0) return list[0]; return default(T); } public static T First<T>(this List<T> list) where T : class { if (list.Count != 0) return list[0]; return null; } } public static partial class DictionaryExtensions { internal static T FirstOrDefault<T>(this Dictionary<string, T> dict) { if (dict.Count != 0) foreach (var value in dict.Values) return value; return default(T); } internal static T First<T>(this Dictionary<string, T> dict) where T : class { if (dict.Count != 0) foreach (var value in dict.Values) return value; return null; } internal static IEnumerable<T> AsSingleEnumerable<T>(this T value) { yield return value; } } public static partial class SignatureHelpers { public static SZArraySignature AsSZArray(this MetadataRecord record) { return new SZArraySignature() { ElementType = record }; } } // SequenceEquals on IEnumerable is painfully slow and allocates memory. public static class SequenceExtensions { public static bool SequenceEqual<T>(this List<T> first, List<T> second) { return first.SequenceEqual(second, null); } public static bool SequenceEqual<T>(this List<T> first, List<T> second, IEqualityComparer<T> comparer) { if (first.Count != second.Count) { return false; } if (comparer == null) { comparer = EqualityComparer<T>.Default; } for (int i = 0; i < first.Count; i++) { if (!comparer.Equals(first[i], second[i])) { return false; } } return true; } public static bool SequenceEqual<T>(this T[] first, T[] second) { return first.SequenceEqual(second, null); } public static bool SequenceEqual<T>(this T[] first, T[] second, IEqualityComparer<T> comparer) { if (first.Length != second.Length) { return false; } if (comparer == null) { comparer = EqualityComparer<T>.Default; } for (int i = 0; i < first.Length; i++) { if (!comparer.Equals(first[i], second[i])) { return false; } } return true; } } // Distinguishes positive and negative zeros for float and double values public static class CustomComparer { public static unsafe bool Equals(float x, float y) { return *(int*)&x == *(int*)&y; } public static bool Equals(double x, double y) { return BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y); } } public sealed class SingleComparer : IEqualityComparer<float> { public static readonly SingleComparer Instance = new SingleComparer(); public bool Equals(float x, float y) => CustomComparer.Equals(x, y); public int GetHashCode(float obj) => obj.GetHashCode(); } public sealed class DoubleComparer : IEqualityComparer<double> { public static readonly DoubleComparer Instance = new DoubleComparer(); public bool Equals(double x, double y) => CustomComparer.Equals(x, y); public int GetHashCode(double obj) => obj.GetHashCode(); } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion #if NET_2_0 using System; using System.Collections; using log4net.Core; namespace log4net.Util { /// <summary> /// Implementation of Stack for the <see cref="log4net.LogicalThreadContext"/> /// </summary> /// <remarks> /// <para> /// Implementation of Stack for the <see cref="log4net.LogicalThreadContext"/> /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class LogicalThreadContextStack : IFixingRequired { #region Private Instance Fields /// <summary> /// The stack store. /// </summary> private Stack m_stack = new Stack(); /// <summary> /// The name of this <see cref="log4net.LogicalThreadContextStack"/> within the /// <see cref="log4net.LogicalThreadContextProperties"/>. /// </summary> private string m_propertyKey; /// <summary> /// The callback used to let the <see cref="log4net.LogicalThreadContextStacks"/> register a /// new instance of a <see cref="log4net.LogicalThreadContextStack"/>. /// </summary> private Action<string, LogicalThreadContextStack> m_registerNew; #endregion Private Instance Fields #region Public Instance Constructors /// <summary> /// Internal constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LogicalThreadContextStack" /> class. /// </para> /// </remarks> internal LogicalThreadContextStack(string propertyKey, Action<string, LogicalThreadContextStack> registerNew) { m_propertyKey = propertyKey; m_registerNew = registerNew; } #endregion Public Instance Constructors #region Public Properties /// <summary> /// The number of messages in the stack /// </summary> /// <value> /// The current number of messages in the stack /// </value> /// <remarks> /// <para> /// The current number of messages in the stack. That is /// the number of times <see cref="Push"/> has been called /// minus the number of times <see cref="Pop"/> has been called. /// </para> /// </remarks> public int Count { get { return m_stack.Count; } } #endregion // Public Properties #region Public Methods /// <summary> /// Clears all the contextual information held in this stack. /// </summary> /// <remarks> /// <para> /// Clears all the contextual information held in this stack. /// Only call this if you think that this thread is being reused after /// a previous call execution which may not have completed correctly. /// You do not need to use this method if you always guarantee to call /// the <see cref="IDisposable.Dispose"/> method of the <see cref="IDisposable"/> /// returned from <see cref="Push"/> even in exceptional circumstances, /// for example by using the <c>using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message"))</c> /// syntax. /// </para> /// </remarks> public void Clear() { m_registerNew(m_propertyKey, new LogicalThreadContextStack(m_propertyKey, m_registerNew)); } /// <summary> /// Removes the top context from this stack. /// </summary> /// <returns>The message in the context that was removed from the top of this stack.</returns> /// <remarks> /// <para> /// Remove the top context from this stack, and return /// it to the caller. If this stack is empty then an /// empty string (not <see langword="null"/>) is returned. /// </para> /// </remarks> public string Pop() { // copy current stack Stack stack = new Stack(new Stack(m_stack)); string result = ""; if (stack.Count > 0) { result = ((StackFrame)(stack.Pop())).Message; } m_registerNew(m_propertyKey, new LogicalThreadContextStack(m_propertyKey, m_registerNew) { m_stack = stack }); return result; } /// <summary> /// Pushes a new context message into this stack. /// </summary> /// <param name="message">The new context message.</param> /// <returns> /// An <see cref="IDisposable"/> that can be used to clean up the context stack. /// </returns> /// <remarks> /// <para> /// Pushes a new context onto this stack. An <see cref="IDisposable"/> /// is returned that can be used to clean up this stack. This /// can be easily combined with the <c>using</c> keyword to scope the /// context. /// </para> /// </remarks> /// <example>Simple example of using the <c>Push</c> method with the <c>using</c> keyword. /// <code lang="C#"> /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) /// { /// log.Warn("This should have an ThreadContext Stack message"); /// } /// </code> /// </example> public IDisposable Push(string message) { // do modifications on a copy Stack stack = new Stack(new Stack(m_stack)); stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); var contextStack = new LogicalThreadContextStack(m_propertyKey, m_registerNew) { m_stack = stack }; m_registerNew(m_propertyKey, contextStack); return new AutoPopStackFrame(contextStack, stack.Count - 1); } #endregion Public Methods #region Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>The current context information.</returns> internal string GetFullMessage() { Stack stack = m_stack; if (stack.Count > 0) { return ((StackFrame)(stack.Peek())).FullMessage; } return null; } /// <summary> /// Gets and sets the internal stack used by this <see cref="LogicalThreadContextStack"/> /// </summary> /// <value>The internal storage stack</value> /// <remarks> /// <para> /// This property is provided only to support backward compatability /// of the <see cref="NDC"/>. Tytpically the internal stack should not /// be modified. /// </para> /// </remarks> internal Stack InternalStack { get { return m_stack; } set { m_stack = value; } } #endregion Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>Gets the current context information</returns> /// <remarks> /// <para> /// Gets the current context information for this stack. /// </para> /// </remarks> public override string ToString() { return GetFullMessage(); } /// <summary> /// Get a portable version of this object /// </summary> /// <returns>the portable instance of this object</returns> /// <remarks> /// <para> /// Get a cross thread portable version of this object /// </para> /// </remarks> object IFixingRequired.GetFixedObject() { return GetFullMessage(); } /// <summary> /// Inner class used to represent a single context frame in the stack. /// </summary> /// <remarks> /// <para> /// Inner class used to represent a single context frame in the stack. /// </para> /// </remarks> private sealed class StackFrame { #region Private Instance Fields private readonly string m_message; private readonly StackFrame m_parent; private string m_fullMessage = null; #endregion #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="message">The message for this context.</param> /// <param name="parent">The parent context in the chain.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="StackFrame" /> class /// with the specified message and parent context. /// </para> /// </remarks> internal StackFrame(string message, StackFrame parent) { m_message = message; m_parent = parent; if (parent == null) { m_fullMessage = message; } } #endregion Internal Instance Constructors #region Internal Instance Properties /// <summary> /// Get the message. /// </summary> /// <value>The message.</value> /// <remarks> /// <para> /// Get the message. /// </para> /// </remarks> internal string Message { get { return m_message; } } /// <summary> /// Gets the full text of the context down to the root level. /// </summary> /// <value> /// The full text of the context down to the root level. /// </value> /// <remarks> /// <para> /// Gets the full text of the context down to the root level. /// </para> /// </remarks> internal string FullMessage { get { if (m_fullMessage == null && m_parent != null) { m_fullMessage = string.Concat(m_parent.FullMessage, " ", m_message); } return m_fullMessage; } } #endregion Internal Instance Properties } /// <summary> /// Struct returned from the <see cref="LogicalThreadContextStack.Push"/> method. /// </summary> /// <remarks> /// <para> /// This struct implements the <see cref="IDisposable"/> and is designed to be used /// with the <see langword="using"/> pattern to remove the stack frame at the end of the scope. /// </para> /// </remarks> private struct AutoPopStackFrame : IDisposable { #region Private Instance Fields /// <summary> /// The depth to trim the stack to when this instance is disposed /// </summary> private int m_frameDepth; /// <summary> /// The outer LogicalThreadContextStack. /// </summary> private LogicalThreadContextStack m_logicalThreadContextStack; #endregion Private Instance Fields #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="frameStack">The internal stack used by the ThreadContextStack.</param> /// <param name="frameDepth">The depth to return the stack to when this object is disposed.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="AutoPopStackFrame" /> class with /// the specified stack and return depth. /// </para> /// </remarks> internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) { m_frameDepth = frameDepth; m_logicalThreadContextStack = logicalThreadContextStack; } #endregion Internal Instance Constructors #region Implementation of IDisposable /// <summary> /// Returns the stack to the correct depth. /// </summary> /// <remarks> /// <para> /// Returns the stack to the correct depth. /// </para> /// </remarks> public void Dispose() { if (m_frameDepth >= 0 && m_logicalThreadContextStack.m_stack != null) { Stack stack = new Stack(new Stack(m_logicalThreadContextStack.m_stack)); while (stack.Count > m_frameDepth) { stack.Pop(); } m_logicalThreadContextStack.m_registerNew(m_logicalThreadContextStack.m_propertyKey, new LogicalThreadContextStack(m_logicalThreadContextStack.m_propertyKey, m_logicalThreadContextStack.m_registerNew) { m_stack = stack }); } } #endregion Implementation of IDisposable } } } #endif
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //========================================================================== // File: CombinedTcpChannel.cs // // Summary: Merges the client and server TCP channels // // Classes: public TcpChannel // //========================================================================== using System; using System.Collections; using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System.Globalization; using System.Security.Permissions; namespace System.Runtime.Remoting.Channels.Tcp { public class TcpChannel : IChannelReceiver, IChannelSender, ISecurableChannel { private TcpClientChannel _clientChannel = null; // client channel private TcpServerChannel _serverChannel = null; // server channel private int _channelPriority = 1; // channel priority private String _channelName = "tcp"; // channel name public TcpChannel() { _clientChannel = new TcpClientChannel(); // server channel will not be activated. } // TcpChannel public TcpChannel(int port) : this() { _serverChannel = new TcpServerChannel(port); } // TcpChannel public TcpChannel(IDictionary properties, IClientChannelSinkProvider clientSinkProvider, IServerChannelSinkProvider serverSinkProvider) { Hashtable clientData = new Hashtable(); Hashtable serverData = new Hashtable(); bool portFound = false; // divide properties up for respective channels if (properties != null) { foreach (DictionaryEntry entry in properties) { switch ((String)entry.Key) { // general channel properties case "name": _channelName = (String)entry.Value; break; case "priority": _channelPriority = Convert.ToInt32((String)entry.Value, CultureInfo.InvariantCulture); break; case "port": { serverData["port"] = entry.Value; portFound = true; break; } default: clientData[entry.Key] = entry.Value; serverData[entry.Key] = entry.Value; break; } } } _clientChannel = new TcpClientChannel(clientData, clientSinkProvider); if (portFound) _serverChannel = new TcpServerChannel(serverData, serverSinkProvider); } // TcpChannel // // ISecurableChannel implementation // public bool IsSecured { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { if (_clientChannel != null) return _clientChannel.IsSecured; if (_serverChannel != null) return _serverChannel.IsSecured; return false; } [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] set { if (((IList)ChannelServices.RegisteredChannels).Contains(this)) throw new InvalidOperationException(CoreChannel.GetResourceString("Remoting_InvalidOperation_IsSecuredCannotBeChangedOnRegisteredChannels")); if (_clientChannel != null) _clientChannel.IsSecured = value; if (_serverChannel != null) _serverChannel.IsSecured = value; } } // // IChannel implementation // public int ChannelPriority { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { return _channelPriority; } } // ChannelPriority public String ChannelName { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { return _channelName; } } // ChannelName // returns channelURI and places object uri into out parameter [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public String Parse(String url, out String objectURI) { return TcpChannelHelper.ParseURL(url, out objectURI); } // Parse // // end of IChannel implementation // // // IChannelSender implementation // [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public IMessageSink CreateMessageSink(String url, Object remoteChannelData, out String objectURI) { return _clientChannel.CreateMessageSink(url, remoteChannelData, out objectURI); } // CreateMessageSink // // end of IChannelSender implementation // // // IChannelReceiver implementation // public Object ChannelData { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { if (_serverChannel != null) return _serverChannel.ChannelData; else return null; } } // ChannelData [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public String[] GetUrlsForUri(String objectURI) { if (_serverChannel != null) return _serverChannel.GetUrlsForUri(objectURI); else return null; } // GetUrlsforURI [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StartListening(Object data) { if (_serverChannel != null) _serverChannel.StartListening(data); } // StartListening [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public void StopListening(Object data) { if (_serverChannel != null) _serverChannel.StopListening(data); } // StopListening // // IChannelReceiver implementation // } // class TcpChannel } // namespace System.Runtime.Remoting.Channels.Tcp
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; using System.Management.Automation.Provider; using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings #pragma warning disable 56500 namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session /// </summary> internal sealed partial class SessionStateInternal { #region IContentCmdletProvider accessors #region GetContentReader /// <summary> /// Gets the content reader for the specified item. /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) to get the content reader for. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// The content readers for all items that the path resolves to. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal Collection<IContentReader> GetContentReader(string[] paths, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; Collection<IContentReader> results = GetContentReader(paths, context); context.ThrowFirstErrorOrDoNothing(); return results; } // GetContentReader /// <summary> /// Gets the content reader for the specified item. /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) to get the content reader from. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// The content readers for all items that the path resolves to. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// internal Collection<IContentReader> GetContentReader( string[] paths, CmdletProviderContext context) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } ProviderInfo provider = null; CmdletProvider providerInstance = null; Collection<IContentReader> results = new Collection<IContentReader>(); foreach (string path in paths) { if (path == null) { throw PSTraceSource.NewArgumentNullException("paths"); } Collection<string> providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, false, context, out provider, out providerInstance); foreach (string providerPath in providerPaths) { IContentReader reader = GetContentReaderPrivate(providerInstance, providerPath, context); if (reader != null) { results.Add(reader); } context.ThrowFirstErrorOrDoNothing(true); } } return results; } // GetContentReader /// <summary> /// Gets the content reader for the item at the specified path. /// </summary> /// /// <param name="providerInstance"> /// The provider instance to use. /// </param> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private IContentReader GetContentReaderPrivate( CmdletProvider providerInstance, string path, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); IContentReader result = null; try { result = providerInstance.GetContentReader(path, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "GetContentReaderProviderException", SessionStateStrings.GetContentReaderProviderException, providerInstance.ProviderInfo, path, e); } return result; } // GetContentReaderPrivate /// <summary> /// Gets the dynamic parameters for the get-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// internal object GetContentReaderDynamicParameters( string path, CmdletProviderContext context) { if (path == null) { return null; } ProviderInfo provider = null; CmdletProvider providerInstance = null; CmdletProviderContext newContext = new CmdletProviderContext(context); newContext.SetFilters( new Collection<string>(), new Collection<string>(), null); Collection<string> providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, true, newContext, out provider, out providerInstance); if (providerPaths.Count > 0) { // Get the dynamic parameters for the first resolved path return GetContentReaderDynamicParameters(providerInstance, providerPaths[0], newContext); } return null; } // GetContentReaderDynamicParameters /// <summary> /// Gets the dynamic parameters for the get-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private object GetContentReaderDynamicParameters( CmdletProvider providerInstance, string path, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); object result = null; try { result = providerInstance.GetContentReaderDynamicParameters(path, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "GetContentReaderDynamicParametersProviderException", SessionStateStrings.GetContentReaderDynamicParametersProviderException, providerInstance.ProviderInfo, path, e); } return result; } // GetContentReaderDynamicParameters #endregion GetContentReader #region GetContentWriter /// <summary> /// Gets the content writer for the specified item. /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) to get the content writer for. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <returns> /// The content writers for all items that the path resolves to. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal Collection<IContentWriter> GetContentWriter(string[] paths, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; Collection<IContentWriter> results = GetContentWriter(paths, context); context.ThrowFirstErrorOrDoNothing(); return results; } // GetContentWriter /// <summary> /// Gets the content writer for the specified item. /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) to get the content writer from. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// The content writers for all items that the path resolves to. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// internal Collection<IContentWriter> GetContentWriter( string[] paths, CmdletProviderContext context) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } ProviderInfo provider = null; CmdletProvider providerInstance = null; Collection<IContentWriter> results = new Collection<IContentWriter>(); foreach (string path in paths) { if (path == null) { throw PSTraceSource.NewArgumentNullException("paths"); } Collection<string> providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, true, context, out provider, out providerInstance); foreach (string providerPath in providerPaths) { IContentWriter result = GetContentWriterPrivate(providerInstance, providerPath, context); if (result != null) { results.Add(result); } } } return results; } // GetContentWriter /// <summary> /// Gets the content writer for the item at the specified path. /// </summary> /// /// <param name="providerInstance"> /// The provider instance to use. /// </param> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private IContentWriter GetContentWriterPrivate( CmdletProvider providerInstance, string path, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); IContentWriter result = null; try { result = providerInstance.GetContentWriter(path, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "GetContentWriterProviderException", SessionStateStrings.GetContentWriterProviderException, providerInstance.ProviderInfo, path, e); } return result; } // GetContentWriterPrivate /// <summary> /// Gets the dynamic parameters for the set-content and add-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// internal object GetContentWriterDynamicParameters( string path, CmdletProviderContext context) { if (path == null) { return null; } ProviderInfo provider = null; CmdletProvider providerInstance = null; CmdletProviderContext newContext = new CmdletProviderContext(context); newContext.SetFilters( new Collection<string>(), new Collection<string>(), null); Collection<string> providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, true, newContext, out provider, out providerInstance); if (providerPaths.Count > 0) { // Get the dynamic parameters for the first resolved path return GetContentWriterDynamicParameters(providerInstance, providerPaths[0], newContext); } return null; } // GetContentWriterDynamicParameters /// <summary> /// Gets the dynamic parameters for the set-content and add-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="providerInstance"> /// The instance of the provider to use. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private object GetContentWriterDynamicParameters( CmdletProvider providerInstance, string path, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); object result = null; try { result = providerInstance.GetContentWriterDynamicParameters(path, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "GetContentWriterDynamicParametersProviderException", SessionStateStrings.GetContentWriterDynamicParametersProviderException, providerInstance.ProviderInfo, path, e); } return result; } // GetContentWriterDynamicParameters #endregion GetContentWriter #region ClearContent /// <summary> /// Clears all the content from the specified item. /// </summary> /// /// <param name="paths"> /// The path(s) to the item(s) to clear the content from. /// </param> /// /// <param name="force"> /// Passed on to providers to force operations. /// </param> /// /// <param name="literalPath"> /// If true, globbing is not done on paths. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// internal void ClearContent(string[] paths, bool force, bool literalPath) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; context.SuppressWildcardExpansion = literalPath; ClearContent(paths, context); context.ThrowFirstErrorOrDoNothing(); } // ClearContent /// <summary> /// Clears all of the content from the specified item. /// </summary> /// /// <param name="paths"> /// The path to the item to clear the content from. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// internal void ClearContent( string[] paths, CmdletProviderContext context) { if (paths == null) { throw PSTraceSource.NewArgumentNullException("paths"); } ProviderInfo provider = null; CmdletProvider providerInstance = null; foreach (string path in paths) { if (path == null) { PSTraceSource.NewArgumentNullException("paths"); } Collection<string> providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, false, context, out provider, out providerInstance); foreach (string providerPath in providerPaths) { ClearContentPrivate(providerInstance, providerPath, context); } } } // ClearContent /// <summary> /// Clears the content from the item at the specified path. /// </summary> /// /// <param name="providerInstance"> /// The provider instance to use. /// </param> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private void ClearContentPrivate( CmdletProvider providerInstance, string path, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); try { providerInstance.ClearContent(path, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "ClearContentProviderException", SessionStateStrings.ClearContentProviderException, providerInstance.ProviderInfo, path, e); } } // ClearContentPrivate /// <summary> /// Gets the dynamic parameters for the clear-content cmdlet. /// </summary> /// /// <param name="path"> /// The path to the item if it was specified on the command line. /// </param> /// /// <param name="context"> /// The context which the core command is running. /// </param> /// /// <returns> /// An object that has properties and fields decorated with /// parsing attributes similar to a cmdlet class. /// </returns> /// /// <exception cref="ProviderNotFoundException"> /// If the <paramref name="path"/> refers to a provider that could not be found. /// </exception> /// /// <exception cref="DriveNotFoundException"> /// If the <paramref name="path"/> refers to a drive that could not be found. /// </exception> /// /// <exception cref="NotSupportedException"> /// If the provider that the <paramref name="path"/> refers to does /// not support this operation. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// /// <exception cref="ItemNotFoundException"> /// If <paramref name="path"/> does not contain glob characters and /// could not be found. /// </exception> /// internal object ClearContentDynamicParameters( string path, CmdletProviderContext context) { if (path == null) { return null; } ProviderInfo provider = null; CmdletProvider providerInstance = null; CmdletProviderContext newContext = new CmdletProviderContext(context); newContext.SetFilters( new Collection<string>(), new Collection<string>(), null); Collection<string> providerPaths = Globber.GetGlobbedProviderPathsFromMonadPath( path, true, newContext, out provider, out providerInstance); if (providerPaths.Count > 0) { // Get the dynamic parameters for the first resolved path return ClearContentDynamicParameters(providerInstance, providerPaths[0], newContext); } return null; } // ClearContentDynamicParameters /// <summary> /// Calls the provider to get the clear-content dynamic parameters /// </summary> /// /// <param name="providerInstance"> /// The instance of the provider to call /// </param> /// /// <param name="path"> /// The path to pass to the provider. /// </param> /// /// <param name="context"> /// The context the command is executing under. /// </param> /// /// <returns> /// The dynamic parameter object returned by the provider. /// </returns> /// /// <exception cref="NotSupportedException"> /// If the <paramref name="providerInstance"/> does not support this operation. /// </exception> /// /// <exception cref="PipelineStoppedException"> /// If the pipeline is being stopped while executing the command. /// </exception> /// /// <exception cref="ProviderInvocationException"> /// If the provider threw an exception. /// </exception> /// private object ClearContentDynamicParameters( CmdletProvider providerInstance, string path, CmdletProviderContext context) { // All parameters should have been validated by caller Dbg.Diagnostics.Assert( providerInstance != null, "Caller should validate providerInstance before calling this method"); Dbg.Diagnostics.Assert( path != null, "Caller should validate path before calling this method"); Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); object result = null; try { result = providerInstance.ClearContentDynamicParameters(path, context); } catch (NotSupportedException) { throw; } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception e) // Catch-all OK, 3rd party callout. { CommandProcessorBase.CheckForSevereException(e); throw NewProviderInvocationException( "ClearContentDynamicParametersProviderException", SessionStateStrings.ClearContentDynamicParametersProviderException, providerInstance.ProviderInfo, path, e); } return result; } // ClearContentDynamicParameters #endregion ClearContent #endregion IContentCmdletProvider accessors } // SessionStateInternal class } #pragma warning restore 56500
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.Configuration; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Frapid.NPoco; using Serilog; namespace Frapid.Config.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "config.custom_field_data_types". /// </summary> public class CustomFieldDataType : DbAccess, ICustomFieldDataTypeRepository { /// <summary> /// The schema of this table. Returns literal "config". /// </summary> public override string _ObjectNamespace => "config"; /// <summary> /// The schema unqualified name of this table. Returns literal "custom_field_data_types". /// </summary> public override string _ObjectName => "custom_field_data_types"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "config.custom_field_data_types". /// </summary> /// <returns>Returns the number of rows of the table "config.custom_field_data_types".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM config.custom_field_data_types;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.custom_field_data_types" to return all instances of the "CustomFieldDataType" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "CustomFieldDataType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomFieldDataType> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types ORDER BY data_type;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.custom_field_data_types" to return all instances of the "CustomFieldDataType" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "CustomFieldDataType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types ORDER BY data_type;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "config.custom_field_data_types" with a where filter on the column "data_type" to return a single instance of the "CustomFieldDataType" class. /// </summary> /// <param name="dataType">The column "data_type" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "CustomFieldDataType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomFieldDataType Get(string dataType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"CustomFieldDataType\" filtered by \"DataType\" with value {DataType} was denied to the user with Login ID {_LoginId}", dataType, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types WHERE data_type=@0;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql, dataType).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "config.custom_field_data_types". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "CustomFieldDataType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomFieldDataType GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"CustomFieldDataType\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types ORDER BY data_type LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "config.custom_field_data_types" sorted by dataType. /// </summary> /// <param name="dataType">The column "data_type" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "CustomFieldDataType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomFieldDataType GetPrevious(string dataType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"CustomFieldDataType\" by \"DataType\" with value {DataType} was denied to the user with Login ID {_LoginId}", dataType, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types WHERE data_type < @0 ORDER BY data_type DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql, dataType).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "config.custom_field_data_types" sorted by dataType. /// </summary> /// <param name="dataType">The column "data_type" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "CustomFieldDataType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomFieldDataType GetNext(string dataType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"CustomFieldDataType\" by \"DataType\" with value {DataType} was denied to the user with Login ID {_LoginId}", dataType, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types WHERE data_type > @0 ORDER BY data_type LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql, dataType).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "config.custom_field_data_types". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "CustomFieldDataType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public Frapid.Config.Entities.CustomFieldDataType GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"CustomFieldDataType\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types ORDER BY data_type DESC LIMIT 1;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "config.custom_field_data_types" with a where filter on the column "data_type" to return a multiple instances of the "CustomFieldDataType" class. /// </summary> /// <param name="dataTypes">Array of column "data_type" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "CustomFieldDataType" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomFieldDataType> Get(string[] dataTypes) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. dataTypes: {dataTypes}.", this._LoginId, dataTypes); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types WHERE data_type IN (@0);"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql, dataTypes); } /// <summary> /// Custom fields are user defined form elements for config.custom_field_data_types. /// </summary> /// <returns>Returns an enumerable custom field collection for the table config.custom_field_data_types</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM config.custom_field_definition_view WHERE table_name='config.custom_field_data_types' ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql); } sql = "SELECT * from config.get_custom_field_definition('config.custom_field_data_types'::text, @0::text) ORDER BY field_order;"; return Factory.Get<Frapid.DataAccess.Models.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of config.custom_field_data_types. /// </summary> /// <returns>Returns an enumerable name and value collection for the table config.custom_field_data_types</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { List<Frapid.DataAccess.Models.DisplayField> displayFields = new List<Frapid.DataAccess.Models.DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT data_type AS key, is_number as value FROM config.custom_field_data_types;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of CustomFieldDataType class on the database table "config.custom_field_data_types". /// </summary> /// <param name="customFieldDataType">The instance of "CustomFieldDataType" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic customFieldDataType, List<Frapid.DataAccess.Models.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } object primaryKeyValue = customFieldDataType.data_type; if (!string.IsNullOrWhiteSpace(customFieldDataType.data_type)) { this.Update(customFieldDataType, customFieldDataType.data_type); } else { primaryKeyValue = this.Add(customFieldDataType); } string sql = "DELETE FROM config.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM config.custom_field_setup " + "WHERE form_name=config.get_custom_field_form_name('config.custom_field_data_types')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO config.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT config.get_custom_field_setup_id_by_table_name('config.custom_field_data_types', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of CustomFieldDataType class on the database table "config.custom_field_data_types". /// </summary> /// <param name="customFieldDataType">The instance of "CustomFieldDataType" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic customFieldDataType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. {CustomFieldDataType}", this._LoginId, customFieldDataType); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, customFieldDataType, "config.custom_field_data_types", "data_type"); } /// <summary> /// Inserts or updates multiple instances of CustomFieldDataType class on the database table "config.custom_field_data_types"; /// </summary> /// <param name="customFieldDataTypes">List of "CustomFieldDataType" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> customFieldDataTypes) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. {customFieldDataTypes}", this._LoginId, customFieldDataTypes); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(ConnectionString.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (ITransaction transaction = db.GetTransaction()) { foreach (dynamic customFieldDataType in customFieldDataTypes) { line++; object primaryKeyValue = customFieldDataType.data_type; if (!string.IsNullOrWhiteSpace(customFieldDataType.data_type)) { result.Add(customFieldDataType.data_type); db.Update("config.custom_field_data_types", "data_type", customFieldDataType, customFieldDataType.data_type); } else { result.Add(db.Insert("config.custom_field_data_types", "data_type", customFieldDataType)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDbErrorResource(ex); throw new DataAccessException(errorMessage, ex); } errorMessage += ex.Message; throw new DataAccessException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new DataAccessException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "config.custom_field_data_types" with an instance of "CustomFieldDataType" class against the primary key value. /// </summary> /// <param name="customFieldDataType">The instance of "CustomFieldDataType" class to update.</param> /// <param name="dataType">The value of the column "data_type" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic customFieldDataType, string dataType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"CustomFieldDataType\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {CustomFieldDataType}", dataType, this._LoginId, customFieldDataType); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, customFieldDataType, dataType, "config.custom_field_data_types", "data_type"); } /// <summary> /// Deletes the row of the table "config.custom_field_data_types" against the primary key value. /// </summary> /// <param name="dataType">The value of the column "data_type" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(string dataType) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"CustomFieldDataType\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", dataType, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM config.custom_field_data_types WHERE data_type=@0;"; Factory.NonQuery(this._Catalog, sql, dataType); } /// <summary> /// Performs a select statement on table "config.custom_field_data_types" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "CustomFieldDataType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomFieldDataType> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM config.custom_field_data_types ORDER BY data_type LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "config.custom_field_data_types" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "CustomFieldDataType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomFieldDataType> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM config.custom_field_data_types ORDER BY data_type LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='config.custom_field_data_types' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "config.custom_field_data_types". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "CustomFieldDataType" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.custom_field_data_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldDataType(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.custom_field_data_types" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "CustomFieldDataType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomFieldDataType> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.custom_field_data_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldDataType(), filters); sql.OrderBy("data_type"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "config.custom_field_data_types". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "CustomFieldDataType" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM config.custom_field_data_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldDataType(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "config.custom_field_data_types" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "CustomFieldDataType" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.Config.Entities.CustomFieldDataType> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"CustomFieldDataType\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM config.custom_field_data_types WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.Config.Entities.CustomFieldDataType(), filters); sql.OrderBy("data_type"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.Config.Entities.CustomFieldDataType>(this._Catalog, sql); } } }
/************************************************************************ * * The MIT License (MIT) * * Copyright (c) 2025 - Christian Falch * * 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 NControl.Abstractions; using Xamarin.Forms; using NControlDemo.FormsApp.Controls; using NGraphics; using NControlDemo.Localization; using System.Threading.Tasks; using NControlDemo.FormsApp.Views; using NControlDemo.FormsApp.ViewModels; using Xamarin.Forms.Maps; namespace NControlDemo.FormsApp.Views { /// <summary> /// Main view. /// </summary> public class MainView: BaseContentsView<MainViewModel> { /// <summary> /// The chrome visible. /// </summary> private bool _chromeVisible = false; /// <summary> /// The map container. /// </summary> private RelativeLayout _mapContainer; /// <summary> /// The bottom bar. /// </summary> private NControlView _bottomBar; /// <summary> /// The top bar. /// </summary> private NControlView _navigationBar; /// <summary> /// The progress. /// </summary> private ProgressControl _progress; /// <summary> /// The top background view. /// </summary> private NControlView _topBackgroundView; /// <summary> /// The bottom background view. /// </summary> private NControlView _bottomBackgroundView; /// <summary> /// Initializes a new instance of the <see cref="NControlDemo.FormsApp.Views.MainView"/> class. /// </summary> public MainView() { NavigationPage.SetHasNavigationBar(this, false); } /// <summary> /// Implement to create the layout on the page /// </summary> /// <returns>The layout.</returns> protected override View CreateContents() { _topBackgroundView = new NControlView { DrawingFunction = (canvas, rect) => canvas.FillRectangle(rect, new SolidBrush(new NGraphics.Color("#3498DB"))) }; _bottomBackgroundView = new NControlView { DrawingFunction = (canvas, rect) => canvas.FillRectangle(rect, new SolidBrush(new NGraphics.Color("#3498DB"))) }; var firstButton = new CircularButtonControl { FAIcon = FontAwesomeLabel.FAPlay }; var secondButton = new CircularButtonControl { FAIcon = FontAwesomeLabel.FAPlus, Command = new Command(()=> firstButton.FillColor = Xamarin.Forms.Color.Red) }; var grid = new Grid(); grid.Children.Add(new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.CenterAndExpand, Padding = 11, Children = { firstButton, secondButton, new CircularButtonControl { FAIcon = FontAwesomeLabel.FATerminal }, new CircularButtonControl { FAIcon = FontAwesomeLabel.FATasks }, } }, 0, 0); // var buttonOverlay = new BlueFrameControl(); // // grid.Children.Add(buttonOverlay, 0, 0); _bottomBar = new NControlView { BackgroundColor = Xamarin.Forms.Color.FromHex("#EEEEEE"), DrawingFunction = (ICanvas canvas, Rect rect) => canvas.DrawLine(0, 0, rect.Width, 0, NGraphics.Colors.Gray, 0.5) , Content = grid }; // Navigation bar _navigationBar = new NavigationBarEx { Title = Strings.AppName }; // Progress controll _progress = new ProgressControl(); // Map _mapContainer = new RelativeLayout(); // Layout var layout = new RelativeLayout(); layout.Children.Add(_mapContainer, () => layout.Bounds); layout.Children.Add(_topBackgroundView, () => new Xamarin.Forms.Rectangle(0, 0, layout.Width, 1 + (layout.Height / 2))); layout.Children.Add(_bottomBackgroundView, () => new Xamarin.Forms.Rectangle(0, layout.Height / 2, layout.Width, layout.Height / 2)); layout.Children.Add(_bottomBar, () => new Xamarin.Forms.Rectangle(0, layout.Height, layout.Width, 65)); layout.Children.Add(_navigationBar, () => new Xamarin.Forms.Rectangle(0, -80, layout.Width, 80)); layout.Children.Add(_progress, () => new Xamarin.Forms.Rectangle((layout.Width / 2) - (25), (layout.Height / 2) - 25, 50, 50)); return layout; } /// <summary> /// Startup animations /// </summary> protected override async void OnAppearing() { base.OnAppearing(); // Start the progress control _progress.Start(); // Lets pretend we're doing something await Task.Delay(1500); // Introduce the navigation bar and toolbar await ShowChromeAsync(); // Hide the background and remove progressbar await Task.WhenAll(new[] { _topBackgroundView.TranslateTo(0, -Height/2, 465, Easing.CubicIn), _bottomBackgroundView.TranslateTo(0, Height, 465, Easing.CubicIn), _progress.FadeTo(0, 365, Easing.CubicIn) }); // Add map var map = new Map(); var mapOverlay = new NControlView { BackgroundColor = Xamarin.Forms.Color.Transparent, }; mapOverlay.OnTouchesBegan += async (sender, e) => await ToggleChromeAsync(); _mapContainer.Children.Add(map, () => _mapContainer.Bounds); _mapContainer.Children.Add(mapOverlay, () => _mapContainer.Bounds); } /// <summary> /// Toggles the chrome async. /// </summary> /// <returns>The chrome async.</returns> private Task ToggleChromeAsync() { if (_chromeVisible) return HideChromeAsync(); return ShowChromeAsync(); } /// <summary> /// Shows the chrome, ie the navigation bar and button bar /// </summary> private async Task ShowChromeAsync() { _chromeVisible = true; await Task.WhenAll(new []{ _bottomBar.TranslateTo(0, -_bottomBar.Height, 550, Easing.BounceOut), _navigationBar.TranslateTo(0, Device.OnPlatform<int>(61, 80, 55), 550, Easing.BounceOut), }); } /// <summary> /// Shows the chrome, ie the navigation bar and button bar /// </summary> private async Task HideChromeAsync() { _chromeVisible = false; await Task.WhenAll(new []{ _bottomBar.TranslateTo(0, 0, 550, Easing.CubicIn), _navigationBar.TranslateTo(0, 0, 550, Easing.CubicIn), }); } } }
#region Apache Notice /***************************************************************************** * $Revision: 374175 $ * $LastChangedDate: 2006-03-22 22:39:21 +0100 (mer., 22 mars 2006) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; #if dotnet2 using System.Collections.Generic; #endif using IBatisNet.Common.Utilities.TypesResolver; namespace IBatisNet.Common.Utilities { /// <summary> /// Helper methods with regard to type. /// </summary> /// <remarks> /// <p> /// Mainly for internal use within the framework. /// </p> /// </remarks> public sealed class TypeUtils { #region Fields private static readonly ITypeResolver _internalTypeResolver = new CachedTypeResolver(new TypeResolver()); #endregion #region Constructor (s) / Destructor /// <summary> /// Creates a new instance of the <see cref="IBatisNet.Common.Utilities.TypeUtils"/> class. /// </summary> /// <remarks> /// <p> /// This is a utility class, and as such exposes no public constructors. /// </p> /// </remarks> private TypeUtils() { } #endregion /// <summary> /// Resolves the supplied type name into a <see cref="System.Type"/> /// instance. /// </summary> /// <param name="typeName"> /// The (possibly partially assembly qualified) name of a /// <see cref="System.Type"/>. /// </param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the type cannot be resolved. /// </exception> public static Type ResolveType(string typeName) { Type type = TypeRegistry.ResolveType(typeName); if (type == null) { type = _internalTypeResolver.Resolve(typeName); } return type; } /// <summary> /// Instantiate a 'Primitive' Type. /// </summary> /// <param name="typeCode">a typeCode.</param> /// <returns>An object.</returns> public static object InstantiatePrimitiveType(TypeCode typeCode) { object resultObject = null; switch (typeCode) { case TypeCode.Boolean: resultObject = new Boolean(); break; case TypeCode.Byte: resultObject = new Byte(); break; case TypeCode.Char: resultObject = new Char(); break; case TypeCode.DateTime: resultObject = new DateTime(); break; case TypeCode.Decimal: resultObject = new Decimal(); break; case TypeCode.Double: resultObject = new Double(); break; case TypeCode.Int16: resultObject = new Int16(); break; case TypeCode.Int32: resultObject = new Int32(); break; case TypeCode.Int64: resultObject = new Int64(); break; case TypeCode.SByte: resultObject = new SByte(); break; case TypeCode.Single: resultObject = new Single(); break; case TypeCode.String: resultObject = ""; break; case TypeCode.UInt16: resultObject = new UInt16(); break; case TypeCode.UInt32: resultObject = new UInt32(); break; case TypeCode.UInt64: resultObject = new UInt64(); break; } return resultObject; } #if dotnet2 /// <summary> /// Instantiate a Nullable Type. /// </summary> /// <param name="type">The nullable type.</param> /// <returns>An object.</returns> public static object InstantiateNullableType(Type type) { object resultObject = null; if (type== typeof(bool?)) { resultObject = new Nullable<bool>(false); } else if (type== typeof(byte?)) { resultObject = new Nullable<byte>(byte.MinValue); } else if (type== typeof(char?)) { resultObject = new Nullable<char>(char.MinValue); } else if (type == typeof(DateTime?)) { resultObject = new Nullable<DateTime>(DateTime.MinValue); } else if (type == typeof(decimal?)) { resultObject = new Nullable<decimal>(decimal.MinValue); } else if (type == typeof(double?)) { resultObject = new Nullable<double>(double.MinValue); } else if (type == typeof(Int16?)) { resultObject = new Nullable<Int16>(Int16.MinValue); } else if (type == typeof(Int32?)) { resultObject = new Nullable<Int32>(Int32.MinValue); } else if (type == typeof(Int64?)) { resultObject = new Nullable<Int64>(Int64.MinValue); } else if (type == typeof(SByte?)) { resultObject = new Nullable<SByte>(SByte.MinValue); } else if (type == typeof(Single?)) { resultObject = new Nullable<Single>(Single.MinValue); } else if (type == typeof(UInt16?)) { resultObject = new Nullable<UInt16>(UInt16.MinValue); } else if (type == typeof(UInt32?)) { resultObject = new Nullable<UInt32>(UInt32.MinValue); } else if (type == typeof(UInt64?)) { resultObject = new Nullable<UInt64>(UInt64.MinValue); } return resultObject; } /// <summary> /// Determines whether the specified type is implement generic Ilist interface. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the specified type is implement generic Ilist interface; otherwise, <c>false</c>. /// </returns> public static bool IsImplementGenericIListInterface(Type type) { bool ret = false; if (!type.IsGenericType) { ret = false; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return true; } else // check if one of the derived interfaces is IList<> { Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { ret = IsImplementGenericIListInterface(interfaceType); if (ret) { break; } } } return ret; } #endif } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using gameLIB.main; using System.Reflection; namespace PeaceGame { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { public Game1(string scriptData) : this() { this.scriptData = scriptData; } GraphicsDeviceManager graphics; GameApi api; string scriptData; readonly Rectangle[] PLAYER_PARTS = new Rectangle[] { new Rectangle(1, 1, 31, 47), new Rectangle(33, 1, 31, 47), new Rectangle(65, 1, 31, 47), new Rectangle(97, 1, 31, 47) }; readonly Rectangle[] FAIRIES_PARTS = new Rectangle[] { new Rectangle(1, 1, 30, 30), new Rectangle(33, 1, 30, 30), new Rectangle(65, 1, 30, 30), new Rectangle(97, 1, 30, 30) }; readonly int WINDOW_WIDTH = 800; readonly int WINDOW_HEIGHT = 600; readonly bool IS_FULLSCREEN = false; readonly bool ALLOW_RESIZING = true; readonly int FAIRIES_FRAMES_IMAGE_COUNT = 4; readonly string MENU_SELECT_SOUND = @"sounds\menu\selectMenu"; readonly string PLAYER_SHOOT_SOUND = @"sounds\particle\playerShoot"; readonly string PLAYER_DEAD_SOUND = @"sounds\player\playerDead"; readonly string ENEMY_DAMAGE_SOUND = @"sounds\enemy\enemyDamage"; readonly string BORDER_TEXTURE = @"images\background\black"; readonly string BACKGROUND_TEXTURE = @"images\menu\menuBackground"; readonly string PLAYER_TEXTURE = @"images\player\player00"; readonly string PLAYER_TEXTURE_ALPHA = @"images\player\player00_a"; readonly string MISSILE_TEXTURE = @"images\player\player00"; readonly string MISSILE_TEXTURE_ALPHA = @"images\player\player00_a"; readonly string TEXT_FONT = @"spritefonts\menuFont"; readonly string BULLETS_TEXTURE = @"images\particles\etama3"; readonly string BULLETS_TEXTURE_ALPHA = @"images\particles\etama3_a"; readonly string STAGE1_ENM_TEXTURE = @"images\enemy\stg1enm"; readonly string STAGE1_ENM_TEXTURE_ALPHA = @"images\enemy\stg1enm_a"; readonly string STAGE1_ENM2_TEXTURE = @"images\enemy\stg1enm2"; readonly string STAGE1_ENM2_TEXUTURE_ALPHA = @"images\enemy\stg1enm2_a"; readonly string ALPHA_SHADER = @"alpha\AlphaMap"; readonly string BULLETS = "BULLETS"; readonly string STAGE1_ENM = "STAGE1_ENM"; readonly string STAGE1_ENM2 = "STAGE1_ENM2"; readonly string GRAY_KNIFE = "GRAY_KNIFE"; readonly string RED_KNIFE = "RED_KNIFE"; readonly string PINK_KNIFE = "PINK_KNIFE"; readonly string BLUE_KNIFE = "BLUE_KNIFE"; readonly string TURQUOISE_KNIFE = "TURQUOISE_KNIFE"; readonly string GREEN_KNIFE = "GREEN_KNIFE"; readonly string YELLOW_KNIFE = "YELLOW_KNIFE"; readonly string WHITE_KNIFE = "WHITE_KNIFE"; readonly string FAIRIES = "FAIRIES"; readonly int PLAYER_LIFES_COUNT = 100; readonly int PLAYER_FRAMES_IMAGE_COUNT = 4; readonly float PLAYER_IMAGE_SCALE = 1f; readonly float FAIRIES_SCALE = 1.5f; readonly Vector2 PLAYER_INITIAL_POSITION = new Vector2(300, 200); readonly Vector2 PLAYER_LEFT_PARTICLE_POSITION = new Vector2(-9, -15); readonly Vector2 PLAYER_RIGHT_PARTICLE_POSITION = new Vector2(6, -15); readonly Rectangle PLAYER_PARTICLE_PART = new Rectangle(197, 0, 8, 47); readonly int PLAYER_PARTICLE_DAMAGE = 20; readonly float PLAYER_PARTICLE_SPEED = 15; readonly float PLAYER_PARTICLE_IMAGE_SCALE = 1f; readonly float KNIFE_SCALE = 1.25f; readonly Vector2 MENU_MARGIN = new Vector2(200, 200); readonly Rectangle GRAY_KNIFE_PART = new Rectangle(0, 160, 32, 32); readonly Rectangle RED_KNIFE_PART = new Rectangle(32, 160, 32, 32); readonly Rectangle PINK_KNIFE_PART = new Rectangle(64, 160, 32, 32); readonly Rectangle BLUE_KNIFE_PART = new Rectangle(96, 160, 32, 32); readonly Rectangle TURQUOISE_KNIFE_PART = new Rectangle(128, 160, 32, 32); readonly Rectangle GREEN_KNIFE_PART = new Rectangle(160, 160, 32, 32); readonly Rectangle YELLOW_KNIFE_PART = new Rectangle(192, 160, 32, 32); readonly Rectangle WHITE_KNIFE_PART = new Rectangle(224, 160, 32, 32); public Game1() { graphics = new GraphicsDeviceManager(this); this.graphics.PreferredBackBufferWidth = WINDOW_WIDTH; this.graphics.PreferredBackBufferHeight = WINDOW_HEIGHT; this.graphics.IsFullScreen = IS_FULLSCREEN; this.Window.AllowUserResizing = ALLOW_RESIZING; graphics.SynchronizeWithVerticalRetrace = false; Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { api = new GameApi(); api.instantiateGameController(this, Content, GraphicsDevice); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { api.loadSound(GameApi.LoadHelper.MENU_SELECT_SOUND, MENU_SELECT_SOUND); api.loadSound(GameApi.LoadHelper.PLAYER_SHOOT_SOUND, PLAYER_SHOOT_SOUND); api.loadSound(GameApi.LoadHelper.PLAYER_DIES_SOUND, PLAYER_DEAD_SOUND); api.loadSound(GameApi.LoadHelper.ENEMY_DAMAGE_SOUND, ENEMY_DAMAGE_SOUND); api.loadImage(GameApi.LoadHelper.BORDER_TEXTURE, BORDER_TEXTURE); api.loadImage(GameApi.LoadHelper.BACKGROUND_TEXTURE, BACKGROUND_TEXTURE); api.loadImage(GameApi.LoadHelper.PLAYER_TEXTURE, PLAYER_TEXTURE, PLAYER_TEXTURE_ALPHA); api.loadImage(GameApi.LoadHelper.MISSILE_TEXTURE, MISSILE_TEXTURE, MISSILE_TEXTURE_ALPHA); api.loadFont(GameApi.LoadHelper.TEXT_FONT, TEXT_FONT); api.createScreenMenu(MENU_MARGIN); api.createPauseMenu(MENU_MARGIN); api.createInGameBackground(); api.loadImage(BULLETS, BULLETS_TEXTURE, BULLETS_TEXTURE_ALPHA); api.loadImage(STAGE1_ENM, STAGE1_ENM_TEXTURE, STAGE1_ENM_TEXTURE_ALPHA); api.loadImage(STAGE1_ENM2, STAGE1_ENM2_TEXTURE, STAGE1_ENM2_TEXUTURE_ALPHA); api.loadAlphaShader(ALPHA_SHADER); api.createPlayer(PLAYER_PARTS, PLAYER_LIFES_COUNT, PLAYER_INITIAL_POSITION, PLAYER_FRAMES_IMAGE_COUNT, PLAYER_IMAGE_SCALE); api.createPlayerParticle(PLAYER_LEFT_PARTICLE_POSITION, PLAYER_RIGHT_PARTICLE_POSITION, PLAYER_PARTICLE_PART, PLAYER_PARTICLE_DAMAGE, PLAYER_PARTICLE_SPEED, PLAYER_PARTICLE_IMAGE_SCALE); api.createParticle(GRAY_KNIFE, BULLETS, GRAY_KNIFE_PART, KNIFE_SCALE); api.createParticle(RED_KNIFE, BULLETS, RED_KNIFE_PART, KNIFE_SCALE); api.createParticle(PINK_KNIFE, BULLETS, PINK_KNIFE_PART, KNIFE_SCALE); api.createParticle(BLUE_KNIFE, BULLETS, BLUE_KNIFE_PART, KNIFE_SCALE); api.createParticle(TURQUOISE_KNIFE, BULLETS, TURQUOISE_KNIFE_PART, KNIFE_SCALE); api.createParticle(GREEN_KNIFE, BULLETS, GREEN_KNIFE_PART, KNIFE_SCALE); api.createParticle(YELLOW_KNIFE, BULLETS, YELLOW_KNIFE_PART, KNIFE_SCALE); api.createParticle(WHITE_KNIFE, BULLETS, WHITE_KNIFE_PART, KNIFE_SCALE); api.createEnemy(FAIRIES, STAGE1_ENM, FAIRIES_PARTS, FAIRIES_FRAMES_IMAGE_COUNT, FAIRIES_SCALE); if (scriptData == null) { api.createStageFromPath(@"script.json"); } else { api.createStage(scriptData); } } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { api.dispose(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } api.update(gameTime); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Green); api.draw(); base.Draw(gameTime); } } }
using System; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; namespace NXTLib.USBWrapper { /// <summary> /// Routines for the WinUsb driver supported by Windows Vista and Windows XP. /// </summary> sealed internal partial class WinUsbDevice { internal struct devInfo { internal SafeFileHandle deviceHandle; internal IntPtr winUsbHandle; internal Byte bulkInPipe; internal Byte bulkOutPipe; internal Byte interruptInPipe; internal Byte interruptOutPipe; internal UInt32 devicespeed; } internal devInfo myDevInfo = new devInfo(); /// <summary> /// Closes the device handle obtained with CreateFile and frees resources. /// </summary> internal void CloseDeviceHandle() { WinUsb_Free(myDevInfo.winUsbHandle); if (!(myDevInfo.deviceHandle == null)) { if (!(myDevInfo.deviceHandle.IsInvalid)) { myDevInfo.deviceHandle.Close(); } } } /// <summary> /// Initiates a Control Read transfer. Data stage is device to host. /// </summary> /// <param name="dataStage"> The received data. </param> /// <returns> /// True on success, False on failure. /// </returns> internal Boolean Do_Control_Read_Transfer(ref Byte[] dataStage) { UInt32 bytesReturned = 0; WINUSB_SETUP_PACKET setupPacket; Boolean success; // Vendor-specific request to an interface with device-to-host Data stage. setupPacket.RequestType = 0XC1; // The request number that identifies the specific request. setupPacket.Request = 2; // Command-specific value to send to the device. setupPacket.Index = 0; // Number of bytes in the request's Data stage. setupPacket.Length = System.Convert.ToUInt16(dataStage.Length); // Command-specific value to send to the device. setupPacket.Value = 0; // *** // winusb function // summary // Initiates a control transfer. // paramaters // Device handle returned by WinUsb_Initialize. // WINUSB_SETUP_PACKET structure // Buffer to hold the returned Data-stage data. // Number of data bytes to read in the Data stage. // Number of bytes read in the Data stage. // Null pointer for non-overlapped. // returns // True on success. // *** success = WinUsb_ControlTransfer(myDevInfo.winUsbHandle, setupPacket, dataStage, System.Convert.ToUInt16(dataStage.Length), ref bytesReturned, IntPtr.Zero); return success; } /// <summary> /// Initiates a Control Write transfer. Data stage is host to device. /// </summary> /// <param name="dataStage"> The data to send. </param> /// <returns> /// True on success, False on failure. /// </returns> internal Boolean Do_Control_Write_Transfer(Byte[] dataStage) { UInt32 bytesReturned = 0; ushort index = System.Convert.ToUInt16(0); WINUSB_SETUP_PACKET setupPacket; Boolean success; ushort value = System.Convert.ToUInt16(0); // Vendor-specific request to an interface with host-to-device Data stage. setupPacket.RequestType = 0X41; // The request number that identifies the specific request. setupPacket.Request = 1; // Command-specific value to send to the device. setupPacket.Index = index; // Number of bytes in the request's Data stage. setupPacket.Length = System.Convert.ToUInt16(dataStage.Length); // Command-specific value to send to the device. setupPacket.Value = value; // *** // winusb function // summary // Initiates a control transfer. // parameters // Device handle returned by WinUsb_Initialize. // WINUSB_SETUP_PACKET structure // Buffer containing the Data-stage data. // Number of data bytes to send in the Data stage. // Number of bytes sent in the Data stage. // Null pointer for non-overlapped. // Returns // True on success. // *** success = WinUsb_ControlTransfer (myDevInfo.winUsbHandle, setupPacket, dataStage, System.Convert.ToUInt16(dataStage.Length), ref bytesReturned, IntPtr.Zero); return success; } /// <summary> /// Requests a handle with CreateFile. /// </summary> /// /// <param name="devicePathName"> Returned by SetupDiGetDeviceInterfaceDetail /// in an SP_DEVICE_INTERFACE_DETAIL_DATA structure. </param> /// /// <returns> /// The handle. /// </returns> internal Boolean GetDeviceHandle(String devicePathName) { // *** // API function // summary // Retrieves a handle to a device. // parameters // Device path name returned by SetupDiGetDeviceInterfaceDetail // Type of access requested (read/write). // FILE_SHARE attributes to allow other processes to access the device while this handle is open. // Security structure. Using Null for this may cause problems under Windows XP. // Creation disposition value. Use OPEN_EXISTING for devices. // Flags and attributes for files. The winsub driver requires FILE_FLAG_OVERLAPPED. // Handle to a template file. Not used. // Returns // A handle or INVALID_HANDLE_VALUE. // *** myDevInfo.deviceHandle = FileIO.CreateFile (devicePathName, (FileIO.GENERIC_WRITE | FileIO.GENERIC_READ), FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED, 0); if (!(myDevInfo.deviceHandle.IsInvalid)) { return true; } else { return false; } } /// <summary> /// Initializes a device interface and obtains information about it. /// Calls these winusb API functions: /// WinUsb_Initialize /// WinUsb_QueryInterfaceSettings /// WinUsb_QueryPipe /// </summary> /// /// <returns> /// True on success, False on failure. /// </returns> internal Boolean InitializeDevice() { USB_INTERFACE_DESCRIPTOR ifaceDescriptor; WINUSB_PIPE_INFORMATION pipeInfo; UInt32 pipeTimeout = 2000; Boolean success; ifaceDescriptor.bLength = 0; ifaceDescriptor.bDescriptorType = 0; ifaceDescriptor.bInterfaceNumber = 0; ifaceDescriptor.bAlternateSetting = 0; ifaceDescriptor.bNumEndpoints = 0; ifaceDescriptor.bInterfaceClass = 0; ifaceDescriptor.bInterfaceSubClass = 0; ifaceDescriptor.bInterfaceProtocol = 0; ifaceDescriptor.iInterface = 0; pipeInfo.PipeType = 0; pipeInfo.PipeId = 0; pipeInfo.MaximumPacketSize = 0; pipeInfo.Interval = 0; // *** // winusb function // summary // get a handle for communications with a winusb device ' // parameters // Handle returned by CreateFile. // Device handle to be returned. // returns // True on success. // *** success = WinUsb_Initialize (myDevInfo.deviceHandle, ref myDevInfo.winUsbHandle); if (success) { // *** // winusb function // summary // Get a structure with information about the device interface. // parameters // handle returned by WinUsb_Initialize // alternate interface setting number // USB_INTERFACE_DESCRIPTOR structure to be returned. // returns // True on success. success = WinUsb_QueryInterfaceSettings (myDevInfo.winUsbHandle, 0, ref ifaceDescriptor); if (success) { // Get the transfer type, endpoint number, and direction for the interface's // bulk and interrupt endpoints. Set pipe policies. // *** // winusb function // summary // returns information about a USB pipe (endpoint address) // parameters // Handle returned by WinUsb_Initialize // Alternate interface setting number // Number of an endpoint address associated with the interface. // (The values count up from zero and are NOT the same as the endpoint address // in the endpoint descriptor.) // WINUSB_PIPE_INFORMATION structure to be returned // returns // True on success // *** for (Int32 i = 0; i <= ifaceDescriptor.bNumEndpoints - 1; i++) { WinUsb_QueryPipe (myDevInfo.winUsbHandle, 0, System.Convert.ToByte(i), ref pipeInfo); if (((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeBulk) & UsbEndpointDirectionIn(pipeInfo.PipeId))) { myDevInfo.bulkInPipe = pipeInfo.PipeId; SetPipePolicy (myDevInfo.bulkInPipe, Convert.ToUInt32(POLICY_TYPE.IGNORE_SHORT_PACKETS), Convert.ToByte(false)); SetPipePolicy (myDevInfo.bulkInPipe, Convert.ToUInt32(POLICY_TYPE.PIPE_TRANSFER_TIMEOUT), pipeTimeout); } else if (((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeBulk) & UsbEndpointDirectionOut(pipeInfo.PipeId))) { myDevInfo.bulkOutPipe = pipeInfo.PipeId; SetPipePolicy (myDevInfo.bulkOutPipe, Convert.ToUInt32(POLICY_TYPE.IGNORE_SHORT_PACKETS), Convert.ToByte(false)); SetPipePolicy (myDevInfo.bulkOutPipe, Convert.ToUInt32(POLICY_TYPE.PIPE_TRANSFER_TIMEOUT), pipeTimeout); } else if ((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeInterrupt) & UsbEndpointDirectionIn(pipeInfo.PipeId)) { myDevInfo.interruptInPipe = pipeInfo.PipeId; SetPipePolicy (myDevInfo.interruptInPipe, Convert.ToUInt32(POLICY_TYPE.IGNORE_SHORT_PACKETS), Convert.ToByte(false)); SetPipePolicy (myDevInfo.interruptInPipe, Convert.ToUInt32(POLICY_TYPE.PIPE_TRANSFER_TIMEOUT), pipeTimeout); } else if ((pipeInfo.PipeType == USBD_PIPE_TYPE.UsbdPipeTypeInterrupt) & UsbEndpointDirectionOut(pipeInfo.PipeId)) { myDevInfo.interruptOutPipe = pipeInfo.PipeId; SetPipePolicy (myDevInfo.interruptOutPipe, Convert.ToUInt32(POLICY_TYPE.IGNORE_SHORT_PACKETS), Convert.ToByte(false)); SetPipePolicy (myDevInfo.interruptOutPipe, Convert.ToUInt32(POLICY_TYPE.PIPE_TRANSFER_TIMEOUT), pipeTimeout); } } } else { success = false; } } return success; } /// <summary> /// Is the current operating system Windows XP or later? /// The WinUSB driver requires Windows XP or later. /// </summary> /// <returns> /// True if Windows XP or later, False if not. /// </returns> internal Boolean IsWindowsXpOrLater() { OperatingSystem myEnvironment = Environment.OSVersion; // Windows XP is version 5.1. System.Version versionXP = new System.Version(5, 1); if (myEnvironment.Version >= versionXP) { return true; } else { return false; } } /// <summary> /// Gets a value that corresponds to a USB_DEVICE_SPEED. /// </summary> internal Boolean QueryDeviceSpeed() { UInt32 length = 1; Byte[] speed = new Byte[1]; Boolean success; // *** // winusb function // summary // Get the device speed. // (Normally not required but can be nice to know.) // parameters // Handle returned by WinUsb_Initialize // Requested information type. // Number of bytes to read. // Information to be returned. // returns // True on success. // *** success = WinUsb_QueryDeviceInformation (myDevInfo.winUsbHandle, DEVICE_SPEED, ref length, ref speed[0]); if (success) { myDevInfo.devicespeed = System.Convert.ToUInt32(speed[0]); } return success; } /// <summary> /// Attempts to read data from a bulk IN endpoint. /// </summary> /// /// <param name="pipeID"> Endpoint address. </param> /// <param name="bytesToRead"> Number of bytes to read. </param> /// <param name="buffer"> Buffer for storing the bytes read. </param> /// <param name="bytesRead"> Number of bytes read. </param> /// <param name="success"> Success or failure status. </param> /// internal void ReadViaBulkTransfer(Byte pipeID, UInt32 bytesToRead, ref Byte[] buffer, ref UInt32 bytesRead, ref Boolean success) { // *** // winusb function // summary // Attempts to read data from a device interface. // parameters // Device handle returned by WinUsb_Initialize. // Endpoint address. // Buffer to store the data. // Maximum number of bytes to return. // Number of bytes read. // Null pointer for non-overlapped. // Returns // True on success. // *** success = WinUsb_ReadPipe (myDevInfo.winUsbHandle, pipeID, buffer, bytesToRead, ref bytesRead, IntPtr.Zero); if (!(success)) { CloseDeviceHandle(); } } /// <summary> /// Attempts to read data from an interrupt IN endpoint. /// </summary> /// /// <param name="pipeID"> Endpoint address. </param> /// <param name="bytesToRead"> Number of bytes to read. </param> /// <param name="buffer"> Buffer for storing the bytes read. </param> /// <param name="bytesRead"> Number of bytes read. </param> /// <param name="success"> Success or failure status. </param> internal void ReadViaInterruptTransfer(Byte pipeID, UInt32 bytesToRead, ref Byte[] buffer, ref UInt32 bytesRead, ref Boolean success) { // *** // winusb function // summary // Attempts to read data from a device interface. // parameters // Device handle returned by WinUsb_Initialize. // Endpoint address. // Buffer to store the data. // Maximum number of bytes to return. // Number of bytes read. // Null pointer for non-overlapped. // Returns // True on success. // *** success = WinUsb_ReadPipe (myDevInfo.winUsbHandle, pipeID, buffer, bytesToRead, ref bytesRead, IntPtr.Zero); if (!(success)) { CloseDeviceHandle(); } } /// <summary> /// Attempts to send data via a bulk OUT endpoint. /// </summary> /// /// <param name="buffer"> Buffer containing the bytes to write. </param> /// <param name="bytesToWrite"> Number of bytes to write. </param> /// /// <returns> /// True on success, False on failure. /// </returns> internal Boolean SendViaBulkTransfer(ref Byte[] buffer, UInt32 bytesToWrite) { UInt32 bytesWritten = 0; Boolean success; // *** // winusb function // summary // Attempts to write data to a device interface. // parameters // Device handle returned by WinUsb_Initialize. // Endpoint address. // Buffer with data to write. // Number of bytes to write. // Number of bytes written. // IntPtr.Zero for non-overlapped I/O. // Returns // True on success. // *** success = WinUsb_WritePipe (myDevInfo.winUsbHandle, myDevInfo.bulkOutPipe, buffer, bytesToWrite, ref bytesWritten, IntPtr.Zero); if (!(success)) { CloseDeviceHandle(); } return success; } /// <summary> /// Attempts to send data via an interrupt OUT endpoint. /// </summary> /// /// <param name="buffer"> Buffer containing the bytes to write. </param> /// <param name="bytesToWrite"> Number of bytes to write. </param> /// /// <returns> /// True on success, False on failure. /// </returns> internal Boolean SendViaInterruptTransfer(ref Byte[] buffer, UInt32 bytesToWrite) { UInt32 bytesWritten = 0; Boolean success; // *** // winusb function // summary // Attempts to write data to a device interface. // parameters // Device handle returned by WinUsb_Initialize. // Endpoint address. // Buffer with data to write. // Number of bytes to write. // Number of bytes written. // IntPtr.Zero for non-overlapped I/O. // Returns // True on success. // *** success = WinUsb_WritePipe (myDevInfo.winUsbHandle, myDevInfo.interruptOutPipe, buffer, bytesToWrite, ref bytesWritten, IntPtr.Zero); if (!(success)) { CloseDeviceHandle(); } return success; } /// <summary> /// Sets pipe policy. /// Used when the value parameter is a Byte (all except PIPE_TRANSFER_TIMEOUT). /// </summary> /// /// <param name="pipeId"> Pipe to set a policy for. </param> /// <param name="policyType"> POLICY_TYPE member. </param> /// <param name="value"> Policy value. </param> /// /// <returns> /// True on success, False on failure. /// </returns> /// private Boolean SetPipePolicy(Byte pipeId, UInt32 policyType, Byte value) { Boolean success; // *** // winusb function // summary // sets a pipe policy // parameters // handle returned by WinUsb_Initialize // identifies the pipe // POLICY_TYPE member. // length of value in bytes // value to set for the policy. // returns // True on success // *** success = WinUsb_SetPipePolicy (myDevInfo.winUsbHandle, pipeId, policyType, 1, ref value); return success; } /// <summary> /// Sets pipe policy. /// Used when the value parameter is a UInt32 (PIPE_TRANSFER_TIMEOUT only). /// </summary> /// /// <param name="pipeId"> Pipe to set a policy for. </param> /// <param name="policyType"> POLICY_TYPE member. </param> /// <param name="value"> Policy value. </param> /// /// <returns> /// True on success, False on failure. /// </returns> /// private Boolean SetPipePolicy(Byte pipeId, UInt32 policyType, UInt32 value) { Boolean success; // *** // winusb function // summary // sets a pipe policy // parameters // handle returned by WinUsb_Initialize // identifies the pipe // POLICY_TYPE member. // length of value in bytes // value to set for the policy. // returns // True on success // *** success = WinUsb_SetPipePolicy1 (myDevInfo.winUsbHandle, pipeId, policyType, 4, ref value); return success; } /// <summary> /// Is the endpoint's direction IN (device to host)? /// </summary> /// /// <param name="addr"> The endpoint address. </param> /// <returns> /// True if IN (device to host), False if OUT (host to device) /// </returns> private Boolean UsbEndpointDirectionIn(Int32 addr) { Boolean directionIn; try { if (((addr & 0X80) == 0X80)) { directionIn = true; } else { directionIn = false; } } catch { throw; } return directionIn; } /// <summary> /// Is the endpoint's direction OUT (host to device)? /// </summary> /// /// <param name="addr"> The endpoint address. </param> /// /// <returns> /// True if OUT (host to device, False if IN (device to host) /// </returns> private Boolean UsbEndpointDirectionOut(Int32 addr) { Boolean directionOut; try { if (((addr & 0X80) == 0)) { directionOut = true; } else { directionOut = false; } } catch { throw; } return directionOut; } } }
using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { public abstract class CCTransitionProgress : CCTransitionScene { const int SceneRadial = 0xc001; protected float From; protected float To; protected CCNode SceneNodeContainerToBeModified; #region Constructors public CCTransitionProgress(float t, CCScene scene) : base(t, scene) { } #endregion Constructors protected override void InitialiseScenes() { if (Layer == null || Viewport == null) return; base.InitialiseScenes(); SetupTransition(); // create a transparent color layer // in which we are going to add our rendertextures var bounds = Layer.VisibleBoundsWorldspace; CCRect viewportRect = Viewport.ViewportInPixels; // create the second render texture for outScene CCRenderTexture texture = new CCRenderTexture(bounds.Size, viewportRect.Size); texture.Position = bounds.Center; texture.AnchorPoint = CCPoint.AnchorMiddle; // Temporarily add render texture to get layer/scene properties Layer.AddChild(texture); texture.Visible = false; // Render outScene to its texturebuffer texture.BeginWithClear(1, 1, 1, 1); SceneNodeContainerToBeModified.Visit(); texture.End(); texture.Visible = true; // No longer want to render texture RemoveChild(texture); // Since we've passed the outScene to the texture we don't need it. if (SceneNodeContainerToBeModified == OutSceneNodeContainer) { HideOutShowIn(); } CCProgressTimer node = ProgressTimerNodeWithRenderTexture(texture); // create the blend action var layerAction = new CCProgressFromTo(Duration, From, To); // add the layer (which contains our two rendertextures) to the scene AddChild(node, 2, SceneRadial); // run the blend action node.RunAction(layerAction); } // clean up on exit public override void OnExit() { // remove our layer and release all containing objects RemoveChildByTag(SceneRadial, true); base.OnExit(); } protected abstract CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture); protected virtual void SetupTransition() { SceneNodeContainerToBeModified = OutSceneNodeContainer; From = 100; To = 0; } protected override void SceneOrder() { IsInSceneOnTop = false; } } /** CCTransitionRadialCCW transition. A counter colock-wise radial transition to the next scene */ public class CCTransitionProgressRadialCCW : CCTransitionProgress { public CCTransitionProgressRadialCCW(float t, CCScene scene) : base(t, scene) { } protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture) { var bounds = Layer.VisibleBoundsWorldspace; CCProgressTimer node = new CCProgressTimer(texture.Sprite); // but it is flipped upside down so we flip the sprite //node.Sprite.IsFlipY = true; node.Type = CCProgressTimerType.Radial; // Return the radial type that we want to use node.ReverseDirection = false; node.Percentage = 100; node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2); node.AnchorPoint = CCPoint.AnchorMiddle; return node; } } /** CCTransitionRadialCW transition. A counter colock-wise radial transition to the next scene */ public class CCTransitionProgressRadialCW : CCTransitionProgress { public CCTransitionProgressRadialCW(float t, CCScene scene) : base(t, scene) { } protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture) { var bounds = Layer.VisibleBoundsWorldspace; CCProgressTimer node = new CCProgressTimer(texture.Sprite); // but it is flipped upside down so we flip the sprite //node.Sprite.IsFlipY = true; node.Type = CCProgressTimerType.Radial; // Return the radial type that we want to use node.ReverseDirection = true; node.Percentage = 100; node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2); node.AnchorPoint = CCPoint.AnchorMiddle; return node; } } /** CCTransitionProgressHorizontal transition. A colock-wise radial transition to the next scene */ public class CCTransitionProgressHorizontal : CCTransitionProgress { public CCTransitionProgressHorizontal(float t, CCScene scene) : base(t, scene) { } protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture) { var bounds = Layer.VisibleBoundsWorldspace; CCProgressTimer node = new CCProgressTimer(texture.Sprite); // but it is flipped upside down so we flip the sprite //node.Sprite.IsFlipY = true; node.Type = CCProgressTimerType.Bar; node.Midpoint = new CCPoint(1, 0); node.BarChangeRate = new CCPoint(1, 0); node.Percentage = 100; node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2); node.AnchorPoint = CCPoint.AnchorMiddle; return node; } } public class CCTransitionProgressVertical : CCTransitionProgress { //OLD_TRANSITION_CREATE_FUNC(CCTransitionProgressVertical) //TRANSITION_CREATE_FUNC(CCTransitionProgressVertical) public CCTransitionProgressVertical(float t, CCScene scene) : base(t, scene) { } protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture) { var bounds = Layer.VisibleBoundsWorldspace; CCProgressTimer node = new CCProgressTimer(texture.Sprite); // but it is flipped upside down so we flip the sprite //node.Sprite.IsFlipY = true; node.Type = CCProgressTimerType.Bar; node.Midpoint = new CCPoint(0, 0); node.BarChangeRate = new CCPoint(0, 1); node.Percentage = 100; node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2); node.AnchorPoint = CCPoint.AnchorMiddle; return node; } } public class CCTransitionProgressInOut : CCTransitionProgress { public CCTransitionProgressInOut(float t, CCScene scene) : base(t, scene) { } protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture) { var bounds = Layer.VisibleBoundsWorldspace; CCProgressTimer node = new CCProgressTimer(texture.Sprite); // but it is flipped upside down so we flip the sprite //node.Sprite.IsFlipY = true; node.Type = CCProgressTimerType.Bar; node.Midpoint = new CCPoint(0.5f, 0.5f); node.BarChangeRate = new CCPoint(1, 1); node.Percentage = 0; node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2); node.AnchorPoint = CCPoint.AnchorMiddle; return node; } protected override void SceneOrder() { IsInSceneOnTop = false; } protected override void SetupTransition() { SceneNodeContainerToBeModified = InSceneNodeContainer; From = 0; To = 100; } } public class CCTransitionProgressOutIn : CCTransitionProgress { public CCTransitionProgressOutIn(float t, CCScene scene) : base(t, scene) { } protected override CCProgressTimer ProgressTimerNodeWithRenderTexture(CCRenderTexture texture) { var bounds = Layer.VisibleBoundsWorldspace; CCProgressTimer node = new CCProgressTimer(texture.Sprite); // but it is flipped upside down so we flip the sprite //node.Sprite.IsFlipY = true; node.Type = CCProgressTimerType.Bar; node.Midpoint = new CCPoint(0.5f, 0.5f); node.BarChangeRate = new CCPoint(1, 1); node.Percentage = 100; node.Position = new CCPoint(bounds.Origin.X + bounds.Size.Width / 2, bounds.Size.Height / 2); node.AnchorPoint = CCPoint.AnchorMiddle; return node; } } }
// <copyright file="ChiSquareTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous { using Random = System.Random; /// <summary> /// Chi square distribution test /// </summary> [TestFixture, Category("Distributions")] public class ChiSquareTests { /// <summary> /// Can create chi square. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(1.0)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void CanCreateChiSquare(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof, n.DegreesOfFreedom); } /// <summary> /// Chi square create fails with bad parameters. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(0.0)] [TestCase(-1.0)] [TestCase(-100.0)] [TestCase(Double.NegativeInfinity)] [TestCase(Double.NaN)] public void ChiSquareCreateFailsWithBadParameters(double dof) { Assert.That(() => new ChiSquared(dof), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var n = new ChiSquared(1.0); Assert.AreEqual("ChiSquared(k = 1)", n.ToString()); } /// <summary> /// Validate mean. /// </summary> /// <param name="dof">Degrees of freedom.</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(5.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMean(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof, n.Mean); } /// <summary> /// Validate variance. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateVariance(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(2 * dof, n.Variance); } /// <summary> /// Validate standard deviation /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateStdDev(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(Math.Sqrt(n.Variance), n.StdDev); } /// <summary> /// Validate mode. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMode(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof - 2, n.Mode); } /// <summary> /// Validate median. /// </summary> /// <param name="dof">Degrees of freedom</param> [TestCase(1.0)] [TestCase(2.0)] [TestCase(2.5)] [TestCase(3.0)] [TestCase(Double.PositiveInfinity)] public void ValidateMedian(double dof) { var n = new ChiSquared(dof); Assert.AreEqual(dof - (2.0 / 3.0), n.Median); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var n = new ChiSquared(1.0); Assert.AreEqual(0.0, n.Minimum); } /// <summary> /// Validate maximum. /// </summary> [Test] public void ValidateMaximum() { var n = new ChiSquared(1.0); Assert.AreEqual(Double.PositiveInfinity, n.Maximum); } /// <summary> /// Validate density. /// </summary> /// <remarks>Reference: N[PDF[ChiSquaredDistribution[dof],x],20]</remarks> [TestCase(1.0, 0.0, 0.0)] [TestCase(1.0, 0.1, 1.2000389484301359798)] [TestCase(1.0, 1.0, 0.24197072451914334980)] [TestCase(1.0, 5.5, 0.010874740337283141714)] [TestCase(1.0, 110.1, 4.7000792147504127122e-26)] [TestCase(1.0, Double.PositiveInfinity, 0.0)] [TestCase(2.0, 0.0, 0.0)] [TestCase(2.0, 0.1, 0.47561471225035700455)] [TestCase(2.0, 1.0, 0.30326532985631671180)] [TestCase(2.0, 5.5, 0.031963930603353786351)] [TestCase(2.0, 110.1, 6.1810004550085248492e-25)] [TestCase(2.0, Double.PositiveInfinity, 0.0)] [TestCase(2.5, 0.0, 0.0)] [TestCase(2.5, 0.1, 0.24812852712543073541)] [TestCase(2.5, 1.0, 0.28134822576318228131)] [TestCase(2.5, 5.5, 0.045412171451573920401)] [TestCase(2.5, 110.1, 1.8574923023527248767e-24)] [TestCase(2.5, Double.PositiveInfinity, 0.0)] [TestCase(Double.PositiveInfinity, 0.0, 0.0)] [TestCase(Double.PositiveInfinity, 0.1, 0.0)] [TestCase(Double.PositiveInfinity, 1.0, 0.0)] [TestCase(Double.PositiveInfinity, 5.5, 0.0)] [TestCase(Double.PositiveInfinity, 110.1, 0.0)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity, 0.0)] public void ValidateDensity(double dof, double x, double expected) { var chiSquared = new ChiSquared(dof); Assert.That(chiSquared.Density(x), Is.EqualTo(expected).Within(13)); Assert.That(ChiSquared.PDF(dof, x), Is.EqualTo(expected).Within(13)); } /// <summary> /// Validate density log. /// </summary> /// <remarks>Reference: N[Ln[PDF[ChiSquaredDistribution[dof],x]],20]</remarks> [TestCase(1.0, 0.0, Double.NegativeInfinity)] [TestCase(1.0, 0.1, 0.18235401329235010023)] [TestCase(1.0, 1.0, -1.4189385332046727418)] [TestCase(1.0, 5.5, -4.5213125793238853591)] [TestCase(1.0, 110.1, -58.319633055068989881)] [TestCase(1.0, Double.PositiveInfinity, Double.NegativeInfinity)] [TestCase(2.0, 0.0, Double.NegativeInfinity)] [TestCase(2.0, 0.1, -0.74314718055994530942)] [TestCase(2.0, 1.0, -1.1931471805599453094)] [TestCase(2.0, 5.5, -3.4431471805599453094)] [TestCase(2.0, 110.1, -55.743147180559945309)] [TestCase(2.0, Double.PositiveInfinity, Double.NegativeInfinity)] [TestCase(2.5, 0.0, Double.NegativeInfinity)] [TestCase(2.5, 0.1, -1.3938084125266298963)] [TestCase(2.5, 1.0, -1.2681621392781184753)] [TestCase(2.5, 5.5, -3.0919751162185121666)] [TestCase(2.5, 110.1, -54.642814878345959906)] [TestCase(2.5, Double.PositiveInfinity, Double.NegativeInfinity)] [TestCase(Double.PositiveInfinity, 0.0, Double.NegativeInfinity)] [TestCase(Double.PositiveInfinity, 0.1, Double.NegativeInfinity)] [TestCase(Double.PositiveInfinity, 1.0, Double.NegativeInfinity)] [TestCase(Double.PositiveInfinity, 5.5, Double.NegativeInfinity)] [TestCase(Double.PositiveInfinity, 110.1, Double.NegativeInfinity)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity, Double.NegativeInfinity)] public void ValidateDensityLn(double dof, double x, double expected) { var chiSquared = new ChiSquared(dof); Assert.That(chiSquared.DensityLn(x), Is.EqualTo(expected).Within(13)); Assert.That(ChiSquared.PDFLn(dof, x), Is.EqualTo(expected).Within(13)); } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { ChiSquared.Sample(new Random(0), 2.0); } /// <summary> /// Fail sample static with bad parameters. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => ChiSquared.Sample(new Random(0), -1.0), Throws.ArgumentException); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new ChiSquared(1.0); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new ChiSquared(1.0); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="dof">Degrees of freedom.</param> /// <param name="x">Input X value.</param> /// <param name="expected">N[CDF[ChiSquaredDistribution[dof],x],20]</param> [TestCase(1.0, 0.0, 0.0)] [TestCase(1.0, 0.1, 0.24817036595415071751)] [TestCase(1.0, 1.0, 0.68268949213708589717)] [TestCase(1.0, 5.5, 0.98098352632769945624)] [TestCase(1.0, 110.1, 1.0)] [TestCase(2.0, 0.0, 0.0)] [TestCase(2.0, 0.1, 0.048770575499285990909)] [TestCase(2.0, 1.0, 0.39346934028736657640)] [TestCase(2.0, 5.5, 0.93607213879329242730)] [TestCase(2.0, 110.1, 1.0)] [TestCase(2.5, 0.0, 0.0)] [TestCase(2.5, 0.1, 0.020298266579604156571)] [TestCase(2.5, 1.0, 0.28378995266531297417)] [TestCase(2.5, 5.5, 0.90239512593899828629)] [TestCase(2.5, 110.1, 1.0)] [TestCase(10000.0, 1.0, 0.0)] [TestCase(10000.0, 7500.0, 3.3640453687878842514e-84)] [TestCase(20000.0, 1.0, 0.0)] public void ValidateCumulativeDistribution(double dof, double x, double expected) { var chiSquared = new ChiSquared(dof); Assert.That(chiSquared.CumulativeDistribution(x), Is.EqualTo(expected).Within(1e-14)); Assert.That(ChiSquared.CDF(dof, x), Is.EqualTo(expected).Within(1e-14)); } [TestCase(1.0, 0.0, 0.0)] [TestCase(1.0, 0.24817036595415071751, 0.1)] [TestCase(1.0, 0.68268949213708589717, 1.0)] [TestCase(1.0, 0.98098352632769945624, 5.5)] [TestCase(1.0, 1.0, Double.PositiveInfinity)] [TestCase(2.0, 0.0, 0.0)] [TestCase(2.0, 0.048770575499285990909, 0.1)] [TestCase(2.0, 0.39346934028736657640, 1.0)] [TestCase(2.0, 0.93607213879329242730, 5.5)] [TestCase(2.0, 1.0, Double.PositiveInfinity)] [TestCase(2.5, 0.0, 0.0)] [TestCase(2.5, 0.020298266579604156571, 0.1)] [TestCase(2.5, 0.28378995266531297417, 1.0)] [TestCase(2.5, 0.90239512593899828629, 5.5)] [TestCase(2.5, 1.0, Double.PositiveInfinity)] [TestCase(10000.0, 0.0, 0.0)] [TestCase(10000.0, 0.5, 9999.3333412343982)] [TestCase(20000.0, 0.0, 0.0)] [TestCase(100000, 0.1, 99427.302671875732)] public void ValidateInverseCumulativeDistribution(double dof, double x, double expected) { var chiSquared = new ChiSquared(dof); Assert.That(chiSquared.InverseCumulativeDistribution(x), Is.EqualTo(expected).Within(1e-14)); Assert.That(ChiSquared.InvCDF(dof, x), Is.EqualTo(expected).Within(1e-14)); } } }
namespace InControl { using System; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; public sealed class AutoDiscover : Attribute { } public class UnityInputDeviceProfile : UnityInputDeviceProfileBase { [SerializeField] protected string[] JoystickNames; [SerializeField] protected string[] JoystickRegex; [SerializeField] protected string LastResortRegex; [SerializeField] public VersionInfo MinUnityVersion { get; protected set; } [SerializeField] public VersionInfo MaxUnityVersion { get; protected set; } public UnityInputDeviceProfile() { Sensitivity = 1.0f; LowerDeadZone = 0.2f; UpperDeadZone = 0.9f; MinUnityVersion = new VersionInfo( 3, 0, 0, 0 ); MaxUnityVersion = new VersionInfo( 9, 0, 0, 0 ); } public override bool IsJoystick { get { return (LastResortRegex != null) || (JoystickNames != null && JoystickNames.Length > 0) || (JoystickRegex != null && JoystickRegex.Length > 0); } } public override bool HasJoystickName( string joystickName ) { if (IsNotJoystick) { return false; } if (JoystickNames != null) { if (JoystickNames.Contains( joystickName, StringComparer.OrdinalIgnoreCase )) { return true; } } if (JoystickRegex != null) { for (var i = 0; i < JoystickRegex.Length; i++) { if (Regex.IsMatch( joystickName, JoystickRegex[i], RegexOptions.IgnoreCase )) { return true; } } } return false; } public override bool HasLastResortRegex( string joystickName ) { if (IsNotJoystick) { return false; } if (LastResortRegex == null) { return false; } return Regex.IsMatch( joystickName, LastResortRegex, RegexOptions.IgnoreCase ); } public override bool HasJoystickOrRegexName( string joystickName ) { return HasJoystickName( joystickName ) || HasLastResortRegex( joystickName ); } public override bool IsSupportedOnThisPlatform { get { return IsSupportedOnThisVersionOfUnity && base.IsSupportedOnThisPlatform; } } bool IsSupportedOnThisVersionOfUnity { get { var unityVersion = VersionInfo.UnityVersion(); return unityVersion >= MinUnityVersion && unityVersion <= MaxUnityVersion; } } /* #region Serialization public string Save() { var data = JSON.Dump( this, EncodeOptions.PrettyPrint | EncodeOptions.NoTypeHints ); // Somewhat silly, but removes all default values for brevity. data = Regex.Replace( data, @"\t""JoystickRegex"": null,?\n", "" ); data = Regex.Replace( data, @"\t""LastResortRegex"": null,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""Invert"": false,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""Scale"": 1,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""Raw"": false,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""IgnoreInitialZeroValue"": false,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""Sensitivity"": 1,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""LowerDeadZone"": 0,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""UpperDeadZone"": 1,?\n", "" ); data = Regex.Replace( data, @"\t""Sensitivity"": 1,?\n", "" ); data = Regex.Replace( data, @"\t""LowerDeadZone"": 0.2,?\n", "" ); data = Regex.Replace( data, @"\t""UpperDeadZone"": 0.9,?\n", "" ); data = Regex.Replace( data, @"\t\t\t""(Source|Target)Range"": {\n\t\t\t\t""Value0"": -1,\n\t\t\t\t""Value1"": 1\n\t\t\t},?\n", "" ); data = Regex.Replace( data, @"\t""MinUnityVersion"": {\n\t\t""Major"": 3,\n\t\t""Minor"": 0,\n\t\t""Patch"": 0,\n\t\t""Build"": 0\n\t},?\n", "" ); data = Regex.Replace( data, @"\t""MaxUnityVersion"": {\n\t\t""Major"": 9,\n\t\t""Minor"": 0,\n\t\t""Patch"": 0,\n\t\t""Build"": 0\n\t},?\n", "" ); return data; } public static UnityInputDeviceProfile Load( string data ) { return JSON.Load( data ).Make<UnityInputDeviceProfile>(); } public void SaveToFile( string filePath ) { var data = Save(); Utility.WriteToFile( filePath, data ); } public static UnityInputDeviceProfile LoadFromFile( string filePath ) { var data = Utility.ReadFromFile( filePath ); return Load( data ); } #endregion */ #region InputControlSource helpers protected static InputControlSource Button( int index ) { return new UnityButtonSource( index ); } protected static InputControlSource Analog( int index ) { return new UnityAnalogSource( index ); } protected static InputControlSource Button0 = Button( 0 ); protected static InputControlSource Button1 = Button( 1 ); protected static InputControlSource Button2 = Button( 2 ); protected static InputControlSource Button3 = Button( 3 ); protected static InputControlSource Button4 = Button( 4 ); protected static InputControlSource Button5 = Button( 5 ); protected static InputControlSource Button6 = Button( 6 ); protected static InputControlSource Button7 = Button( 7 ); protected static InputControlSource Button8 = Button( 8 ); protected static InputControlSource Button9 = Button( 9 ); protected static InputControlSource Button10 = Button( 10 ); protected static InputControlSource Button11 = Button( 11 ); protected static InputControlSource Button12 = Button( 12 ); protected static InputControlSource Button13 = Button( 13 ); protected static InputControlSource Button14 = Button( 14 ); protected static InputControlSource Button15 = Button( 15 ); protected static InputControlSource Button16 = Button( 16 ); protected static InputControlSource Button17 = Button( 17 ); protected static InputControlSource Button18 = Button( 18 ); protected static InputControlSource Button19 = Button( 19 ); protected static InputControlSource Analog0 = Analog( 0 ); protected static InputControlSource Analog1 = Analog( 1 ); protected static InputControlSource Analog2 = Analog( 2 ); protected static InputControlSource Analog3 = Analog( 3 ); protected static InputControlSource Analog4 = Analog( 4 ); protected static InputControlSource Analog5 = Analog( 5 ); protected static InputControlSource Analog6 = Analog( 6 ); protected static InputControlSource Analog7 = Analog( 7 ); protected static InputControlSource Analog8 = Analog( 8 ); protected static InputControlSource Analog9 = Analog( 9 ); protected static InputControlSource Analog10 = Analog( 10 ); protected static InputControlSource Analog11 = Analog( 11 ); protected static InputControlSource Analog12 = Analog( 12 ); protected static InputControlSource Analog13 = Analog( 13 ); protected static InputControlSource Analog14 = Analog( 14 ); protected static InputControlSource Analog15 = Analog( 15 ); protected static InputControlSource Analog16 = Analog( 16 ); protected static InputControlSource Analog17 = Analog( 17 ); protected static InputControlSource Analog18 = Analog( 18 ); protected static InputControlSource Analog19 = Analog( 19 ); protected static InputControlSource MenuKey = new UnityKeyCodeSource( KeyCode.Menu ); protected static InputControlSource EscapeKey = new UnityKeyCodeSource( KeyCode.Escape ); #endregion #region InputDeviceMapping helpers protected static InputControlMapping LeftStickLeftMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Left Stick Left", Target = InputControlType.LeftStickLeft, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping LeftStickRightMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Left Stick Right", Target = InputControlType.LeftStickRight, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping LeftStickUpMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Left Stick Up", Target = InputControlType.LeftStickUp, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping LeftStickDownMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Left Stick Down", Target = InputControlType.LeftStickDown, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping RightStickLeftMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Right Stick Left", Target = InputControlType.RightStickLeft, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping RightStickRightMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Right Stick Right", Target = InputControlType.RightStickRight, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping RightStickUpMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Right Stick Up", Target = InputControlType.RightStickUp, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping RightStickDownMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Right Stick Down", Target = InputControlType.RightStickDown, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping LeftTriggerMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Left Trigger", Target = InputControlType.LeftTrigger, Source = analog, SourceRange = InputRange.MinusOneToOne, TargetRange = InputRange.ZeroToOne, IgnoreInitialZeroValue = true }; } protected static InputControlMapping RightTriggerMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "Right Trigger", Target = InputControlType.RightTrigger, Source = analog, SourceRange = InputRange.MinusOneToOne, TargetRange = InputRange.ZeroToOne, IgnoreInitialZeroValue = true }; } protected static InputControlMapping DPadLeftMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "DPad Left", Target = InputControlType.DPadLeft, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping DPadRightMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "DPad Right", Target = InputControlType.DPadRight, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping DPadUpMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping DPadDownMapping( InputControlSource analog ) { return new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping DPadUpMapping2( InputControlSource analog ) { return new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = analog, SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlMapping DPadDownMapping2( InputControlSource analog ) { return new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = analog, SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne }; } protected static InputControlSource MouseButton0 = new UnityMouseButtonSource( 0 ); protected static InputControlSource MouseButton1 = new UnityMouseButtonSource( 1 ); protected static InputControlSource MouseButton2 = new UnityMouseButtonSource( 2 ); protected static InputControlSource MouseXAxis = new UnityMouseAxisSource( "x" ); protected static InputControlSource MouseYAxis = new UnityMouseAxisSource( "y" ); protected static InputControlSource MouseScrollWheel = new UnityMouseAxisSource( "z" ); #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // #define LLVM namespace Microsoft.Zelig.Runtime { using System; using TS = Microsoft.Zelig.Runtime.TypeSystem; [ExtendClass(typeof(System.Buffer), NoConstructors=true, ProcessAfter=typeof(ArrayImpl))] public static class BufferImpl { // // Helper Methods // public unsafe static void BlockCopy( ArrayImpl src , int srcOffset , ArrayImpl dst , int dstOffset , int count ) { TS.VTable vtSrc = TS.VTable.Get( src ); TS.VTable vtDst = TS.VTable.Get( dst ); if((vtSrc.TypeInfo.ContainedType is TS.ScalarTypeRepresentation) == false) { #if EXCEPTION_STRINGS throw new NotSupportedException( "Not a scalar" ); #else throw new NotSupportedException(); #endif } if((vtDst.TypeInfo.ContainedType is TS.ScalarTypeRepresentation) == false) { #if EXCEPTION_STRINGS throw new NotSupportedException( "Not a scalar" ); #else throw new NotSupportedException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "count" ); #else throw new IndexOutOfRangeException(); #endif } if(srcOffset < 0 || (uint)(srcOffset + count) > src.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "src" ); #else throw new IndexOutOfRangeException(); #endif } if(dstOffset < 0 || (uint)(dstOffset + count) > dst.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "dst" ); #else throw new IndexOutOfRangeException(); #endif } byte* srcPtr = (byte*)src.GetDataPointer(); byte* dstPtr = (byte*)dst.GetDataPointer(); InternalMemoryMove( &srcPtr[srcOffset], &dstPtr[dstOffset], count ); } internal unsafe static void InternalBlockCopy( ArrayImpl src , int srcOffset , ArrayImpl dst , int dstOffset , int count ) { BugCheck.Assert( TS.VTable.Get( src ) == TS.VTable.Get( dst ), BugCheck.StopCode.IncorrectArgument ); if(count < 0) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "count" ); #else throw new IndexOutOfRangeException(); #endif } if(srcOffset < 0 || (uint)(srcOffset + count) > src.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "src" ); #else throw new IndexOutOfRangeException(); #endif } if(dstOffset < 0 || (uint)(dstOffset + count) > dst.Size) { #if EXCEPTION_STRINGS throw new IndexOutOfRangeException( "dst" ); #else throw new IndexOutOfRangeException(); #endif } byte* srcPtr = (byte*)src.GetDataPointer(); byte* dstPtr = (byte*)dst.GetDataPointer(); InternalMemoryMove( &srcPtr[srcOffset], &dstPtr[dstOffset], count ); } //--//--// [DisableNullChecks] #if LLVM [NoInline] // Disable inlining so we always have a chance to replace the method. [TS.WellKnownMethod("System_Buffer_InternalMemoryCopy")] #endif // LLVM internal unsafe static void InternalMemoryCopy( byte* src , byte* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { int count32 = count / 4; InternalMemoryCopy( (uint*)src, (uint*)dst, count32 ); int count2 = count32 * 4; src += count2; dst += count2; count -= count2; } else if(AddressMath.IsAlignedTo16bits( src ) && AddressMath.IsAlignedTo16bits( dst ) ) { int count16 = count / 2; InternalMemoryCopy( (ushort*)src, (ushort*)dst, count16 ); int count2 = count16 * 2; src += count2; dst += count2; count -= count2; } if(count > 0) { while(count >= 4) { var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; dst += 4; src += 4; count -= 4; } if((count & 2) != 0) { var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; dst += 2; src += 2; } if((count & 1) != 0) { dst[0] = src[0]; } } } [Inline] internal unsafe static void InternalMemoryCopy( sbyte* src , sbyte* dst , int count ) { InternalMemoryCopy( (byte*)src, (byte*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalMemoryCopy( ushort* src , ushort* dst , int count ) { #if LLVM InternalMemoryCopy((byte*)src, (byte*)dst, count * sizeof(ushort)); #else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { int count32 = count / 2; InternalMemoryCopy( (uint*)src, (uint*)dst, count32 ); int count2 = count32 * 2; src += count2; dst += count2; count -= count2; } if(count > 0) { while(count >= 4) { var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; dst += 4; src += 4; count -= 4; } if((count & 2) != 0) { var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; dst += 2; src += 2; } if((count & 1) != 0) { dst[0] = src[0]; } } #endif // LLVM } [Inline] internal unsafe static void InternalMemoryCopy( short* src , short* dst , int count ) { InternalMemoryCopy( (ushort*)src, (ushort*)dst, count ); } [Inline] internal unsafe static void InternalMemoryCopy( char* src , char* dst , int count ) { InternalMemoryCopy( (ushort*)src, (ushort*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalMemoryCopy( uint* src , uint* dst , int count ) { #if LLVM InternalMemoryCopy((byte*)src, (byte*)dst, count * sizeof(uint)); #else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(count > 0) { while(count >= 4) { var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; dst += 4; src += 4; count -= 4; } if((count & 2) != 0) { var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; dst += 2; src += 2; } if((count & 1) != 0) { dst[0] = src[0]; } } #endif // LLVM } [Inline] internal unsafe static void InternalMemoryCopy( int* src , int* dst , int count ) { InternalMemoryCopy( (uint*)src, (uint*)dst, count ); } //--//--// [DisableNullChecks] //////#if LLVM ////// [NoInline] // Disable inlining so we always have a chance to replace the method. ////// [TS.WellKnownMethod("System_Buffer_InternalBackwardMemoryCopy")] //////#endif // LLVM internal unsafe static void InternalBackwardMemoryCopy( byte* src , byte* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); src += count; dst += count; if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { uint* src2 = (uint*)src; uint* dst2 = (uint*)dst; int count32 = count / 4; src2 -= count32; dst2 -= count32; InternalBackwardMemoryCopy( src2, dst2, count32 ); int count2 = count32 * 4; src = (byte*)src2; dst = (byte*)dst2; count -= count2; } else if(AddressMath.IsAlignedTo16bits( src ) && AddressMath.IsAlignedTo16bits( dst ) ) { ushort* src2 = (ushort*)src; ushort* dst2 = (ushort*)dst; int count16 = count / 2; src2 -= count16; dst2 -= count16; InternalBackwardMemoryCopy( src2, dst2, count16 ); int count2 = count16 * 2; src = (byte*)src2; dst = (byte*)dst2; count -= count2; } if(count > 0) { while(count >= 4) { dst -= 4; src -= 4; count -= 4; var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; } if((count & 2) != 0) { dst -= 2; src -= 2; var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; } if((count & 1) != 0) { dst -= 1; src -= 1; dst[0] = src[0]; } } } [Inline] internal unsafe static void InternalBackwardMemoryCopy( sbyte* src , sbyte* dst , int count ) { InternalBackwardMemoryCopy( (byte*)src, (byte*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalBackwardMemoryCopy( ushort* src , ushort* dst , int count ) { //////#if LLVM ////// InternalBackwardMemoryCopy((byte*)src, (byte*)dst, count * sizeof(ushort)); //////#else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); src += count; dst += count; if(AddressMath.IsAlignedTo32bits( src ) && AddressMath.IsAlignedTo32bits( dst ) ) { uint* src2 = (uint*)src; uint* dst2 = (uint*)dst; int count32 = count / 2; src2 -= count32; dst2 -= count32; InternalBackwardMemoryCopy( src2, dst2, count32 ); int count2 = count32 * 2; src = (ushort*)src2; dst = (ushort*)dst2; count -= count2; } if(count > 0) { while(count >= 4) { dst -= 4; src -= 4; count -= 4; var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; } if((count & 2) != 0) { dst -= 2; src -= 2; var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; } if((count & 1) != 0) { dst -= 1; src -= 1; dst[0] = src[0]; } } //////#endif // LLVM } [Inline] internal unsafe static void InternalBackwardMemoryCopy( short* src , short* dst , int count ) { InternalBackwardMemoryCopy( (ushort*)src, (ushort*)dst, count ); } [Inline] internal unsafe static void InternalBackwardMemoryCopy( char* src , char* dst , int count ) { InternalBackwardMemoryCopy( (ushort*)src, (ushort*)dst, count ); } //--// [DisableNullChecks] internal unsafe static void InternalBackwardMemoryCopy( uint* src , uint* dst , int count ) { //////#if LLVM ////// InternalBackwardMemoryCopy((byte*)src, (byte*)dst, count * sizeof(uint)); //////#else // LLVM BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(count > 0) { src += count; dst += count; while(count >= 4) { dst -= 4; src -= 4; count -= 4; var v0 = src[0]; var v1 = src[1]; var v2 = src[2]; var v3 = src[3]; dst[0] = v0; dst[1] = v1; dst[2] = v2; dst[3] = v3; } if((count & 2) != 0) { dst -= 2; src -= 2; var v0 = src[0]; var v1 = src[1]; dst[0] = v0; dst[1] = v1; } if((count & 1) != 0) { dst -= 1; src -= 1; dst[0] = src[0]; } } //////#endif // LLVM } [Inline] internal unsafe static void InternalBackwardMemoryCopy( int* src , int* dst , int count ) { InternalBackwardMemoryCopy( (uint*)src, (uint*)dst, count ); } //--//--// internal unsafe static void InternalMemoryMove( byte* src , byte* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(src <= dst && dst < &src[count]) { InternalBackwardMemoryCopy( src, dst, count ); } else { InternalMemoryCopy( src, dst, count ); } } [Inline] internal unsafe static void InternalMemoryMove( sbyte* src , sbyte* dst , int count ) { InternalMemoryMove( (byte*)src, (byte*)dst, count ); } //--// internal unsafe static void InternalMemoryMove( ushort* src , ushort* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(src <= dst && dst < &src[count]) { InternalBackwardMemoryCopy( src, dst, count ); } else { InternalMemoryCopy( src, dst, count ); } } [Inline] internal unsafe static void InternalMemoryMove( short* src , short* dst , int count ) { InternalMemoryMove( (ushort*)src, (ushort*)dst, count ); } [Inline] internal unsafe static void InternalMemoryMove( char* src , char* dst , int count ) { InternalMemoryMove( (ushort*)src, (ushort*)dst, count ); } //--// internal unsafe static void InternalMemoryMove( uint* src , uint* dst , int count ) { BugCheck.Assert( count >= 0, BugCheck.StopCode.NegativeIndex ); if(src <= dst && dst < &src[count]) { InternalBackwardMemoryCopy( src, dst, count ); } else { InternalMemoryCopy( src, dst, count ); } } [Inline] internal unsafe static void InternalMemoryMove( int* src , int* dst , int count ) { InternalMemoryMove( (uint*)src, (uint*)dst, count ); } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Indicates that steaming call has finished. TaskCompletionSource<object> streamingCallFinishedTcs = new TaskCompletionSource<object>(); // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer, callDetails.Channel.Environment) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { var profiler = Profilers.ForCurrentThread(); using (profiler.NewScope("AsyncCall.UnaryCall")) using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create()) { byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) using (var ctx = BatchContextSafeHandle.Create()) { call.StartUnary(ctx, payload, metadataArray, GetWriteFlagsForCall()); var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); } } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(HandleUnaryResponse, payload, metadataArray, GetWriteFlagsForCall()); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(HandleUnaryResponse, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); halfcloseRequested = true; byte[] payload = UnsafeSerialize(msg); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(HandleFinished, payload, metadataArray, GetWriteFlagsForCall()); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(HandleFinished, metadataArray); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendMessage(TRequest msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate) { StartSendMessageInternal(msg, writeFlags, completionDelegate); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate) { StartReadMessageInternal(completionDelegate); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate) { lock (myLock) { GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendCloseFromClient(HandleHalfclosed); halfcloseRequested = true; sendCompletionDelegate = completionDelegate; } } /// <summary> /// Get the task that completes once if streaming call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingCallFinishedTask { get { return streamingCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResources() { details.Channel.RemoveCallReference(this); } protected override bool IsClient { get { return true; } } private void Initialize(CompletionQueueSafeHandle cq) { using (Profilers.ForCurrentThread().NewScope("AsyncCall.Initialize")) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); InitializeInternal(call); RegisterCancellationCallback(); } } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { using (Profilers.ForCurrentThread().NewScope("AsyncCall.CreateNativeCall")) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance; var credentials = details.Options.Credentials; using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null) { var result = details.Channel.Handle.CreateCall(environment.CompletionRegistry, parentCall, ContextPropagationToken.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials); return result; } } } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { var token = details.Options.CancellationToken; if (token.CanBeCanceled) { token.Register(() => this.Cancel()); } } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { using (Profilers.ForCurrentThread().NewScope("AsyncCall.HandleUnaryResponse")) { TResponse msg = default(TResponse); var deserializeException = success ? TryDeserialize(receivedMessage, out msg) : null; lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; ReleaseResourcesIfPossible(); } responseHeadersTcs.SetResult(responseHeaders); var status = receivedStatus.Status; if (!success || status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status)); return; } unaryResponseTcs.SetResult(msg); } } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { lock (myLock) { finished = true; finishedStatus = receivedStatus; ReleaseResourcesIfPossible(); } var status = receivedStatus.Status; if (!success || status.StatusCode != StatusCode.OK) { streamingCallFinishedTcs.SetException(new RpcException(status)); return; } streamingCallFinishedTcs.SetResult(null); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// TrustProductsChannelEndpointAssignmentResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Trusthub.V1.TrustProducts { public class TrustProductsChannelEndpointAssignmentResource : Resource { private static Request BuildCreateRequest(CreateTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Trusthub, "/v1/TrustProducts/" + options.PathTrustProductSid + "/ChannelEndpointAssignments", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new Assigned Item. /// </summary> /// <param name="options"> Create TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static TrustProductsChannelEndpointAssignmentResource Create(CreateTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new Assigned Item. /// </summary> /// <param name="options"> Create TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<TrustProductsChannelEndpointAssignmentResource> CreateAsync(CreateTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new Assigned Item. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="channelEndpointType"> The type of channel endpoint </param> /// <param name="channelEndpointSid"> The sid of an channel endpoint </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static TrustProductsChannelEndpointAssignmentResource Create(string pathTrustProductSid, string channelEndpointType, string channelEndpointSid, ITwilioRestClient client = null) { var options = new CreateTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid, channelEndpointType, channelEndpointSid); return Create(options, client); } #if !NET35 /// <summary> /// Create a new Assigned Item. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="channelEndpointType"> The type of channel endpoint </param> /// <param name="channelEndpointSid"> The sid of an channel endpoint </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<TrustProductsChannelEndpointAssignmentResource> CreateAsync(string pathTrustProductSid, string channelEndpointType, string channelEndpointSid, ITwilioRestClient client = null) { var options = new CreateTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid, channelEndpointType, channelEndpointSid); return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Trusthub, "/v1/TrustProducts/" + options.PathTrustProductSid + "/ChannelEndpointAssignments", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Assigned Items for an account. /// </summary> /// <param name="options"> Read TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static ResourceSet<TrustProductsChannelEndpointAssignmentResource> Read(ReadTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<TrustProductsChannelEndpointAssignmentResource>.FromJson("results", response.Content); return new ResourceSet<TrustProductsChannelEndpointAssignmentResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Assigned Items for an account. /// </summary> /// <param name="options"> Read TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<ResourceSet<TrustProductsChannelEndpointAssignmentResource>> ReadAsync(ReadTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<TrustProductsChannelEndpointAssignmentResource>.FromJson("results", response.Content); return new ResourceSet<TrustProductsChannelEndpointAssignmentResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Assigned Items for an account. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="channelEndpointSid"> The sid of an channel endpoint </param> /// <param name="channelEndpointSids"> comma separated list of channel endpoint sids </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static ResourceSet<TrustProductsChannelEndpointAssignmentResource> Read(string pathTrustProductSid, string channelEndpointSid = null, string channelEndpointSids = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid){ChannelEndpointSid = channelEndpointSid, ChannelEndpointSids = channelEndpointSids, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Assigned Items for an account. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="channelEndpointSid"> The sid of an channel endpoint </param> /// <param name="channelEndpointSids"> comma separated list of channel endpoint sids </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<ResourceSet<TrustProductsChannelEndpointAssignmentResource>> ReadAsync(string pathTrustProductSid, string channelEndpointSid = null, string channelEndpointSids = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid){ChannelEndpointSid = channelEndpointSid, ChannelEndpointSids = channelEndpointSids, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<TrustProductsChannelEndpointAssignmentResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<TrustProductsChannelEndpointAssignmentResource>.FromJson("results", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<TrustProductsChannelEndpointAssignmentResource> NextPage(Page<TrustProductsChannelEndpointAssignmentResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Trusthub) ); var response = client.Request(request); return Page<TrustProductsChannelEndpointAssignmentResource>.FromJson("results", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<TrustProductsChannelEndpointAssignmentResource> PreviousPage(Page<TrustProductsChannelEndpointAssignmentResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Trusthub) ); var response = client.Request(request); return Page<TrustProductsChannelEndpointAssignmentResource>.FromJson("results", response.Content); } private static Request BuildFetchRequest(FetchTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Trusthub, "/v1/TrustProducts/" + options.PathTrustProductSid + "/ChannelEndpointAssignments/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch specific Assigned Item Instance. /// </summary> /// <param name="options"> Fetch TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static TrustProductsChannelEndpointAssignmentResource Fetch(FetchTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch specific Assigned Item Instance. /// </summary> /// <param name="options"> Fetch TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<TrustProductsChannelEndpointAssignmentResource> FetchAsync(FetchTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch specific Assigned Item Instance. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static TrustProductsChannelEndpointAssignmentResource Fetch(string pathTrustProductSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch specific Assigned Item Instance. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<TrustProductsChannelEndpointAssignmentResource> FetchAsync(string pathTrustProductSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Trusthub, "/v1/TrustProducts/" + options.PathTrustProductSid + "/ChannelEndpointAssignments/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Remove an Assignment Item Instance. /// </summary> /// <param name="options"> Delete TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static bool Delete(DeleteTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Remove an Assignment Item Instance. /// </summary> /// <param name="options"> Delete TrustProductsChannelEndpointAssignment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteTrustProductsChannelEndpointAssignmentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Remove an Assignment Item Instance. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of TrustProductsChannelEndpointAssignment </returns> public static bool Delete(string pathTrustProductSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Remove an Assignment Item Instance. /// </summary> /// <param name="pathTrustProductSid"> The unique string that identifies the resource. </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of TrustProductsChannelEndpointAssignment </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathTrustProductSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteTrustProductsChannelEndpointAssignmentOptions(pathTrustProductSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a TrustProductsChannelEndpointAssignmentResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> TrustProductsChannelEndpointAssignmentResource object represented by the provided JSON </returns> public static TrustProductsChannelEndpointAssignmentResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<TrustProductsChannelEndpointAssignmentResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The unique string that identifies the CustomerProfile resource. /// </summary> [JsonProperty("trust_product_sid")] public string TrustProductSid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The type of channel endpoint /// </summary> [JsonProperty("channel_endpoint_type")] public string ChannelEndpointType { get; private set; } /// <summary> /// The sid of an channel endpoint /// </summary> [JsonProperty("channel_endpoint_sid")] public string ChannelEndpointSid { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The absolute URL of the Identity resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private TrustProductsChannelEndpointAssignmentResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic; using System.IO; using System.Runtime.CompilerServices; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Interpreter; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using MSAst = System.Linq.Expressions; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; /// <summary> /// Top-level ast for all Python code. Typically represents a module but could also /// be exec or eval code. /// </summary> public sealed class PythonAst : ScopeStatement { private Statement _body; private CompilationMode _mode; private readonly bool _isModule; private readonly bool _printExpressions; private ModuleOptions _languageFeatures; private readonly CompilerContext _compilerContext; private readonly MSAst.SymbolDocumentInfo _document; private readonly string/*!*/ _name; internal int[] _lineLocations; private PythonVariable _docVariable, _nameVariable, _fileVariable; private ModuleContext _modContext; private readonly bool _onDiskProxy; internal MSAst.Expression _arrayExpression; private CompilationMode.ConstantInfo _contextInfo; private Dictionary<PythonVariable, MSAst.Expression> _globalVariables = new Dictionary<PythonVariable, MSAst.Expression>(); internal readonly Profiler _profiler; // captures timing data if profiling internal const string GlobalContextName = "$globalContext"; internal static MSAst.ParameterExpression _functionCode = Ast.Variable(typeof(FunctionCode), "$functionCode"); internal static readonly MSAst.ParameterExpression/*!*/ _globalArray = Ast.Parameter(typeof(PythonGlobal[]), "$globalArray"); internal static readonly MSAst.ParameterExpression/*!*/ _globalContext = Ast.Parameter(typeof(CodeContext), GlobalContextName); internal static readonly ReadOnlyCollection<MSAst.ParameterExpression> _arrayFuncParams = new ReadOnlyCollectionBuilder<MSAst.ParameterExpression>(new[] { _globalContext, _functionCode }).ToReadOnlyCollection(); public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions) { ContractUtils.RequiresNotNull(body, "body"); _body = body; _isModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; } public PythonAst(Statement body, bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context, int[] lineLocations) : this(isModule, languageFeatures, printExpressions, context) { ContractUtils.RequiresNotNull(body, "body"); _body = body; _lineLocations = lineLocations; } /// <summary> /// Creates a new PythonAst without a body. ParsingFinished should be called afterwards to set /// the body. /// </summary> public PythonAst(bool isModule, ModuleOptions languageFeatures, bool printExpressions, CompilerContext context) { _isModule = isModule; _printExpressions = printExpressions; _languageFeatures = languageFeatures; _mode = ((PythonCompilerOptions)context.Options).CompilationMode ?? GetCompilationMode(context); _compilerContext = context; FuncCodeExpr = _functionCode; PythonCompilerOptions pco = context.Options as PythonCompilerOptions; Debug.Assert(pco != null); string name; if (!context.SourceUnit.HasPath || (pco.Module & ModuleOptions.ExecOrEvalCode) != 0) { name = "<module>"; } else { name = context.SourceUnit.Path; } _name = name; Debug.Assert(_name != null); PythonOptions po = ((PythonContext)context.SourceUnit.LanguageContext).PythonOptions; if (po.EnableProfiler #if FEATURE_REFEMIT && _mode != CompilationMode.ToDisk #endif ) { _profiler = Profiler.GetProfiler(PyContext); } _document = context.SourceUnit.Document ?? Ast.SymbolDocument(name, PyContext.LanguageGuid, PyContext.VendorGuid); } internal PythonAst(CompilerContext context) : this(new EmptyStatement(), true, ModuleOptions.None, false, context, null) { _onDiskProxy = true; } /// <summary> /// Called when parsing is complete, the body is built, the line mapping and language features are known. /// /// This is used in conjunction with the constructor which does not take a body. It enables creating /// the outer most PythonAst first so that nodes can always have a global parent. This lets an un-bound /// tree to still provide it's line information immediately after parsing. When we set the location /// of each node during construction we also set the global parent. When we name bind the global /// parent gets replaced with the real parent ScopeStatement. /// </summary> /// <param name="lineLocations">a mapping of where each line begins</param> /// <param name="body">The body of code</param> /// <param name="languageFeatures">The language features which were set during parsing.</param> public void ParsingFinished(int[] lineLocations, Statement body, ModuleOptions languageFeatures) { ContractUtils.RequiresNotNull(body, "body"); if (_body != null) { throw new InvalidOperationException("cannot set body twice"); } _body = body; _lineLocations = lineLocations; _languageFeatures = languageFeatures; } /// <summary> /// Binds an AST and makes it capable of being reduced and compiled. Before calling Bind an AST cannot successfully /// be reduced. /// </summary> public void Bind() { PythonNameBinder.BindAst(this, _compilerContext); } public override string Name { get { return "<module>"; } } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { _body?.Walk(walker); } walker.PostWalk(this); } #region Name Binding Support internal override bool ExposesLocalVariable(PythonVariable variable) { return true; } internal override void FinishBind(PythonNameBinder binder) { _contextInfo = CompilationMode.GetContext(); // create global variables for compiler context. PythonGlobal[] globalArray = new PythonGlobal[Variables == null ? 0 : Variables.Count]; Dictionary<string, PythonGlobal> globals = new Dictionary<string, PythonGlobal>(); GlobalDictionaryStorage storage = new GlobalDictionaryStorage(globals, globalArray); var modContext = _modContext = new ModuleContext(new PythonDictionary(storage), PyContext); #if FEATURE_REFEMIT if (_mode == CompilationMode.ToDisk) { _arrayExpression = _globalArray; } else #endif { var newArray = new ConstantExpression(globalArray); newArray.Parent = this; _arrayExpression = newArray; } if (Variables != null) { int globalIndex = 0; foreach (PythonVariable variable in Variables.Values) { PythonGlobal global = new PythonGlobal(modContext.GlobalContext, variable.Name); _globalVariables[variable] = CompilationMode.GetGlobal(GetGlobalContext(), globals.Count, variable, global); globalArray[globalIndex++] = globals[variable.Name] = global; } } CompilationMode.PublishContext(modContext.GlobalContext, _contextInfo); } internal override MSAst.Expression LocalContext { get { return GetGlobalContext(); } } internal override PythonVariable BindReference(PythonNameBinder binder, PythonReference reference) { return EnsureVariable(reference.Name); } internal override bool TryBindOuter(ScopeStatement from, PythonReference reference, out PythonVariable variable) { // Unbound variable from.AddReferencedGlobal(reference.Name); if (from.HasLateBoundVariableSets) { // If the context contains unqualified exec, new locals can be introduced // Therefore we need to turn this into a fully late-bound lookup which // happens when we don't have a PythonVariable. variable = null; return false; } else { // Create a global variable to bind to. variable = EnsureGlobalVariable(reference.Name); return true; } } internal override bool IsGlobal { get { return true; } } internal PythonVariable DocVariable { get { return _docVariable; } set { _docVariable = value; } } internal PythonVariable NameVariable { get { return _nameVariable; } set { _nameVariable = value; } } internal PythonVariable FileVariable { get { return _fileVariable; } set { _fileVariable = value; } } internal CompilerContext CompilerContext { get { return _compilerContext; } } internal MSAst.Expression GlobalArrayInstance { get { return _arrayExpression; } } internal MSAst.SymbolDocumentInfo Document { get { return _document; } } internal Dictionary<PythonVariable, MSAst.Expression> ModuleVariables { get { return _globalVariables; } } internal ModuleContext ModuleContext { get { return _modContext; } } /// <summary> /// Creates a variable at the global level. Called for known globals (e.g. __name__), /// for variables explicitly declared global by the user, and names accessed /// but not defined in the lexical scope. /// </summary> internal PythonVariable/*!*/ EnsureGlobalVariable(string name) { PythonVariable variable; if (!TryGetVariable(name, out variable)) { variable = CreateVariable(name, VariableKind.Global); } return variable; } #endregion #region MSASt.Expression Overrides public override Type Type { get { return CompilationMode.DelegateType; } } /// <summary> /// Reduces the PythonAst to a LambdaExpression of type Type. /// </summary> public override MSAst.Expression Reduce() { return GetLambda(); } internal override Microsoft.Scripting.Ast.LightLambdaExpression GetLambda() { string name = ((PythonCompilerOptions)_compilerContext.Options).ModuleName ?? "<unnamed>"; return CompilationMode.ReduceAst(this, name); } #endregion #region Public API /// <summary> /// True division is enabled in this AST. /// </summary> public bool TrueDivision { get { return (_languageFeatures & ModuleOptions.TrueDivision) != 0; } } /// <summary> /// True if the with statement is enabled in this AST. /// </summary> public bool AllowWithStatement { get { return (_languageFeatures & ModuleOptions.WithStatement) != 0; } } /// <summary> /// True if absolute imports are enabled /// </summary> public bool AbsoluteImports { get { return (_languageFeatures & ModuleOptions.AbsoluteImports) != 0; } } internal PythonDivisionOptions DivisionOptions { get { return PyContext.PythonOptions.DivisionOptions; } } public Statement Body { get { return _body; } } public bool Module { get { return _isModule; } } #endregion #region Transformation /// <summary> /// Returns a ScriptCode object for this PythonAst. The ScriptCode object /// can then be used to execute the code against it's closed over scope or /// to execute it against a different scope. /// </summary> internal ScriptCode ToScriptCode() { return CompilationMode.MakeScriptCode(this); } internal MSAst.Expression ReduceWorker() { if (_body is ReturnStatement retStmt && (_languageFeatures == ModuleOptions.None || _languageFeatures == (ModuleOptions.ExecOrEvalCode | ModuleOptions.Interpret) || _languageFeatures == (ModuleOptions.ExecOrEvalCode | ModuleOptions.Interpret | ModuleOptions.LightThrow))) { // for simple eval's we can construct a simple tree which just // leaves the value on the stack. Return's can't exist in modules // so this is always safe. Debug.Assert(!_isModule); var ret = (ReturnStatement)_body; Ast simpleBody; if ((_languageFeatures & ModuleOptions.LightThrow) != 0) { simpleBody = LightExceptions.Rewrite(retStmt.Expression.Reduce()); } else { simpleBody = retStmt.Expression.Reduce(); } var start = IndexToLocation(ret.Expression.StartIndex); var end = IndexToLocation(ret.Expression.EndIndex); return Ast.Block( Ast.DebugInfo( _document, start.Line, start.Column, end.Line, end.Column ), AstUtils.Convert(simpleBody, typeof(object)) ); } ReadOnlyCollectionBuilder<MSAst.Expression> block = new ReadOnlyCollectionBuilder<MSAst.Expression>(); AddInitialiation(block); if (_isModule) { block.Add(AssignValue(GetVariableExpression(_docVariable), Ast.Constant(GetDocumentation(_body)))); } if (!(_body is SuiteStatement) && _body.CanThrow) { // we only initialize line numbers in suite statements but if we don't generate a SuiteStatement // at the top level we can miss some line number updates. block.Add(UpdateLineNumber(_body.Start.Line)); } block.Add(_body); MSAst.Expression body = Ast.Block(block.ToReadOnlyCollection()); body = WrapScopeStatements(body, Body.CanThrow); // new ComboActionRewriter().VisitNode(Transform(ag)) body = AddModulePublishing(body); body = AddProfiling(body); if ((((PythonCompilerOptions)_compilerContext.Options).Module & ModuleOptions.LightThrow) != 0) { body = LightExceptions.Rewrite(body); } body = Ast.Label(FunctionDefinition._returnLabel, AstUtils.Convert(body, typeof(object))); if (body.Type == typeof(void)) { body = Ast.Block(body, Ast.Constant(null)); } return body; } private void AddInitialiation(ReadOnlyCollectionBuilder<MSAst.Expression> block) { if (_isModule) { block.Add(AssignValue(GetVariableExpression(_fileVariable), Ast.Constant(ModuleFileName))); block.Add(AssignValue(GetVariableExpression(_nameVariable), Ast.Constant(ModuleName))); } if (_languageFeatures != ModuleOptions.None || _isModule) { block.Add( Ast.Call( AstMethods.ModuleStarted, LocalContext, AstUtils.Constant(_languageFeatures) ) ); } } internal override bool PrintExpressions { get { return _printExpressions; } } private MSAst.Expression AddModulePublishing(MSAst.Expression body) { if (_isModule) { PythonCompilerOptions pco = _compilerContext.Options as PythonCompilerOptions; string moduleName = ModuleName; if ((pco.Module & ModuleOptions.Initialize) != 0) { var tmp = Ast.Variable(typeof(object), "$originalModule"); // TODO: Should be try/fault body = Ast.Block( new[] { tmp }, AstUtils.Try( Ast.Assign(tmp, Ast.Call(AstMethods.PublishModule, LocalContext, Ast.Constant(moduleName))), body ).Catch( typeof(Exception), Ast.Call(AstMethods.RemoveModule, LocalContext, Ast.Constant(moduleName), tmp), Ast.Rethrow(body.Type) ) ); } } return body; } private string ModuleFileName { get { return _name; } } private string ModuleName { get { PythonCompilerOptions pco = _compilerContext.Options as PythonCompilerOptions; string moduleName = pco.ModuleName; if (moduleName == null) { if (_compilerContext.SourceUnit.HasPath && _compilerContext.SourceUnit.Path.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) { moduleName = Path.GetFileNameWithoutExtension(_compilerContext.SourceUnit.Path); } else { moduleName = "<module>"; } } return moduleName; } } internal override FunctionAttributes Flags { get { ModuleOptions features = ((PythonCompilerOptions)_compilerContext.Options).Module; FunctionAttributes funcAttrs = 0; if ((features & ModuleOptions.TrueDivision) != 0) { funcAttrs |= FunctionAttributes.FutureDivision; } return funcAttrs; } } internal SourceUnit SourceUnit { get { if (_compilerContext == null) { return null; } return _compilerContext.SourceUnit; } } internal string[] GetNames() { string[] res = new string[Variables.Count]; int i = 0; foreach (var variable in Variables.Values) { res[i++] = variable.Name; } return res; } #endregion #region Compilation Mode (TODO: Factor out) private static Compiler.CompilationMode GetCompilationMode(CompilerContext context) { PythonCompilerOptions options = (PythonCompilerOptions)context.Options; if ((options.Module & ModuleOptions.ExecOrEvalCode) != 0) { return CompilationMode.Lookup; } #if FEATURE_REFEMIT PythonContext pc = ((PythonContext)context.SourceUnit.LanguageContext); return ((pc.PythonOptions.Optimize || options.Optimized) && !pc.PythonOptions.LightweightScopes) ? CompilationMode.Uncollectable : CompilationMode.Collectable; #else return CompilationMode.Collectable; #endif } internal CompilationMode CompilationMode { get { return _mode; } } private MSAst.Expression GetGlobalContext() { if (_contextInfo != null) { return _contextInfo.Expression; } return _globalContext; } internal void PrepareScope(ReadOnlyCollectionBuilder<MSAst.ParameterExpression> locals, List<MSAst.Expression> init) { CompilationMode.PrepareScope(this, locals, init); } internal new MSAst.Expression Constant(object value) { return new PythonConstantExpression(CompilationMode, value); } #endregion #region Binder Factories internal MSAst.Expression/*!*/ Convert(Type/*!*/ type, ConversionResultKind resultKind, MSAst.Expression/*!*/ target) { if (resultKind == ConversionResultKind.ExplicitCast) { return new DynamicConvertExpression( PyContext.Convert( type, resultKind ), CompilationMode, target ); } return CompilationMode.Dynamic( PyContext.Convert( type, resultKind ), type, target ); } internal MSAst.Expression/*!*/ Operation(Type/*!*/ resultType, PythonOperationKind operation, MSAst.Expression arg0) { if (resultType == typeof(object)) { return new PythonDynamicExpression1( Binders.UnaryOperationBinder( PyContext, operation ), CompilationMode, arg0 ); } return CompilationMode.Dynamic( Binders.UnaryOperationBinder( PyContext, operation ), resultType, arg0 ); } internal MSAst.Expression/*!*/ Operation(Type/*!*/ resultType, PythonOperationKind operation, MSAst.Expression arg0, MSAst.Expression arg1) { if (resultType == typeof(object)) { return new PythonDynamicExpression2( Binders.BinaryOperationBinder( PyContext, operation ), _mode, arg0, arg1 ); } return CompilationMode.Dynamic( Binders.BinaryOperationBinder( PyContext, operation ), resultType, arg0, arg1 ); } internal MSAst.Expression/*!*/ Set(string/*!*/ name, MSAst.Expression/*!*/ target, MSAst.Expression/*!*/ value) { return new PythonDynamicExpression2( PyContext.SetMember( name ), CompilationMode, target, value ); } internal MSAst.Expression/*!*/ Get(string/*!*/ name, MSAst.Expression/*!*/ target) { return new DynamicGetMemberExpression(PyContext.GetMember(name), _mode, target, LocalContext); } internal MSAst.Expression/*!*/ Delete(Type/*!*/ resultType, string/*!*/ name, MSAst.Expression/*!*/ target) { return CompilationMode.Dynamic( PyContext.DeleteMember( name ), resultType, target ); } internal MSAst.Expression/*!*/ GetIndex(MSAst.Expression/*!*/[]/*!*/ expressions) { return new PythonDynamicExpressionN( PyContext.GetIndex( expressions.Length ), CompilationMode, expressions ); } internal MSAst.Expression/*!*/ GetSlice(MSAst.Expression/*!*/[]/*!*/ expressions) { return new PythonDynamicExpressionN( PyContext.GetSlice, CompilationMode, expressions ); } internal MSAst.Expression/*!*/ SetIndex(MSAst.Expression/*!*/[]/*!*/ expressions) { return new PythonDynamicExpressionN( PyContext.SetIndex( expressions.Length - 1 ), CompilationMode, expressions ); } internal MSAst.Expression/*!*/ SetSlice(MSAst.Expression/*!*/[]/*!*/ expressions) { return new PythonDynamicExpressionN( PyContext.SetSliceBinder, CompilationMode, expressions ); } internal MSAst.Expression/*!*/ DeleteIndex(MSAst.Expression/*!*/[]/*!*/ expressions) { return CompilationMode.Dynamic( PyContext.DeleteIndex( expressions.Length ), typeof(void), expressions ); } internal MSAst.Expression/*!*/ DeleteSlice(MSAst.Expression/*!*/[]/*!*/ expressions) { return new PythonDynamicExpressionN( PyContext.DeleteSlice, CompilationMode, expressions ); } #endregion #region Lookup Rewriting /// <summary> /// Rewrites the tree for performing lookups against globals instead of being bound /// against the optimized scope. This is used if the user compiles optimied code and then /// runs it against a different scope. /// </summary> internal PythonAst MakeLookupCode() { PythonAst res = (PythonAst)MemberwiseClone(); res._mode = CompilationMode.Lookup; res._contextInfo = null; // update the top-level globals for class/funcs accessing __name__, __file__, etc... Dictionary<PythonVariable, MSAst.Expression> newGlobals = new Dictionary<PythonVariable, MSAst.Expression>(); foreach (var v in _globalVariables) { newGlobals[v.Key] = CompilationMode.Lookup.GetGlobal(_globalContext, -1, v.Key, null); } res._globalVariables = newGlobals; res._body = new RewrittenBodyStatement(_body, new LookupVisitor(res, GetGlobalContext()).Visit(_body)); return res; } internal class LookupVisitor : MSAst.ExpressionVisitor { private readonly MSAst.Expression _globalContext; private ScopeStatement _curScope; public LookupVisitor(PythonAst ast, MSAst.Expression globalContext) { _globalContext = globalContext; _curScope = ast; } protected override MSAst.Expression VisitMember(MSAst.MemberExpression node) { if (node == _globalContext) { return PythonAst._globalContext; } return base.VisitMember(node); } protected override MSAst.Expression VisitExtension(MSAst.Expression node) { if (node == _globalContext) { return PythonAst._globalContext; } // we need to re-write nested scoeps if (node is ScopeStatement scope) { return base.VisitExtension(VisitScope(scope)); } if (node is LambdaExpression lambda) { return base.VisitExtension(new LambdaExpression((FunctionDefinition)VisitScope(lambda.Function))); } if (node is GeneratorExpression generator) { return base.VisitExtension(new GeneratorExpression((FunctionDefinition)VisitScope(generator.Function), generator.Iterable)); } // update the global get/set/raw gets variables if (node is PythonGlobalVariableExpression global) { return new LookupGlobalVariable( _curScope == null ? PythonAst._globalContext : _curScope.LocalContext, global.Variable.Name, global.Variable.Kind == VariableKind.Local ); } // set covers sets and deletes if (node is PythonSetGlobalVariableExpression setGlobal) { if (setGlobal.Value == PythonGlobalVariableExpression.Uninitialized) { return new LookupGlobalVariable( _curScope == null ? PythonAst._globalContext : _curScope.LocalContext, setGlobal.Global.Variable.Name, setGlobal.Global.Variable.Kind == VariableKind.Local ).Delete(); } else { return new LookupGlobalVariable( _curScope == null ? PythonAst._globalContext : _curScope.LocalContext, setGlobal.Global.Variable.Name, setGlobal.Global.Variable.Kind == VariableKind.Local ).Assign(Visit(setGlobal.Value)); } } if (node is PythonRawGlobalValueExpression rawValue) { return new LookupGlobalVariable( _curScope == null ? PythonAst._globalContext : _curScope.LocalContext, rawValue.Global.Variable.Name, rawValue.Global.Variable.Kind == VariableKind.Local ); } return base.VisitExtension(node); } private ScopeStatement VisitScope(ScopeStatement scope) { var newScope = scope.CopyForRewrite(); ScopeStatement prevScope = _curScope; try { // rewrite the method body _curScope = newScope; newScope.Parent = prevScope; newScope.RewriteBody(this); } finally { _curScope = prevScope; } return newScope; } } #endregion internal override string ProfilerName { get { if (_mode == CompilationMode.Lookup) { return NameForExec; } if (_name.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0) { return "module " + _name; } else { return "module " + System.IO.Path.GetFileNameWithoutExtension(_name); } } } internal new bool EmitDebugSymbols { get { return PyContext.EmitDebugSymbols(SourceUnit); } } /// <summary> /// True if this is on-disk code which we don't really have an AST for. /// </summary> internal bool OnDiskProxy { get { return _onDiskProxy; } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Raven.Client; using SolutionForms.Data.Models; using SolutionForms.Service.Providers.Helpers; using SolutionForms.Service.Providers.Parameters; using SolutionForms.Service.Providers.Returns; using System.Linq; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Raven.Abstractions.Data; using Raven.Abstractions.Extensions; using Raven.Client.Connection; using Raven.Json.Linq; using SolutionForms.Data.Indexes; using SolutionForms.Service.Providers.Models; namespace SolutionForms.Service.Providers.Providers { // ReSharper disable once InconsistentNaming public class DataFormsProvider { private readonly IDocumentStore _documentStore; public DataFormsProvider(IDocumentStore documentStore) { if (documentStore == null) throw new ArgumentNullException(nameof(documentStore)); _documentStore = documentStore; } #region Data Form operations public async Task<IEnumerable<DataFormReturn>> GetDataForms(string tenant, bool onlyHomepageLinks) { new DataForms_Menu().Execute(_documentStore.DatabaseCommands.ForDatabase(tenant), _documentStore.Conventions); using (var session = _documentStore.OpenAsyncSession(tenant)) { // Appparently, RavenDB can't handle inclusion of variable in filtering expression (!onlyHomepageLinks) //return (await session.Query<DataForm, DataForms_Menu>() // .Where(f => !onlyHomepageLinks || f.LinkOnHomePage) // .ToListAsync()) // .Project().To<DataFormReturn>(); var q = onlyHomepageLinks ? session.Query<DataForm, DataForms_Menu>() .Where(f => f.LinkOnHomePage) : session.Query<DataForm>(); return (await q.ToListAsync()).Project().To<DataFormReturn>(); } } public async Task<DataFormReturn> GetDataFormAsync(string tenant, string id) { using (var session = _documentStore.OpenAsyncSession(tenant)) { var dataform = await session .Include<DataSource>(m => m.Id) .LoadAsync<DataForm>(id); var response = dataform.Map().To<DataFormReturn>(); response.DataSource = (await session.LoadAsync<DataSource>(dataform.DataSourceId)) .Map().To<DataSourceReturn>(); return response; } } public async Task UpdateDataFormAsync(string tenant, string id, UpdateDataformRequest dataform) { using (var session = _documentStore.OpenAsyncSession(tenant)) { var doc = await session.LoadAsync<DataForm>(id); if (doc == null) return; doc.Description = dataform.Description; doc.Title = dataform.Title; doc.Fields = new List<FieldConfiguration>(dataform.Fields.Project().To<FieldConfiguration>()); doc.Plugins = dataform.Plugins; doc.Components = dataform.Components; doc.AuthorizedClaims = dataform.AuthorizedClaims?.ToArray() ?? new string[0]; doc.DataSourceId = dataform.DataSourceId; doc.RestrictDataAccessByOwner = dataform.RestrictDataAccessByOwner; if (!string.IsNullOrWhiteSpace(dataform.NewDataSourceName)) { var factory = new DataSourceFactory(session); doc.DataSourceId = (await factory.CreateDataSourceAsync(dataform.NewDataSourceName)).Id; } await session.SaveChangesAsync(); } } public async Task<CreateDataFormReturn> CreateDataFormAsync(string tenant, CreateDataformRequest dataform) { var entity = new DataForm { Description = dataform.Description, Title = dataform.Title, Fields = dataform.Fields.Project().To<FieldConfiguration>().ToList(), Plugins = dataform.Plugins, AuthorizedClaims = dataform.AuthorizedClaims as string[], DataSourceId = dataform.DataSourceId, RestrictDataAccessByOwner = dataform.RestrictDataAccessByOwner }; using (var session = _documentStore.OpenAsyncSession(tenant)) { try { if (!string.IsNullOrWhiteSpace(dataform.NewDataSourceName)) { var factory = new DataSourceFactory(session); entity.DataSourceId = (await factory.CreateDataSourceAsync(dataform.NewDataSourceName)).Id; } await session.StoreAsync(entity); await session.SaveChangesAsync(); return entity.Map().To<CreateDataFormReturn>(); } catch (Exception) { session.Dispose(); throw; } } } public async Task DeleteDataFormAsync(string tenant, int id) { using (var session = _documentStore.OpenAsyncSession(tenant)) { var dataform = await session.LoadAsync<DataForm>(id); if (dataform == null) { return; } try { session.Delete(dataform); await session.SaveChangesAsync(); } catch { session.Dispose(); throw; } } } #endregion #region Data Entry operations public async Task<IEnumerable<JObject>> GetDataEntriesByEntityName(string tenant, string entityName, IEnumerable<KeyValuePair<string, string>> queryParams) { using (var session = _documentStore.OpenAsyncSession(tenant)) { var query = session.Advanced.AsyncDocumentQuery<dynamic>() .WhereEquals("@metadata.Raven-Entity-Name", entityName) .UsingDefaultOperator(QueryOperator.And); AppendQueryStringParams(query, queryParams); var queryResult = await query.QueryResultAsync(); return queryResult.Results.Select(r => JObject.Parse(r.ToJsonDocument().DataAsJson.ToString())); } } private static void AppendQueryStringParams(IAsyncDocumentQuery<dynamic> query, IEnumerable<KeyValuePair<string, string>> queryParams) { queryParams.ForEach(q => { switch (q.Key.ToLowerInvariant()) { case "$top": int pageSize; if (int.TryParse(q.Value, out pageSize)) { query.Take(pageSize); } break; case "$skip": int skipCount; if (int.TryParse(q.Value, out skipCount)) { query.Skip(skipCount); } break; case "$filter": query.Where(q.Value); break; } }); } public async Task<IEnumerable<JObject>> GetDataEntriesByIndexName(string tenant, string indexName, IDictionary<string, string> queryParams) { var query = new IndexQuery { Query = queryParams.ContainsKey("$filter") ? queryParams["$filter"] : null }; int pageSize; if (queryParams.ContainsKey("$top") && int.TryParse(queryParams["$top"], out pageSize)) { query.PageSize = pageSize; } int skip; if (queryParams.ContainsKey("$skip") && int.TryParse(queryParams["$skip"], out skip)) { query.Start = skip; } var includes = GetQueryStringIncludes(queryParams); var queryResult = await _documentStore.AsyncDatabaseCommands.ForDatabase(tenant) .QueryAsync( indexName, query, includes ); var jsonResult = queryResult.Results; if (queryResult.Includes != null && queryResult.Includes.Count > 0) { jsonResult.ForEach(r => { includes.ForEach(i => { r[i.Replace("Id", "")] = r.ContainsKey(i) ? queryResult.Includes.FirstOrDefault(ri => r[i].Value<string>() == ri["Id"].Value<string>()) : null; }); }); } return jsonResult.Select(r => JObject.Parse(r.ToJsonDocument().DataAsJson.ToString())); ; } public async Task<DataEntryCreatedReturn> CreateDataEntryAsync(string tenant, string entityName, object values, ApplicationUser ownerUser, bool awaitIndexing = false) { var jobject = JObject.FromObject(values); var id = $"{entityName}{_documentStore.Conventions.IdentityPartsSeparator}{_documentStore.DatabaseCommands.NextIdentityFor(entityName)}"; jobject.Add(DatabaseConstants.IdPropertyName, id); await SaveEntryAsync(tenant, entityName, ownerUser, jobject, id); if (awaitIndexing) { await ClearIndexesAsync(tenant); } return new DataEntryCreatedReturn { Key = id, Entity = jobject }; } public async Task<JObject> GetDataEntryByKeyAsync(string tenant, string id) { var commands = _documentStore.AsyncDatabaseCommands.ForDatabase(tenant); var result = await commands.GetAsync(id); return result == null ? null : JObject.Parse(result.DataAsJson.ToString()); } public async Task<JObject> UpdateDataEntryAsync(string tenant, string entityName, string id, object values, ApplicationUser userAccount, bool awaitIndexing = false) { if (await GetDataEntryByKeyAsync(tenant, id) == null) { return null; } var jobject = JObject.FromObject(values); jobject.Add(DatabaseConstants.IdPropertyName, id); await SaveEntryAsync(tenant, entityName, userAccount, jobject, id); if (awaitIndexing) { await ClearIndexesAsync(tenant); } return jobject; } public async Task PatchDataEntryAsync(string tenant, string id, ScriptedPatchRequestParameters patchParams, ApplicationUser userAccount) { var commands = _documentStore.AsyncDatabaseCommands.ForDatabase(tenant); await commands.PatchAsync(id, patchParams.ToScriptedPatchRequest()); } public async Task DeleteDataEntryAsync(string tenant, string id, bool awaitIndexing = false) { var commands = _documentStore.AsyncDatabaseCommands.ForDatabase(tenant); await commands.DeleteAsync(id, null); if (awaitIndexing) { await ClearIndexesAsync(tenant); } } public IEnumerable<DataEntryCreatedReturn> LoadDataEntriesFromJson(string tenant, string entityName, string jsonData, ApplicationUser ownerUser) { var jsonArray = JArray.Parse(jsonData); var maxId = 0; using (var bulkInsert = _documentStore.BulkInsert(tenant)) { foreach (var d in jsonArray.Children<JObject>()) { UserIdentityHelper.SetUserIdentity(d, ownerUser); var entity = RavenJObject.Parse(d.ToString()); var meta = new RavenJObject {{"Raven-Entity-Name", entityName}}; var id = (string) d["Id"]; var identity = int.Parse( id.Substring( id.IndexOf(_documentStore.Conventions.IdentityPartsSeparator, StringComparison.Ordinal) + 1)); maxId = Math.Max(identity, maxId); bulkInsert.Store(entity, meta, id); yield return new DataEntryCreatedReturn { Key = id, Entity = d }; } } _documentStore.DatabaseCommands.SeedIdentityFor(entityName, maxId); } public async Task SeedIdentityForTable(string entityname, long nextId) { await _documentStore.AsyncDatabaseCommands.SeedIdentityForAsync(entityname, nextId); } #endregion #region private members private static string[] GetQueryStringIncludes(IDictionary<string, string> queryStringParams) { return queryStringParams.ContainsKey("$includes") ? queryStringParams["$includes"].Split(',') : null; } private async Task<PutResult> SaveEntryAsync(string tenant, string entityName, ApplicationUser ownerUser, JObject jobject, string id) { UserIdentityHelper.SetUserIdentity(jobject, ownerUser); var dataEntry = JsonConvert.SerializeObject(jobject); var commands = _documentStore.AsyncDatabaseCommands.ForDatabase(tenant); // NOTE: The PutAsync database command allows us to set the `Raven-Entity-Name` metadata which tells RavenDB to put this entity in it's own entity collection. // Using the `session.Store` or `asyncSession.StoreAsync` methods will cause RavenDB to reflect on the parameter object causing all entites to be stored in // a single entity collection of `JObject` which is not what we want. var result = await commands.PutAsync( id, null, RavenJObject.Parse(dataEntry), new RavenJObject { {"Raven-Entity-Name", entityName}, }); return result; } private async Task ClearIndexesAsync(string tenant) { await ClearIndexesAsync(_documentStore, tenant, staleIndexes => staleIndexes.Any()); } private async Task ClearIndexAsync(string tenant, string indexName) { await ClearIndexesAsync(_documentStore, tenant, staleIndexes => staleIndexes.Any(i => i.Equals(indexName))); } private async Task ClearIndexAsync(string tenant, string[] indexNamees) { await ClearIndexesAsync(_documentStore, tenant, indexes => indexes.Any(indexNamees.Contains)); } private static async Task ClearIndexesAsync(IDocumentStore documentStore, string tenant, Func<IEnumerable<string>, bool> waitExpression) { var stats = await documentStore.AsyncDatabaseCommands.ForDatabase(tenant) .GetStatisticsAsync(); var staleIndexes = stats.StaleIndexes; Thread.Sleep(10); if(waitExpression.Invoke(staleIndexes)) { await ClearIndexesAsync(documentStore, tenant, waitExpression); } } #endregion } public class DataEntryCreatedReturn { public string Key { get; set; } public object Entity { get; set; } } public static class DatabaseConstants { public const string GetByIdRouteName = "GetDynamicEntityByIdRoute"; public const string GetQueryRouteName = "GetDynamicEntityQueryRoute"; public const string PostRouteName = "PostDynamicEntityQueryRoute"; public const string PutRouteName = "PutDynamicEntityQueryRoute"; public const string IdPropertyName = "Id"; public const string UserNamePropertyName = "Last-Modified-By"; } public static class UserIdentityHelper { public static void SetUserIdentity(JObject target, ApplicationUser user) { target.Add(DatabaseConstants.UserNamePropertyName, user.ID); } } }
// // DatabaseAlbumInfo.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 Novell, 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 Mono.Unix; using Hyena.Data; using Hyena.Data.Sqlite; using Banshee.Database; using Banshee.ServiceStack; namespace Banshee.Collection.Database { public class DatabaseAlbumInfo : AlbumInfo { private static BansheeModelProvider<DatabaseAlbumInfo> provider = new BansheeModelProvider<DatabaseAlbumInfo> ( ServiceManager.DbConnection, "CoreAlbums" ); public static BansheeModelProvider<DatabaseAlbumInfo> Provider { get { return provider; } } private static HyenaSqliteCommand default_select_command = new HyenaSqliteCommand (String.Format ( "SELECT {0} FROM {1} WHERE {2} AND CoreAlbums.ArtistID = ? AND CoreAlbums.Title = ?", provider.Select, provider.From, (String.IsNullOrEmpty (provider.Where) ? "1=1" : provider.Where) )); private static HyenaSqliteCommand null_select_command = new HyenaSqliteCommand (String.Format ( "SELECT {0} FROM {1} WHERE {2} AND CoreAlbums.ArtistID = ? AND CoreAlbums.Title IS NULL", provider.Select, provider.From, (String.IsNullOrEmpty (provider.Where) ? "1=1" : provider.Where) )); private static long last_artist_id; private static string last_title; private static DatabaseAlbumInfo last_album; public static void Reset () { last_artist_id = -1; last_title = null; last_album = null; } public static DatabaseAlbumInfo FindOrCreate (DatabaseArtistInfo artist, string title, string title_sort, bool isCompilation) { return FindOrCreate (artist, title, title_sort, isCompilation, null); } public static DatabaseAlbumInfo FindOrCreate (DatabaseArtistInfo artist, string title, string title_sort, bool isCompilation, string album_musicrainz_id) { DatabaseAlbumInfo album = new DatabaseAlbumInfo (); album.Title = title; album.TitleSort = title_sort; album.IsCompilation = isCompilation; album.MusicBrainzId = album_musicrainz_id; return FindOrCreate (artist, album); } private static IDataReader FindExistingArtists (long artist_id, string title) { HyenaSqliteConnection db = ServiceManager.DbConnection; if (title == null) { return db.Query (null_select_command, artist_id); } return db.Query (default_select_command, artist_id, title); } public static DatabaseAlbumInfo FindOrCreate (DatabaseArtistInfo artist, DatabaseAlbumInfo album) { if (album.Title == last_title && artist.DbId == last_artist_id && last_album != null) { return last_album; } if (String.IsNullOrEmpty (album.Title) || album.Title.Trim () == String.Empty) { album.Title = null; } using (IDataReader reader = FindExistingArtists (artist.DbId, album.Title)) { if (reader.Read ()) { bool save = false; last_album = provider.Load (reader); // If the artist name has changed since last time (but it's the same artist) then update our copy of the ArtistName if (last_album.ArtistName != artist.Name) { last_album.ArtistName = artist.Name; save = true; } // Ditto artist sort name if (last_album.ArtistNameSort != artist.NameSort) { last_album.ArtistNameSort = artist.NameSort; save = true; } // And album sort name if (last_album.TitleSort != album.TitleSort) { last_album.TitleSort = album.TitleSort; save = true; } // If the album IsCompilation status has changed, update the saved album info if (last_album.IsCompilation != album.IsCompilation) { last_album.IsCompilation = album.IsCompilation; save = true; } // If the album MusicBrainzId has changed, but is not null if (last_album.MusicBrainzId != album.MusicBrainzId && !String.IsNullOrEmpty (album.MusicBrainzId)) { last_album.MusicBrainzId = album.MusicBrainzId; save = true; } // If the ArtworkId has changed, update the db if (last_album.ArtworkId != album.ArtworkId) { last_album.ArtworkId = album.ArtworkId; save = true; } if (save) { last_album.Save (); } } else { album.ArtistId = artist.DbId; album.ArtistName = artist.Name; album.ArtistNameSort = artist.NameSort; album.Save (); last_album = album; } } last_title = album.Title; last_artist_id = artist.DbId; return last_album; } public static DatabaseAlbumInfo UpdateOrCreate (DatabaseArtistInfo artist, DatabaseAlbumInfo album) { DatabaseAlbumInfo found = FindOrCreate (artist, album); if (found != album) { // Overwrite the found album album.Title = found.Title; album.TitleSort = found.TitleSort; album.ArtistName = found.ArtistName; album.ArtistNameSort = found.ArtistNameSort; album.IsCompilation = found.IsCompilation; album.MusicBrainzId = found.MusicBrainzId; album.dbid = found.DbId; album.ArtistId = found.ArtistId; album.ArtworkId = found.ArtworkId; album.Save (); } return album; } public DatabaseAlbumInfo () : base (null) { } public void Save () { Provider.Save (this); } [DatabaseColumn("AlbumID", Constraints = DatabaseColumnConstraints.PrimaryKey)] private long dbid; public long DbId { get { return dbid; } } [DatabaseColumn("ArtistID")] private long artist_id; public long ArtistId { get { return artist_id; } set { artist_id = value; } } [DatabaseColumn("MusicBrainzID")] public override string MusicBrainzId { get { return base.MusicBrainzId; } set { base.MusicBrainzId = value; } } [DatabaseColumn] public override DateTime ReleaseDate { get { return base.ReleaseDate; } set { base.ReleaseDate = value; } } [DatabaseColumn("ArtworkID")] public override string ArtworkId { get { return base.ArtworkId; } set { base.ArtworkId = value; } } [DatabaseColumn] public override bool IsCompilation { get { return base.IsCompilation; } set { base.IsCompilation = value; } } [DatabaseColumn] public override string Title { get { return base.Title; } set { base.Title = value; } } [DatabaseColumn] public override string TitleSort { get { return base.TitleSort; } set { base.TitleSort = value; } } [DatabaseColumn(Select = false)] internal byte[] TitleSortKey { get { return Hyena.StringUtil.SortKey (TitleSort ?? DisplayTitle); } } [DatabaseColumn(Select = false)] internal string TitleLowered { get { return Hyena.StringUtil.SearchKey (DisplayTitle); } } [DatabaseColumn] public override string ArtistName { get { return base.ArtistName; } set { base.ArtistName = value; } } [DatabaseColumn] public override string ArtistNameSort { get { return base.ArtistNameSort; } set { base.ArtistNameSort = value; } } [DatabaseColumn(Select = false)] internal byte[] ArtistNameSortKey { get { return Hyena.StringUtil.SortKey (ArtistNameSort ?? DisplayArtistName); } } [DatabaseColumn(Select = false)] internal string ArtistNameLowered { get { return Hyena.StringUtil.SearchKey (DisplayArtistName); } } public override string ToString () { return String.Format ("<LibraryAlbumInfo Title={0} DbId={1}>", Title, DbId); } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** using System; using System.IO; using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// Summary description for FileAssert. /// </summary> public class FileAssert { #region Equals and ReferenceEquals /// <summary> /// The Equals method throws an AssertionException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new AssertionException("Assert.Equals should not be used for Assertions"); } /// <summary> /// override the default ReferenceEquals to throw an AssertionException. This /// implementation makes sure there is no mistake in calling this function /// as part of Assert. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new AssertionException("Assert.ReferenceEquals should not be used for Assertions"); } #endregion #region Constructor /// <summary> /// We don't actually want any instances of this object, but some people /// like to inherit from it to add other static methods. Hence, the /// protected constructor disallows any instances of this object. /// </summary> protected FileAssert() {} #endregion #region AreEqual #region Streams /// <summary> /// Verifies that two Streams are equal. Two Streams are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreEqual(Stream expected, Stream actual, string message, params object[] args) { Assert.That( actual, new EqualConstraint( expected ), message, args ); } /// <summary> /// Verifies that two Streams are equal. Two Streams are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> /// <param name="message">The message to display if objects are not equal</param> static public void AreEqual(Stream expected, Stream actual, string message) { AreEqual(expected, actual, message, null); } /// <summary> /// Verifies that two Streams are equal. Two Streams are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> static public void AreEqual(Stream expected, Stream actual) { AreEqual(expected, actual, string.Empty, null); } #endregion #region FileInfo /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreEqual(FileInfo expected, FileInfo actual, string message, params object[] args) { using (FileStream exStream = expected.OpenRead()) { using (FileStream acStream = actual.OpenRead()) { AreEqual(exStream,acStream,message,args); } } } /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if objects are not equal</param> static public void AreEqual(FileInfo expected, FileInfo actual, string message) { AreEqual(expected, actual, message, null); } /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> static public void AreEqual(FileInfo expected, FileInfo actual) { AreEqual(expected, actual, string.Empty, null); } #endregion #region String /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreEqual(string expected, string actual, string message, params object[] args) { using (FileStream exStream = File.OpenRead(expected)) { using (FileStream acStream = File.OpenRead(actual)) { AreEqual(exStream,acStream,message,args); } } } /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if objects are not equal</param> static public void AreEqual(string expected, string actual, string message) { AreEqual(expected, actual, message, null); } /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> static public void AreEqual(string expected, string actual) { AreEqual(expected, actual, string.Empty, null); } #endregion #endregion #region AreNotEqual #region Streams /// <summary> /// Asserts that two Streams are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> /// <param name="message">The message to be displayed when the two Stream are the same.</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreNotEqual( Stream expected, Stream actual, string message, params object[] args) { Assert.That( actual, new NotConstraint( new EqualConstraint( expected ) ), message, args ); } /// <summary> /// Asserts that two Streams are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> /// <param name="message">The message to be displayed when the Streams are the same.</param> static public void AreNotEqual(Stream expected, Stream actual, string message) { AreNotEqual(expected, actual, message, null); } /// <summary> /// Asserts that two Streams are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> static public void AreNotEqual(Stream expected, Stream actual) { AreNotEqual(expected, actual, string.Empty, null); } #endregion #region FileInfo /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreNotEqual(FileInfo expected, FileInfo actual, string message, params object[] args) { using (FileStream exStream = expected.OpenRead()) { using (FileStream acStream = actual.OpenRead()) { AreNotEqual(exStream,acStream,message,args); } } } /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if objects are not equal</param> static public void AreNotEqual(FileInfo expected, FileInfo actual, string message) { AreNotEqual(expected, actual, message, null); } /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> static public void AreNotEqual(FileInfo expected, FileInfo actual) { AreNotEqual(expected, actual, string.Empty, null); } #endregion #region String /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreNotEqual(string expected, string actual, string message, params object[] args) { using (FileStream exStream = File.OpenRead(expected)) { using (FileStream acStream = File.OpenRead(actual)) { AreNotEqual(exStream,acStream,message,args); } } } /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if objects are not equal</param> static public void AreNotEqual(string expected, string actual, string message) { AreNotEqual(expected, actual, message, null); } /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> static public void AreNotEqual(string expected, string actual) { AreNotEqual(expected, actual, string.Empty, null); } #endregion #endregion } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="GrainReference"/>s for grains. /// </summary> public static class GrainReferenceGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Reference"; /// <summary> /// A reference to the CheckGrainObserverParamInternal method. /// </summary> private static readonly Expression<Action> CheckGrainObserverParamInternalExpression = () => GrainFactoryBase.CheckGrainObserverParamInternal(null); /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType"> /// The grain interface type. /// </param> /// <param name="onEncounteredType"> /// The callback which is invoked when a type is encountered. /// </param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType, Action<Type> onEncounteredType) { var grainTypeInfo = grainType.GetTypeInfo(); var genericTypes = grainTypeInfo.IsGenericTypeDefinition ? grainTypeInfo.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special marker attribute. var markerAttribute = SF.Attribute(typeof(GrainReferenceAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument( SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)))); var attributes = SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(SerializableAttribute).GetNameSyntax()), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), markerAttribute); var className = CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix; var classDeclaration = SF.ClassDeclaration(className) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes( SF.SimpleBaseType(typeof(GrainReference).GetTypeSyntax()), SF.SimpleBaseType(grainType.GetTypeSyntax())) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(GenerateConstructors(className)) .AddMembers( GenerateInterfaceIdProperty(grainType), GenerateInterfaceNameProperty(grainType), GenerateIsCompatibleMethod(grainType), GenerateGetMethodNameMethod(grainType)) .AddMembers(GenerateInvokeMethods(grainType, onEncounteredType)) .AddAttributeLists(attributes); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Generates constructors. /// </summary> /// <param name="className">The class name.</param> /// <returns>Constructor syntax for the provided class name.</returns> private static MemberDeclarationSyntax[] GenerateConstructors(string className) { var baseConstructors = typeof(GrainReference).GetConstructors( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(_ => !_.IsPrivate); var constructors = new List<MemberDeclarationSyntax>(); foreach (var baseConstructor in baseConstructors) { var args = baseConstructor.GetParameters() .Select(arg => SF.Argument(arg.Name.ToIdentifierName())) .ToArray(); var declaration = baseConstructor.GetDeclarationSyntax(className) .WithInitializer( SF.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer) .AddArgumentListArguments(args)) .AddBodyStatements(); constructors.Add(declaration); } return constructors.ToArray(); } /// <summary> /// Generates invoker methods. /// </summary> /// <param name="grainType">The grain type.</param> /// <param name="onEncounteredType"> /// The callback which is invoked when a type is encountered. /// </param> /// <returns>Invoker methods for the provided grain type.</returns> private static MemberDeclarationSyntax[] GenerateInvokeMethods(Type grainType, Action<Type> onEncounteredType) { var baseReference = SF.BaseExpression(); var methods = GrainInterfaceUtils.GetMethods(grainType); var members = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { onEncounteredType(method.ReturnType); var methodId = GrainInterfaceUtils.ComputeMethodId(method); var methodIdArgument = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId))); // Construct a new object array from all method arguments. var parameters = method.GetParameters(); var body = new List<StatementSyntax>(); foreach (var parameter in parameters) { onEncounteredType(parameter.ParameterType); if (typeof(IGrainObserver).IsAssignableFrom(parameter.ParameterType)) { body.Add( SF.ExpressionStatement( CheckGrainObserverParamInternalExpression.Invoke() .AddArgumentListArguments(SF.Argument(parameter.Name.ToIdentifierName())))); } } // Get the parameters argument value. ExpressionSyntax args; if (parameters.Length == 0) { args = SF.LiteralExpression(SyntaxKind.NullLiteralExpression); } else { args = SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax()) .WithInitializer( SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(parameters.Select(GetParameterForInvocation).ToArray())); } var options = GetInvokeOptions(method); // Construct the invocation call. if (method.ReturnType == typeof(void)) { var invocation = SF.InvocationExpression(baseReference.Member("InvokeOneWayMethod")) .AddArgumentListArguments(methodIdArgument) .AddArgumentListArguments(SF.Argument(args)); if (options != null) { invocation = invocation.AddArgumentListArguments(options); } body.Add(SF.ExpressionStatement(invocation)); } else { var returnType = method.ReturnType == typeof(Task) ? typeof(object) : method.ReturnType.GenericTypeArguments[0]; var invocation = SF.InvocationExpression(baseReference.Member("InvokeMethodAsync", returnType)) .AddArgumentListArguments(methodIdArgument) .AddArgumentListArguments(SF.Argument(args)); if (options != null) { invocation = invocation.AddArgumentListArguments(options); } body.Add(SF.ReturnStatement(invocation)); } members.Add(method.GetDeclarationSyntax().AddBodyStatements(body.ToArray())); } return members.ToArray(); } /// <summary> /// Returns syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and <see cref="GrainReference.InvokeOneWayMethod"/>. /// </summary> /// <param name="method">The method which an invoke call is being generated for.</param> /// <returns> /// Argument syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and /// <see cref="GrainReference.InvokeOneWayMethod"/>, or <see langword="null"/> if no options are to be specified. /// </returns> private static ArgumentSyntax GetInvokeOptions(MethodInfo method) { var options = new List<ExpressionSyntax>(); if (GrainInterfaceUtils.IsReadOnly(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.ReadOnly.ToString())); } if (GrainInterfaceUtils.IsUnordered(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.Unordered.ToString())); } if (GrainInterfaceUtils.IsAlwaysInterleave(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.AlwaysInterleave.ToString())); } ExpressionSyntax allOptions; if (options.Count <= 1) { allOptions = options.FirstOrDefault(); } else { allOptions = options.Aggregate((a, b) => SF.BinaryExpression(SyntaxKind.BitwiseOrExpression, a, b)); } if (allOptions == null) { return null; } return SF.Argument(SF.NameColon("options"), SF.Token(SyntaxKind.None), allOptions); } private static ExpressionSyntax GetParameterForInvocation(ParameterInfo arg, int argIndex) { var argIdentifier = arg.GetOrCreateName(argIndex).ToIdentifierName(); // Addressable arguments must be converted to references before passing. if (typeof(IAddressable).IsAssignableFrom(arg.ParameterType) && (typeof(Grain).IsAssignableFrom(arg.ParameterType) || arg.ParameterType.GetTypeInfo().IsInterface)) { return SF.ConditionalExpression( SF.BinaryExpression(SyntaxKind.IsExpression, argIdentifier, typeof(Grain).GetTypeSyntax()), SF.InvocationExpression(argIdentifier.Member("AsReference", arg.ParameterType)), argIdentifier); } return argIdentifier; } private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.ProtectedKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateIsCompatibleMethod(Type grainType) { var method = TypeUtils.Method((GrainReference _) => _.IsCompatible(default(int))); var methodDeclaration = method.GetDeclarationSyntax(); var interfaceIdParameter = method.GetParameters()[0].Name.ToIdentifierName(); var interfaceIds = new HashSet<int>( new[] { GrainInterfaceUtils.GetGrainInterfaceId(grainType) }.Concat( GrainInterfaceUtils.GetRemoteInterfaces(grainType).Keys)); var returnValue = default(BinaryExpressionSyntax); foreach (var interfaceId in interfaceIds) { var check = SF.BinaryExpression( SyntaxKind.EqualsExpression, interfaceIdParameter, SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId))); // If this is the first check, assign it, otherwise OR this check with the previous checks. returnValue = returnValue == null ? check : SF.BinaryExpression(SyntaxKind.LogicalOrExpression, returnValue, check); } return methodDeclaration.AddBodyStatements(SF.ReturnStatement(returnValue)) .AddModifiers(SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceNameProperty(Type grainType) { var propertyName = TypeUtils.Member((GrainReference _) => _.InterfaceName); var returnValue = grainType.GetParseableName().GetLiteralExpression(); return SF.PropertyDeclaration(typeof(string).GetTypeSyntax(), propertyName.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MethodDeclarationSyntax GenerateGetMethodNameMethod(Type grainType) { // Get the method with the correct type. var method = typeof(GrainReference) .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) .FirstOrDefault(m => m.Name == "GetMethodName"); var methodDeclaration = method.GetDeclarationSyntax() .AddModifiers(SF.Token(SyntaxKind.OverrideKeyword)); var parameters = method.GetParameters(); var interfaceIdArgument = parameters[0].Name.ToIdentifierName(); var methodIdArgument = parameters[1].Name.ToIdentifierName(); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdArgument, methodType => new StatementSyntax[] { SF.ReturnStatement(methodType.Name.GetLiteralExpression()) }); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdArgument); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); return methodDeclaration.AddBodyStatements(interfaceIdSwitch); } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmGRVimport { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmGRVimport() : base() { Load += frmGRVimport_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Timer withEventsField_tmrAutoGRV; public System.Windows.Forms.Timer tmrAutoGRV { get { return withEventsField_tmrAutoGRV; } set { if (withEventsField_tmrAutoGRV != null) { withEventsField_tmrAutoGRV.Tick -= tmrAutoGRV_Tick; } withEventsField_tmrAutoGRV = value; if (withEventsField_tmrAutoGRV != null) { withEventsField_tmrAutoGRV.Tick += tmrAutoGRV_Tick; } } } private System.Windows.Forms.Button withEventsField_cmdNext; public System.Windows.Forms.Button cmdNext { get { return withEventsField_cmdNext; } set { if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click -= cmdNext_Click; } withEventsField_cmdNext = value; if (withEventsField_cmdNext != null) { withEventsField_cmdNext.Click += cmdNext_Click; } } } public System.Windows.Forms.OpenFileDialog CDOpen; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_1; public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_2; public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_3; public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_4; public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_5; public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_6; public System.Windows.Forms.ColumnHeader _lvImport_ColumnHeader_7; public System.Windows.Forms.ListView lvImport; public System.Windows.Forms.GroupBox _Frame1_0; private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } public System.Windows.Forms.GroupBox _Frame1_1; //Public WithEvents Frame1 As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmGRVimport)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.tmrAutoGRV = new System.Windows.Forms.Timer(components); this.cmdNext = new System.Windows.Forms.Button(); this.CDOpen = new System.Windows.Forms.OpenFileDialog(); this.cmdExit = new System.Windows.Forms.Button(); this._Frame1_0 = new System.Windows.Forms.GroupBox(); this.lvImport = new System.Windows.Forms.ListView(); this._lvImport_ColumnHeader_1 = new System.Windows.Forms.ColumnHeader(); this._lvImport_ColumnHeader_2 = new System.Windows.Forms.ColumnHeader(); this._lvImport_ColumnHeader_3 = new System.Windows.Forms.ColumnHeader(); this._lvImport_ColumnHeader_4 = new System.Windows.Forms.ColumnHeader(); this._lvImport_ColumnHeader_5 = new System.Windows.Forms.ColumnHeader(); this._lvImport_ColumnHeader_6 = new System.Windows.Forms.ColumnHeader(); this._lvImport_ColumnHeader_7 = new System.Windows.Forms.ColumnHeader(); this._Frame1_1 = new System.Windows.Forms.GroupBox(); this.DataList1 = new myDataGridView(); //Me.Frame1 = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components) this._Frame1_0.SuspendLayout(); this.lvImport.SuspendLayout(); this._Frame1_1.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); //CType(Me.Frame1, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Import a GRV ..."; this.ClientSize = new System.Drawing.Size(590, 462); this.Location = new System.Drawing.Point(3, 29); this.ControlBox = false; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.KeyPreview = false; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmGRVimport"; this.tmrAutoGRV.Enabled = false; this.tmrAutoGRV.Interval = 10; this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNext.Text = "&Next"; this.cmdNext.Size = new System.Drawing.Size(88, 49); this.cmdNext.Location = new System.Drawing.Point(486, 402); this.cmdNext.TabIndex = 1; this.cmdNext.BackColor = System.Drawing.SystemColors.Control; this.cmdNext.CausesValidation = true; this.cmdNext.Enabled = true; this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNext.TabStop = true; this.cmdNext.Name = "cmdNext"; this.CDOpen.Title = "Select GRV import file ..."; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(88, 49); this.cmdExit.Location = new System.Drawing.Point(15, 402); this.cmdExit.TabIndex = 0; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.TabStop = true; this.cmdExit.Name = "cmdExit"; this._Frame1_0.Text = "Imported GRV Data"; this._Frame1_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._Frame1_0.Size = new System.Drawing.Size(559, 370); this._Frame1_0.Location = new System.Drawing.Point(15, 24); this._Frame1_0.TabIndex = 2; this._Frame1_0.BackColor = System.Drawing.SystemColors.Control; this._Frame1_0.Enabled = true; this._Frame1_0.ForeColor = System.Drawing.SystemColors.ControlText; this._Frame1_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Frame1_0.Visible = true; this._Frame1_0.Padding = new System.Windows.Forms.Padding(0); this._Frame1_0.Name = "_Frame1_0"; this.lvImport.Size = new System.Drawing.Size(541, 346); this.lvImport.Location = new System.Drawing.Point(9, 15); this.lvImport.TabIndex = 3; this.lvImport.View = System.Windows.Forms.View.Details; this.lvImport.LabelEdit = false; this.lvImport.LabelWrap = true; this.lvImport.HideSelection = false; this.lvImport.ForeColor = System.Drawing.SystemColors.WindowText; this.lvImport.BackColor = System.Drawing.SystemColors.Window; this.lvImport.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lvImport.Name = "lvImport"; this._lvImport_ColumnHeader_1.Text = "Barcode"; this._lvImport_ColumnHeader_1.Width = 118; this._lvImport_ColumnHeader_2.Text = "Name"; this._lvImport_ColumnHeader_2.Width = 236; this._lvImport_ColumnHeader_3.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._lvImport_ColumnHeader_3.Text = "Pack Size"; this._lvImport_ColumnHeader_3.Width = 106; this._lvImport_ColumnHeader_4.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._lvImport_ColumnHeader_4.Text = "Quantity"; this._lvImport_ColumnHeader_4.Width = 95; this._lvImport_ColumnHeader_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._lvImport_ColumnHeader_5.Text = "Cost"; this._lvImport_ColumnHeader_5.Width = 118; this._lvImport_ColumnHeader_6.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._lvImport_ColumnHeader_6.Text = "Price"; this._lvImport_ColumnHeader_6.Width = 118; this._lvImport_ColumnHeader_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this._lvImport_ColumnHeader_7.Text = "Order"; this._lvImport_ColumnHeader_7.Width = 71; this._Frame1_1.Text = "Select a Supplier for this GRV ..."; this._Frame1_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._Frame1_1.Size = new System.Drawing.Size(559, 370); this._Frame1_1.Location = new System.Drawing.Point(15, 24); this._Frame1_1.TabIndex = 4; this._Frame1_1.Visible = false; this._Frame1_1.BackColor = System.Drawing.SystemColors.Control; this._Frame1_1.Enabled = true; this._Frame1_1.ForeColor = System.Drawing.SystemColors.ControlText; this._Frame1_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Frame1_1.Padding = new System.Windows.Forms.Padding(0); this._Frame1_1.Name = "_Frame1_1"; //'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(328, 342); this.DataList1.Location = new System.Drawing.Point(219, 15); this.DataList1.TabIndex = 5; this.DataList1.Name = "DataList1"; this.Controls.Add(cmdNext); this.Controls.Add(cmdExit); this.Controls.Add(_Frame1_0); this.Controls.Add(_Frame1_1); this._Frame1_0.Controls.Add(lvImport); this.lvImport.Columns.Add(_lvImport_ColumnHeader_1); this.lvImport.Columns.Add(_lvImport_ColumnHeader_2); this.lvImport.Columns.Add(_lvImport_ColumnHeader_3); this.lvImport.Columns.Add(_lvImport_ColumnHeader_4); this.lvImport.Columns.Add(_lvImport_ColumnHeader_5); this.lvImport.Columns.Add(_lvImport_ColumnHeader_6); this.lvImport.Columns.Add(_lvImport_ColumnHeader_7); this._Frame1_1.Controls.Add(DataList1); //Me.Frame1.SetIndex(_Frame1_0, CType(0, Short)) //Me.Frame1.SetIndex(_Frame1_1, CType(1, Short)) //CType(Me.Frame1, System.ComponentModel.ISupportInitialize).EndInit() ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this._Frame1_0.ResumeLayout(false); this.lvImport.ResumeLayout(false); this._Frame1_1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using Loon.Utils; using System.Runtime.CompilerServices; namespace Loon.Core.Geom { public abstract class Shape { public float x; public float y; protected internal float rotation; protected internal float[] points; protected internal float[] center; protected internal float scaleX, scaleY; protected internal float maxX, maxY; protected internal float minX, minY; protected internal float boundingCircleRadius; protected internal bool pointsDirty; protected internal Triangle triangle; protected internal bool trianglesDirty; protected internal AABB aabb; protected internal RectBox rect; public Shape() { pointsDirty = true; scaleX = scaleY = 1f; } public virtual void SetLocation(float x_0, float y_1) { SetX(x_0); SetY(y_1); } public abstract Shape Transform(Matrix transform); protected abstract internal void CreatePoints(); public void Translate(int deltaX, int deltaY) { SetX(x + deltaX); SetY(y + deltaY); } public virtual float GetX() { return x; } public virtual void SetX(float x_0) { if (x_0 != this.x || x_0 == 0) { float dx = x_0 - this.x; this.x = x_0; if ((points == null) || (center == null)) { CheckPoints(); } for (int i = 0; i < points.Length / 2; i++) { points[i * 2] += dx; } center[0] += dx; x_0 += dx; maxX += dx; minX += dx; trianglesDirty = true; } } public virtual void SetY(float y_0) { if (y_0 != this.y || y_0 == 0) { float dy = y_0 - this.y; this.y = y_0; if ((points == null) || (center == null)) { CheckPoints(); } for (int i = 0; i < points.Length / 2; i++) { points[(i * 2) + 1] += dy; } center[1] += dy; y_0 += dy; maxY += dy; minY += dy; trianglesDirty = true; } } public virtual float GetY() { return y; } public virtual float Length() { return MathUtils.Sqrt(x * x + y * y); } public void SetLocation(Vector2f loc) { SetX(loc.x); SetY(loc.y); } public virtual float GetCenterX() { CheckPoints(); return center[0]; } public void SetCenterX(float centerX) { if ((points == null) || (center == null)) { CheckPoints(); } float xDiff = centerX - GetCenterX(); SetX(x + xDiff); } public virtual float GetCenterY() { CheckPoints(); return center[1]; } public void SetCenterY(float centerY) { if ((points == null) || (center == null)) { CheckPoints(); } float yDiff = centerY - GetCenterY(); SetY(y + yDiff); } public virtual float GetMaxX() { CheckPoints(); return maxX; } public virtual float GetMaxY() { CheckPoints(); return maxY; } public virtual float GetMinX() { CheckPoints(); return minX; } public virtual float GetMinY() { CheckPoints(); return minY; } public float GetBoundingCircleRadius() { CheckPoints(); return boundingCircleRadius; } public float[] GetCenter() { CheckPoints(); return center; } public float[] GetPoints() { CheckPoints(); return points; } public int GetPointCount() { CheckPoints(); return points.Length / 2; } public float[] GetPoint(int index) { CheckPoints(); float[] result = new float[2]; result[0] = points[index * 2]; result[1] = points[index * 2 + 1]; return result; } public float[] GetNormal(int index) { float[] current = GetPoint(index); float[] prev = GetPoint((index - 1 < 0) ? GetPointCount() - 1 : index - 1); float[] next = GetPoint((index + 1 >= GetPointCount()) ? 0 : index + 1); float[] t1 = GetNormal(prev, current); float[] t2 = GetNormal(current, next); if ((index == 0) && (!Closed())) { return t2; } if ((index == GetPointCount() - 1) && (!Closed())) { return t1; } float tx = (t1[0] + t2[0]) / 2; float ty = (t1[1] + t2[1]) / 2; float len = MathUtils.Sqrt((tx * tx) + (ty * ty)); return new float[] { tx / len, ty / len }; } public bool Contains(Shape other) { if (other.Intersects(this)) { return false; } for (int i = 0; i < other.GetPointCount(); i++) { float[] pt = other.GetPoint(i); if (!Contains(pt[0], pt[1])) { return false; } } return true; } private float[] GetNormal(float[] start, float[] end) { float dx = start[0] - end[0]; float dy = start[1] - end[1]; float len = MathUtils.Sqrt((dx * dx) + (dy * dy)); dx /= len; dy /= len; return new float[] { -dy, dx }; } public bool Includes(float x_0, float y_1) { if (points.Length == 0) { return false; } CheckPoints(); Line testLine = new Line(0, 0, 0, 0); Vector2f pt = new Vector2f(x_0, y_1); for (int i = 0; i < points.Length; i += 2) { int n = i + 2; if (n >= points.Length) { n = 0; } testLine.Set(points[i], points[i + 1], points[n], points[n + 1]); if (testLine.On(pt)) { return true; } } return false; } public int IndexOf(float x_0, float y_1) { for (int i = 0; i < points.Length; i += 2) { if ((points[i] == x_0) && (points[i + 1] == y_1)) { return i / 2; } } return -1; } public virtual bool Contains(float x_0, float y_1) { CheckPoints(); if (points.Length == 0) { return false; } bool result = false; float xnew, ynew; float xold, yold; float x1, y1; float x2, y2; int npoints = points.Length; xold = points[npoints - 2]; yold = points[npoints - 1]; for (int i = 0; i < npoints; i += 2) { xnew = points[i]; ynew = points[i + 1]; if (xnew > xold) { x1 = xold; x2 = xnew; y1 = yold; y2 = ynew; } else { x1 = xnew; x2 = xold; y1 = ynew; y2 = yold; } if ((xnew < x_0) == (x_0 <= xold) && ((double) y_1 - (double) y1) * (x2 - x1) < ((double) y2 - (double) y1) * (x_0 - x1)) { result = !result; } xold = xnew; yold = ynew; } return result; } public virtual bool Intersects(Shape shape) { if (shape == null) { return false; } CheckPoints(); bool result = false; float[] points_0 = GetPoints(); float[] thatPoints = shape.GetPoints(); int length = points_0.Length; int thatLength = thatPoints.Length; double unknownA; double unknownB; if (!Closed()) { length -= 2; } if (!shape.Closed()) { thatLength -= 2; } for (int i = 0; i < length; i += 2) { int iNext = i + 2; if (iNext >= points_0.Length) { iNext = 0; } for (int j = 0; j < thatLength; j += 2) { int jNext = j + 2; if (jNext >= thatPoints.Length) { jNext = 0; } unknownA = (((points_0[iNext] - points_0[i]) * (double) (thatPoints[j + 1] - points_0[i + 1])) - ((points_0[iNext + 1] - points_0[i + 1]) * (thatPoints[j] - points_0[i]))) / (((points_0[iNext + 1] - points_0[i + 1]) * (thatPoints[jNext] - thatPoints[j])) - ((points_0[iNext] - points_0[i]) * (thatPoints[jNext + 1] - thatPoints[j + 1]))); unknownB = (((thatPoints[jNext] - thatPoints[j]) * (double) (thatPoints[j + 1] - points_0[i + 1])) - ((thatPoints[jNext + 1] - thatPoints[j + 1]) * (thatPoints[j] - points_0[i]))) / (((points_0[iNext + 1] - points_0[i + 1]) * (thatPoints[jNext] - thatPoints[j])) - ((points_0[iNext] - points_0[i]) * (thatPoints[jNext + 1] - thatPoints[j + 1]))); if (unknownA >= 0 && unknownA <= 1 && unknownB >= 0 && unknownB <= 1) { result = true; break; } } if (result) { break; } } return result; } public bool HasVertex(float x_0, float y_1) { if (points.Length == 0) { return false; } CheckPoints(); for (int i = 0; i < points.Length; i += 2) { if ((points[i] == x_0) && (points[i + 1] == y_1)) { return true; } } return false; } protected internal virtual void FindCenter() { center = new float[] { 0, 0 }; int length = points.Length; for (int i = 0; i < length; i += 2) { center[0] += points[i]; center[1] += points[i + 1]; } center[0] /= (length / 2); center[1] /= (length / 2); } protected internal virtual void CalculateRadius() { boundingCircleRadius = 0; for (int i = 0; i < points.Length; i += 2) { float temp = ((points[i] - center[0]) * (points[i] - center[0])) + ((points[i + 1] - center[1]) * (points[i + 1] - center[1])); boundingCircleRadius = (boundingCircleRadius > temp) ? boundingCircleRadius : temp; } boundingCircleRadius = MathUtils.Sqrt(boundingCircleRadius); } protected internal void CalculateTriangles() { if ((!trianglesDirty) && (triangle != null)) { return; } if (points.Length >= 6) { triangle = new TriangleNeat(); for (int i = 0; i < points.Length; i += 2) { triangle.AddPolyPoint(points[i], points[i + 1]); } triangle.Triangulate(); } trianglesDirty = false; } private void CallTransform(Matrix m) { if (points != null) { float[] result = new float[points.Length]; m.Transform(points, 0, result, 0, points.Length / 2); this.points = result; this.CheckPoints(); } } public void SetScale(float s) { this.SetScale(s, s); } public virtual void SetScale(float sx, float sy) { if (scaleX != sx || scaleY != sy) { Matrix m = new Matrix(); m.Scale(scaleX = sx, scaleY = sy); this.CallTransform(m); } } public float GetScaleX() { return scaleX; } public float GetScaleY() { return scaleY; } public void SetRotation(float r) { if (rotation != r) { this.CallTransform(Matrix.CreateRotateTransform( rotation = (r / 180f * MathUtils.PI), this.center[0], this.center[1])); } } public void SetRotation(float r, float x_0, float y_1) { if (rotation != r) { this.CallTransform(Matrix.CreateRotateTransform( rotation = (r / 180f * MathUtils.PI), x_0, y_1)); } } public float GetRotation() { return (rotation * 180f / MathUtils.PI); } public void IncreaseTriangulation() { CheckPoints(); CalculateTriangles(); triangle = new TriangleOver(triangle); } public Triangle GetTriangles() { CheckPoints(); CalculateTriangles(); return triangle; } [MethodImpl(MethodImplOptions.Synchronized)] protected internal void CheckPoints() { if (pointsDirty) { CreatePoints(); FindCenter(); CalculateRadius(); if (points == null) { return; } lock (points) { int size = points.Length; if (size > 0) { maxX = points[0]; maxY = points[1]; minX = points[0]; minY = points[1]; for (int i = 0; i < size / 2; i++) { maxX = MathUtils.Max(points[i * 2], maxX); maxY = MathUtils.Max(points[(i * 2) + 1], maxY); minX = MathUtils.Min(points[i * 2], minX); minY = MathUtils.Min(points[(i * 2) + 1], minY); } } pointsDirty = false; trianglesDirty = true; } } } public void PreCache() { CheckPoints(); GetTriangles(); } public virtual bool Closed() { return true; } public Shape Prune() { Polygon result = new Polygon(); for (int i = 0; i < GetPointCount(); i++) { int next = (i + 1 >= GetPointCount()) ? 0 : i + 1; int prev = (i - 1 < 0) ? GetPointCount() - 1 : i - 1; float dx1 = GetPoint(i)[0] - GetPoint(prev)[0]; float dy1 = GetPoint(i)[1] - GetPoint(prev)[1]; float dx2 = GetPoint(next)[0] - GetPoint(i)[0]; float dy2 = GetPoint(next)[1] - GetPoint(i)[1]; float len1 = MathUtils.Sqrt((dx1 * dx1) + (dy1 * dy1)); float len2 = MathUtils.Sqrt((dx2 * dx2) + (dy2 * dy2)); dx1 /= len1; dy1 /= len1; dx2 /= len2; dy2 /= len2; if ((dx1 != dx2) || (dy1 != dy2)) { result.AddPoint(GetPoint(i)[0], GetPoint(i)[1]); } } return result; } public virtual float GetWidth() { return maxX - minX; } public virtual float GetHeight() { return maxY - minY; } public virtual RectBox GetRect() { if (rect == null) { rect = new RectBox(x, y, GetWidth(), GetHeight()); } else { rect.SetBounds(x, y, GetWidth(), GetHeight()); } return rect; } public AABB GetAABB() { if (aabb == null) { aabb = new AABB(minX, minY, maxX, maxY); } else { aabb.Set(minX, minY, maxX, maxY); } return aabb; } } }
// // MonoTests.System.Xml.XPathAtomicValueTests.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // (C)2004 Novell 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. // #if NET_2_0 using System; using System.Collections; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; using NUnit.Framework; namespace MonoTests.System.Xml { [TestFixture] public class XPathAtomicValueTests { internal const string XdtNamespace = "http://www.w3.org/2003/11/xpath-datatypes"; static XmlTypeCode [] AllTypeCode = new ArrayList (Enum.GetValues (typeof (XmlTypeCode))).ToArray (typeof (XmlTypeCode)) as XmlTypeCode []; static XmlQualifiedName [] allTypeNames; static XmlSchemaType [] allTypes; static string [] xstypes = new string [] { "anyType", "anySimpleType", "string", "boolean", "decimal", "float", "double", "duration", "dateTime", "time", "date", "gYearMonth", "gYear", "gMonthDay", "gDay", "gMonth", "hexBinary", "base64Binary", "anyUri", "QName", "NOTATION", "normalizedString", "token", "language", "NMTOKEN", "NMTOKENS", "Name", "NCName", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "integer", "nonPositiveInteger", "negativeInteger", "long", "int", "short", "byte", "nonNegativeInteger", "unsignedLong", "unsignedInt", "unsignedShort", "unsignedByte", "positiveInteger" }; static string [] xdttypes = { "anyAtomicType", "untypedAtomic", "yearMonthDuration", "dayTimeDuration" }; private static XmlQualifiedName [] AllTypeNames { get { if (allTypeNames == null) { ArrayList al = new ArrayList (); foreach (string name in xstypes) AddXsType (name, XmlSchema.Namespace, al); foreach (string name in xdttypes) AddXsType (name, XdtNamespace, al); allTypeNames = al.ToArray (typeof (XmlQualifiedName)) as XmlQualifiedName []; } return allTypeNames; } } private static void AddXsType (string name, string ns, ArrayList al) { al.Add (new XmlQualifiedName (name, ns)); } private static XmlSchemaType [] AllTypes { get { if (allTypes == null) { ArrayList al = new ArrayList (); foreach (XmlQualifiedName name in AllTypeNames) { XmlSchemaType t = XmlSchemaType.GetBuiltInSimpleType (name); if (t == null) t = XmlSchemaType.GetBuiltInComplexType (name); al.Add (t); } allTypes = al.ToArray (typeof (XmlSchemaType)) as XmlSchemaType []; } return allTypes; } } public void AssertAtomicValue (XPathAtomicValue av, bool isNode, Type valueType, XmlSchemaType xmlType, object typedValue, Type typedValueType, string value, object boolValue, object dateValue, object decimalValue, object doubleValue, object int32Value, object int64Value, object singleValue, int listCount) { Assert.AreEqual (isNode, av.IsNode, "IsNode"); Assert.AreEqual (valueType, av.ValueType, "ValueType"); Assert.AreEqual (xmlType, av.XmlType, "XmlType"); Assert.AreEqual (typedValue, av.TypedValue, "TypedValue"); Assert.AreEqual (typedValueType, typedValue.GetType (), "typedValue.GetType()"); if (value != null) Assert.AreEqual (value, av.Value, "Value"); else { try { value = av.Value; Assert.Fail ("not supported conversion to String."); } catch (InvalidCastException) { } } // FIXME: Failure cases could not be tested; // any kind of Exceptions are thrown as yet. if (boolValue != null) Assert.AreEqual (boolValue, av.ValueAsBoolean, "ValueAsBoolean"); /* else { try { boolValue = av.ValueAsBoolean; Assert.Fail ("not supported conversion to Boolean."); } catch (InvalidCastException) { } } */ if (dateValue != null) Assert.AreEqual (dateValue, av.ValueAsDateTime, "ValueAsDateTime"); /* else { try { dateValue = av.ValueAsDateTime; Assert.Fail ("not supported conversion to DateTime."); } catch (InvalidCastException) { } } */ if (decimalValue != null) Assert.AreEqual (decimalValue, av.ValueAsDecimal, "ValueAsDecimal"); /* else { try { decimalValue = av.ValueAsDecimal; Assert.Fail ("not supported conversion to Decimal."); } catch (InvalidCastException) { } } */ if (doubleValue != null) Assert.AreEqual (doubleValue, av.ValueAsDouble, "ValueAsDouble"); /* else { try { doubleValue = av.ValueAsDouble; Assert.Fail ("not supported conversion to Double."); } catch (InvalidCastException) { } } */ if (int32Value != null) Assert.AreEqual (int32Value, av.ValueAsInt32, "ValueAsInt32"); /* else { try { int32Value = av.ValueAsInt32; Assert.Fail ("not supported conversion to Int32."); } catch (InvalidCastException) { } } */ if (int64Value != null) Assert.AreEqual (int64Value, av.ValueAsInt64, "ValueAsInt64"); /* else { try { int64Value = av.ValueAsInt64; Assert.Fail ("not supported conversion to Int64."); } catch (InvalidCastException) { } } */ if (singleValue != null) Assert.AreEqual (singleValue, av.ValueAsSingle, "ValueAsSingle"); /* else { try { singleValue = av.ValueAsSingle; Assert.Fail ("not supported conversion to Single."); } catch (InvalidCastException) { } } */ Assert.AreEqual (listCount, av.ValueAsList.Count, "ValueAsList.Count"); } [Test] public void BooleanType () { XmlSchemaType xstype = XmlSchemaType.GetBuiltInSimpleType (XmlTypeCode.Boolean); XPathAtomicValue av; // true av = new XPathAtomicValue (true, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 1, // decimal 1.0, // double 1, // int32 1, // int64 (float) 1.0, // single 1); // array count // false av = new XPathAtomicValue (false, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType false, // TypedValue typeof (bool), // actual Type of TypedValue "false", // string false, // bool null, // DateTime (decimal) 0, // decimal 0.0, // double 0, // int32 0, // int64 (float) 0.0, // single 1); // array count // 0 av = new XPathAtomicValue (false, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType false, // TypedValue typeof (bool), // actual Type of TypedValue "false", // string false, // bool null, // DateTime (decimal) 0, // decimal 0.0, // double 0, // int32 0, // int64 (float) 0.0, // single 1); // array count // 5 av = new XPathAtomicValue (5, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 5, // decimal 5.0, // double 5, // int32 5, // int64 (float) 5.0, // single 1); // array count // short short shortValue = 3; av = new XPathAtomicValue (shortValue, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 3, // decimal 3.0, // double 3, // int32 3, // int64 (float) 3.0, // single 1); // array count // "1" av = new XPathAtomicValue ("1", xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 1, // decimal 1.0, // double 1, // int32 1, // int64 (float) 1.0, // single 1); // array count // new bool [] {true} av = new XPathAtomicValue (new bool [] {true}, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 1, // decimal 1.0, // double 1, // int32 1, // int64 (float) 1.0, // single 1); // array count // new ArrayList (new int [] {6}) av = new XPathAtomicValue (new ArrayList (new int [] {6}), xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 6, // decimal 6.0, // double 6, // int32 6, // int64 (float) 6.0, // single 1); // array count // Hashtable, [7] = 7 Hashtable ht = new Hashtable (); ht [7] = 7; av = new XPathAtomicValue (ht, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 7, // decimal 7.0, // double 7, // int32 7, // int64 (float) 7.0, // single 1); // array count // - MS.NET will fail here due to its bug - // another XPathAtomicValue that is bool av = new XPathAtomicValue (true, xstype); av = new XPathAtomicValue (av, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 1, // decimal 1.0, // double 1, // int32 1, // int64 (float) 1.0, // single 1); // array count // Array, [0] = XPathAtomicValue av = new XPathAtomicValue (new XPathAtomicValue [] {av}, xstype); AssertAtomicValue (av, false, typeof (bool), // ValueType xstype, // XmlType true, // TypedValue typeof (bool), // actual Type of TypedValue "true", // string true, // bool null, // DateTime (decimal) 1, // decimal 1.0, // double 1, // int32 1, // int64 (float) 1.0, // single 1); // array count // new bool [] {true, false} av = new XPathAtomicValue (new bool [] {true, false}, xstype); try { object o = av.ValueAsBoolean; Assert.Fail ("ArrayList must contain just one item to be castable to bool"); } catch (InvalidCastException) { } // empty ArrayList av = new XPathAtomicValue (new ArrayList (), xstype); try { object o = av.ValueAsBoolean; Assert.Fail ("ArrayList must contain just one item to be castable to bool"); } catch (InvalidCastException) { } // "True" av = new XPathAtomicValue ("True", xstype); try { object o = av.ValueAsBoolean; Assert.Fail ("\"True\" is not a boolean representation (\"true\" is)."); } catch (InvalidCastException) { } // DateTime av = new XPathAtomicValue (DateTime.Now, xstype); try { object o = av.ValueAsBoolean; Assert.Fail ("DateTime should not be castable to bool."); } catch (InvalidCastException) { } // XmlText node that contains boolean representation value XmlDocument doc = new XmlDocument (); doc.LoadXml ("<root>true</root>"); XmlNode node = doc.DocumentElement.FirstChild; av = new XPathAtomicValue (node, xstype); try { object o = av.ValueAsBoolean; Assert.Fail ("XmlText cannot be castable to bool."); } catch (InvalidCastException) { } // XPathNavigator whose node points to text node whose // value represents boolean string. av = new XPathAtomicValue (node.CreateNavigator (), xstype); try { object o = av.ValueAsBoolean; Assert.Fail ("XmlText cannot be castable to bool."); } catch (InvalidCastException) { } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal interface IInstructionProvider { void AddInstructions(LightCompiler compiler); } internal abstract partial class Instruction { public const int UnknownInstrIndex = int.MaxValue; public virtual int ConsumedStack { get { return 0; } } public virtual int ProducedStack { get { return 0; } } public virtual int ConsumedContinuations { get { return 0; } } public virtual int ProducedContinuations { get { return 0; } } public int StackBalance { get { return ProducedStack - ConsumedStack; } } public int ContinuationsBalance { get { return ProducedContinuations - ConsumedContinuations; } } public abstract int Run(InterpretedFrame frame); public virtual string InstructionName { get { return "<Unknown>"; } } public override string ToString() { return InstructionName + "()"; } public virtual string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return ToString(); } public virtual object GetDebugCookie(LightCompiler compiler) { return null; } } internal abstract class NotInstruction : Instruction { public static Instruction _Bool, _Int64, _Int32, _Int16, _UInt64, _UInt32, _UInt16, _Byte, _SByte; private NotInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Not"; } } private class BoolNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((bool)value ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True); } return +1; } } private class Int64Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int64)~(Int64)value); } return +1; } } private class Int32Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int32)(~(Int32)value)); } return +1; } } private class Int16Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int16)(~(Int16)value)); } return +1; } } private class UInt64Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt64)(~(UInt64)value)); } return +1; } } private class UInt32Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt32)(~(UInt32)value)); } return +1; } } private class UInt16Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt16)(~(UInt16)value)); } return +1; } } private class ByteNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((object)(Byte)(~(Byte)value)); } return +1; } } private class SByteNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((object)(SByte)(~(SByte)value)); } return +1; } } public static Instruction Create(Type t) { switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(t))) { case TypeCode.Boolean: return _Bool ?? (_Bool = new BoolNot()); case TypeCode.Int64: return _Int64 ?? (_Int64 = new Int64Not()); case TypeCode.Int32: return _Int32 ?? (_Int32 = new Int32Not()); case TypeCode.Int16: return _Int16 ?? (_Int16 = new Int16Not()); case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new UInt64Not()); case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new UInt32Not()); case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new UInt16Not()); case TypeCode.Byte: return _Byte ?? (_Byte = new ByteNot()); case TypeCode.SByte: return _SByte ?? (_SByte = new SByteNot()); default: throw new InvalidOperationException("Not for " + t.ToString()); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Management.Automation; using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { /// <summary> /// A command to set the property of an item at a specified path. /// </summary> [Cmdlet(VerbsCommon.Set, "ItemProperty", DefaultParameterSetName = "propertyValuePathSet", SupportsShouldProcess = true, SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113396")] public class SetItemPropertyCommand : PassThroughItemPropertyCommandBase { private const string propertyValuePathSet = "propertyValuePathSet"; private const string propertyValueLiteralPathSet = "propertyValueLiteralPathSet"; private const string propertyPSObjectPathSet = "propertyPSObjectPathSet"; private const string propertyPSObjectLiteralPathSet = "propertyPSObjectLiteralPathSet"; #region Parameters /// <summary> /// Gets or sets the path parameter to the command. /// </summary> [Parameter(Position = 0, ParameterSetName = propertyPSObjectPathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] [Parameter(Position = 0, ParameterSetName = propertyValuePathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { return paths; } set { paths = value; } } /// <summary> /// Gets or sets the literal path parameter to the command. /// </summary> [Parameter(ParameterSetName = propertyValueLiteralPathSet, Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Parameter(ParameterSetName = propertyPSObjectLiteralPathSet, Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath", "LP")] public string[] LiteralPath { get { return paths; } set { base.SuppressWildcardExpansion = true; paths = value; } } #region Property Value set /// <summary> /// The name of the property to set. /// </summary> /// <value> /// This value type is determined by the InvokeProvider. /// </value> [Parameter(Position = 1, ParameterSetName = propertyValuePathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] [Parameter(Position = 1, ParameterSetName = propertyValueLiteralPathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] [Alias("PSProperty")] public string Name { get; set; } = string.Empty; /// <summary> /// The value of the property to set. /// </summary> /// <value> /// This value type is determined by the InvokeProvider. /// </value> [Parameter(Position = 2, ParameterSetName = propertyValuePathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] [Parameter(Position = 2, ParameterSetName = propertyValueLiteralPathSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] [AllowNull] public object Value { get; set; } #endregion Property Value set #region Shell object set /// <summary> /// A PSObject that contains the properties and values to be set. /// </summary> /// <value></value> [Parameter(ParameterSetName = propertyPSObjectPathSet, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] [Parameter(ParameterSetName = propertyPSObjectLiteralPathSet, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] public PSObject InputObject { get; set; } #endregion Shell object set /// <summary> /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the /// dynamic parameter object. /// </summary> /// <param name="context"> /// The context under which the command is running. /// </param> /// <returns> /// An object representing the dynamic parameters for the cmdlet or null if there /// are none. /// </returns> internal override object GetDynamicParameters(CmdletProviderContext context) { PSObject mshObject = null; switch (ParameterSetName) { case propertyValuePathSet: case propertyValueLiteralPathSet: if (!string.IsNullOrEmpty(Name)) { mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty(Name, Value)); } break; default: mshObject = InputObject; break; } if (Path != null && Path.Length > 0) { return InvokeProvider.Property.SetPropertyDynamicParameters(Path[0], mshObject, context); } return InvokeProvider.Property.SetPropertyDynamicParameters(".", mshObject, context); } #endregion Parameters #region parameter data #endregion parameter data #region Command code /// <summary> /// Sets the content of the item at the specified path. /// </summary> protected override void ProcessRecord() { // Default to the CmdletProviderContext that will direct output to // the pipeline. CmdletProviderContext currentCommandContext = CmdletProviderContext; currentCommandContext.PassThru = PassThru; PSObject mshObject = null; switch (ParameterSetName) { case propertyValuePathSet: case propertyValueLiteralPathSet: mshObject = new PSObject(); mshObject.Properties.Add(new PSNoteProperty(Name, Value)); break; case propertyPSObjectPathSet: mshObject = InputObject; break; default: Diagnostics.Assert( false, "One of the parameter sets should have been resolved or an error should have been thrown by the command processor"); break; } foreach (string path in Path) { try { InvokeProvider.Property.Set(path, mshObject, currentCommandContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } } } #endregion Command code } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.Diagnostics; using log4net.Util; namespace log4net.Core { /// <summary> /// The internal representation of caller location information. /// </summary> /// <remarks> /// <para> /// This class uses the <c>System.Diagnostics.StackTrace</c> class to generate /// a call stack. The caller's information is then extracted from this stack. /// </para> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class is not supported on the /// .NET Compact Framework 1.0 therefore caller location information is not /// available on that framework. /// </para> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds: /// </para> /// <para> /// "StackTrace information will be most informative with Debug build configurations. /// By default, Debug builds include debug symbols, while Release builds do not. The /// debug symbols contain most of the file, method name, line number, and column /// information used in constructing StackFrame and StackTrace objects. StackTrace /// might not report as many method calls as expected, due to code transformations /// that occur during optimization." /// </para> /// <para> /// This means that in a Release build the caller information may be incomplete or may /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if !NETCF [Serializable] #endif public class LocationInfo { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is /// the stack boundary into the logging system for this call.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LocationInfo" /> /// class based on the current thread. /// </para> /// </remarks> public LocationInfo(Type callerStackBoundaryDeclaringType) { // Initialize all fields m_className = NA; m_fileName = NA; m_lineNumber = NA; m_methodName = NA; m_fullInfo = NA; #if !(NETCF || NETSTANDARD1_3) // StackTrace isn't fully implemented for NETSTANDARD1_3 https://github.com/dotnet/corefx/issues/1797 if (callerStackBoundaryDeclaringType != null) { try { StackTrace st = new StackTrace(true); int frameIndex = 0; // skip frames not from fqnOfCallingClass while (frameIndex < st.FrameCount) { StackFrame frame = st.GetFrame(frameIndex); if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType) { break; } frameIndex++; } // skip frames from fqnOfCallingClass while (frameIndex < st.FrameCount) { StackFrame frame = st.GetFrame(frameIndex); if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType) { break; } frameIndex++; } if (frameIndex < st.FrameCount) { // take into account the frames we skip above int adjustedFrameCount = st.FrameCount - frameIndex; ArrayList stackFramesList = new ArrayList(adjustedFrameCount); m_stackFrames = new StackFrameItem[adjustedFrameCount]; for (int i=frameIndex; i < st.FrameCount; i++) { stackFramesList.Add(new StackFrameItem(st.GetFrame(i))); } stackFramesList.CopyTo(m_stackFrames, 0); // now frameIndex is the first 'user' caller frame StackFrame locationFrame = st.GetFrame(frameIndex); if (locationFrame != null) { System.Reflection.MethodBase method = locationFrame.GetMethod(); if (method != null) { m_methodName = method.Name; if (method.DeclaringType != null) { m_className = method.DeclaringType.FullName; } } m_fileName = locationFrame.GetFileName(); m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); // Combine all location info m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')'; } } } catch(System.Security.SecurityException) { // This security exception will occur if the caller does not have // some undefined set of SecurityPermission flags. LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available."); } } #endif } /// <summary> /// Constructor /// </summary> /// <param name="className">The fully qualified class name.</param> /// <param name="methodName">The method name.</param> /// <param name="fileName">The file name.</param> /// <param name="lineNumber">The line number of the method within the file.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LocationInfo" /> /// class with the specified data. /// </para> /// </remarks> public LocationInfo(string className, string methodName, string fileName, string lineNumber) { m_className = className; m_fileName = fileName; m_lineNumber = lineNumber; m_methodName = methodName; m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')'; } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets the fully qualified class name of the caller making the logging /// request. /// </summary> /// <value> /// The fully qualified class name of the caller making the logging /// request. /// </value> /// <remarks> /// <para> /// Gets the fully qualified class name of the caller making the logging /// request. /// </para> /// </remarks> public string ClassName { get { return m_className; } } /// <summary> /// Gets the file name of the caller. /// </summary> /// <value> /// The file name of the caller. /// </value> /// <remarks> /// <para> /// Gets the file name of the caller. /// </para> /// </remarks> public string FileName { get { return m_fileName; } } /// <summary> /// Gets the line number of the caller. /// </summary> /// <value> /// The line number of the caller. /// </value> /// <remarks> /// <para> /// Gets the line number of the caller. /// </para> /// </remarks> public string LineNumber { get { return m_lineNumber; } } /// <summary> /// Gets the method name of the caller. /// </summary> /// <value> /// The method name of the caller. /// </value> /// <remarks> /// <para> /// Gets the method name of the caller. /// </para> /// </remarks> public string MethodName { get { return m_methodName; } } /// <summary> /// Gets all available caller information /// </summary> /// <value> /// All available caller information, in the format /// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c> /// </value> /// <remarks> /// <para> /// Gets all available caller information, in the format /// <c>fully.qualified.classname.of.caller.methodName(Filename:line)</c> /// </para> /// </remarks> public string FullInfo { get { return m_fullInfo; } } #if !(NETCF || NETSTANDARD1_3) /// <summary> /// Gets the stack frames from the stack trace of the caller making the log request /// </summary> public StackFrameItem[] StackFrames { get { return m_stackFrames; } } #endif #endregion Public Instance Properties #region Private Instance Fields private readonly string m_className; private readonly string m_fileName; private readonly string m_lineNumber; private readonly string m_methodName; private readonly string m_fullInfo; #if !(NETCF || NETSTANDARD1_3) private readonly StackFrameItem[] m_stackFrames; #endif #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the LocationInfo class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LocationInfo); /// <summary> /// When location information is not available the constant /// <c>NA</c> is returned. Current value of this string /// constant is <b>?</b>. /// </summary> private const string NA = "?"; #endregion Private Static Fields } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; using System.Xml.Linq; using System.Xml.XmlDiff; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; namespace XLinqTests { public class SaveWithWriter : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+SaveWithWriter // Test Case #region Constants private const string BaseSaveFileName = "baseSave.xml"; private const string TestSaveFileName = "testSave"; private const string xml = "<PurchaseOrder><Item price=\"100\">Motor<![CDATA[cdata]]><elem>innertext</elem>text<?pi pi pi?></Item></PurchaseOrder>"; private const string xmlForXElementWriteContent = "<Item price=\"100\">Motor<![CDATA[cdata]]><elem>innertext</elem>text<?pi pi pi?></Item>"; #endregion #region Fields private readonly XmlDiff _diff; #endregion #region Constructors and Destructors public SaveWithWriter() { _diff = new XmlDiff(); } #endregion #region Public Methods and Operators public static string[] GetExpectedXml() { string[] xml = { "text", "", " ", "<!--comment1 comment1 -->", "<!---->", "<!-- -->", "<?pi1 pi1 pi1 ?>", "<?pi1?>", "<?pi1 ?>", "<![CDATA[cdata cdata ]]>", "<![CDATA[]]>", "<![CDATA[ ]]>", "<elem attr=\"val\">text<!--comm--><?pi hffgg?><![CDATA[jfggr]]></elem>" }; return xml; } public static object[] GetObjects() { object[] objects = { new XText("text"), new XText(""), new XText(" "), new XComment("comment1 comment1 "), new XComment(""), new XComment(" "), new XProcessingInstruction("pi1", "pi1 pi1 "), new XProcessingInstruction("pi1", ""), new XProcessingInstruction("pi1", " "), new XCData("cdata cdata "), new XCData(""), new XCData(" "), new XElement("elem", new XAttribute("attr", "val"), new XText("text"), new XComment("comm"), new XProcessingInstruction("pi", "hffgg"), new XCData("jfggr")) }; return objects; } public override void AddChildren() { AddChild(new TestVariation(writer_5) { Attribute = new VariationAttribute("Write and valIdate XDocumentType") { Priority = 0 } }); AddChild(new TestVariation(writer_18) { Attribute = new VariationAttribute("WriteTo after WriteState = Error") { Param = "WriteTo", Priority = 2 } }); AddChild(new TestVariation(writer_18) { Attribute = new VariationAttribute("Save after WriteState = Error") { Param = "Save", Priority = 2 } }); AddChild(new TestVariation(writer_20) { Attribute = new VariationAttribute("XDocument: Null parameters for Save") { Priority = 1 } }); AddChild(new TestVariation(writer_21) { Attribute = new VariationAttribute("XElement: Null parameters for Save") { Priority = 1 } }); AddChild(new TestVariation(writer_23) { Attribute = new VariationAttribute("XDocument: Null parameters for WriteTo") { Priority = 1 } }); AddChild(new TestVariation(writer_24) { Attribute = new VariationAttribute("XElement: Null parameters for WriteTo") { Priority = 1 } }); } public Encoding[] GetEncodings() { Encoding[] encodings = { Encoding.UTF8 //Encoding.Unicode, //Encoding.BigEndianUnicode, }; return encodings; } //[Variation(Priority = 2, Desc = "Save after WriteState = Error", Param = "Save")] //[Variation(Priority = 2, Desc = "WriteTo after WriteState = Error", Param = "WriteTo")] public void writer_18() { var doc = new XDocument(); foreach (Encoding encoding in GetEncodings()) { foreach (XmlWriter w in GetXmlWriters(encoding)) { try { if (Variation.Param.ToString() == "Save") { doc.Save(w); } else { doc.WriteTo(w); } throw new TestException(TestResult.Failed, ""); } catch (Exception ex) { if (!(ex is InvalidOperationException) && !(ex is ArgumentException)) { throw; } TestLog.Equals(w.WriteState, WriteState.Error, "Error in WriteState"); try { if (Variation.Param.ToString() == "Save") { doc.Save(w); } else { doc.WriteTo(w); } throw new TestException(TestResult.Failed, ""); } catch (InvalidOperationException) { } } finally { w.Dispose(); } } } } //[Variation(Priority = 1, Desc = "XDocument: Null parameters for Save")] public void writer_20() { var doc = new XDocument(new XElement("PurchaseOrder")); //save with TextWriter try { doc.Save((TextWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((TextWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } try { doc.Save((TextWriter)null, SaveOptions.DisableFormatting); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((TextWriter)null, SaveOptions.DisableFormatting); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } try { doc.Save((TextWriter)null, SaveOptions.None); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((TextWriter)null, SaveOptions.None); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //save with XmlWriter try { doc.Save((XmlWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { try { doc.Save((XmlWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } } //[Variation(Priority = 1, Desc = "XElement: Null parameters for Save")] public void writer_21() { var doc = new XElement(new XElement("PurchaseOrder")); //save with TextWriter try { doc.Save((TextWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } try { doc.Save((TextWriter)null, SaveOptions.DisableFormatting); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } try { doc.Save((TextWriter)null, SaveOptions.None); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } //save with XmlWriter try { doc.Save((XmlWriter)null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Priority = 1, Desc = "XDocument: Null parameters for WriteTo")] public void writer_23() { var doc = new XDocument(new XElement("PurchaseOrder")); try { doc.WriteTo(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Priority = 1, Desc = "XElement: Null parameters for WriteTo")] public void writer_24() { var doc = new XElement(new XElement("PurchaseOrder")); try { doc.WriteTo(null); throw new TestException(TestResult.Failed, ""); } catch (ArgumentNullException) { } } //[Variation(Priority = 0, Desc = "Write and valIdate XDocumentType")] public void writer_5() { string expectedXml = "<!DOCTYPE root PUBLIC \"\" \"\"[<!ELEMENT root ANY>]>"; var doc = new XDocumentType("root", "", "", "<!ELEMENT root ANY>"); TestToStringAndXml(doc, expectedXml); var ws = new XmlWriterSettings(); ws.ConformanceLevel = ConformanceLevel.Document; ws.OmitXmlDeclaration = true; // Set to true when FileIO is ok ws.CloseOutput = false; // Use a file to replace this when FileIO is ok var m = new MemoryStream(); using (XmlWriter wr = XmlWriter.Create(m, ws)) { doc.WriteTo(wr); } m.Position = 0; using (TextReader r = new StreamReader(m)) { string actualXml = r.ReadToEnd(); TestLog.Compare(expectedXml, actualXml, "XDocumentType writeTo method failed"); } } #endregion // // helpers // #region Methods private string GenerateTestFileName(int index) { string filename = string.Format("{0}{1}.xml", TestSaveFileName, index); try { FilePathUtil.getStream(filename); } catch (Exception) { FilePathUtil.addStream(filename, new MemoryStream()); } return filename; } private List<XmlWriter> GetXmlWriters(Encoding encoding) { return GetXmlWriters(encoding, ConformanceLevel.Document); } private List<XmlWriter> GetXmlWriters(Encoding encoding, ConformanceLevel conformanceLevel) { var xmlWriters = new List<XmlWriter>(); int count = 0; var s = new XmlWriterSettings(); s.CheckCharacters = true; s.Encoding = encoding; var ws = new XmlWriterSettings(); ws.CheckCharacters = false; // Set it to true when FileIO is ok ws.CloseOutput = false; ws.Encoding = encoding; s.ConformanceLevel = conformanceLevel; ws.ConformanceLevel = conformanceLevel; TextWriter tw = new StreamWriter(FilePathUtil.getStream(GenerateTestFileName(count++))); xmlWriters.Add(new CoreXml.Test.XLinq.CustomWriter(tw, ws)); // CustomWriter xmlWriters.Add(XmlWriter.Create(FilePathUtil.getStream(GenerateTestFileName(count++)), s)); // Factory XmlWriter xmlWriters.Add(XmlWriter.Create(FilePathUtil.getStream(GenerateTestFileName(count++)), ws)); // Factory Writer return xmlWriters; } private void SaveBaseline(string xml) { var ms = new MemoryStream(); var sw = new StreamWriter(ms); sw.Write(xml); sw.Flush(); FilePathUtil.addStream(BaseSaveFileName, ms); } private void SaveWithFile(object doc) { string file0 = GenerateTestFileName(0); string file1 = GenerateTestFileName(1); string file2 = GenerateTestFileName(2); foreach (Encoding encoding in GetEncodings()) { if (doc is XDocument) { ((XDocument)doc).Save(FilePathUtil.getStream(file0)); ((XDocument)doc).Save(FilePathUtil.getStream(file1), SaveOptions.DisableFormatting); ((XDocument)doc).Save(FilePathUtil.getStream(file2), SaveOptions.None); } else if (doc is XElement) { ((XElement)doc).Save(FilePathUtil.getStream(file0)); ((XElement)doc).Save(FilePathUtil.getStream(file1), SaveOptions.DisableFormatting); ((XElement)doc).Save(FilePathUtil.getStream(file2), SaveOptions.None); } else { TestLog.Compare(false, "Wrong object"); } TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file0)), "Save failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file1)), "Save(preserveWhitespace true) failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file2)), "Save(preserveWhitespace false) " + encoding); } } private void SaveWithTextWriter(object doc) { string file0 = GenerateTestFileName(0); string file1 = GenerateTestFileName(1); string file2 = GenerateTestFileName(2); foreach (Encoding encoding in GetEncodings()) { using (TextWriter w0 = new StreamWriter(FilePathUtil.getStream(file0))) using (TextWriter w1 = new StreamWriter(FilePathUtil.getStream(file1))) using (TextWriter w2 = new StreamWriter(FilePathUtil.getStream(file2))) { if (doc is XDocument) { ((XDocument)doc).Save(w0); ((XDocument)doc).Save(w1, SaveOptions.DisableFormatting); ((XDocument)doc).Save(w2, SaveOptions.None); } else if (doc is XElement) { ((XElement)doc).Save(w0); ((XElement)doc).Save(w1, SaveOptions.DisableFormatting); ((XElement)doc).Save(w2, SaveOptions.None); } else { TestLog.Compare(false, "Wrong object"); } w0.Dispose(); w1.Dispose(); w2.Dispose(); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file0)), "TextWriter failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file1)), "TextWriter(preserveWhtsp=true) failed:encoding " + encoding); TestLog.Compare(_diff.Compare(FilePathUtil.getStream(BaseSaveFileName), FilePathUtil.getStream(file2)), "TextWriter(preserveWhtsp=false) failed:encoding " + encoding); } } } private void SaveWithXmlWriter(object doc) { foreach (Encoding encoding in GetEncodings()) { List<XmlWriter> xmlWriters = GetXmlWriters(encoding); try { for (int i = 0; i < xmlWriters.Count; ++i) { if (doc is XDocument) { ((XDocument)doc).Save(xmlWriters[i]); } else if (doc is XElement) { ((XElement)doc).Save(xmlWriters[i]); } else { TestLog.Compare(false, "Wrong object"); } xmlWriters[i].Dispose(); if (doc is XDocument) { ((XDocument)doc).Save(FilePathUtil.getStream(GenerateTestFileName(i))); } else if (doc is XElement) { ((XElement)doc).Save(FilePathUtil.getStream(GenerateTestFileName(i))); } else { TestLog.Compare(false, "Wrong object"); } TestLog.Skip("ReEnable this when FileIO is OK"); } } finally { for (int i = 0; i < xmlWriters.Count; ++i) { xmlWriters[i].Dispose(); } } } } private void TestToStringAndXml(object doc, string expectedXml) { string toString = doc.ToString(); string xml = string.Empty; if (doc is XDocument) { xml = ((XDocument)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XElement) { xml = ((XElement)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XText) { xml = ((XText)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XCData) { xml = ((XCData)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XComment) { xml = ((XComment)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XProcessingInstruction) { xml = ((XProcessingInstruction)doc).ToString(SaveOptions.DisableFormatting); } else if (doc is XDocumentType) { xml = ((XDocumentType)doc).ToString(SaveOptions.DisableFormatting); } else { TestLog.Compare(false, "Wrong object"); } TestLog.Compare(toString, expectedXml, "Test ToString failed"); TestLog.Compare(xml, expectedXml, "Test .ToString(SaveOptions.DisableFormatting) failed"); } #endregion } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using DecodeHintType = com.google.zxing.DecodeHintType; using ReaderException = com.google.zxing.ReaderException; using ResultPoint = com.google.zxing.ResultPoint; using ResultPointCallback = com.google.zxing.ResultPointCallback; using BitMatrix = com.google.zxing.common.BitMatrix; using DetectorResult = com.google.zxing.common.DetectorResult; using GridSampler = com.google.zxing.common.GridSampler; using PerspectiveTransform = com.google.zxing.common.PerspectiveTransform; using Version = com.google.zxing.qrcode.decoder.Version; namespace com.google.zxing.qrcode.detector { /// <summary> <p>Encapsulates logic that can detect a QR Code in an image, even if the QR Code /// is rotated or skewed, or partially obscured.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public class Detector { virtual protected internal BitMatrix Image { get { return image; } } virtual protected internal ResultPointCallback ResultPointCallback { get { return resultPointCallback; } } //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private BitMatrix image; private ResultPointCallback resultPointCallback; public Detector(BitMatrix image) { this.image = image; } /// <summary> <p>Detects a QR Code in an image, simply.</p> /// /// </summary> /// <returns> {@link DetectorResult} encapsulating results of detecting a QR Code /// </returns> /// <throws> ReaderException if no QR Code can be found </throws> public virtual DetectorResult detect() { return detect(null); } /// <summary> <p>Detects a QR Code in an image, simply.</p> /// /// </summary> /// <param name="hints">optional hints to detector /// </param> /// <returns> {@link DetectorResult} encapsulating results of detecting a QR Code /// </returns> /// <throws> ReaderException if no QR Code can be found </throws> public virtual DetectorResult detect(System.Collections.Hashtable hints) { resultPointCallback = hints == null?null:(ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK]; FinderPatternFinder finder = new FinderPatternFinder(image, resultPointCallback); FinderPatternInfo info = finder.find(hints); return processFinderPatternInfo(info); } protected internal virtual DetectorResult processFinderPatternInfo(FinderPatternInfo info) { FinderPattern topLeft = info.TopLeft; FinderPattern topRight = info.TopRight; FinderPattern bottomLeft = info.BottomLeft; float moduleSize = calculateModuleSize(topLeft, topRight, bottomLeft); if (moduleSize < 1.0f) { throw ReaderException.Instance; } int dimension = computeDimension(topLeft, topRight, bottomLeft, moduleSize); Version provisionalVersion = Version.getProvisionalVersionForDimension(dimension); int modulesBetweenFPCenters = provisionalVersion.DimensionForVersion - 7; AlignmentPattern alignmentPattern = null; // Anything above version 1 has an alignment pattern if (provisionalVersion.AlignmentPatternCenters.Length > 0) { // Guess where a "bottom right" finder pattern would have been float bottomRightX = topRight.X - topLeft.X + bottomLeft.X; float bottomRightY = topRight.Y - topLeft.Y + bottomLeft.Y; // Estimate that alignment pattern is closer by 3 modules // from "bottom right" to known top left location //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float correctionToTopLeft = 1.0f - 3.0f / (float) modulesBetweenFPCenters; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int estAlignmentX = (int) (topLeft.X + correctionToTopLeft * (bottomRightX - topLeft.X)); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int estAlignmentY = (int) (topLeft.Y + correctionToTopLeft * (bottomRightY - topLeft.Y)); // Kind of arbitrary -- expand search radius before giving up for (int i = 4; i <= 16; i <<= 1) { try { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" alignmentPattern = findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, (float) i); break; } catch (ReaderException re) { // try next round } } // If we didn't find alignment pattern... well try anyway without it } PerspectiveTransform transform = createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension); BitMatrix bits = sampleGrid(image, transform, dimension); ResultPoint[] points; if (alignmentPattern == null) { points = new ResultPoint[]{bottomLeft, topLeft, topRight}; } else { points = new ResultPoint[]{bottomLeft, topLeft, topRight, alignmentPattern}; } return new DetectorResult(bits, points); } public virtual PerspectiveTransform createTransform(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, ResultPoint alignmentPattern, int dimension) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float dimMinusThree = (float) dimension - 3.5f; float bottomRightX; float bottomRightY; float sourceBottomRightX; float sourceBottomRightY; if (alignmentPattern != null) { bottomRightX = alignmentPattern.X; bottomRightY = alignmentPattern.Y; sourceBottomRightX = sourceBottomRightY = dimMinusThree - 3.0f; } else { // Don't have an alignment pattern, just make up the bottom-right point bottomRightX = (topRight.X - topLeft.X) + bottomLeft.X; bottomRightY = (topRight.Y - topLeft.Y) + bottomLeft.Y; sourceBottomRightX = sourceBottomRightY = dimMinusThree; } PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(3.5f, 3.5f, dimMinusThree, 3.5f, sourceBottomRightX, sourceBottomRightY, 3.5f, dimMinusThree, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRightX, bottomRightY, bottomLeft.X, bottomLeft.Y); return transform; } private static BitMatrix sampleGrid(BitMatrix image, PerspectiveTransform transform, int dimension) { GridSampler sampler = GridSampler.Instance; return sampler.sampleGrid(image, dimension, transform); } /// <summary> <p>Computes the dimension (number of modules on a size) of the QR Code based on the position /// of the finder patterns and estimated module size.</p> /// </summary> protected internal static int computeDimension(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft, float moduleSize) { int tltrCentersDimension = round(ResultPoint.distance(topLeft, topRight) / moduleSize); int tlblCentersDimension = round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize); int dimension = ((tltrCentersDimension + tlblCentersDimension) >> 1) + 7; switch (dimension & 0x03) { // mod 4 case 0: dimension++; break; // 1? do nothing case 2: dimension--; break; case 3: throw ReaderException.Instance; } return dimension; } /// <summary> <p>Computes an average estimated module size based on estimated derived from the positions /// of the three finder patterns.</p> /// </summary> protected internal virtual float calculateModuleSize(ResultPoint topLeft, ResultPoint topRight, ResultPoint bottomLeft) { // Take the average return (calculateModuleSizeOneWay(topLeft, topRight) + calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0f; } /// <summary> <p>Estimates module size based on two finder patterns -- it uses /// {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the /// width of each, measuring along the axis between their centers.</p> /// </summary> private float calculateModuleSizeOneWay(ResultPoint pattern, ResultPoint otherPattern) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float moduleSizeEst1 = sizeOfBlackWhiteBlackRunBothWays((int) pattern.X, (int) pattern.Y, (int) otherPattern.X, (int) otherPattern.Y); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float moduleSizeEst2 = sizeOfBlackWhiteBlackRunBothWays((int) otherPattern.X, (int) otherPattern.Y, (int) pattern.X, (int) pattern.Y); if (System.Single.IsNaN(moduleSizeEst1)) { return moduleSizeEst2 / 7.0f; } if (System.Single.IsNaN(moduleSizeEst2)) { return moduleSizeEst1 / 7.0f; } // Average them, and divide by 7 since we've counted the width of 3 black modules, // and 1 white and 1 black module on either side. Ergo, divide sum by 14. return (moduleSizeEst1 + moduleSizeEst2) / 14.0f; } /// <summary> See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of /// a finder pattern by looking for a black-white-black run from the center in the direction /// of another point (another finder pattern center), and in the opposite direction too.</p> /// </summary> private float sizeOfBlackWhiteBlackRunBothWays(int fromX, int fromY, int toX, int toY) { float result = sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY); // Now count other way -- don't run off image though of course float scale = 1.0f; int otherToX = fromX - (toX - fromX); if (otherToX < 0) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) fromX / (float) (fromX - otherToX); otherToX = 0; } else if (otherToX >= image.Width) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) (image.Width - 1 - fromX) / (float) (otherToX - fromX); otherToX = image.Width - 1; } //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int otherToY = (int) (fromY - (toY - fromY) * scale); scale = 1.0f; if (otherToY < 0) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) fromY / (float) (fromY - otherToY); otherToY = 0; } else if (otherToY >= image.Height) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" scale = (float) (image.Height - 1 - fromY) / (float) (otherToY - fromY); otherToY = image.Height - 1; } //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" otherToX = (int) (fromX + (otherToX - fromX) * scale); result += sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY); return result - 1.0f; // -1 because we counted the middle pixel twice } /// <summary> <p>This method traces a line from a point in the image, in the direction towards another point. /// It begins in a black region, and keeps going until it finds white, then black, then white again. /// It reports the distance from the start to this point.</p> /// /// <p>This is used when figuring out how wide a finder pattern is, when the finder pattern /// may be skewed or rotated.</p> /// </summary> private float sizeOfBlackWhiteBlackRun(int fromX, int fromY, int toX, int toY) { // Mild variant of Bresenham's algorithm; // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm bool steep = System.Math.Abs(toY - fromY) > System.Math.Abs(toX - fromX); if (steep) { int temp = fromX; fromX = fromY; fromY = temp; temp = toX; toX = toY; toY = temp; } int dx = System.Math.Abs(toX - fromX); int dy = System.Math.Abs(toY - fromY); int error = - dx >> 1; int ystep = fromY < toY?1:- 1; int xstep = fromX < toX?1:- 1; int state = 0; // In black pixels, looking for white, first or second time for (int x = fromX, y = fromY; x != toX; x += xstep) { int realX = steep?y:x; int realY = steep?x:y; if (state == 1) { // In white pixels, looking for black if (image.get_Renamed(realX, realY)) { state++; } } else { if (!image.get_Renamed(realX, realY)) { state++; } } if (state == 3) { // Found black, white, black, and stumbled back onto white; done int diffX = x - fromX; int diffY = y - fromY; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (float) System.Math.Sqrt((double) (diffX * diffX + diffY * diffY)); } error += dy; if (error > 0) { if (y == toY) { break; } y += ystep; error -= dx; } } int diffX2 = toX - fromX; int diffY2 = toY - fromY; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (float) System.Math.Sqrt((double) (diffX2 * diffX2 + diffY2 * diffY2)); } /// <summary> <p>Attempts to locate an alignment pattern in a limited region of the image, which is /// guessed to contain it. This method uses {@link AlignmentPattern}.</p> /// /// </summary> /// <param name="overallEstModuleSize">estimated module size so far /// </param> /// <param name="estAlignmentX">x coordinate of center of area probably containing alignment pattern /// </param> /// <param name="estAlignmentY">y coordinate of above /// </param> /// <param name="allowanceFactor">number of pixels in all directions to search from the center /// </param> /// <returns> {@link AlignmentPattern} if found, or null otherwise /// </returns> /// <throws> ReaderException if an unexpected error occurs during detection </throws> protected internal virtual AlignmentPattern findAlignmentInRegion(float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor) { // Look for an alignment pattern (3 modules in size) around where it // should be //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" int allowance = (int) (allowanceFactor * overallEstModuleSize); int alignmentAreaLeftX = System.Math.Max(0, estAlignmentX - allowance); int alignmentAreaRightX = System.Math.Min(image.Width - 1, estAlignmentX + allowance); if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) { throw ReaderException.Instance; } int alignmentAreaTopY = System.Math.Max(0, estAlignmentY - allowance); int alignmentAreaBottomY = System.Math.Min(image.Height - 1, estAlignmentY + allowance); AlignmentPatternFinder alignmentFinder = new AlignmentPatternFinder(image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, resultPointCallback); return alignmentFinder.find(); } /// <summary> Ends up being a bit faster than Math.round(). This merely rounds its argument to the nearest int, /// where x.5 rounds up. /// </summary> private static int round(float d) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (int) (d + 0.5f); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Ceen.Database; using Ceen.Mvc; namespace Ceen.Extras { /// <summary> /// The parameters to a list request /// </summary> public class ListRequest { /// <summary> /// The start of the list results /// </summary> public int Offset; /// <summary> /// The maximum number of list results /// </summary> public int Count; /// <summary> /// The filter to apply /// </summary> public string Filter; /// <summary> /// The sort order to use /// </summary> public string SortOrder; } /// <summary> /// The response to a list request /// </summary> public class ListResponse { /// <summary> /// The offset of these results /// </summary> public long Offset; /// <summary> /// The total number of entries /// </summary> public long Total; /// <summary> /// The result data /// </summary> public Array Result; /// <summary> /// Creates a new list response /// </summary> public ListResponse() { } /// <summary> /// Creates a new list response and uses the array to fill the total count /// </summary> /// <param name="data">The data to send</param> public ListResponse(Array data) { Result = data; if (data != null) Total = data.Length; } /// <summary> /// Creates a new list response with manual specification of the fields /// </summary> /// <param name="data">The data to send</param> /// <param name="offset">The current offset</param> /// <param name="total">The total number of lines</param> public ListResponse(Array data, long offset, long total) { Result = data; Offset = offset; Total = total; } } /// <summary> /// Class for containing the exception wrapper code /// </summary> public static class CRUDExceptionHelper { /// <summary> /// Helper method that extracts known exceptions into status messages /// </summary> /// <param name="ex">The error to handle</param> /// <returns>A result if the error was handled, <c>null</c> otherwise</returns> public static IResult WrapExceptionMessage(Exception ex) { if (ex is ValidationException vex) { var pre = string.Empty; if (vex.Member != null) pre = vex.Member.Name + " - "; return new StatusCodeResult(HttpStatusCode.BadRequest, pre + vex.Message); } else if (ex is FilterParser.ParserException pex) { return new StatusCodeResult(HttpStatusCode.BadRequest, "Filter error: " + pex.Message); } return null; } } /// <summary> /// Simple CRUD helper /// </summary> /// <typeparam name="TKey">The key type</typeparam> /// <typeparam name="TValue">The item value type</typeparam> public abstract class CRUDHelper<TKey, TValue> : Controller where TValue : new() { /// <summary> /// Helper to allow reporting the updated item entry /// in overridden methods /// </summary> protected class CRUDResult : IResult { /// <summary> /// The item being returned /// </summary> public readonly TValue Item; /// <summary> /// The result to execute /// </summary> private readonly IResult Result; /// <summary> /// Constructs a new result instance /// </summary> /// <param name="parent">The parent controller</param> /// <param name="item">The item to report</param> /// <param name="result">The result item to report</param> public CRUDResult(Controller parent, TValue item, IResult result) { Item = item; Result = result ?? throw new ArgumentNullException(nameof(result)); } /// <inheritdoc /> public Task Execute(IHttpContext context) { return Result.Execute(context); } } /// <summary> /// Returns a response value /// </summary> /// <param name="item">The item to wrap</param> /// <returns>The wrapped result item</returns> protected IResult ReportJson(object item) { if (item is TValue tv) return new CRUDResult(this, tv, Json(tv)); return Json(item); } /// <summary> /// Attempts to extract the item from a result /// </summary> /// <param name="item">The result to examine</param> /// <returns>The item, or null</returns> protected TValue ExtractResult(IResult item) { if (item is CRUDResult cr) return cr.Item; return default(TValue); } /// <summary> /// The database instance to use /// </summary> protected abstract Ceen.Extras.DatabaseBackedModule Connection { get; } /// <summary> /// Helper property for full access /// </summary> protected static readonly AccessType[] FullAccess = new AccessType[] { AccessType.Add, AccessType.Delete, AccessType.Get, AccessType.List, AccessType.Update }; /// <summary> /// Helper property for read-only access /// </summary> protected static readonly AccessType[] ReadOnlyAccess = new AccessType[] { AccessType.Get, AccessType.List }; /// <summary> /// The access type allowed /// </summary> protected abstract AccessType[] AllowedAccess { get; } /// <summary> /// Helper to grant access to the operation /// </summary> /// <param name="type">The operation being attempted</param> /// <param name="id">The key of the item, unless adding or listing</param> /// <returns></returns> public virtual Task Authorize(AccessType type, TKey id) { if (AllowedAccess.Contains(type)) return Task.FromResult(true); throw new HttpException(HttpStatusCode.MethodNotAllowed); } /// <summary> /// Hook function for patching the query before submitting it /// </summary> /// <param name="type">The operation being attempted</param> /// <param name="id">The key of the item, unless adding or listing</param> /// <param name="q">The query</param> /// <returns>The query</returns> public virtual Task<Query<TValue>> OnQueryAsync(AccessType type, TKey id, Query<TValue> q) => Task.FromResult(q); /// <summary> /// Avoid repeated allocations of unused tasks /// </summary> /// <returns></returns> protected readonly Task m_completedTask = Task.FromResult(true); /// <summary> /// Hook function for validating an item before inserting it /// </summary> /// <param name="item">The item being inserted</param> protected virtual Task BeforeInsertAsync(TValue item) => m_completedTask; /// <summary> /// Hook function for validating an item before inserting it /// </summary> /// <param name="key">The ID of the item being inserted</param> /// <param name="item">The item being inserted</param> protected virtual Task BeforeUpdateAsync(TKey key, Dictionary<string, object> values) => m_completedTask; /// <summary> /// Hook function that can convert a source item before passing it to the Json serializer /// </summary> /// <param name="source">The item to patch</param> /// <returns>The patched object</returns> protected virtual object PostProcess(TValue source) => source; /// <summary> /// The different access types /// </summary> public enum AccessType { /// <summary>Read an item</summary> Get, /// <summary>Update an item</summary> Update, /// <summary>Add an item</summary> Add, /// <summary>List items</summary> List, /// <summary>Delete an item</summary> Delete } /// <summary> /// Statically allocated instance of a null result /// </summary> protected static readonly Task<IResult> NULL_RESULT_TASK = Task.FromResult<IResult>(null); /// <summary> /// Custom exception handler, used to report messages from validation to the user /// </summary> /// <param name="ex">The error to handle</param> /// <returns>A result if the error was handled, <c>null</c> otherwise</returns> protected virtual Task<IResult> HandleExceptionAsync(Exception ex) { var t = CRUDExceptionHelper.WrapExceptionMessage(ex); if (t != null) return Task.FromResult(t); return NULL_RESULT_TASK; } /// <summary> /// Gets an item /// </summary> /// <param name="id">The item to get</param> /// <returns>The response</returns> [HttpGet] [Ceen.Mvc.Name("index")] [Route("{id}")] public virtual async Task<IResult> Get(TKey id) { await Authorize(AccessType.Get, id); try { var q = Connection .Query<TValue>() .Select() .MatchPrimaryKeys(new object[] { id }) .Limit(1); q = await OnQueryAsync(AccessType.Get, id, q); // TODO: Should return NotFound for non-nullable entries as well var res = await Connection.RunInTransactionAsync(db => db.SelectSingle(q)); if (res == null) return NotFound; return ReportJson(PostProcess(res)); } catch (Exception ex) { var r = await HandleExceptionAsync(ex); if (r != null) return r; throw; } } /// <summary> /// Updates an item /// </summary> /// <param name="id">The item ID</param> /// <param name="values">The values to patch with</param> /// <returns>The response</returns> [HttpPut] [HttpPatch] [Ceen.Mvc.Name("index")] [Route("{id}")] public virtual async Task<IResult> Patch(TKey id, Dictionary<string, object> values) { await Authorize(AccessType.Update, id); if (values == null || values.Count == 0) return BadRequest; try { await BeforeUpdateAsync(id, values); // We need to keep the lock, otherwise we could have // a race between reading the current item and updating // We do not want to deserialize the data while holding the lock, // as that would make a any hanging transfer hold the lock. // So we accept a dictionary as input, but we cannot call `Populate` // with the dictionary directly, so we re-serialize it to a string, // such that we can call `Populate` without any potential hang. // This is not ideal, but we cannot accept a TValue as input, // because it might be partial (PATCH) and applying the partial // input would cause data loss, and we cannot go back and see which // properties were present // Re-build a string representation of the data var jsonSr = Newtonsoft.Json.JsonConvert.SerializeObject(values); return await Connection.RunInTransactionAsync(async db => { var item = db.SelectItemById<TValue>(id); if (item == null) return NotFound; // Patch with the source data Newtonsoft.Json.JsonConvert.PopulateObject(jsonSr, item); var q = Connection .Query<TValue>() .Update(item) .MatchPrimaryKeys(new object[] { id }) .Limit(1); q = await OnQueryAsync(AccessType.Update, id, q); if (db.Update(q) > 0) return ReportJson(PostProcess(db.SelectItemById<TValue>(id))); return NotFound; }); } catch (Exception ex) { var r = await HandleExceptionAsync(ex); if (r != null) return r; throw; } } /// <summary> /// Inserts an item into the database /// </summary> /// <param name="item"></param> /// <returns>The response</returns> [HttpPost] [Ceen.Mvc.Name("index")] public virtual async Task<IResult> Post(TValue item) { await Authorize(AccessType.Add, default(TKey)); if (item == null) return BadRequest; try { await BeforeInsertAsync(item); var q = Connection .Query<TValue>() .Insert(item); q = await OnQueryAsync(AccessType.Add, default(TKey), q); return ReportJson(PostProcess(await Connection.RunInTransactionAsync(db => { db.Insert(q); return item; }))); } catch (Exception ex) { var r = await HandleExceptionAsync(ex); if (r != null) return r; throw; } } /// <summary> /// Deletes an item from the database /// </summary> /// <param name="id">The key of the item to delete</param> /// <returns>The response</returns> [HttpDelete] [Ceen.Mvc.Name("index")] [Route("{id}")] public virtual async Task<IResult> Delete(TKey id) { await Authorize(AccessType.Delete, id); try { var q = Connection .Query<TValue>() .Delete() .Limit(1) .MatchPrimaryKeys(new object[] { id }); q = await OnQueryAsync(AccessType.Delete, id, q); return await Connection.RunInTransactionAsync(db => { if (db.Delete(q) > 0) return OK; return NotFound; }); } catch (Exception ex) { var r = await HandleExceptionAsync(ex); if (r != null) return r; throw; } } /// <summary> /// Gets the current list of items /// </summary> /// <returns>The results</returns> [HttpGet] [Ceen.Mvc.Name("index")] public virtual Task<IResult> List(ListRequest request) { return Search(request); } /// <summary> /// Gets the current list of items /// </summary> /// <returns>The results</returns> [HttpPost] [Ceen.Mvc.Route("search")] public virtual async Task<IResult> Search(ListRequest request) { await Authorize(AccessType.List, default(TKey)); if (request == null) return BadRequest; try { var q = Connection .Query<TValue>() .Select() .Where(request.Filter) .OrderBy(request.SortOrder) .Offset(request.Offset) .Limit(request.Count); q = await OnQueryAsync(AccessType.List, default(TKey), q); return Json(await Connection.RunInTransactionAsync(db => new ListResponse() { Offset = request.Offset, Total = db.SelectCount(q), Result = db.Select(q).Select(PostProcess).ToArray() } )); } catch (Exception ex) { var r = await HandleExceptionAsync(ex); if (r != null) return r; throw; } } } }
using System; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is * based on a draft this implementation is subject to change. * * <pre> * block word digest * SHA-1 512 32 160 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ internal class Sha256Digest : GeneralDigest { private const int DigestLength = 32; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; public Sha256Digest() { initHs(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha256Digest(Sha256Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha256Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-256"; } } public byte[] MidState { get { var ms = new System.IO.MemoryStream(); BitcoinStream bs = new BitcoinStream(ms, true); bs.BigEndianScope(); bs.ReadWrite(this.H1); bs.ReadWrite(this.H2); bs.ReadWrite(this.H3); bs.ReadWrite(this.H4); bs.ReadWrite(this.H5); bs.ReadWrite(this.H6); bs.ReadWrite(this.H7); bs.ReadWrite(this.H8); return ms.ToArray(); } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if (++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if (xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE((uint)H1, output, outOff); Pack.UInt32_To_BE((uint)H2, output, outOff + 4); Pack.UInt32_To_BE((uint)H3, output, outOff + 8); Pack.UInt32_To_BE((uint)H4, output, outOff + 12); Pack.UInt32_To_BE((uint)H5, output, outOff + 16); Pack.UInt32_To_BE((uint)H6, output, outOff + 20); Pack.UInt32_To_BE((uint)H7, output, outOff + 24); Pack.UInt32_To_BE((uint)H8, output, outOff + 28); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); initHs(); xOff = 0; Array.Clear(X, 0, X.Length); } private void initHs() { /* SHA-256 initial hash value * The first 32 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667; H2 = 0xbb67ae85; H3 = 0x3c6ef372; H4 = 0xa54ff53a; H5 = 0x510e527f; H6 = 0x9b05688c; H7 = 0x1f83d9ab; H8 = 0x5be0cd19; } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for (int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for (int i = 0; i < 8; ++i) { // t = 8 * i h += Sum1Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } private static uint Sum1Ch( uint x, uint y, uint z) { // return Sum1(x) + Ch(x, y, z); return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) + ((x & y) ^ ((~x) & z)); } private static uint Sum0Maj( uint x, uint y, uint z) { // return Sum0(x) + Maj(x, y, z); return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) + ((x & y) ^ (x & z) ^ (y & z)); } // /* SHA-256 functions */ // private static uint Ch( // uint x, // uint y, // uint z) // { // return ((x & y) ^ ((~x) & z)); // } // // private static uint Maj( // uint x, // uint y, // uint z) // { // return ((x & y) ^ (x & z) ^ (y & z)); // } // // private static uint Sum0( // uint x) // { // return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); // } // // private static uint Sum1( // uint x) // { // return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); // } private static uint Theta0( uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1( uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ private static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; #if !NO_BC public override IMemoable Copy() { return new Sha256Digest(this); } public override void Reset(IMemoable other) { Sha256Digest d = (Sha256Digest)other; CopyIn(d); } #endif } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonViewInspector.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Custom inspector for the PhotonView component. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- #if UNITY_5 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2 #define UNITY_MIN_5_3 #endif using System; using UnityEditor; using UnityEngine; using Rotorz.ReorderableList.Internal; [CustomEditor(typeof (PhotonView))] public class PhotonViewInspector : Editor { private PhotonView m_Target; public override void OnInspectorGUI() { m_Target = (PhotonView) this.target; bool isProjectPrefab = EditorUtility.IsPersistent(m_Target.gameObject); if (m_Target.ObservedComponents == null) { m_Target.ObservedComponents = new System.Collections.Generic.List<Component>(); } if (m_Target.ObservedComponents.Count == 0) { m_Target.ObservedComponents.Add(null); } EditorGUILayout.BeginHorizontal(); // Owner if (isProjectPrefab) { EditorGUILayout.LabelField("Owner:", "Set at runtime"); } else if (m_Target.isSceneView) { EditorGUILayout.LabelField("Owner", "Scene"); } else { PhotonPlayer owner = m_Target.owner; string ownerInfo = (owner != null) ? owner.name : "<no PhotonPlayer found>"; if (string.IsNullOrEmpty(ownerInfo)) { ownerInfo = "<no playername set>"; } EditorGUILayout.LabelField("Owner", "[" + m_Target.ownerId + "] " + ownerInfo); } // ownership requests EditorGUI.BeginDisabledGroup(Application.isPlaying); m_Target.ownershipTransfer = (OwnershipOption) EditorGUILayout.EnumPopup(m_Target.ownershipTransfer, GUILayout.Width(100)); EditorGUI.EndDisabledGroup(); EditorGUILayout.EndHorizontal(); // View ID if (isProjectPrefab) { EditorGUILayout.LabelField("View ID", "Set at runtime"); } else if (EditorApplication.isPlaying) { EditorGUILayout.LabelField("View ID", m_Target.viewID.ToString()); } else { int idValue = EditorGUILayout.IntField("View ID [1.." + (PhotonNetwork.MAX_VIEW_IDS - 1) + "]", m_Target.viewID); m_Target.viewID = idValue; } // Locally Controlled if (EditorApplication.isPlaying) { string masterClientHint = PhotonNetwork.isMasterClient ? "(master)" : ""; EditorGUILayout.Toggle("Controlled locally: " + masterClientHint, m_Target.isMine); } //DrawOldObservedItem(); this.ConvertOldObservedItemToObservedList(); // ViewSynchronization (reliability) if (m_Target.synchronization == ViewSynchronization.Off) { GUI.color = Color.grey; } EditorGUILayout.PropertyField(serializedObject.FindProperty("synchronization"), new GUIContent("Observe option:")); if (m_Target.synchronization != ViewSynchronization.Off && m_Target.ObservedComponents.FindAll(item => item != null).Count == 0) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("Warning", EditorStyles.boldLabel); GUILayout.Label("Setting the synchronization option only makes sense if you observe something."); GUILayout.EndVertical(); } /*ViewSynchronization vsValue = (ViewSynchronization)EditorGUILayout.EnumPopup("Observe option:", m_Target.synchronization); if (vsValue != m_Target.synchronization) { m_Target.synchronization = vsValue; if (m_Target.synchronization != ViewSynchronization.Off && m_Target.observed == null) { EditorUtility.DisplayDialog("Warning", "Setting the synchronization option only makes sense if you observe something.", "OK, I will fix it."); } }*/ DrawSpecificTypeSerializationOptions(); GUI.color = Color.white; DrawObservedComponentsList(); // Cleanup: save and fix look if (GUI.changed) { EditorUtility.SetDirty(m_Target); PhotonViewHandler.HierarchyChange(); // TODO: check if needed } GUI.color = Color.white; #if !UNITY_MIN_5_3 EditorGUIUtility.LookLikeControls(); #endif } private void DrawSpecificTypeSerializationOptions() { if (m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof(Transform)).Count > 0 || (m_Target.observed != null && m_Target.observed.GetType() == typeof(Transform))) { m_Target.onSerializeTransformOption = (OnSerializeTransform) EditorGUILayout.EnumPopup("Transform Serialization:", m_Target.onSerializeTransformOption); } else if (m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof(Rigidbody)).Count > 0 || (m_Target.observed != null && m_Target.observed.GetType() == typeof(Rigidbody)) || m_Target.ObservedComponents.FindAll(item => item != null && item.GetType() == typeof(Rigidbody2D)).Count > 0 || (m_Target.observed != null && m_Target.observed.GetType() == typeof(Rigidbody2D))) { m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody) EditorGUILayout.EnumPopup("Rigidbody Serialization:", m_Target.onSerializeRigidBodyOption); } } private void DrawSpecificTypeOptions() { if (m_Target.observed != null) { Type type = m_Target.observed.GetType(); if (type == typeof (Transform)) { m_Target.onSerializeTransformOption = (OnSerializeTransform) EditorGUILayout.EnumPopup("Serialization:", m_Target.onSerializeTransformOption); } else if (type == typeof (Rigidbody)) { m_Target.onSerializeRigidBodyOption = (OnSerializeRigidBody) EditorGUILayout.EnumPopup("Serialization:", m_Target.onSerializeRigidBodyOption); } } } private void ConvertOldObservedItemToObservedList() { if (Application.isPlaying) { return; } if (m_Target.observed != null) { if (m_Target.ObservedComponents.Contains(m_Target.observed) == false) { bool wasAdded = false; for (int i = 0; i < m_Target.ObservedComponents.Count; ++i) { if (m_Target.ObservedComponents[i] == null) { m_Target.ObservedComponents[i] = m_Target.observed; wasAdded = true; } } if (wasAdded == false) { m_Target.ObservedComponents.Add(m_Target.observed); } } m_Target.observed = null; EditorUtility.SetDirty(m_Target); } } private void DrawOldObservedItem() { EditorGUILayout.BeginHorizontal(); // Using a lower version then 3.4? Remove the TRUE in the next line to fix an compile error string typeOfObserved = string.Empty; if (m_Target.observed != null) { int firstBracketPos = m_Target.observed.ToString().LastIndexOf('('); if (firstBracketPos > 0) { typeOfObserved = m_Target.observed.ToString().Substring(firstBracketPos); } } Component componenValue = (Component) EditorGUILayout.ObjectField("Observe: " + typeOfObserved, m_Target.observed, typeof (Component), true); if (m_Target.observed != componenValue) { if (m_Target.observed == null) { m_Target.synchronization = ViewSynchronization.UnreliableOnChange; // if we didn't observe anything yet. use unreliable on change as default } if (componenValue == null) { m_Target.synchronization = ViewSynchronization.Off; } m_Target.observed = componenValue; } EditorGUILayout.EndHorizontal(); } private int GetObservedComponentsCount() { int count = 0; for (int i = 0; i < m_Target.ObservedComponents.Count; ++i) { if (m_Target.ObservedComponents[i] != null) { count++; } } return count; } private void DrawObservedComponentsList() { GUILayout.Space(5); SerializedProperty listProperty = serializedObject.FindProperty("ObservedComponents"); if (listProperty == null) { return; } float containerElementHeight = 22; float containerHeight = listProperty.arraySize*containerElementHeight; bool isOpen = PhotonGUI.ContainerHeaderFoldout("Observed Components (" + GetObservedComponentsCount() + ")", serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue); serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue = isOpen; if (isOpen == false) { containerHeight = 0; } //Texture2D statsIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonViewStats.png", typeof( Texture2D ) ) as Texture2D; Rect containerRect = PhotonGUI.ContainerBody(containerHeight); bool wasObservedComponentsEmpty = m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (isOpen == true) { for (int i = 0; i < listProperty.arraySize; ++i) { Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + containerElementHeight*i, containerRect.width, containerElementHeight); { Rect texturePosition = new Rect(elementRect.xMin + 6, elementRect.yMin + elementRect.height/2f - 1, 9, 5); ReorderableListResources.DrawTexture(texturePosition, ReorderableListResources.texGrabHandle); Rect propertyPosition = new Rect(elementRect.xMin + 20, elementRect.yMin + 3, elementRect.width - 45, 16); EditorGUI.PropertyField(propertyPosition, listProperty.GetArrayElementAtIndex(i), new GUIContent()); //Debug.Log( listProperty.GetArrayElementAtIndex( i ).objectReferenceValue.GetType() ); //Rect statsPosition = new Rect( propertyPosition.xMax + 7, propertyPosition.yMin, statsIcon.width, statsIcon.height ); //ReorderableListResources.DrawTexture( statsPosition, statsIcon ); Rect removeButtonRect = new Rect(elementRect.xMax - PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, elementRect.yMin + 2, PhotonGUI.DefaultRemoveButtonStyle.fixedWidth, PhotonGUI.DefaultRemoveButtonStyle.fixedHeight); GUI.enabled = listProperty.arraySize > 1; if (GUI.Button(removeButtonRect, new GUIContent(ReorderableListResources.texRemoveButton), PhotonGUI.DefaultRemoveButtonStyle)) { listProperty.DeleteArrayElementAtIndex(i); } GUI.enabled = true; if (i < listProperty.arraySize - 1) { texturePosition = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1); PhotonGUI.DrawSplitter(texturePosition); } } } } if (PhotonGUI.AddButton()) { listProperty.InsertArrayElementAtIndex(Mathf.Max(0, listProperty.arraySize - 1)); } serializedObject.ApplyModifiedProperties(); bool isObservedComponentsEmpty = m_Target.ObservedComponents.FindAll(item => item != null).Count == 0; if (wasObservedComponentsEmpty == true && isObservedComponentsEmpty == false && m_Target.synchronization == ViewSynchronization.Off) { m_Target.synchronization = ViewSynchronization.UnreliableOnChange; EditorUtility.SetDirty(m_Target); serializedObject.Update(); } if (wasObservedComponentsEmpty == false && isObservedComponentsEmpty == true) { m_Target.synchronization = ViewSynchronization.Off; EditorUtility.SetDirty(m_Target); serializedObject.Update(); } } private static GameObject GetPrefabParent(GameObject mp) { #if UNITY_2_6_1 || UNITY_2_6 || UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 // Unity 3.4 and older use EditorUtility return (EditorUtility.GetPrefabParent(mp) as GameObject); #else // Unity 3.5 uses PrefabUtility return PrefabUtility.GetPrefabParent(mp) as GameObject; #endif } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Htc.Vita.Core.Log; using Htc.Vita.Core.Runtime; using Htc.Vita.Core.Util; namespace Htc.Vita.Core.Diagnostics { /// <summary> /// Class DefaultWebBrowserManager. /// Implements the <see cref="WebBrowserManager" /> /// </summary> /// <seealso cref="WebBrowserManager" /> public class DefaultWebBrowserManager : WebBrowserManager { private static readonly Dictionary<string, WebBrowserType> SchemeDisplayNameWithWebBrowserType = new Dictionary<string, WebBrowserType>(); private static readonly List<WebBrowserType> WebBrowserTypeOrder = new List<WebBrowserType>(); private static readonly Dictionary<WebBrowserType, string> WebBrowserTypeWithDisplayName = new Dictionary<WebBrowserType, string>(); private static string _previousMicrosoftInternetExplorerVersion; private static bool _previousMicrosoftInternetExplorerVersionChanged; static DefaultWebBrowserManager() { InitKnownWebBrowsers(); } private static FileInfo GetFullFilePath(string fileName) { if (File.Exists(fileName)) { return new FileInfo(Path.GetFullPath(fileName)); } var paths = Environment.GetEnvironmentVariable("PATH"); if (string.IsNullOrWhiteSpace(paths)) { Logger.GetInstance(typeof(WebBrowserManager)).Error("Can not find PATH environment variable"); return null; } return ( from path in paths.Split(';') select Path.Combine(path, fileName) into fullPath where File.Exists(fullPath) select new FileInfo(fullPath) ).FirstOrDefault(); } private static List<WebBrowserInfo> GetInstalledWebBrowserListFromRegistryMicrosoftEdgeLegacy() { var result = new List<WebBrowserInfo>(); using (var baseKey = Win32Registry.Key.OpenBaseKey(Win32Registry.Hive.ClassesRoot, Win32Registry.View.Default)) { using (var subKey = baseKey.OpenSubKey("microsoft-edge", Win32Registry.KeyPermissionCheck.ReadSubTree)) { if (subKey == null) { return result; } var explorerPath = GetFullFilePath("explorer.exe"); if (explorerPath == null) { return result; } Scheme[] targetSchemes = { Scheme.Http, Scheme.Https }; foreach (var targetScheme in targetSchemes) { const WebBrowserType webBrowserType = WebBrowserType.MicrosoftEdge; result.Add(new WebBrowserInfo { DisplayName = GetKnownWebBrowserNameFrom(webBrowserType), LaunchParams = new[] { "\"microsoft-edge:%1\"" }, LaunchPath = explorerPath, SupportedScheme = targetScheme, Type = webBrowserType }); } } } return result; } private static List<WebBrowserInfo> GetInstalledWebBrowserListFromRegistryMicrosoftInternetExplorer() { var schemeList = new List<Scheme> { Scheme.Http, Scheme.Https }; var result = new List<WebBrowserInfo>(); using (var baseKey = Win32Registry.Key.OpenBaseKey(Win32Registry.Hive.LocalMachine, Win32Registry.View.Default)) { using (var subKey = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\Internet Explorer\\Capabilities\\UrlAssociations", Win32Registry.KeyPermissionCheck.ReadSubTree)) { if (subKey != null) { foreach (var scheme in schemeList) { var valueName = scheme.ToString().ToLowerInvariant(); var valueData = subKey.GetValue(valueName); if (valueData == null) { continue; } if (subKey.GetValueKind(valueName) != Win32Registry.ValueKind.String) { continue; } var redirectedSchemeName = valueData as string; var schemeDisplayName = GetSchemeDisplayNameFrom(redirectedSchemeName); var launchCommand = GetSchemeLaunchCommandFrom(redirectedSchemeName); var launchCommandTokenList = GetSchemeLaunchCommandTokenListFrom(launchCommand); FileInfo launchCommandPath = null; var launchCommandParam = new List<string>(); if (launchCommandTokenList.Count >= 1) { launchCommandPath = GetSchemeLaunchCommandPathFrom(launchCommandTokenList[0]); launchCommandTokenList.RemoveAt(0); launchCommandParam = launchCommandTokenList; } else { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Error($"Can not parse launch command: \"{launchCommand}\""); } if (launchCommandPath == null) { continue; } var version = FilePropertiesInfo.GetPropertiesInfo(launchCommandPath).Version; if (string.IsNullOrWhiteSpace(version)) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Warn($"Can not detect Microsoft Internet Explorer version. Path: {launchCommandPath}"); continue; } if (!version.Equals(_previousMicrosoftInternetExplorerVersion)) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Debug($"Microsoft Internet Explorer {version} detected"); _previousMicrosoftInternetExplorerVersion = version; _previousMicrosoftInternetExplorerVersionChanged = true; } if (version.StartsWith("8.0")) { // Drop IE8 support if (_previousMicrosoftInternetExplorerVersionChanged) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Warn($"Skip adding Microsoft Internet Explorer {version} into available web browser list"); _previousMicrosoftInternetExplorerVersionChanged = false; } continue; } var webBrowserType = GetKnownWebBrowserTypeFrom(schemeDisplayName); result.Add(new WebBrowserInfo { DisplayName = GetKnownWebBrowserNameFrom(webBrowserType), LaunchParams = launchCommandParam.ToArray(), LaunchPath = launchCommandPath, SchemeDisplayName = schemeDisplayName, SupportedScheme = scheme, Type = webBrowserType }); } } } } return result; } private static List<WebBrowserInfo> GetInstalledWebBrowserListFromRegistryStartMenuInternet() { var registryHiveList = new List<Win32Registry.Hive> { Win32Registry.Hive.LocalMachine, Win32Registry.Hive.CurrentUser }; var schemeList = new List<Scheme> { Scheme.Http, Scheme.Https }; var result = new List<WebBrowserInfo>(); foreach (var registryHive in registryHiveList) { using (var baseKey = Win32Registry.Key.OpenBaseKey(registryHive, Win32Registry.View.Default)) { using (var subKey = baseKey.OpenSubKey("SOFTWARE\\Clients\\StartMenuInternet", Win32Registry.KeyPermissionCheck.ReadSubTree)) { if (subKey != null) { foreach (var subKeyName in subKey.GetSubKeyNames()) { if (string.IsNullOrWhiteSpace(subKeyName)) { continue; } using (var subKey2 = subKey.OpenSubKey($"{subKeyName}\\Capabilities\\URLAssociations")) { if (subKey2 == null) { continue; } foreach (var scheme in schemeList) { var valueName = scheme.ToString().ToLowerInvariant(); var valueData = subKey2.GetValue(valueName); if (valueData == null) { continue; } if (subKey2.GetValueKind(valueName) != Win32Registry.ValueKind.String) { continue; } var redirectedSchemeName = valueData as string; var schemeDisplayName = GetSchemeDisplayNameFrom(redirectedSchemeName); var launchCommand = GetSchemeLaunchCommandFrom(redirectedSchemeName); var launchCommandTokenList = GetSchemeLaunchCommandTokenListFrom(launchCommand); FileInfo launchCommandPath = null; var launchCommandParam = new List<string>(); if (launchCommandTokenList.Count >= 1) { launchCommandPath = GetSchemeLaunchCommandPathFrom(launchCommandTokenList[0]); launchCommandTokenList.RemoveAt(0); launchCommandParam = launchCommandTokenList; } else { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Error($"Can not parse launch command: \"{launchCommand}\""); } if (launchCommandPath == null) { continue; } var webBrowserType = GetKnownWebBrowserTypeFrom(schemeDisplayName); result.Add(new WebBrowserInfo { DisplayName = GetKnownWebBrowserNameFrom(webBrowserType), LaunchParams = launchCommandParam.ToArray(), LaunchPath = launchCommandPath, SchemeDisplayName = schemeDisplayName, SupportedScheme = scheme, Type = webBrowserType }); } } } } } } } return result; } private static string GetKnownWebBrowserNameFrom(WebBrowserType webBrowserType) { if (WebBrowserTypeWithDisplayName.ContainsKey(webBrowserType)) { return WebBrowserTypeWithDisplayName[webBrowserType]; } Logger.GetInstance(typeof(DefaultWebBrowserManager)).Warn($"Can not find known web browser name for {webBrowserType}"); return "Unknown"; } private static WebBrowserType GetKnownWebBrowserTypeFrom(string schemeDisplayName) { if (SchemeDisplayNameWithWebBrowserType.ContainsKey(schemeDisplayName)) { return SchemeDisplayNameWithWebBrowserType[schemeDisplayName]; } Logger.GetInstance(typeof(DefaultWebBrowserManager)).Warn($"Can not find known WebBrowserType for \"{schemeDisplayName}\""); return WebBrowserType.Unknown; } private static string GetSchemeDisplayNameFrom(string schemeName) { var result = string.Empty; if (string.IsNullOrWhiteSpace(schemeName)) { return result; } using (var baseKey = Win32Registry.Key.OpenBaseKey(Win32Registry.Hive.ClassesRoot, Win32Registry.View.Default)) { using (var subKey = baseKey.OpenSubKey(schemeName, Win32Registry.KeyPermissionCheck.ReadSubTree)) { if (subKey == null) { return result; } try { if (subKey.GetValueKind(null) == Win32Registry.ValueKind.String) { result = subKey.GetValue(null) as string; } } catch (Exception e) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Warn($"Can not find display name from default string for: \"{schemeName}\", {e.Message}"); } if (!string.IsNullOrWhiteSpace(result)) { return result; } const string valueName = "FriendlyTypeName"; try { if (subKey.GetValueKind(valueName) == Win32Registry.ValueKind.String) { result = subKey.GetValue(valueName) as string; } } catch (Exception e) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Warn($"Can not find display name from FriendlyTypeName string for: \"{schemeName}\", {e.Message}"); } } } return result; } private static string GetSchemeLaunchCommandFrom(string schemeName) { var result = string.Empty; if (string.IsNullOrWhiteSpace(schemeName)) { return result; } using (var baseKey = Win32Registry.Key.OpenBaseKey(Win32Registry.Hive.ClassesRoot, Win32Registry.View.Default)) { using (var subKey = baseKey.OpenSubKey($"{schemeName}\\shell\\open\\command", Win32Registry.KeyPermissionCheck.ReadSubTree)) { if (subKey == null) { return result; } if (subKey.GetValueKind(null) == Win32Registry.ValueKind.String) { result = subKey.GetValue(null) as string; } } } return result; } private static FileInfo GetSchemeLaunchCommandPathFrom(string stringPath) { if (string.IsNullOrWhiteSpace(stringPath)) { return null; } const string quotation = "\""; var executablePath = stringPath; if (executablePath.StartsWith(quotation)) { executablePath = executablePath.Substring(quotation.Length); } if (executablePath.EndsWith(quotation)) { executablePath = executablePath.Substring(0, executablePath.Length - quotation.Length); } try { var path = new FileInfo(executablePath); if (path.Exists) { return path; } Logger.GetInstance(typeof(DefaultWebBrowserManager)).Error($"Can not find existing launch command path: \"{executablePath}\""); } catch (Exception e) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Error($"Can not parse launch command path: \"{stringPath}\", {e}"); } return null; } private static List<string> GetSchemeLaunchCommandTokenListFrom(string schemeLaunchCommand) { var result = new List<string>(); var builder = new StringBuilder(); var charArray = schemeLaunchCommand.Trim().ToCharArray(); var isInQuote = false; foreach (var c in charArray) { if (c == '"') { builder.Append(c); if (isInQuote) { result.Add(builder.ToString()); builder.Clear(); } isInQuote = !isInQuote; } else if (c == ' ') { if (isInQuote) { builder.Append(c); } else { if (builder.Length <= 0) { continue; } result.Add(builder.ToString()); builder.Clear(); } } else { builder.Append(c); } } if (builder.Length > 0) { result.Add(builder.ToString()); builder.Clear(); } return result; } private static void InitKnownWebBrowsers() { WebBrowserTypeOrder.Add(WebBrowserType.GoogleChrome); WebBrowserTypeOrder.Add(WebBrowserType.MozillaFirefox); WebBrowserTypeOrder.Add(WebBrowserType.Opera); WebBrowserTypeOrder.Add(WebBrowserType.Qihoo360ExtremeBrowser); WebBrowserTypeOrder.Add(WebBrowserType.Qihoo360SafeBrowser); WebBrowserTypeOrder.Add(WebBrowserType.MicrosoftEdge); WebBrowserTypeOrder.Add(WebBrowserType.MicrosoftInternetExplorer); WebBrowserTypeWithDisplayName.Add(WebBrowserType.GoogleChrome, "Google Chrome"); WebBrowserTypeWithDisplayName.Add(WebBrowserType.MozillaFirefox, "Mozilla Firefox"); WebBrowserTypeWithDisplayName.Add(WebBrowserType.MicrosoftEdge, "Microsoft Edge"); WebBrowserTypeWithDisplayName.Add(WebBrowserType.MicrosoftInternetExplorer, "Microsoft Internet Explorer"); WebBrowserTypeWithDisplayName.Add(WebBrowserType.Opera, "Opera"); WebBrowserTypeWithDisplayName.Add(WebBrowserType.Qihoo360ExtremeBrowser, "Qihoo 360 Extreme Browser"); WebBrowserTypeWithDisplayName.Add(WebBrowserType.Qihoo360SafeBrowser, "Qihoo 360 Safe Browser"); SchemeDisplayNameWithWebBrowserType.Add("360 Chrome HTML Document", WebBrowserType.Qihoo360ExtremeBrowser); SchemeDisplayNameWithWebBrowserType.Add("360 se HTML Document", WebBrowserType.Qihoo360SafeBrowser); SchemeDisplayNameWithWebBrowserType.Add("Chrome HTML Document", WebBrowserType.GoogleChrome); SchemeDisplayNameWithWebBrowserType.Add("Firefox URL", WebBrowserType.MozillaFirefox); SchemeDisplayNameWithWebBrowserType.Add("Microsoft Edge HTML Document", WebBrowserType.MicrosoftEdge); SchemeDisplayNameWithWebBrowserType.Add("Opera Web Document", WebBrowserType.Opera); SchemeDisplayNameWithWebBrowserType.Add("URL:HyperText Transfer Protocol", WebBrowserType.MicrosoftInternetExplorer); SchemeDisplayNameWithWebBrowserType.Add("URL:HyperText Transfer Protocol with Privacy", WebBrowserType.MicrosoftInternetExplorer); } /// <inheritdoc /> protected override GetInstalledWebBrowserListResult OnGetInstalledWebBrowserList() { if (!Platform.IsWindows) { return new GetInstalledWebBrowserListResult { Status = GetInstalledWebBrowserListStatus.UnsupportedPlatform }; } var unorderedWebBrowserList = GetInstalledWebBrowserListFromRegistryStartMenuInternet(); if (unorderedWebBrowserList.All(webBrowserInfo => webBrowserInfo.Type != WebBrowserType.MicrosoftEdge)) { unorderedWebBrowserList.AddRange(GetInstalledWebBrowserListFromRegistryMicrosoftEdgeLegacy()); } unorderedWebBrowserList.AddRange(GetInstalledWebBrowserListFromRegistryMicrosoftInternetExplorer()); var countedWebBrowserSet = new HashSet<WebBrowserInfo>(); var webBrowserList = new List<WebBrowserInfo>(); foreach (var webBrowserType in WebBrowserTypeOrder) { foreach (var detectedWebBrowserInfo in unorderedWebBrowserList) { if (detectedWebBrowserInfo.Type != webBrowserType) { continue; } countedWebBrowserSet.Add(detectedWebBrowserInfo); webBrowserList.Add(detectedWebBrowserInfo); } } foreach (var detectedWebBrowserInfo in unorderedWebBrowserList) { if (countedWebBrowserSet.Contains(detectedWebBrowserInfo)) { continue; } webBrowserList.Add(detectedWebBrowserInfo); } return new GetInstalledWebBrowserListResult { Status = GetInstalledWebBrowserListStatus.Ok, WebBrowserList = webBrowserList }; } /// <inheritdoc /> protected override bool OnLaunch( Uri uri, WebBrowserInfo webBrowserInfo) { var arguments = new StringBuilder(); foreach (var param in webBrowserInfo.LaunchParams) { arguments.Append(' ').Append(param.Replace("%1", uri.AbsoluteUri)); } var processStartInfo = new ProcessStartInfo { Arguments = arguments.ToString(), CreateNoWindow = true, FileName = webBrowserInfo.LaunchPath.FullName }; try { using (Process.Start(processStartInfo)) { // Skip } return true; } catch (Exception e) { Logger.GetInstance(typeof(DefaultWebBrowserManager)).Error($"Can not launch uri: \"{uri} with \"{webBrowserInfo.Type}\", {e.Message}"); } return false; } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.PublicationOutput25ServiceReference; namespace Trisoft.ISHRemote.Cmdlets.PublicationOutput { /// <summary> /// <para type="synopsis">The Remove-IshPublicationOutput cmdlet removes the publication outputs that are passed through the pipeline or determined via provided parameters</para> /// <para type="description">The Remove-IshPublicationOutput cmdlet removes the publication outputs that are passed through the pipeline or determined via provided parameters</para> /// </summary> /// <example> /// <code> /// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -IshUserName "username" -IshUserPassword "userpassword" /// # Remove publication output /// Remove-IshPublicationOutput ` /// -LogicalId "GUID-F66C1BB5-076D-455C-B055-DAC5D61AB3D9" ` /// -Version "1" ` /// -OutputFormat "PDF (A4 Manual)" ` /// -LanguageCombination "en" /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Removing a publication output</para> /// </example> [Cmdlet(VerbsCommon.Remove, "IshPublicationOutput", SupportsShouldProcess = true)] public sealed class RemoveIshPublicationOutput : PublicationOutputCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">Array with the publication outputs to remove. This array can be passed through the pipeline or explicitly passed via the parameter.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectsGroup")] [AllowEmptyCollection] public IshObject[] IshObject { get; set; } /// <summary> /// <para type="description">The LogicalId of the publication output</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty] public string LogicalId { get; set; } /// <summary> /// <para type="description">The version of the publication output</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty] public string Version { get; set; } /// <summary> /// <para type="description">The output format of the publication output.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty] public string OutputFormat { get; set; } /// <summary> /// <para type="description">The language combination of the publication output.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty] public string LanguageCombination { get; set; } /// <summary> /// <para type="description">The required current metadata of the publication output. This parameter can be used to avoid that users override changes done by other users. The cmdlet will check whether the fields provided in this parameter still have the same values in the repository:</para> /// <para type="description">If the metadata is still the same, the publication output is removed.</para> /// <para type="description">If the metadata is not the same anymore, an error is given and the publication output is not removed.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public IshField[] RequiredCurrentMetadata { get; set; } /// <summary> /// <para type="description">When the Force switch is set, after deleting the publication output object, the publication version object and publication logical object will be deleted if they don't have any publication outputs anymore. /// Be carefull using this option, as it will delete the publication (version) and baseline if there are no outputformats left!!</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public SwitchParameter Force { get; set; } protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); base.BeginProcessing(); } /// <summary> /// Process the Remove-IshPublicationOutput commandlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes an <see cref="Objects.Public.IshObject"/> array to the pipeline.</remarks> protected override void ProcessRecord() { try { var logicalIdsVersionsCollection = new NameValueCollection(); if (IshObject != null && IshObject.Length == 0) { // Do nothing WriteVerbose("IshObject is empty, so nothing to remove"); } else { WriteDebug("Removing"); IshFields requiredCurrentMetadata = new IshFields(RequiredCurrentMetadata); if (IshObject != null) { // Using the pipeline int current = 0; IshObjects ishObjects = new IshObjects(IshObject); foreach (IshObject ishObject in ishObjects.Objects) { long lngRef = Convert.ToInt64(ishObject.ObjectRef[Enumerations.ReferenceType.Lng]); WriteDebug($"lngRef[{lngRef}] {++current}/{ishObjects.Objects.Length}"); if (ShouldProcess(Convert.ToString(lngRef))) { IshSession.PublicationOutput25.DeleteByIshLngRef(lngRef, requiredCurrentMetadata.ToXml()); } logicalIdsVersionsCollection.Add(ishObject.IshRef, ishObject.IshFields.GetFieldValue("VERSION", Enumerations.Level.Version, Enumerations.ValueType.Value)); } } else { if (ShouldProcess(LogicalId + "=" + Version + "=" + LanguageCombination + "=" + OutputFormat)) { IshSession.PublicationOutput25.Delete( LogicalId, Version, OutputFormat, LanguageCombination, requiredCurrentMetadata.ToXml()); } logicalIdsVersionsCollection.Add(LogicalId, Version); } } if (Force.IsPresent && logicalIdsVersionsCollection.Count > 0) { var xmlIshObjects = IshSession.PublicationOutput25.RetrieveMetadata(logicalIdsVersionsCollection.AllKeys.ToArray(), StatusFilter.ISHNoStatusFilter, "", "<ishfields><ishfield name='VERSION' level='version'/><ishfield name='FISHPUBLNGCOMBINATION' level='lng'/></ishfields>"); List<IshObject> retrievedObjects = new List<IshObject>(); retrievedObjects.AddRange(new IshObjects(xmlIshObjects).Objects); // Delete versions which do not have any language card anymore foreach (string logicalId in logicalIdsVersionsCollection.AllKeys) { var versions = logicalIdsVersionsCollection.GetValues(logicalId).Distinct(); foreach (var version in versions) { bool versionWithLanguagesFound = false; foreach (var retrievedObject in retrievedObjects) { if (retrievedObject.IshRef == logicalId && retrievedObject.IshFields.GetFieldValue("VERSION", Enumerations.Level.Version, Enumerations.ValueType.Value) == version) { versionWithLanguagesFound = true; } } if (!versionWithLanguagesFound) { if (ShouldProcess(logicalId + "=" + version + "=" + "=")) { IshSession.PublicationOutput25.Delete(logicalId, version, "", "", ""); } } } } // Delete logical cards which do not have any languages anymore foreach (string logicalId in logicalIdsVersionsCollection.AllKeys) { bool logicalIdFound = false; foreach (var retrievedObject in retrievedObjects) { if (retrievedObject.IshRef == logicalId) { logicalIdFound = true; } } if (!logicalIdFound) { if (ShouldProcess(logicalId + "===")) { IshSession.PublicationOutput25.Delete(logicalId, "", "", "", ""); } } } } WriteVerbose("returned object count[0]"); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; public class GCTests { [Fact] public static void ValidCollectionGenerations() { Assert.Throws<ArgumentOutOfRangeException>(() => GC.Collect(-1)); for (int i = 0; i < GC.MaxGeneration + 10; i++) { GC.Collect(i); } } [Fact] public static void CollectionCountDefault() { VerifyCollectionCount(GCCollectionMode.Default); } [Fact] public static void CollectionCountForced() { VerifyCollectionCount(GCCollectionMode.Forced); } private static void VerifyCollectionCount(GCCollectionMode mode) { for (int gen = 0; gen <= 2; gen++) { byte[] b = new byte[1024 * 1024 * 10]; int oldCollectionCount = GC.CollectionCount(gen); b = null; GC.Collect(gen, GCCollectionMode.Default); Assert.True(GC.CollectionCount(gen) > oldCollectionCount); } } [Fact] public static void InvalidCollectionModes() { Assert.Throws<ArgumentOutOfRangeException>(() => GC.Collect(2, (GCCollectionMode)(GCCollectionMode.Default - 1))); Assert.Throws<ArgumentOutOfRangeException>(() => GC.Collect(2, (GCCollectionMode)(GCCollectionMode.Optimized + 1))); } [Fact] public static void Finalizer() { FinalizerTest.Run(); } private class FinalizerTest { public static void Run() { var obj = new TestObject(); obj = null; GC.Collect(); // Make sure Finalize() is called GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAlive() { KeepAliveTest.Run(); } private class KeepAliveTest { public static void Run() { var keepAlive = new KeepAliveObject(); var doNotKeepAlive = new DoNotKeepAliveObject(); doNotKeepAlive = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(DoNotKeepAliveObject.Finalized); Assert.False(KeepAliveObject.Finalized); GC.KeepAlive(keepAlive); } private class KeepAliveObject { public static bool Finalized { get; private set; } ~KeepAliveObject() { Finalized = true; } } private class DoNotKeepAliveObject { public static bool Finalized { get; private set; } ~DoNotKeepAliveObject() { Finalized = true; } } } [Fact] public static void KeepAliveNull() { KeepAliveNullTest.Run(); } private class KeepAliveNullTest { public static void Run() { var obj = new TestObject(); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.KeepAlive(obj); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAliveRecursive() { KeepAliveRecursiveTest.Run(); } private class KeepAliveRecursiveTest { public static void Run() { int recursionCount = 0; RunWorker(new TestObject(), ref recursionCount); } private static void RunWorker(object obj, ref int recursionCount) { if (recursionCount++ == 10) return; GC.Collect(); GC.WaitForPendingFinalizers(); RunWorker(obj, ref recursionCount); Assert.False(TestObject.Finalized); GC.KeepAlive(obj); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void SuppressFinalizer() { SuppressFinalizerTest.Run(); } private class SuppressFinalizerTest { public static void Run() { var obj = new TestObject(); GC.SuppressFinalize(obj); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void ReRegisterForFinalize() { ReRegisterForFinalizeTest.Run(); } private class ReRegisterForFinalizeTest { public static void Run() { TestObject.Finalized = false; CreateObject(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private static void CreateObject() { using (var obj = new TestObject()) { GC.SuppressFinalize(obj); } } private class TestObject : IDisposable { public static bool Finalized { get; set; } ~TestObject() { Finalized = true; } public void Dispose() { GC.ReRegisterForFinalize(this); } } } [Fact] public static void GetTotalMemoryTest_ForceCollection() { GC.Collect(); int gen0 = GC.CollectionCount(0); int gen1 = GC.CollectionCount(1); int gen2 = GC.CollectionCount(2); Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue); Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue); Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue); Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue); // We don't test GetTotalMemory(false) at all because a collection // could still occur even if not due to the GetTotalMemory call, // and as such there's no way to validate the behavior. We also // don't verify a tighter bound for the result of GetTotalMemory // because collections could cause significant fluctuations. } [Fact] public static void GetGenerationTest() { GC.Collect(); object obj = new object(); for (int i = 0; i <= GC.MaxGeneration + 1; i++) { Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration); GC.Collect(); } // We don't test a tighter bound on GetGeneration as objects // can actually get demoted or stay in the same generation // across collections. } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System { // These sources are taken from corclr repo (src\mscorlib\src\System\Buffer.cs with x64 path removed) // The reason for this duplication is that System.Runtime.dll 4.0.10 did not expose Buffer.MemoryCopy, // but we need to make this component work with System.Runtime.dll 4.0.10 // The methods AreOverlapping and SlowCopyBackwards are not from Buffer.cs. Buffer.cs does an internal CLR call for these. static class BufferInternal { // This method has different signature for x64 and other platforms and is done for performance reasons. [System.Security.SecurityCritical] private unsafe static void Memmove(byte* dest, byte* src, uint len) { if (AreOverlapping(dest, src, len)) { SlowCopyBackwards(dest, src, len); return; } // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short*)dest = *(short*)src; return; case 3: *(short*)dest = *(short*)src; *(dest + 2) = *(src + 2); return; case 4: *(int*)dest = *(int*)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); return; case 9: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(dest + 8) = *(src + 8); return; case 10: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); return; default: break; } if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *dest = *src; src++; dest++; len--; if (((int)dest & 2) == 0) goto Aligned; } *(short*)dest = *(short*)src; src += 2; dest += 2; len -= 2; Aligned:; } uint count = len / 16; while (count > 0) { ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; ((int*)dest)[2] = ((int*)src)[2]; ((int*)dest)[3] = ((int*)src)[3]; dest += 16; src += 16; count--; } if ((len & 8) != 0) { ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; dest += 8; src += 8; } if ((len & 4) != 0) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; } if ((len & 2) != 0) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; } if ((len & 1) != 0) *dest = *src; return; } private static unsafe void SlowCopyBackwards(byte* dest, byte* src, uint len) { Debug.Assert(len <= int.MaxValue); if (len == 0) return; for(int i=((int)len)-1; i>=0; i--) { dest[i] = src[i]; } } private static unsafe bool AreOverlapping(byte* dest, byte* src, uint len) { byte* srcEnd = src + len; byte* destEnd = dest + len; if (srcEnd >= dest && srcEnd <= destEnd) { return true; } return false; } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [System.Security.SecurityCritical] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void MemoryCopy(void* source, void* destination, int destinationSizeInBytes, int sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { throw new ArgumentOutOfRangeException("sourceBytesToCopy"); } Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); } } }
using System; using System.Collections; using System.Windows.Forms; using System.Data; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// Consonant Chart Search /// </summary> public class ConsonantChartSearch : Search { //Search parameters private bool m_Labialized; private bool m_Palatalized; private bool m_Velarized; private bool m_Prenasalized; private bool m_Syllabic; private bool m_Aspirated; private bool m_Long; private bool m_Glottalized; private bool m_Combination; //same as complex private Settings m_Settings; private string m_Title; private ConsonantChartTable m_CnsTable; private CombinationChartTable m_CmbTable; //private const string kTitle = "Consonant Chart"; //Search definition tags private const string kLabial = "labialized"; private const string kPalat = "palatalized"; private const string kVelar = "velarized"; private const string kPrenas = "prenasalized"; private const string kSyll = "syllabic"; private const string kAspir = "aspirated"; private const string kLong = "long"; private const string kGlott = "glottalized"; private const string kCombn = "combination"; public ConsonantChartSearch(int number, Settings s) : base(number, SearchDefinition.kConsonant) { m_Labialized = false; m_Palatalized = false; m_Velarized = false; m_Prenasalized = false; m_Syllabic = false; m_Aspirated = false; m_Long = false; m_Glottalized = false; m_Combination = false; m_Settings = s; //m_Title = ConsonantChartSearch.kTitle; m_Title = m_Settings.LocalizationTable.GetMessage("ConsonantChartSearchT"); if (m_Title == "") m_Title = "Consonant Chart"; m_CnsTable = new ConsonantChartTable(); m_CmbTable = new CombinationChartTable(); } public bool Labialized { get {return m_Labialized;} set {m_Labialized = value;} } public bool Palatalized { get {return m_Palatalized;} set {m_Palatalized = value;} } public bool Velarized { get {return m_Velarized;} set {m_Velarized = value;} } public bool Prenasalized { get {return m_Prenasalized;} set {m_Prenasalized = value;} } public bool Syllabic { get {return m_Syllabic;} set {m_Syllabic = value;} } public bool Aspirated { get { return m_Aspirated; } set { m_Aspirated = value; } } public bool Long { get { return m_Long; } set { m_Long = value; } } public bool Glottalized { get { return m_Glottalized; } set { m_Glottalized = value; } } public bool Combination { get { return m_Combination; } set { m_Combination = value; } } public string Title { get {return m_Title;} } public ConsonantChartTable CnsTable { get {return m_CnsTable;} set {m_CnsTable = value;} } public CombinationChartTable CmbTable { get { return m_CmbTable; } set { m_CmbTable = value; } } public bool SetupSearch() { bool flag = false; //FormConsonantChart fpb = new FormConsonantChart(); FormConsonantChart form = new FormConsonantChart(m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.Labialized = form.Labialized; this.Palatalized = form.Palatalized; this.Velarized = form.Velarized; this.Prenasalized = form.Prenasalized; this.Syllabic = form.Syllabic; this.Aspirated = form.Aspirated; this.Long = form.Long; this.Glottalized = form.Glottalized; this.Combination = form.Combination; SearchDefinition sd = new SearchDefinition(SearchDefinition.kConsonant); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; string strType = ""; if (this.Labialized) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kLabial) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kLabial, ""); sd.AddSearchParm(sdp); } if (this.Palatalized) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kPalat) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kPalat, ""); sd.AddSearchParm(sdp); } if (this.Velarized) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kVelar) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kVelar, ""); sd.AddSearchParm(sdp); } if (this.Prenasalized) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kPrenas) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kPrenas, ""); sd.AddSearchParm(sdp); } if (this.Syllabic) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kSyll) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kSyll, ""); sd.AddSearchParm(sdp); } if (this.Aspirated) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kAspir) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kAspir, ""); sd.AddSearchParm(sdp); } if (this.Long) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kLong) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kLong, ""); sd.AddSearchParm(sdp); } if (this.Glottalized) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kGlott) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kGlott, ""); sd.AddSearchParm(sdp); } if (this.Combination) { strType += this.CapitalizeFirstChar(ConsonantChartSearch.kCombn) + Constants.Space; sdp = new SearchDefinitionParm(ConsonantChartSearch.kCombn, ""); sd.AddSearchParm(sdp); } if (strType != "") m_Title = strType + m_Title; this.SearchDefinition = sd; flag = true; } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = true; string strTag = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); m_Title = this.CapitalizeFirstChar(strTag) + Constants.Space + m_Title; switch (strTag) { case ConsonantChartSearch.kLabial: this.Labialized = true; break; case ConsonantChartSearch.kPalat: this.Palatalized = true; break; case ConsonantChartSearch.kVelar: this.Velarized = true; break; case ConsonantChartSearch.kPrenas: this.Prenasalized = true; break; case ConsonantChartSearch.kSyll: this.Syllabic = true; break; case ConsonantChartSearch.kAspir: this.Aspirated = true; break; case ConsonantChartSearch.kLong: this.Long = true; break; case ConsonantChartSearch.kGlott: this.Glottalized = true; break; case ConsonantChartSearch.kCombn: this.Combination = true; break; default: break; } } this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title; strText += Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public ConsonantChartSearch ExecuteConsonantChart(GraphemeInventory gi) { this.SearchResults = ""; if (this.Combination) { CombinationChartTable tbl = BuildCombinationTable(gi); if (tbl != null) { this.SearchResults += tbl.GetColumnHeaders(); this.SearchResults += tbl.GetRows(); } } else { ConsonantChartTable tbl = BuildConsonantTable(gi); if (tbl != null) { this.SearchResults += tbl.GetColumnHeaders(); this.SearchResults += tbl.GetRows(this); } } return this; } private ConsonantChartTable BuildConsonantTable(GraphemeInventory gi) { ConsonantChartTable tbl = null; Consonant cns = null; bool fLabialized = this.Labialized; bool fPalatalized = this.Palatalized; bool fVelarized = this.Velarized; bool fPrenasalized = this.Prenasalized; bool fSyllabic = this.Syllabic; bool fAspirated = this.Aspirated; bool fLong = this.Long; bool fGlottalized = this.Glottalized; bool fCombination = this.Combination; for (int i = 0; i < gi.ConsonantCount(); i++) { cns = gi.GetConsonant(i); if ((fLabialized == cns.IsLabialized) && (fPalatalized == cns.IsPalatalized) && (fVelarized == cns.IsVelarized) && (fPrenasalized == cns.IsPrenasalized) && (fSyllabic == cns.IsSyllabic) && (fAspirated == cns.IsAspirated) && (fLong == cns.IsLong) && (fGlottalized == cns.IsGlottalized) && (fCombination == cns.IsComplex)) { tbl = this.CnsTable; AddConsonantToTable(gi, cns, tbl); } cns = null; } return tbl; } private void AddConsonantToTable(GraphemeInventory gi, Consonant cns, ConsonantChartTable tbl) { string strSymbol = ""; int nRow = -1; int nCol = -1; strSymbol = cns.Symbol.PadLeft(gi.MaxGraphemeSize + 1, Constants.Space); if (cns.IsBilabial) nCol = tbl.GetColNumber("BL"); if (cns.IsLabiodental) nCol = tbl.GetColNumber("LD"); if (cns.IsDental) nCol = tbl.GetColNumber("DE"); if (cns.IsAlveolar) nCol = tbl.GetColNumber("AL"); if (cns.IsPostalveolar) nCol = tbl.GetColNumber("PO"); if (cns.IsRetroflex) nCol = tbl.GetColNumber("RE"); if (cns.IsPalatal) nCol = tbl.GetColNumber("PA"); if (cns.IsVelar) nCol = tbl.GetColNumber("VE"); if (cns.IsLabialvelar) nCol = tbl.GetColNumber("LV"); if (cns.IsUvular) nCol = tbl.GetColNumber("UV"); if (cns.IsPharyngeal) nCol = tbl.GetColNumber("PH"); if (cns.IsGlottal) nCol = tbl.GetColNumber("GL"); if (cns.IsPlosive) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("PL+"); else nRow = tbl.GetRowNumber("PL-"); } if (cns.IsNasal) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("NA+"); else nRow = tbl.GetRowNumber("NA-"); } if (cns.IsTrill) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("TR+"); else nRow = tbl.GetRowNumber("TR-"); } if (cns.IsFlap) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("FL+"); else nRow = tbl.GetRowNumber("FL-"); } if (cns.IsFricative) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("FR+"); else nRow = tbl.GetRowNumber("FR-"); } if (cns.IsAffricate) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("AF+"); else nRow = tbl.GetRowNumber("AF-"); } if (cns.IsLateralFric) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("LF+"); else nRow = tbl.GetRowNumber("LF-"); } if (cns.IsLateralAppr) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("LA+"); else nRow = tbl.GetRowNumber("LA-"); } if (cns.IsApproximant) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("AP+"); else nRow = tbl.GetRowNumber("AP-"); } if (cns.IsImplosive) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("IM+"); else nRow = tbl.GetRowNumber("IM-"); } if (cns.IsEjective) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("EJ+"); else nRow = tbl.GetRowNumber("EJ-"); } if (cns.IsClick) { if (cns.IsVoiced) nRow = tbl.GetRowNumber("CL+"); else nRow = tbl.GetRowNumber("CL-"); } if ((nRow >= 0) && (nCol > 0)) { tbl.UpdChartCell(strSymbol, nRow, nCol); } //else MessageBox.Show(strSymbol + " is not added to chart"); else { string strMsg = m_Settings.LocalizationTable.GetMessage("ConsonantChartSearch1"); if (strMsg == "") strMsg = "is not added to chart"; MessageBox.Show(strSymbol + Constants.Space + strMsg); } } private CombinationChartTable BuildCombinationTable(GraphemeInventory gi) { CombinationChartTable tbl = new CombinationChartTable(); Consonant cns = null; string strSym = ""; ArrayList alComponents = null; string strComponent = ""; string strComponents = ""; for (int i = 0; i < gi.ConsonantCount(); i++) { cns = gi.GetConsonant(i); strComponents = ""; if (cns.IsComplex) { strSym = cns.Symbol; alComponents = cns.ComplexComponents; for (int j = 0; j < alComponents.Count; j++) { strComponent = alComponents[j].ToString().Trim(); if (!gi.IsInInventory(strComponent)) strComponent = Constants.kHCOn + strComponent + Constants.kHCOff; strComponents += strComponent + Constants.Space.ToString(); } tbl = tbl.AddRow(strSym, strComponents); } } return tbl; } private string CapitalizeFirstChar(string str) { string strBegin = str.Substring(0, 1); string strRest = str.Substring(1); strBegin = strBegin.ToUpper(); str = strBegin + strRest; return str; } } }