context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using Couchbase.Lite; using Couchbase.Lite.Internal; using Sharpen; namespace Couchbase.Lite { /// <summary>Represents a query of a CouchbaseLite 'view', or of a view-like resource like _all_documents. /// </summary> /// <remarks>Represents a query of a CouchbaseLite 'view', or of a view-like resource like _all_documents. /// </remarks> public class Query { /// <summary>Determines whether or when the view index is updated.</summary> /// <remarks> /// Determines whether or when the view index is updated. By default, the index will be updated /// if necessary before the query runs -- this guarantees up-to-date results but can cause a delay. /// </remarks> public enum IndexUpdateMode { Before, Never, After } /// <summary>Changes the behavior of a query created by queryAllDocuments.</summary> /// <remarks>Changes the behavior of a query created by queryAllDocuments.</remarks> public enum AllDocsMode { AllDocs, IncludeDeleted, ShowConflicts, OnlyConflicts } /// <summary>The database that contains this view.</summary> /// <remarks>The database that contains this view.</remarks> private Database database; /// <summary>The view object associated with this query</summary> private View view; /// <summary>Is this query based on a temporary view?</summary> private bool temporaryView; /// <summary>The number of initial rows to skip.</summary> /// <remarks> /// The number of initial rows to skip. Default value is 0. /// Should only be used with small values. For efficient paging, use startKey and limit. /// </remarks> private int skip; /// <summary>The maximum number of rows to return.</summary> /// <remarks>The maximum number of rows to return. Default value is 0, meaning 'unlimited'. /// </remarks> private int limit = int.MaxValue; /// <summary>If non-nil, the key value to start at.</summary> /// <remarks>If non-nil, the key value to start at.</remarks> private object startKey; /// <summary>If non-nil, the key value to end after.</summary> /// <remarks>If non-nil, the key value to end after.</remarks> private object endKey; /// <summary>If non-nil, the document ID to start at.</summary> /// <remarks> /// If non-nil, the document ID to start at. /// (Useful if the view contains multiple identical keys, making .startKey ambiguous.) /// </remarks> private string startKeyDocId; /// <summary>If non-nil, the document ID to end at.</summary> /// <remarks> /// If non-nil, the document ID to end at. /// (Useful if the view contains multiple identical keys, making .endKey ambiguous.) /// </remarks> private string endKeyDocId; /// <summary>If set, the view will not be updated for this query, even if the database has changed. /// </summary> /// <remarks> /// If set, the view will not be updated for this query, even if the database has changed. /// This allows faster results at the expense of returning possibly out-of-date data. /// </remarks> private Query.IndexUpdateMode indexUpdateMode; /// <summary>Changes the behavior of a query created by -queryAllDocuments.</summary> /// <remarks> /// Changes the behavior of a query created by -queryAllDocuments. /// - In mode kCBLAllDocs (the default), the query simply returns all non-deleted documents. /// - In mode kCBLIncludeDeleted, it also returns deleted documents. /// - In mode kCBLShowConflicts, the .conflictingRevisions property of each row will return the /// conflicting revisions, if any, of that document. /// - In mode kCBLOnlyConflicts, _only_ documents in conflict will be returned. /// (This mode is especially useful for use with a CBLLiveQuery, so you can be notified of /// conflicts as they happen, i.e. when they're pulled in by a replication.) /// </remarks> private Query.AllDocsMode allDocsMode; /// <summary>Should the rows be returned in descending key order? Default value is NO. /// </summary> /// <remarks>Should the rows be returned in descending key order? Default value is NO. /// </remarks> private bool descending; /// <summary>If set to YES, the results will include the entire document contents of the associated rows. /// </summary> /// <remarks> /// If set to YES, the results will include the entire document contents of the associated rows. /// These can be accessed via QueryRow's -documentProperties property. /// This slows down the query, but can be a good optimization if you know you'll need the entire /// contents of each document. (This property is equivalent to "include_docs" in the CouchDB API.) /// </remarks> private bool prefetch; /// <summary>If set to YES, disables use of the reduce function.</summary> /// <remarks> /// If set to YES, disables use of the reduce function. /// (Equivalent to setting "?reduce=false" in the REST API.) /// </remarks> private bool mapOnly; /// <summary>If set to YES, queries created by -createAllDocumentsQuery will include deleted documents. /// </summary> /// <remarks> /// If set to YES, queries created by -createAllDocumentsQuery will include deleted documents. /// This property has no effect in other types of queries. /// </remarks> private bool includeDeleted; /// <summary>If non-nil, the query will fetch only the rows with the given keys.</summary> /// <remarks>If non-nil, the query will fetch only the rows with the given keys.</remarks> private IList<object> keys; /// <summary>If non-zero, enables grouping of results, in views that have reduce functions. /// </summary> /// <remarks>If non-zero, enables grouping of results, in views that have reduce functions. /// </remarks> private int groupLevel; private long lastSequence; /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Query(Database database, View view) { // Always update index if needed before querying (default) // Don't update the index; results may be out of date // Update index _after_ querying (results may still be out of date) // (the default), the query simply returns all non-deleted documents. // in this mode it also returns deleted documents. // the .conflictingRevisions property of each row will return the conflicting revisions, if any, of that document. // _only_ documents in conflict will be returned. (This mode is especially useful for use with a CBLLiveQuery, so you can be notified of conflicts as they happen, i.e. when they're pulled in by a replication.) // null for _all_docs query this.database = database; this.view = view; limit = int.MaxValue; mapOnly = (view != null && view.GetReduce() == null); indexUpdateMode = Query.IndexUpdateMode.Before; allDocsMode = Query.AllDocsMode.AllDocs; } /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Query(Database database, Mapper mapFunction) : this(database, database.MakeAnonymousView ()) { temporaryView = true; view.SetMap(mapFunction, string.Empty); } /// <summary>Constructor</summary> [InterfaceAudience.Private] internal Query(Database database, Couchbase.Lite.Query query) : this(database, query .GetView()) { limit = query.limit; skip = query.skip; startKey = query.startKey; endKey = query.endKey; descending = query.descending; prefetch = query.prefetch; keys = query.keys; groupLevel = query.groupLevel; mapOnly = query.mapOnly; startKeyDocId = query.startKeyDocId; endKeyDocId = query.endKeyDocId; indexUpdateMode = query.indexUpdateMode; allDocsMode = query.allDocsMode; } /// <summary>The database this query is associated with</summary> [InterfaceAudience.Public] public virtual Database GetDatabase() { return database; } [InterfaceAudience.Public] public virtual int GetLimit() { return limit; } [InterfaceAudience.Public] public virtual void SetLimit(int limit) { this.limit = limit; } [InterfaceAudience.Public] public virtual int GetSkip() { return skip; } [InterfaceAudience.Public] public virtual void SetSkip(int skip) { this.skip = skip; } [InterfaceAudience.Public] public virtual bool IsDescending() { return descending; } [InterfaceAudience.Public] public virtual void SetDescending(bool descending) { this.descending = descending; } [InterfaceAudience.Public] public virtual object GetStartKey() { return startKey; } [InterfaceAudience.Public] public virtual void SetStartKey(object startKey) { this.startKey = startKey; } [InterfaceAudience.Public] public virtual object GetEndKey() { return endKey; } [InterfaceAudience.Public] public virtual void SetEndKey(object endKey) { this.endKey = endKey; } [InterfaceAudience.Public] public virtual string GetStartKeyDocId() { return startKeyDocId; } [InterfaceAudience.Public] public virtual void SetStartKeyDocId(string startKeyDocId) { this.startKeyDocId = startKeyDocId; } [InterfaceAudience.Public] public virtual string GetEndKeyDocId() { return endKeyDocId; } [InterfaceAudience.Public] public virtual void SetEndKeyDocId(string endKeyDocId) { this.endKeyDocId = endKeyDocId; } [InterfaceAudience.Public] public virtual Query.IndexUpdateMode GetIndexUpdateMode() { return indexUpdateMode; } [InterfaceAudience.Public] public virtual void SetIndexUpdateMode(Query.IndexUpdateMode indexUpdateMode) { this.indexUpdateMode = indexUpdateMode; } [InterfaceAudience.Public] public virtual Query.AllDocsMode GetAllDocsMode() { return allDocsMode; } [InterfaceAudience.Public] public virtual void SetAllDocsMode(Query.AllDocsMode allDocsMode) { this.allDocsMode = allDocsMode; } [InterfaceAudience.Public] public virtual IList<object> GetKeys() { return keys; } [InterfaceAudience.Public] public virtual void SetKeys(IList<object> keys) { this.keys = keys; } [InterfaceAudience.Public] public virtual bool IsMapOnly() { return mapOnly; } [InterfaceAudience.Public] public virtual void SetMapOnly(bool mapOnly) { this.mapOnly = mapOnly; } [InterfaceAudience.Public] public virtual int GetGroupLevel() { return groupLevel; } [InterfaceAudience.Public] public virtual void SetGroupLevel(int groupLevel) { this.groupLevel = groupLevel; } [InterfaceAudience.Public] public virtual bool ShouldPrefetch() { return prefetch; } [InterfaceAudience.Public] public virtual void SetPrefetch(bool prefetch) { this.prefetch = prefetch; } [InterfaceAudience.Public] public virtual bool ShouldIncludeDeleted() { return allDocsMode == Query.AllDocsMode.IncludeDeleted; } [InterfaceAudience.Public] public virtual void SetIncludeDeleted(bool includeDeletedParam) { allDocsMode = (includeDeletedParam == true) ? Query.AllDocsMode.IncludeDeleted : Query.AllDocsMode.AllDocs; } /// <summary>Sends the query to the server and returns an enumerator over the result rows (Synchronous). /// </summary> /// <remarks> /// Sends the query to the server and returns an enumerator over the result rows (Synchronous). /// If the query fails, this method returns nil and sets the query's .error property. /// </remarks> /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> [InterfaceAudience.Public] public virtual QueryEnumerator Run() { IList<long> outSequence = new AList<long>(); string viewName = (view != null) ? view.GetName() : null; IList<QueryRow> rows = database.QueryViewNamed(viewName, GetQueryOptions(), outSequence ); lastSequence = outSequence[0]; return new QueryEnumerator(database, rows, lastSequence); } /// <summary>Returns a live query with the same parameters.</summary> /// <remarks>Returns a live query with the same parameters.</remarks> [InterfaceAudience.Public] public virtual LiveQuery ToLiveQuery() { if (view == null) { throw new InvalidOperationException("Cannot convert a Query to LiveQuery if the view is null" ); } return new LiveQuery(this); } /// <summary>Starts an asynchronous query.</summary> /// <remarks> /// Starts an asynchronous query. Returns immediately, then calls the onLiveQueryChanged block when the /// query completes, passing it the row enumerator. If the query fails, the block will receive /// a non-nil enumerator but its .error property will be set to a value reflecting the error. /// The originating Query's .error property will NOT change. /// </remarks> [InterfaceAudience.Public] public virtual Future RunAsync(Query.QueryCompleteListener onComplete) { return RunAsyncInternal(onComplete); } /// <summary>A delegate that can be called to signal the completion of a Query.</summary> /// <remarks>A delegate that can be called to signal the completion of a Query.</remarks> public interface QueryCompleteListener { void Completed(QueryEnumerator rows, Exception error); } /// <exclude></exclude> [InterfaceAudience.Private] internal virtual Future RunAsyncInternal(Query.QueryCompleteListener onComplete) { return database.GetManager().RunAsync(new _Runnable_382(this, onComplete)); } private sealed class _Runnable_382 : Runnable { public _Runnable_382(Query _enclosing, Query.QueryCompleteListener onComplete) { this._enclosing = _enclosing; this.onComplete = onComplete; } public void Run() { try { if (!this._enclosing.GetDatabase().IsOpen()) { throw new InvalidOperationException("The database has been closed."); } string viewName = this._enclosing.view.GetName(); QueryOptions options = this._enclosing.GetQueryOptions(); IList<long> outSequence = new AList<long>(); IList<QueryRow> rows = this._enclosing.database.QueryViewNamed(viewName, options, outSequence); long sequenceNumber = outSequence[0]; QueryEnumerator enumerator = new QueryEnumerator(this._enclosing.database, rows, sequenceNumber); onComplete.Completed(enumerator, null); } catch (Exception t) { onComplete.Completed(null, t); } } private readonly Query _enclosing; private readonly Query.QueryCompleteListener onComplete; } /// <exclude></exclude> [InterfaceAudience.Private] public virtual View GetView() { return view; } [InterfaceAudience.Private] private QueryOptions GetQueryOptions() { QueryOptions queryOptions = new QueryOptions(); queryOptions.SetStartKey(GetStartKey()); queryOptions.SetEndKey(GetEndKey()); queryOptions.SetStartKey(GetStartKey()); queryOptions.SetKeys(GetKeys()); queryOptions.SetSkip(GetSkip()); queryOptions.SetLimit(GetLimit()); queryOptions.SetReduce(!IsMapOnly()); queryOptions.SetReduceSpecified(true); queryOptions.SetGroupLevel(GetGroupLevel()); queryOptions.SetDescending(IsDescending()); queryOptions.SetIncludeDocs(ShouldPrefetch()); queryOptions.SetUpdateSeq(true); queryOptions.SetInclusiveEnd(true); queryOptions.SetStale(GetIndexUpdateMode()); queryOptions.SetAllDocsMode(GetAllDocsMode()); return queryOptions; } ~Query() { base.Finalize(); if (temporaryView) { view.Delete(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Content.Server.Doors.Components; using Content.Shared.Access.Components; using Content.Shared.Doors.Components; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Physics; using Robust.Shared.Utility; namespace Content.Server.AI.Pathfinding { public sealed class PathfindingNode { public PathfindingChunk ParentChunk => _parentChunk; private readonly PathfindingChunk _parentChunk; public TileRef TileRef { get; private set; } /// <summary> /// Whenever there's a change in the collision layers we update the mask as the graph has more reads than writes /// </summary> public int BlockedCollisionMask { get; private set; } private readonly Dictionary<EntityUid, int> _blockedCollidables = new(0); public IReadOnlyDictionary<EntityUid, int> PhysicsLayers => _physicsLayers; private readonly Dictionary<EntityUid, int> _physicsLayers = new(0); /// <summary> /// The entities on this tile that require access to traverse /// </summary> /// We don't store the ICollection, at least for now, as we'd need to replicate the access code here public IReadOnlyCollection<AccessReaderComponent> AccessReaders => _accessReaders.Values; private readonly Dictionary<EntityUid, AccessReaderComponent> _accessReaders = new(0); public PathfindingNode(PathfindingChunk parent, TileRef tileRef) { _parentChunk = parent; TileRef = tileRef; GenerateMask(); } public static bool IsRelevant(EntityUid entity, IPhysBody physicsComponent) { if (IoCManager.Resolve<IEntityManager>().GetComponent<TransformComponent>(entity).GridID == GridId.Invalid || (PathfindingSystem.TrackedCollisionLayers & physicsComponent.CollisionLayer) == 0) { return false; } return true; } /// <summary> /// Return our neighboring nodes (even across chunks) /// </summary> /// <returns></returns> public IEnumerable<PathfindingNode> GetNeighbors() { List<PathfindingChunk>? neighborChunks = null; if (ParentChunk.OnEdge(this)) { neighborChunks = ParentChunk.RelevantChunks(this).ToList(); } for (var x = -1; x <= 1; x++) { for (var y = -1; y <= 1; y++) { if (x == 0 && y == 0) continue; var indices = new Vector2i(TileRef.X + x, TileRef.Y + y); if (ParentChunk.InBounds(indices)) { var (relativeX, relativeY) = (indices.X - ParentChunk.Indices.X, indices.Y - ParentChunk.Indices.Y); yield return ParentChunk.Nodes[relativeX, relativeY]; } else { DebugTools.AssertNotNull(neighborChunks); // Get the relevant chunk and then get the node on it foreach (var neighbor in neighborChunks!) { // A lot of edge transitions are going to have a single neighboring chunk // (given > 1 only affects corners) // So we can just check the count to see if it's inbound if (neighborChunks.Count > 0 && !neighbor.InBounds(indices)) continue; var (relativeX, relativeY) = (indices.X - neighbor.Indices.X, indices.Y - neighbor.Indices.Y); yield return neighbor.Nodes[relativeX, relativeY]; break; } } } } } public PathfindingNode? GetNeighbor(Direction direction) { var chunkXOffset = TileRef.X - ParentChunk.Indices.X; var chunkYOffset = TileRef.Y - ParentChunk.Indices.Y; Vector2i neighborVector2i; switch (direction) { case Direction.East: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset + 1, chunkYOffset]; } neighborVector2i = new Vector2i(TileRef.X + 1, TileRef.Y); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.NorthEast: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset + 1, chunkYOffset + 1]; } neighborVector2i = new Vector2i(TileRef.X + 1, TileRef.Y + 1); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.North: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset, chunkYOffset + 1]; } neighborVector2i = new Vector2i(TileRef.X, TileRef.Y + 1); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.NorthWest: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset - 1, chunkYOffset + 1]; } neighborVector2i = new Vector2i(TileRef.X - 1, TileRef.Y + 1); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.West: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset - 1, chunkYOffset]; } neighborVector2i = new Vector2i(TileRef.X - 1, TileRef.Y); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.SouthWest: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset - 1, chunkYOffset - 1]; } neighborVector2i = new Vector2i(TileRef.X - 1, TileRef.Y - 1); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.South: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset, chunkYOffset - 1]; } neighborVector2i = new Vector2i(TileRef.X, TileRef.Y - 1); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; case Direction.SouthEast: if (!ParentChunk.OnEdge(this)) { return ParentChunk.Nodes[chunkXOffset + 1, chunkYOffset - 1]; } neighborVector2i = new Vector2i(TileRef.X + 1, TileRef.Y - 1); foreach (var neighbor in ParentChunk.GetNeighbors()) { if (neighbor.InBounds(neighborVector2i)) { return neighbor.Nodes[neighborVector2i.X - neighbor.Indices.X, neighborVector2i.Y - neighbor.Indices.Y]; } } return null; default: throw new ArgumentOutOfRangeException(nameof(direction), direction, null); } } public void UpdateTile(TileRef newTile) { TileRef = newTile; ParentChunk.Dirty(); } /// <summary> /// Call if this entity is relevant for the pathfinder /// </summary> /// <param name="entity"></param> /// TODO: These 2 methods currently don't account for a bunch of changes (e.g. airlock unpowered, wrenching, etc.) /// TODO: Could probably optimise this slightly more. public void AddEntity(EntityUid entity, IPhysBody physicsComponent) { var entMan = IoCManager.Resolve<IEntityManager>(); // If we're a door if (entMan.HasComponent<AirlockComponent>(entity) || entMan.HasComponent<DoorComponent>(entity)) { // If we need access to traverse this then add to readers, otherwise no point adding it (except for maybe tile costs in future) // TODO: Check for powered I think (also need an event for when it's depowered // AccessReader calls this whenever opening / closing but it can seem to get called multiple times // Which may or may not be intended? if (entMan.TryGetComponent(entity, out AccessReaderComponent? accessReader) && !_accessReaders.ContainsKey(entity)) { _accessReaders.Add(entity, accessReader); ParentChunk.Dirty(); } return; } DebugTools.Assert((PathfindingSystem.TrackedCollisionLayers & physicsComponent.CollisionLayer) != 0); if (physicsComponent.BodyType != BodyType.Static) { _physicsLayers.Add(entity, physicsComponent.CollisionLayer); } else { _blockedCollidables.Add(entity, physicsComponent.CollisionLayer); GenerateMask(); ParentChunk.Dirty(); } } /// <summary> /// Remove the entity from this node. /// Will check each category and remove it from the applicable one /// </summary> /// <param name="entity"></param> public void RemoveEntity(EntityUid entity) { // There's no guarantee that the entity isn't deleted // 90% of updates are probably entities moving around // Entity can't be under multiple categories so just checking each once is fine. if (_physicsLayers.ContainsKey(entity)) { _physicsLayers.Remove(entity); } else if (_accessReaders.ContainsKey(entity)) { _accessReaders.Remove(entity); ParentChunk.Dirty(); } else if (_blockedCollidables.ContainsKey(entity)) { _blockedCollidables.Remove(entity); GenerateMask(); ParentChunk.Dirty(); } } private void GenerateMask() { BlockedCollisionMask = 0x0; foreach (var layer in _blockedCollidables.Values) { BlockedCollisionMask |= layer; } } } }
using UnityEngine; using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; public enum RuleResult { Done, Working } namespace Casanova.Prelude { public class Tuple<T,E> { public T Item1 { get; set;} public E Item2 { get; set;} public Tuple(T item1, E item2) { Item1 = item1; Item2 = item2; } } public static class MyExtensions { //public T this[List<T> list] //{ // get { return list.ElementAt(0); } //} public static T Head<T>(this List<T> list) { return list.ElementAt(0); } public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); } public static int Length<T>(this List<T> list) { return list.Count; } public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; } } public class Cons<T> : IEnumerable<T> { public class Enumerator : IEnumerator<T> { public Enumerator(Cons<T> parent) { firstEnumerated = 0; this.parent = parent; tailEnumerator = parent.tail.GetEnumerator(); } byte firstEnumerated; Cons<T> parent; IEnumerator<T> tailEnumerator; public T Current { get { if (firstEnumerated == 0) return default(T); if (firstEnumerated == 1) return parent.head; else return tailEnumerator.Current; } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { if (firstEnumerated == 0) { if (parent.head == null) return false; firstEnumerated++; return true; } if (firstEnumerated == 1) firstEnumerated++; return tailEnumerator.MoveNext(); } public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); } public void Dispose() { } } T head; IEnumerable<T> tail; public Cons(T head, IEnumerable<T> tail) { this.head = head; this.tail = tail; } public IEnumerator<T> GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } } public class Empty<T> : IEnumerable<T> { public Empty() { } public class Enumerator : IEnumerator<T> { public T Current { get { throw new Exception("Empty sequence has no elements"); } } object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } } public bool MoveNext() { return false; } public void Reset() { } public void Dispose() { } } public IEnumerator<T> GetEnumerator() { return new Enumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(); } } public abstract class Option<T> : IComparable, IEquatable<Option<T>> { public bool IsSome; public bool IsNone { get { return !IsSome; } } protected abstract Just<T> Some { get; } public U Match<U>(Func<T,U> f, Func<U> g) { if (this.IsSome) return f(this.Some.Value); else return g(); } public bool Equals(Option<T> b) { return this.Match( x => b.Match( y => x.Equals(y), () => false), () => b.Match( y => false, () => true)); } public override bool Equals(System.Object other) { if (other == null) return false; if (other is Option<T>) { var other1 = other as Option<T>; return this.Equals(other1); } return false; } public override int GetHashCode() { return this.GetHashCode(); } public static bool operator ==(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return a.Equals(b); } public static bool operator !=(Option<T> a, Option<T> b) { if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b); return !(a.Equals(b)); } public int CompareTo(object obj) { if (obj == null) return 1; if (obj is Option<T>) { var obj1 = obj as Option<T>; if (this.Equals(obj1)) return 0; } return -1; } abstract public T Value { get; } public override string ToString() { return "Option<" + typeof(T).ToString() + ">"; } } public class Just<T> : Option<T> { T elem; public Just(T elem) { this.elem = elem; this.IsSome = true; } protected override Just<T> Some { get { return this; } } public override T Value { get { return elem; } } } public class Nothing<T> : Option<T> { public Nothing() { this.IsSome = false; } protected override Just<T> Some { get { return null; } } public override T Value { get { throw new Exception("Cant get a value from a None object"); } } } public class Utils { public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e) { if (c()) return t(); else return e(); } } } public class FastStack { public int[] Elements; public int Top; public FastStack(int elems) { Top = 0; Elements = new int[elems]; } public void Clear() { Top = 0; } public void Push(int x) { Elements[Top++] = x; } } public class RuleTable { public RuleTable(int elems) { ActiveIndices = new FastStack(elems); SupportStack = new FastStack(elems); ActiveSlots = new bool[elems]; } public FastStack ActiveIndices; public FastStack SupportStack; public bool[] ActiveSlots; public void Add(int i) { if (!ActiveSlots[i]) { ActiveSlots[i] = true; ActiveIndices.Push(i); } } } public class World : MonoBehaviour{ void Update () { Update(Time.deltaTime, this); } public void Start() { UnityCube = UnityCube.Find(); } public UnityCube UnityCube; public UnityEngine.Color Color{ get { return UnityCube.Color; } set{UnityCube.Color = value; } } public System.Boolean useGUILayout{ get { return UnityCube.useGUILayout; } set{UnityCube.useGUILayout = value; } } public System.Boolean enabled{ get { return UnityCube.enabled; } set{UnityCube.enabled = value; } } public UnityEngine.Transform transform{ get { return UnityCube.transform; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityCube.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityCube.rigidbody2D; } } public UnityEngine.Camera camera{ get { return UnityCube.camera; } } public UnityEngine.Light light{ get { return UnityCube.light; } } public UnityEngine.Animation animation{ get { return UnityCube.animation; } } public UnityEngine.ConstantForce constantForce{ get { return UnityCube.constantForce; } } public UnityEngine.Renderer renderer{ get { return UnityCube.renderer; } } public UnityEngine.AudioSource audio{ get { return UnityCube.audio; } } public UnityEngine.GUIText guiText{ get { return UnityCube.guiText; } } public UnityEngine.NetworkView networkView{ get { return UnityCube.networkView; } } public UnityEngine.GUIElement guiElement{ get { return UnityCube.guiElement; } } public UnityEngine.GUITexture guiTexture{ get { return UnityCube.guiTexture; } } public UnityEngine.Collider collider{ get { return UnityCube.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityCube.collider2D; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityCube.hingeJoint; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityCube.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityCube.particleSystem; } } public UnityEngine.GameObject gameObject{ get { return UnityCube.gameObject; } } public System.Boolean active{ get { return UnityCube.active; } set{UnityCube.active = value; } } public System.String tag{ get { return UnityCube.tag; } set{UnityCube.tag = value; } } public System.String name{ get { return UnityCube.name; } set{UnityCube.name = value; } } public UnityEngine.HideFlags hideFlags{ get { return UnityCube.hideFlags; } set{UnityCube.hideFlags = value; } } public System.Single count_down2; public System.Single count_down1; public void Update(float dt, World world) { this.Rule0(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: count_down2 = 0.5f; goto case 5; case 5: if(((count_down2) > (0f))) { count_down2 = ((count_down2) - (dt)); s0 = 5; return; }else { goto case 3; } case 3: UnityCube.Color = Color.green; s0 = 1; return; case 1: count_down1 = 0.5f; goto case 2; case 2: if(((count_down1) > (0f))) { count_down1 = ((count_down1) - (dt)); s0 = 2; return; }else { goto case 0; } case 0: UnityCube.Color = Color.red; s0 = -1; return; default: return;}} }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Json; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Reflection; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Abp.UI; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Abp.Authorization.Users { public class AbpUserManager<TRole, TUser> : UserManager<TUser>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; set; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } protected AbpUserStore<TRole, TUser> AbpStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; private readonly IOptions<IdentityOptions> _optionsAccessor; public AbpUserManager( AbpRoleManager<TRole, TUser> roleManager, AbpUserStore<TRole, TUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager) : base( store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; _settingManager = settingManager; _optionsAccessor = optionsAccessor; AbpStore = store; RoleManager = roleManager; } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } return await base.CreateAsync(user); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpStore.FindAllAsync(login); } public virtual Task<TUser> FindAsync(int? tenantId, UserLoginInfo login) { return AbpStore.FindAsync(tenantId, login); } public virtual Task<TUser> FindByNameOrEmailAsync(int? tenantId, string userNameOrEmailAddress) { return AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId.ToString()); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public override async Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUserBase.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName)); } } return await base.UpdateAsync(user); } public override async Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var errors = new List<IdentityError>(); foreach (var validator in PasswordValidators) { var validationResult = await validator.ValidateAsync(this, user, newPassword); if (!validationResult.Succeeded) { errors.AddRange(validationResult.Errors); } } if (errors.Any()) { return IdentityResult.Failed(errors.ToArray()); } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(user, newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { await AbpStore.UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles); //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId.ToString()); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException($"Can not set more than {maxCount} organization unit for a user!"); } } public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } } [UnitOfWork] public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return Task.FromResult(query.ToList()); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return Task.FromResult(query.ToList()); } } public virtual async Task InitializeOptionsAsync(int? tenantId) { Options = JsonConvert.DeserializeObject<IdentityOptions>(_optionsAccessor.Value.ToJsonString()); //Lockout Options.Lockout.AllowedForNewUsers = await IsTrueAsync(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); Options.Lockout.MaxFailedAccessAttempts = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); //Password complexity Options.Password.RequireDigit = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId); Options.Password.RequireLowercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId); Options.Password.RequireNonAlphanumeric = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId); Options.Password.RequireUppercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId); Options.Password.RequiredLength = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpStore.GetUserNameFromDatabaseAsync(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId.ToString()); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(user)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user) { var providers = new List<string>(); foreach (var provider in await base.GetValidTwoFactorProvidersAsync(user)) { if (provider == "Email" && !await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, user.TenantId)) { continue; } if (provider == "Phone" && !await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, user.TenantId)) { continue; } providers.Add(provider); } return providers; } private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private Task<bool> IsTrueAsync(string settingName, int? tenantId) { return GetSettingValueAsync<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } private Task<T> GetSettingValueAsync<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplicationAsync<T>(settingName) : _settingManager.GetSettingValueForTenantAsync<T>(settingName, tenantId.Value); } private string L(string name) { return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } } }
// 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; using System.Collections.Generic; using Xunit; using SortedDictionaryTests.SortedDictionary_SortedDictionary_RemoveTest; using SortedDictionary_SortedDictionaryUtils; namespace SortedDictionaryTests { public class SortedDictionary_RemoveTests { [Fact] public static void SortedDictionary_RemoveIntTest() { Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } //Ref<val>,Val<Ref> IntDriver.BasicRemove(intArr1, stringArr1); IntDriver.RemoveNegative(intArr1, stringArr1, intArr2); IntDriver.RemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.RemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.RemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.RemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.RemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.RemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryBasicRemove(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveNegative(intArr1, stringArr1, intArr2); IntDriver.NonGenericIDictionaryRemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 98, 6); } [Fact] public static void SortedDictionary_RemoveStringTest() { Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } ValX1<string>[] stringArr2 = new ValX1<string>[10]; for (int i = 0; i < 10; i++) { stringArr2[i] = new ValX1<string>("SomeTestString" + (i + 100).ToString()); } //Val<Ref>,Ref<Val> StringDriver.BasicRemove(stringArr1, intArr1); StringDriver.RemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.RemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.RemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.RemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.RemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.RemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.RemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryBasicRemove(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.NonGenericIDictionaryRemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 98, 6); } [Fact] public static void SortedDictionary_RemoveTest_Negative() { Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } IntDriver.NonGenericIDictionaryRemoveValidations(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveValidations(new RefX1<int>[] { }, new ValX1<string>[] { }); StringDriver.NonGenericIDictionaryRemoveValidations(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveValidations(new ValX1<string>[] { }, new RefX1<int>[] { }); } } namespace SortedDictionary_SortedDictionary_RemoveTest { /// Helper class public class Driver<K, V> where K : IComparableValue { public void BasicRemove(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_1! Expected count to be equal to keys.Length" for (int i = 0; i < keys.Length; i++) { Assert.True(tbl.Remove(keys[i])); //"Err_2! Expected Remove() to return true" } Assert.Equal(tbl.Count, 0); //"Err_3! Count was expected to be zero" } public void RemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_4! Expected count to be equal to keys.Length" for (int i = 0; i < missingkeys.Length; i++) { Assert.False(tbl.Remove(missingkeys[i])); //"Err_5! Expected Remove() to return false" } Assert.Equal(tbl.Count, keys.Length); //"Err_6! Expected count to be equal to keys.Length" } public void RemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_7! Expected count to be equal to keys.Length" Assert.True(tbl.Remove(keys[index])); //"Err_8! Expected Remove() to return true" for (int i = 0; i < repeat; i++) { Assert.False(tbl.Remove(keys[index])); //"Err_9! Expected Remove() to return false" } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_10! Expected count to be equal to keys.Length-1" } public void AddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_11! Expected count to be equal to keys.Length" Assert.True(tbl.Remove(keys[index])); //"Err_12! Expected Remove() to return true" for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); Assert.True(tbl.Remove(keys[index])); //"Err_13! Expected Remove() to return true" } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_14! Expected count to be equal to keys.Length-1" } public void NonGenericIDictionaryBasicRemove(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_16! Expected count to be equal to keys.Length" for (int i = 0; i < keys.Length; i++) { _idic.Remove(keys[i]); Assert.False(_idic.Contains(keys[i])); //"Err_17! Expected " + keys[i] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, 0); //"Err_18! Count was expected to be zero" } public void NonGenericIDictionaryRemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_19! Expected count to be equal to keys.Length" for (int i = 0; i < missingkeys.Length; i++) { _idic.Remove(missingkeys[i]); Assert.False(_idic.Contains(missingkeys[i])); //"Err_20! Expected " + missingkeys[i] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, keys.Length); //"Err_21! Expected count to be equal to keys.Length" } public void NonGenericIDictionaryRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_22! Expected count to be equal to keys.Length" _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_23! Expected " + keys[index] + " to not still exist, but Contains returned true." for (int i = 0; i < repeat; i++) { _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_24! Expected " + keys[index] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_25! Expected count to be equal to keys.Length-1" } public void NonGenericIDictionaryAddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_26! Expected count to be equal to keys.Length" _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_27! Expected " + keys[index] + " to not still exist, but Contains returned true." for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_28! Expected " + keys[index] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_30! Expected count to be equal to keys.Length-1" } public void NonGenericIDictionaryRemoveValidations(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } //try null key Assert.Throws<ArgumentNullException>(() => _idic.Remove(null)); //"Err_31! wrong exception thrown when trying to remove null." } } } }
// 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.Search { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// IndexesOperations operations. /// </summary> internal partial class IndexesOperations : IServiceOperations<SearchServiceClient>, IIndexesOperations { /// <summary> /// Initializes a new instance of the IndexesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal IndexesOperations(SearchServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SearchServiceClient /// </summary> public SearchServiceClient Client { get; private set; } /// <summary> /// Creates a new Azure Search index. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Index" /> /// </summary> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Index>> CreateWithHttpMessagesAsync(Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (index == null) { throw new ValidationException(ValidationRules.CannotBeNull, "index"); } if (index != null) { index.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("index", index); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(index != null) { _requestContent = SafeJsonConvert.SerializeObject(index, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Index>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Index>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://docs.microsoft.com/rest/api/searchservice/List-Indexes" /> /// </summary> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified /// as a comma-separated list of JSON property names, or '*' for all /// properties. The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IndexListResult>> ListWithHttpMessagesAsync(string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("select", select); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes").ToString(); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", Uri.EscapeDataString(select))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IndexListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IndexListResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Update-Index" /> /// </summary> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='allowIndexDowntime'> /// Allows new analyzers, tokenizers, token filters, or char filters to be /// added to an index by taking the index offline for at least a few seconds. /// This temporarily causes indexing and query requests to fail. Performance /// and write availability of the index can be impaired for several minutes /// after the index is updated, or longer for very large indexes. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Index>> CreateOrUpdateWithHttpMessagesAsync(string indexName, Index index, bool? allowIndexDowntime = default(bool?), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (indexName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "indexName"); } if (index == null) { throw new ValidationException(ValidationRules.CannotBeNull, "index"); } if (index != null) { index.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } string ifMatch = default(string); if (accessCondition != null) { ifMatch = accessCondition.IfMatch; } string ifNoneMatch = default(string); if (accessCondition != null) { ifNoneMatch = accessCondition.IfNoneMatch; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("indexName", indexName); tracingParameters.Add("index", index); tracingParameters.Add("allowIndexDowntime", allowIndexDowntime); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("ifNoneMatch", ifNoneMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')").ToString(); _url = _url.Replace("{indexName}", Uri.EscapeDataString(indexName)); List<string> _queryParameters = new List<string>(); if (allowIndexDowntime != null) { _queryParameters.Add(string.Format("allowIndexDowntime={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(allowIndexDowntime, this.Client.SerializationSettings).Trim('"')))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (ifNoneMatch != null) { if (_httpRequest.Headers.Contains("If-None-Match")) { _httpRequest.Headers.Remove("If-None-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(index != null) { _requestContent = SafeJsonConvert.SerializeObject(index, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Index>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Index>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Index>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Delete-Index" /> /// </summary> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='accessCondition'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (indexName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "indexName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } string ifMatch = default(string); if (accessCondition != null) { ifMatch = accessCondition.IfMatch; } string ifNoneMatch = default(string); if (accessCondition != null) { ifNoneMatch = accessCondition.IfNoneMatch; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("indexName", indexName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("ifNoneMatch", ifNoneMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')").ToString(); _url = _url.Replace("{indexName}", Uri.EscapeDataString(indexName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (ifNoneMatch != null) { if (_httpRequest.Headers.Contains("If-None-Match")) { _httpRequest.Headers.Remove("If-None-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-None-Match", ifNoneMatch); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Index" /> /// </summary> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Index>> GetWithHttpMessagesAsync(string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (indexName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "indexName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("indexName", indexName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')").ToString(); _url = _url.Replace("{indexName}", Uri.EscapeDataString(indexName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Index>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Index>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Index-Statistics" /> /// </summary> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IndexGetStatisticsResult>> GetStatisticsWithHttpMessagesAsync(string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (indexName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "indexName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("indexName", indexName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetStatistics", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')/search.stats").ToString(); _url = _url.Replace("{indexName}", Uri.EscapeDataString(indexName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IndexGetStatisticsResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IndexGetStatisticsResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Shows how an analyzer breaks text into tokens. /// <see href="https://docs.microsoft.com/rest/api/searchservice/test-analyzer" /> /// </summary> /// <param name='indexName'> /// The name of the index for which to test an analyzer. /// </param> /// <param name='request'> /// The text and analyzer or analysis components to test. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AnalyzeResult>> AnalyzeWithHttpMessagesAsync(string indexName, AnalyzeRequest request, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (indexName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "indexName"); } if (request == null) { throw new ValidationException(ValidationRules.CannotBeNull, "request"); } if (request != null) { request.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("indexName", indexName); tracingParameters.Add("request", request); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Analyze", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "indexes('{indexName}')/search.analyze").ToString(); _url = _url.Replace("{indexName}", Uri.EscapeDataString(indexName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(request != null) { _requestContent = SafeJsonConvert.SerializeObject(request, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AnalyzeResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<AnalyzeResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; using Microsoft.Win32; namespace johnLib { public static class CommonUtils { /// <summary> /// Return DateTime with "MM/dd/yyyy HH:mm:ss" format /// </summary> /// <returns></returns> public static string getDateTimeNow() { return DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"); } /// <summary> /// Turn Data Table intogrid view and BIND GridView - WEB ONLY /// </summary> /// <param name="dataTable">Source DataTable</param> /// <param name="yourGridView"></param> public static void turnDataTableTOGridView(DataTable dataTable, GridView yourGridView) { //cleare gridview content while (yourGridView.Columns.Count > 0) { yourGridView.Columns.Remove(yourGridView.Columns[0]); } //Iterate through the columns of the datatable to set the data bound field dynamically. foreach (DataColumn col in dataTable.Columns) { //Declare the bound field and allocate memory for the bound field. BoundField bfield = new BoundField(); //Initalize the DataField value. bfield.DataField = col.ColumnName; //Initialize the HeaderText field value. bfield.HeaderText = col.ColumnName; //Add the newly created bound field to the GridView. yourGridView.Columns.Add(bfield); } ////Initialize the DataSource yourGridView.DataSource = dataTable; ////Bind the datatable with the GridView. yourGridView.DataBind(); } /// <summary> /// Turn Data Table intogrid view and BIND GridView - Transform one column into control - WEB ONLY /// </summary> /// <param name="dataTable"></param> /// <param name="yourGridView"></param> /// <param name="ColumnNeedControl"></param> /// <param name="ControlType"></param> /// <param name="CommandName"></param> public static void turnDataTableTOGridView(DataTable dataTable, GridView yourGridView, string ColumnNeedControl, ButtonType ControlType, string CommandName) { //cleare gridview content while (yourGridView.Columns.Count > 0) { yourGridView.Columns.Remove(yourGridView.Columns[0]); } //Iterate through the columns of the datatable to set the data bound field dynamically. foreach (DataColumn col in dataTable.Columns) { if (col.ColumnName == ColumnNeedControl) { //Declare the bound field and allocate memory for the bound field. ButtonField bfield = new ButtonField(); //choose the type of button bfield.ButtonType = ControlType; //Initalize the DataField value. bfield.DataTextField = col.ColumnName; //Initialize the HeaderText field value. bfield.HeaderText = col.ColumnName; bfield.CommandName = CommandName; //Add the newly created bound field to the GridView. yourGridView.Columns.Add(bfield); } else { //Declare the bound field and allocate memory for the bound field. BoundField bfield = new BoundField(); //Initalize the DataField value. bfield.DataField = col.ColumnName; //Initialize the HeaderText field value. bfield.HeaderText = col.ColumnName; //Add the newly created bound field to the GridView. yourGridView.Columns.Add(bfield); } } ////Initialize the DataSource yourGridView.DataSource = dataTable; ////Bind the datatable with the GridView. yourGridView.DataBind(); } /// <summary> /// Turn Data Table into GridView - Aadd one control into the grid as well - WEB ONLY /// </summary> /// <param name="dataTable"></param> /// <param name="yourGridView"></param> /// <param name="newColumnName"></param> /// <param name="buttonText"></param> /// <param name="columnPosition"></param> /// <param name="buttonType"></param> /// <param name="newCommandName"></param> public static void turnDataTableTOGridView(DataTable dataTable, GridView yourGridView, string newColumnName, string newButtonText, int columnPosition, ButtonType buttonType, string newCommandName) { //cleare gridview content while (yourGridView.Columns.Count > 0) { yourGridView.Columns.Remove(yourGridView.Columns[0]); } // create a column ButtonField newColumn = new ButtonField(); newColumn.ButtonType = buttonType; newColumn.HeaderText = newColumnName; newColumn.Text = newButtonText; newColumn.CommandName = newCommandName; //add column from 0 to desire position - 2 for (int i = 0; i < (columnPosition - 1); i++) { //Declare the bound field and allocate memory for the bound field. BoundField bfield = new BoundField(); //Initalize the DataField value. bfield.DataField = dataTable.Columns[i].ColumnName; //Initialize the HeaderText field value. bfield.HeaderText = dataTable.Columns[i].ColumnName; //Add the newly created bound field to the GridView. yourGridView.Columns.Add(bfield); } //add new column yourGridView.Columns.Add(newColumn); //add column from desire position - 1 to end original grid for (int i = (columnPosition - 1); i < dataTable.Columns.Count; i++) { //Declare the bound field and allocate memory for the bound field. BoundField bfield = new BoundField(); //Initalize the DataField value. bfield.DataField = dataTable.Columns[i].ColumnName; //Initialize the HeaderText field value. bfield.HeaderText = dataTable.Columns[i].ColumnName; //Add the newly created bound field to the GridView. yourGridView.Columns.Add(bfield); } //Initialize the DataSource yourGridView.DataSource = dataTable; //Bind the datatable with the GridView. yourGridView.DataBind(); } /// <summary> /// Generate Unique Key String /// </summary> /// <returns></returns> public static string getUniqueKeyString() { return System.Guid.NewGuid().ToString(); } /// <summary> /// List ODBC DataSources /// </summary> /// <returns></returns> public static List<string> ListODBCSources() { List<string> list = new List<string>(); list.AddRange(EnumDsn(Registry.CurrentUser)); list.AddRange(EnumDsn(Registry.LocalMachine)); return list; } private static IEnumerable<string> EnumDsn(RegistryKey rootKey) { RegistryKey regKey = rootKey.OpenSubKey(@"Software\ODBC\ODBC.INI\ODBC Data Sources"); if (regKey != null) { foreach (string name in regKey.GetValueNames()) { string value = regKey.GetValue(name, "").ToString(); yield return name; } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; 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.Dataflow.V1Beta3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedJobsV1Beta3ClientTest { [xunit::FactAttribute] public void CreateJobRequestObject() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ProjectId = "project_id43ad98b0", Job = new Job(), View = JobView.Summary, ReplaceJobId = "replace_job_id4a0fad7e", Location = "locatione09d18d5", }; Job expectedResponse = new Job { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", Name = "name1c9368b0", Type = JobType.Unknown, Environment = new Environment(), Steps = { new Step(), }, CurrentState = JobState.Unknown, CurrentStateTime = new wkt::Timestamp(), RequestedState = JobState.Stopped, ExecutionInfo = new JobExecutionInfo(), CreateTime = new wkt::Timestamp(), ReplaceJobId = "replace_job_id4a0fad7e", TransformNameMapping = { { "key8a0b6e3c", "value60c16320" }, }, ClientRequestId = "client_request_ide162ec50", ReplacedByJobId = "replaced_by_job_ida56afc22", TempFiles = { "temp_filescb023328", }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Location = "locatione09d18d5", PipelineDescription = new PipelineDescription(), StageStates = { new ExecutionStageState(), }, JobMetadata = new JobMetadata(), StartTime = new wkt::Timestamp(), CreatedFromSnapshotId = "created_from_snapshot_id9b426c65", StepsLocation = "steps_location41e078c5", SatisfiesPzs = false, }; mockGrpcClient.Setup(x => x.CreateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Job response = client.CreateJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateJobRequestObjectAsync() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); CreateJobRequest request = new CreateJobRequest { ProjectId = "project_id43ad98b0", Job = new Job(), View = JobView.Summary, ReplaceJobId = "replace_job_id4a0fad7e", Location = "locatione09d18d5", }; Job expectedResponse = new Job { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", Name = "name1c9368b0", Type = JobType.Unknown, Environment = new Environment(), Steps = { new Step(), }, CurrentState = JobState.Unknown, CurrentStateTime = new wkt::Timestamp(), RequestedState = JobState.Stopped, ExecutionInfo = new JobExecutionInfo(), CreateTime = new wkt::Timestamp(), ReplaceJobId = "replace_job_id4a0fad7e", TransformNameMapping = { { "key8a0b6e3c", "value60c16320" }, }, ClientRequestId = "client_request_ide162ec50", ReplacedByJobId = "replaced_by_job_ida56afc22", TempFiles = { "temp_filescb023328", }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Location = "locatione09d18d5", PipelineDescription = new PipelineDescription(), StageStates = { new ExecutionStageState(), }, JobMetadata = new JobMetadata(), StartTime = new wkt::Timestamp(), CreatedFromSnapshotId = "created_from_snapshot_id9b426c65", StepsLocation = "steps_location41e078c5", SatisfiesPzs = false, }; mockGrpcClient.Setup(x => x.CreateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.CreateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.CreateJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetJobRequestObject() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { ProjectId = "project_id43ad98b0", JobId = "job_id38ea97d6", View = JobView.Summary, Location = "locatione09d18d5", }; Job expectedResponse = new Job { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", Name = "name1c9368b0", Type = JobType.Unknown, Environment = new Environment(), Steps = { new Step(), }, CurrentState = JobState.Unknown, CurrentStateTime = new wkt::Timestamp(), RequestedState = JobState.Stopped, ExecutionInfo = new JobExecutionInfo(), CreateTime = new wkt::Timestamp(), ReplaceJobId = "replace_job_id4a0fad7e", TransformNameMapping = { { "key8a0b6e3c", "value60c16320" }, }, ClientRequestId = "client_request_ide162ec50", ReplacedByJobId = "replaced_by_job_ida56afc22", TempFiles = { "temp_filescb023328", }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Location = "locatione09d18d5", PipelineDescription = new PipelineDescription(), StageStates = { new ExecutionStageState(), }, JobMetadata = new JobMetadata(), StartTime = new wkt::Timestamp(), CreatedFromSnapshotId = "created_from_snapshot_id9b426c65", StepsLocation = "steps_location41e078c5", SatisfiesPzs = false, }; mockGrpcClient.Setup(x => x.GetJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Job response = client.GetJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetJobRequestObjectAsync() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); GetJobRequest request = new GetJobRequest { ProjectId = "project_id43ad98b0", JobId = "job_id38ea97d6", View = JobView.Summary, Location = "locatione09d18d5", }; Job expectedResponse = new Job { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", Name = "name1c9368b0", Type = JobType.Unknown, Environment = new Environment(), Steps = { new Step(), }, CurrentState = JobState.Unknown, CurrentStateTime = new wkt::Timestamp(), RequestedState = JobState.Stopped, ExecutionInfo = new JobExecutionInfo(), CreateTime = new wkt::Timestamp(), ReplaceJobId = "replace_job_id4a0fad7e", TransformNameMapping = { { "key8a0b6e3c", "value60c16320" }, }, ClientRequestId = "client_request_ide162ec50", ReplacedByJobId = "replaced_by_job_ida56afc22", TempFiles = { "temp_filescb023328", }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Location = "locatione09d18d5", PipelineDescription = new PipelineDescription(), StageStates = { new ExecutionStageState(), }, JobMetadata = new JobMetadata(), StartTime = new wkt::Timestamp(), CreatedFromSnapshotId = "created_from_snapshot_id9b426c65", StepsLocation = "steps_location41e078c5", SatisfiesPzs = false, }; mockGrpcClient.Setup(x => x.GetJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.GetJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.GetJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateJobRequestObject() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); UpdateJobRequest request = new UpdateJobRequest { ProjectId = "project_id43ad98b0", JobId = "job_id38ea97d6", Job = new Job(), Location = "locatione09d18d5", }; Job expectedResponse = new Job { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", Name = "name1c9368b0", Type = JobType.Unknown, Environment = new Environment(), Steps = { new Step(), }, CurrentState = JobState.Unknown, CurrentStateTime = new wkt::Timestamp(), RequestedState = JobState.Stopped, ExecutionInfo = new JobExecutionInfo(), CreateTime = new wkt::Timestamp(), ReplaceJobId = "replace_job_id4a0fad7e", TransformNameMapping = { { "key8a0b6e3c", "value60c16320" }, }, ClientRequestId = "client_request_ide162ec50", ReplacedByJobId = "replaced_by_job_ida56afc22", TempFiles = { "temp_filescb023328", }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Location = "locatione09d18d5", PipelineDescription = new PipelineDescription(), StageStates = { new ExecutionStageState(), }, JobMetadata = new JobMetadata(), StartTime = new wkt::Timestamp(), CreatedFromSnapshotId = "created_from_snapshot_id9b426c65", StepsLocation = "steps_location41e078c5", SatisfiesPzs = false, }; mockGrpcClient.Setup(x => x.UpdateJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Job response = client.UpdateJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateJobRequestObjectAsync() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); UpdateJobRequest request = new UpdateJobRequest { ProjectId = "project_id43ad98b0", JobId = "job_id38ea97d6", Job = new Job(), Location = "locatione09d18d5", }; Job expectedResponse = new Job { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", Name = "name1c9368b0", Type = JobType.Unknown, Environment = new Environment(), Steps = { new Step(), }, CurrentState = JobState.Unknown, CurrentStateTime = new wkt::Timestamp(), RequestedState = JobState.Stopped, ExecutionInfo = new JobExecutionInfo(), CreateTime = new wkt::Timestamp(), ReplaceJobId = "replace_job_id4a0fad7e", TransformNameMapping = { { "key8a0b6e3c", "value60c16320" }, }, ClientRequestId = "client_request_ide162ec50", ReplacedByJobId = "replaced_by_job_ida56afc22", TempFiles = { "temp_filescb023328", }, Labels = { { "key8a0b6e3c", "value60c16320" }, }, Location = "locatione09d18d5", PipelineDescription = new PipelineDescription(), StageStates = { new ExecutionStageState(), }, JobMetadata = new JobMetadata(), StartTime = new wkt::Timestamp(), CreatedFromSnapshotId = "created_from_snapshot_id9b426c65", StepsLocation = "steps_location41e078c5", SatisfiesPzs = false, }; mockGrpcClient.Setup(x => x.UpdateJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Job>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Job responseCallSettings = await client.UpdateJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Job responseCancellationToken = await client.UpdateJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CheckActiveJobsRequestObject() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "project_id43ad98b0", }; CheckActiveJobsResponse expectedResponse = new CheckActiveJobsResponse { ActiveJobsExist = false, }; mockGrpcClient.Setup(x => x.CheckActiveJobs(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); CheckActiveJobsResponse response = client.CheckActiveJobs(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CheckActiveJobsRequestObjectAsync() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "project_id43ad98b0", }; CheckActiveJobsResponse expectedResponse = new CheckActiveJobsResponse { ActiveJobsExist = false, }; mockGrpcClient.Setup(x => x.CheckActiveJobsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CheckActiveJobsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); CheckActiveJobsResponse responseCallSettings = await client.CheckActiveJobsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CheckActiveJobsResponse responseCancellationToken = await client.CheckActiveJobsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SnapshotJobRequestObject() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); SnapshotJobRequest request = new SnapshotJobRequest { ProjectId = "project_id43ad98b0", JobId = "job_id38ea97d6", Ttl = new wkt::Duration(), Location = "locatione09d18d5", SnapshotSources = false, Description = "description2cf9da67", }; Snapshot expectedResponse = new Snapshot { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", SourceJobId = "source_job_id1406915d", CreationTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), State = SnapshotState.UnknownSnapshotState, PubsubMetadata = { new PubsubSnapshotMetadata(), }, Description = "description2cf9da67", DiskSizeBytes = -5516951742914183668L, Region = "regionedb20d96", }; mockGrpcClient.Setup(x => x.SnapshotJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Snapshot response = client.SnapshotJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SnapshotJobRequestObjectAsync() { moq::Mock<JobsV1Beta3.JobsV1Beta3Client> mockGrpcClient = new moq::Mock<JobsV1Beta3.JobsV1Beta3Client>(moq::MockBehavior.Strict); SnapshotJobRequest request = new SnapshotJobRequest { ProjectId = "project_id43ad98b0", JobId = "job_id38ea97d6", Ttl = new wkt::Duration(), Location = "locatione09d18d5", SnapshotSources = false, Description = "description2cf9da67", }; Snapshot expectedResponse = new Snapshot { Id = "id74b70bb8", ProjectId = "project_id43ad98b0", SourceJobId = "source_job_id1406915d", CreationTime = new wkt::Timestamp(), Ttl = new wkt::Duration(), State = SnapshotState.UnknownSnapshotState, PubsubMetadata = { new PubsubSnapshotMetadata(), }, Description = "description2cf9da67", DiskSizeBytes = -5516951742914183668L, Region = "regionedb20d96", }; mockGrpcClient.Setup(x => x.SnapshotJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Snapshot>(stt::Task.FromResult(expectedResponse), null, null, null, null)); JobsV1Beta3Client client = new JobsV1Beta3ClientImpl(mockGrpcClient.Object, null); Snapshot responseCallSettings = await client.SnapshotJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Snapshot responseCancellationToken = await client.SnapshotJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
//------------------------------------------------------------------------------ // <copyright file="XmlAttribute.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml { using System; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; // Represents an attribute of the XMLElement object. Valid and default // values for the attribute are defined in a DTD or schema. public class XmlAttribute : XmlNode { XmlName name; XmlLinkedNode lastChild; internal XmlAttribute( XmlName name, XmlDocument doc ): base( doc ) { Debug.Assert(name!=null); Debug.Assert(doc!=null); this.parentNode = null; if ( !doc.IsLoading ) { XmlDocument.CheckName( name.Prefix ); XmlDocument.CheckName( name.LocalName ); } if (name.LocalName.Length == 0) throw new ArgumentException(Res.GetString(Res.Xdom_Attr_Name)); this.name = name; } internal int LocalNameHash { get { return name.HashCode; } } protected internal XmlAttribute( string prefix, string localName, string namespaceURI, XmlDocument doc ) : this(doc.AddAttrXmlName(prefix, localName, namespaceURI, null), doc) { } internal XmlName XmlName { get { return name; } set { name = value; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { // CloneNode for attributes is deep irrespective of parameter 'deep' value Debug.Assert( OwnerDocument != null ); XmlDocument doc = OwnerDocument; XmlAttribute attr = doc.CreateAttribute( Prefix, LocalName, NamespaceURI ); attr.CopyChildren( doc, this, true ); return attr; } // Gets the parent of this node (for nodes that can have parents). public override XmlNode ParentNode { get { return null;} } // Gets the name of the node. public override String Name { get { return name.Name;} } // Gets the name of the node without the namespace prefix. public override String LocalName { get { return name.LocalName;} } // Gets the namespace URI of this node. public override String NamespaceURI { get { return name.NamespaceURI;} } // Gets or sets the namespace prefix of this node. public override String Prefix { get { return name.Prefix;} set { name = name.OwnerDocument.AddAttrXmlName( value, LocalName, NamespaceURI, SchemaInfo ); } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Attribute;} } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return name.OwnerDocument; } } // Gets or sets the value of the node. public override String Value { get { return InnerText; } set { InnerText = value; } //use InnerText which has perf optimization } public override IXmlSchemaInfo SchemaInfo { get { return name; } } public override String InnerText { set { if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = base.InnerText; base.InnerText = value; ResetOwnerElementInElementIdAttrMap(innerText); } else { base.InnerText = value; } } } internal bool PrepareOwnerElementInElementIdAttrMap() { XmlDocument ownerDocument = OwnerDocument; if (ownerDocument.DtdSchemaInfo != null) { // DTD exists XmlElement ownerElement = OwnerElement; if (ownerElement != null) { return ownerElement.Attributes.PrepareParentInElementIdAttrMap(Prefix, LocalName); } } return false; } internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText) { XmlElement ownerElement = OwnerElement; if (ownerElement != null) { ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText); } } internal override bool IsContainer { get { return true;} } //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad( newChild, this ); if (args != null) doc.BeforeEvent( args ); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (lastChild == null) { // if LastNode == null newNode.next = newNode; lastChild = newNode; newNode.SetParentForLoad(this); } else { XmlLinkedNode refNode = lastChild; // refNode = LastNode; newNode.next = refNode.next; refNode.next = newNode; lastChild = newNode; // LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent( args ); return newNode; } internal override XmlLinkedNode LastNode { get { return lastChild;} set { lastChild = value;} } internal override bool IsValidChildType( XmlNodeType type ) { return(type == XmlNodeType.Text) || (type == XmlNodeType.EntityReference); } // Gets a value indicating whether the value was explicitly set. public virtual bool Specified { get { return true;} } public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.InsertBefore(newChild, refChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.InsertBefore(newChild, refChild); } return node; } public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.InsertAfter(newChild, refChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.InsertAfter(newChild, refChild); } return node; } public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.ReplaceChild(newChild, oldChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.ReplaceChild(newChild, oldChild); } return node; } public override XmlNode RemoveChild(XmlNode oldChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.RemoveChild(oldChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.RemoveChild(oldChild); } return node; } public override XmlNode PrependChild(XmlNode newChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.PrependChild(newChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.PrependChild(newChild); } return node; } public override XmlNode AppendChild(XmlNode newChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.AppendChild(newChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.AppendChild(newChild); } return node; } // DOM Level 2 // Gets the XmlElement node that contains this attribute. public virtual XmlElement OwnerElement { get { return parentNode as XmlElement; } } // Gets or sets the markup representing just the children of this node. public override string InnerXml { set { RemoveAll(); XmlLoader loader = new XmlLoader(); loader.LoadInnerXmlAttribute( this, value ); } } // Saves the node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteStartAttribute( Prefix, LocalName, NamespaceURI ); WriteContentTo(w); w.WriteEndAttribute(); } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { for (XmlNode node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } } public override String BaseURI { get { if ( OwnerElement != null ) return OwnerElement.BaseURI; return String.Empty; } } internal override void SetParent(XmlNode node) { this.parentNode = node; } internal override XmlSpace XmlSpace { get { if ( OwnerElement != null ) return OwnerElement.XmlSpace; return XmlSpace.None; } } internal override String XmlLang { get { if ( OwnerElement != null ) return OwnerElement.XmlLang; return String.Empty; } } internal override XPathNodeType XPNodeType { get { if (IsNamespace) { return XPathNodeType.Namespace; } return XPathNodeType.Attribute; } } internal override string XPLocalName { get { if (name.Prefix.Length == 0 && name.LocalName == "xmlns") return string.Empty; return name.LocalName; } } internal bool IsNamespace { get { return Ref.Equal(name.NamespaceURI, name.OwnerDocument.strReservedXmlns); } } } }
using System; using System.Collections; using System.Reflection; using System.Text; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Python.Runtime { using MaybeMethodBase = MaybeMethodBase<MethodBase>; /// <summary> /// A MethodBinder encapsulates information about a (possibly overloaded) /// managed method, and is responsible for selecting the right method given /// a set of Python arguments. This is also used as a base class for the /// ConstructorBinder, a minor variation used to invoke constructors. /// </summary> [Serializable] internal class MethodBinder { /// <summary> /// The overloads of this method /// </summary> public List<MaybeMethodBase> list; [NonSerialized] public MethodBase[]? methods; [NonSerialized] public bool init = false; public const bool DefaultAllowThreads = true; public bool allow_threads = DefaultAllowThreads; internal MethodBinder() { list = new List<MaybeMethodBase>(); } internal MethodBinder(MethodInfo mi) { list = new List<MaybeMethodBase> { new MaybeMethodBase(mi) }; } public int Count { get { return list.Count; } } internal void AddMethod(MethodBase m) { list.Add(m); } /// <summary> /// Given a sequence of MethodInfo and a sequence of types, return the /// MethodInfo that matches the signature represented by those types. /// </summary> internal static MethodBase? MatchSignature(MethodBase[] mi, Type[] tp) { if (tp == null) { return null; } int count = tp.Length; foreach (MethodBase t in mi) { ParameterInfo[] pi = t.GetParameters(); if (pi.Length != count) { continue; } for (var n = 0; n < pi.Length; n++) { if (tp[n] != pi[n].ParameterType) { break; } if (n == pi.Length - 1) { return t; } } } return null; } /// <summary> /// Given a sequence of MethodInfo and a sequence of type parameters, /// return the MethodInfo(s) that represents the matching closed generic. /// If unsuccessful, returns null and may set a Python error. /// </summary> internal static MethodInfo[] MatchParameters(MethodBase[] mi, Type[]? tp) { if (tp == null) { return Array.Empty<MethodInfo>(); } int count = tp.Length; var result = new List<MethodInfo>(); foreach (MethodInfo t in mi) { if (!t.IsGenericMethodDefinition) { continue; } Type[] args = t.GetGenericArguments(); if (args.Length != count) { continue; } try { // MakeGenericMethod can throw ArgumentException if the type parameters do not obey the constraints. MethodInfo method = t.MakeGenericMethod(tp); result.Add(method); } catch (ArgumentException) { // The error will remain set until cleared by a successful match. } } return result.ToArray(); } /// <summary> /// Given a sequence of MethodInfo and two sequences of type parameters, /// return the MethodInfo that matches the signature and the closed generic. /// </summary> internal static MethodInfo? MatchSignatureAndParameters(MethodBase[] mi, Type[] genericTp, Type[] sigTp) { if (genericTp == null || sigTp == null) { return null; } int genericCount = genericTp.Length; int signatureCount = sigTp.Length; foreach (MethodInfo t in mi) { if (!t.IsGenericMethodDefinition) { continue; } Type[] genericArgs = t.GetGenericArguments(); if (genericArgs.Length != genericCount) { continue; } ParameterInfo[] pi = t.GetParameters(); if (pi.Length != signatureCount) { continue; } for (var n = 0; n < pi.Length; n++) { if (sigTp[n] != pi[n].ParameterType) { break; } if (n == pi.Length - 1) { MethodInfo match = t; if (match.IsGenericMethodDefinition) { // FIXME: typeArgs not used Type[] typeArgs = match.GetGenericArguments(); return match.MakeGenericMethod(genericTp); } return match; } } } return null; } /// <summary> /// Return the array of MethodInfo for this method. The result array /// is arranged in order of precedence (done lazily to avoid doing it /// at all for methods that are never called). /// </summary> internal MethodBase[] GetMethods() { if (!init) { // I'm sure this could be made more efficient. list.Sort(new MethodSorter()); methods = (from method in list where method.Valid select method.Value).ToArray(); init = true; } return methods!; } /// <summary> /// Precedence algorithm largely lifted from Jython - the concerns are /// generally the same so we'll start with this and tweak as necessary. /// </summary> /// <remarks> /// Based from Jython `org.python.core.ReflectedArgs.precedence` /// See: https://github.com/jythontools/jython/blob/master/src/org/python/core/ReflectedArgs.java#L192 /// </remarks> internal static int GetPrecedence(MethodBase mi) { if (mi == null) { return int.MaxValue; } ParameterInfo[] pi = mi.GetParameters(); int val = mi.IsStatic ? 3000 : 0; int num = pi.Length; val += mi.IsGenericMethod ? 1 : 0; for (var i = 0; i < num; i++) { val += ArgPrecedence(pi[i].ParameterType); } return val; } /// <summary> /// Return a precedence value for a particular Type object. /// </summary> internal static int ArgPrecedence(Type t) { Type objectType = typeof(object); if (t == objectType) { return 3000; } if (t.IsArray) { Type e = t.GetElementType(); if (e == objectType) { return 2500; } return 100 + ArgPrecedence(e); } TypeCode tc = Type.GetTypeCode(t); // TODO: Clean up switch (tc) { case TypeCode.Object: return 1; case TypeCode.UInt64: return 10; case TypeCode.UInt32: return 11; case TypeCode.UInt16: return 12; case TypeCode.Int64: return 13; case TypeCode.Int32: return 14; case TypeCode.Int16: return 15; case TypeCode.Char: return 16; case TypeCode.SByte: return 17; case TypeCode.Byte: return 18; case TypeCode.Single: return 20; case TypeCode.Double: return 21; case TypeCode.String: return 30; case TypeCode.Boolean: return 40; } return 2000; } /// <summary> /// Bind the given Python instance and arguments to a particular method /// overload in <see cref="list"/> and return a structure that contains the converted Python /// instance, converted arguments and the correct method to call. /// If unsuccessful, may set a Python error. /// </summary> /// <param name="inst">The Python target of the method invocation.</param> /// <param name="args">The Python arguments.</param> /// <param name="kw">The Python keyword arguments.</param> /// <returns>A Binding if successful. Otherwise null.</returns> internal Binding? Bind(BorrowedReference inst, BorrowedReference args, BorrowedReference kw) { return Bind(inst, args, kw, null, null); } /// <summary> /// Bind the given Python instance and arguments to a particular method /// overload in <see cref="list"/> and return a structure that contains the converted Python /// instance, converted arguments and the correct method to call. /// If unsuccessful, may set a Python error. /// </summary> /// <param name="inst">The Python target of the method invocation.</param> /// <param name="args">The Python arguments.</param> /// <param name="kw">The Python keyword arguments.</param> /// <param name="info">If not null, only bind to that method.</param> /// <returns>A Binding if successful. Otherwise null.</returns> internal Binding? Bind(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase? info) { return Bind(inst, args, kw, info, null); } private readonly struct MatchedMethod { public MatchedMethod(int kwargsMatched, int defaultsNeeded, object?[] margs, int outs, MethodBase mb) { KwargsMatched = kwargsMatched; DefaultsNeeded = defaultsNeeded; ManagedArgs = margs; Outs = outs; Method = mb; } public int KwargsMatched { get; } public int DefaultsNeeded { get; } public object?[] ManagedArgs { get; } public int Outs { get; } public MethodBase Method { get; } } private readonly struct MismatchedMethod { public MismatchedMethod(Exception exception, MethodBase mb) { Exception = exception; Method = mb; } public Exception Exception { get; } public MethodBase Method { get; } } /// <summary> /// Bind the given Python instance and arguments to a particular method /// overload in <see cref="list"/> and return a structure that contains the converted Python /// instance, converted arguments and the correct method to call. /// If unsuccessful, may set a Python error. /// </summary> /// <param name="inst">The Python target of the method invocation.</param> /// <param name="args">The Python arguments.</param> /// <param name="kw">The Python keyword arguments.</param> /// <param name="info">If not null, only bind to that method.</param> /// <param name="methodinfo">If not null, additionally attempt to bind to the generic methods in this array by inferring generic type parameters.</param> /// <returns>A Binding if successful. Otherwise null.</returns> internal Binding? Bind(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase? info, MethodBase[]? methodinfo) { // loop to find match, return invoker w/ or w/o error var kwargDict = new Dictionary<string, PyObject>(); if (kw != null) { nint pynkwargs = Runtime.PyDict_Size(kw); using var keylist = Runtime.PyDict_Keys(kw); using var valueList = Runtime.PyDict_Values(kw); for (int i = 0; i < pynkwargs; ++i) { var keyStr = Runtime.GetManagedString(Runtime.PyList_GetItem(keylist.Borrow(), i)); BorrowedReference value = Runtime.PyList_GetItem(valueList.Borrow(), i); kwargDict[keyStr!] = new PyObject(value); } } MethodBase[] _methods; if (info != null) { _methods = new MethodBase[1]; _methods.SetValue(info, 0); } else { _methods = GetMethods(); } return Bind(inst, args, kwargDict, _methods, matchGenerics: true); } static Binding? Bind(BorrowedReference inst, BorrowedReference args, Dictionary<string, PyObject> kwargDict, MethodBase[] methods, bool matchGenerics) { var pynargs = (int)Runtime.PyTuple_Size(args); var isGeneric = false; var argMatchedMethods = new List<MatchedMethod>(methods.Length); var mismatchedMethods = new List<MismatchedMethod>(); // TODO: Clean up foreach (MethodBase mi in methods) { if (mi.IsGenericMethod) { isGeneric = true; } ParameterInfo[] pi = mi.GetParameters(); ArrayList? defaultArgList; bool paramsArray; int kwargsMatched; int defaultsNeeded; bool isOperator = OperatorMethod.IsOperatorMethod(mi); // Binary operator methods will have 2 CLR args but only one Python arg // (unary operators will have 1 less each), since Python operator methods are bound. isOperator = isOperator && pynargs == pi.Length - 1; bool isReverse = isOperator && OperatorMethod.IsReverse((MethodInfo)mi); // Only cast if isOperator. if (isReverse && OperatorMethod.IsComparisonOp((MethodInfo)mi)) continue; // Comparison operators in Python have no reverse mode. if (!MatchesArgumentCount(pynargs, pi, kwargDict, out paramsArray, out defaultArgList, out kwargsMatched, out defaultsNeeded) && !isOperator) { continue; } // Preprocessing pi to remove either the first or second argument. if (isOperator && !isReverse) { // The first Python arg is the right operand, while the bound instance is the left. // We need to skip the first (left operand) CLR argument. pi = pi.Skip(1).ToArray(); } else if (isOperator && isReverse) { // The first Python arg is the left operand. // We need to take the first CLR argument. pi = pi.Take(1).ToArray(); } int outs; var margs = TryConvertArguments(pi, paramsArray, args, pynargs, kwargDict, defaultArgList, outs: out outs); if (margs == null) { var mismatchCause = PythonException.FetchCurrent(); mismatchedMethods.Add(new MismatchedMethod(mismatchCause, mi)); continue; } if (isOperator) { if (inst != null) { if (ManagedType.GetManagedObject(inst) is CLRObject co) { bool isUnary = pynargs == 0; // Postprocessing to extend margs. var margsTemp = isUnary ? new object?[1] : new object?[2]; // If reverse, the bound instance is the right operand. int boundOperandIndex = isReverse ? 1 : 0; // If reverse, the passed instance is the left operand. int passedOperandIndex = isReverse ? 0 : 1; margsTemp[boundOperandIndex] = co.inst; if (!isUnary) { margsTemp[passedOperandIndex] = margs[0]; } margs = margsTemp; } else continue; } } var matchedMethod = new MatchedMethod(kwargsMatched, defaultsNeeded, margs, outs, mi); argMatchedMethods.Add(matchedMethod); } if (argMatchedMethods.Count > 0) { var bestKwargMatchCount = argMatchedMethods.Max(x => x.KwargsMatched); var fewestDefaultsRequired = argMatchedMethods.Where(x => x.KwargsMatched == bestKwargMatchCount).Min(x => x.DefaultsNeeded); int bestCount = 0; int bestMatchIndex = -1; for (int index = 0; index < argMatchedMethods.Count; index++) { var testMatch = argMatchedMethods[index]; if (testMatch.DefaultsNeeded == fewestDefaultsRequired && testMatch.KwargsMatched == bestKwargMatchCount) { bestCount++; if (bestMatchIndex == -1) bestMatchIndex = index; } } if (bestCount > 1 && fewestDefaultsRequired > 0) { // Best effort for determining method to match on gives multiple possible // matches and we need at least one default argument - bail from this point StringBuilder stringBuilder = new StringBuilder("Not enough arguments provided to disambiguate the method. Found:"); foreach (var matchedMethod in argMatchedMethods) { stringBuilder.AppendLine(); stringBuilder.Append(matchedMethod.Method.ToString()); } Exceptions.SetError(Exceptions.TypeError, stringBuilder.ToString()); return null; } // If we're here either: // (a) There is only one best match // (b) There are multiple best matches but none of them require // default arguments // in the case of (a) we're done by default. For (b) regardless of which // method we choose, all arguments are specified _and_ can be converted // from python to C# so picking any will suffice MatchedMethod bestMatch = argMatchedMethods[bestMatchIndex]; var margs = bestMatch.ManagedArgs; var outs = bestMatch.Outs; var mi = bestMatch.Method; object? target = null; if (!mi.IsStatic && inst != null) { //CLRObject co = (CLRObject)ManagedType.GetManagedObject(inst); // InvalidCastException: Unable to cast object of type // 'Python.Runtime.ClassObject' to type 'Python.Runtime.CLRObject' var co = ManagedType.GetManagedObject(inst) as CLRObject; // Sanity check: this ensures a graceful exit if someone does // something intentionally wrong like call a non-static method // on the class rather than on an instance of the class. // XXX maybe better to do this before all the other rigmarole. if (co == null) { Exceptions.SetError(Exceptions.TypeError, "Invoked a non-static method with an invalid instance"); return null; } target = co.inst; } return new Binding(mi, target, margs, outs); } else if (matchGenerics && isGeneric) { // We weren't able to find a matching method but at least one // is a generic method and info is null. That happens when a generic // method was not called using the [] syntax. Let's introspect the // type of the arguments and use it to construct the correct method. Type[]? types = Runtime.PythonArgsToTypeArray(args, true); MethodInfo[] overloads = MatchParameters(methods, types); if (overloads.Length != 0) { return Bind(inst, args, kwargDict, overloads, matchGenerics: false); } } if (mismatchedMethods.Count > 0) { var aggregateException = GetAggregateException(mismatchedMethods); Exceptions.SetError(aggregateException); } return null; } static AggregateException GetAggregateException(IEnumerable<MismatchedMethod> mismatchedMethods) { return new AggregateException(mismatchedMethods.Select(m => new ArgumentException($"{m.Exception.Message} in method {m.Method}", m.Exception))); } static BorrowedReference HandleParamsArray(BorrowedReference args, int arrayStart, int pyArgCount, out NewReference tempObject) { BorrowedReference op; tempObject = default; // for a params method, we may have a sequence or single/multiple items // here we look to see if the item at the paramIndex is there or not // and then if it is a sequence itself. if ((pyArgCount - arrayStart) == 1) { // we only have one argument left, so we need to check it // to see if it is a sequence or a single item BorrowedReference item = Runtime.PyTuple_GetItem(args, arrayStart); if (!Runtime.PyString_Check(item) && Runtime.PySequence_Check(item)) { // it's a sequence (and not a string), so we use it as the op op = item; } else { tempObject = Runtime.PyTuple_GetSlice(args, arrayStart, pyArgCount); op = tempObject.Borrow(); } } else { tempObject = Runtime.PyTuple_GetSlice(args, arrayStart, pyArgCount); op = tempObject.Borrow(); } return op; } /// <summary> /// Attempts to convert Python positional argument tuple and keyword argument table /// into an array of managed objects, that can be passed to a method. /// If unsuccessful, returns null and may set a Python error. /// </summary> /// <param name="pi">Information about expected parameters</param> /// <param name="paramsArray"><c>true</c>, if the last parameter is a params array.</param> /// <param name="args">A pointer to the Python argument tuple</param> /// <param name="pyArgCount">Number of arguments, passed by Python</param> /// <param name="kwargDict">Dictionary of keyword argument name to python object pointer</param> /// <param name="defaultArgList">A list of default values for omitted parameters</param> /// <param name="needsResolution"><c>true</c>, if overloading resolution is required</param> /// <param name="outs">Returns number of output parameters</param> /// <returns>If successful, an array of .NET arguments that can be passed to the method. Otherwise null.</returns> static object?[]? TryConvertArguments(ParameterInfo[] pi, bool paramsArray, BorrowedReference args, int pyArgCount, Dictionary<string, PyObject> kwargDict, ArrayList? defaultArgList, out int outs) { outs = 0; var margs = new object?[pi.Length]; int arrayStart = paramsArray ? pi.Length - 1 : -1; for (int paramIndex = 0; paramIndex < pi.Length; paramIndex++) { var parameter = pi[paramIndex]; bool hasNamedParam = parameter.Name != null ? kwargDict.ContainsKey(parameter.Name) : false; if (paramIndex >= pyArgCount && !(hasNamedParam || (paramsArray && paramIndex == arrayStart))) { if (defaultArgList != null) { margs[paramIndex] = defaultArgList[paramIndex - pyArgCount]; } if (parameter.ParameterType.IsByRef) { outs++; } continue; } BorrowedReference op; NewReference tempObject = default; if (hasNamedParam) { op = kwargDict[parameter.Name!]; } else { if(arrayStart == paramIndex) { op = HandleParamsArray(args, arrayStart, pyArgCount, out tempObject); } else { op = Runtime.PyTuple_GetItem(args, paramIndex); } } bool isOut; if (!TryConvertArgument(op, parameter.ParameterType, out margs[paramIndex], out isOut)) { tempObject.Dispose(); return null; } tempObject.Dispose(); if (isOut) { outs++; } } return margs; } /// <summary> /// Try to convert a Python argument object to a managed CLR type. /// If unsuccessful, may set a Python error. /// </summary> /// <param name="op">Pointer to the Python argument object.</param> /// <param name="parameterType">That parameter's managed type.</param> /// <param name="arg">Converted argument.</param> /// <param name="isOut">Whether the CLR type is passed by reference.</param> /// <returns>true on success</returns> static bool TryConvertArgument(BorrowedReference op, Type parameterType, out object? arg, out bool isOut) { arg = null; isOut = false; var clrtype = TryComputeClrArgumentType(parameterType, op); if (clrtype == null) { return false; } if (!Converter.ToManaged(op, clrtype, out arg, true)) { return false; } isOut = clrtype.IsByRef; return true; } /// <summary> /// Determine the managed type that a Python argument object needs to be converted into. /// </summary> /// <param name="parameterType">The parameter's managed type.</param> /// <param name="argument">Pointer to the Python argument object.</param> /// <returns>null if conversion is not possible</returns> static Type? TryComputeClrArgumentType(Type parameterType, BorrowedReference argument) { // this logic below handles cases when multiple overloading methods // are ambiguous, hence comparison between Python and CLR types // is necessary Type? clrtype = null; if (clrtype != null) { if ((parameterType != typeof(object)) && (parameterType != clrtype)) { BorrowedReference pytype = Converter.GetPythonTypeByAlias(parameterType); BorrowedReference pyoptype = Runtime.PyObject_TYPE(argument); var typematch = false; if (pyoptype != null) { if (pytype != pyoptype) { typematch = false; } else { typematch = true; clrtype = parameterType; } } if (!typematch) { // this takes care of enum values TypeCode parameterTypeCode = Type.GetTypeCode(parameterType); TypeCode clrTypeCode = Type.GetTypeCode(clrtype); if (parameterTypeCode == clrTypeCode) { typematch = true; clrtype = parameterType; } else { Exceptions.RaiseTypeError($"Expected {parameterTypeCode}, got {clrTypeCode}"); } } if (!typematch) { return null; } } else { clrtype = parameterType; } } else { clrtype = parameterType; } return clrtype; } /// <summary> /// Check whether the number of Python and .NET arguments match, and compute additional arg information. /// </summary> /// <param name="positionalArgumentCount">Number of positional args passed from Python.</param> /// <param name="parameters">Parameters of the specified .NET method.</param> /// <param name="kwargDict">Keyword args passed from Python.</param> /// <param name="paramsArray">True if the final param of the .NET method is an array (`params` keyword).</param> /// <param name="defaultArgList">List of default values for arguments.</param> /// <param name="kwargsMatched">Number of kwargs from Python that are also present in the .NET method.</param> /// <param name="defaultsNeeded">Number of non-null defaultsArgs.</param> /// <returns></returns> static bool MatchesArgumentCount(int positionalArgumentCount, ParameterInfo[] parameters, Dictionary<string, PyObject> kwargDict, out bool paramsArray, out ArrayList? defaultArgList, out int kwargsMatched, out int defaultsNeeded) { defaultArgList = null; var match = false; paramsArray = parameters.Length > 0 ? Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute)) : false; kwargsMatched = 0; defaultsNeeded = 0; if (positionalArgumentCount == parameters.Length && kwargDict.Count == 0) { match = true; } else if (positionalArgumentCount < parameters.Length && (!paramsArray || positionalArgumentCount == parameters.Length - 1)) { match = true; // every parameter past 'positionalArgumentCount' must have either // a corresponding keyword arg or a default param, unless the method // method accepts a params array (which cannot have a default value) defaultArgList = new ArrayList(); for (var v = positionalArgumentCount; v < parameters.Length; v++) { if (kwargDict.ContainsKey(parameters[v].Name)) { // we have a keyword argument for this parameter, // no need to check for a default parameter, but put a null // placeholder in defaultArgList defaultArgList.Add(null); kwargsMatched++; } else if (parameters[v].IsOptional) { // IsOptional will be true if the parameter has a default value, // or if the parameter has the [Optional] attribute specified. // The GetDefaultValue() extension method will return the value // to be passed in as the parameter value defaultArgList.Add(parameters[v].GetDefaultValue()); defaultsNeeded++; } else if (parameters[v].IsOut) { defaultArgList.Add(null); } else if (!paramsArray) { match = false; } } } else if (positionalArgumentCount > parameters.Length && parameters.Length > 0 && Attribute.IsDefined(parameters[parameters.Length - 1], typeof(ParamArrayAttribute))) { // This is a `foo(params object[] bar)` style method match = true; paramsArray = true; } return match; } internal virtual NewReference Invoke(BorrowedReference inst, BorrowedReference args, BorrowedReference kw) { return Invoke(inst, args, kw, null, null); } internal virtual NewReference Invoke(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase? info) { return Invoke(inst, args, kw, info, null); } protected static void AppendArgumentTypes(StringBuilder to, BorrowedReference args) { Runtime.AssertNoErorSet(); nint argCount = Runtime.PyTuple_Size(args); to.Append("("); for (nint argIndex = 0; argIndex < argCount; argIndex++) { BorrowedReference arg = Runtime.PyTuple_GetItem(args, argIndex); if (arg != null) { BorrowedReference type = Runtime.PyObject_TYPE(arg); if (type != null) { using var description = Runtime.PyObject_Str(type); if (description.IsNull()) { Exceptions.Clear(); to.Append(Util.BadStr); } else { to.Append(Runtime.GetManagedString(description.Borrow())); } } } if (argIndex + 1 < argCount) to.Append(", "); } to.Append(')'); } internal virtual NewReference Invoke(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase? info, MethodBase[]? methodinfo) { // No valid methods, nothing to bind. if (GetMethods().Length == 0) { var msg = new StringBuilder("The underlying C# method(s) have been deleted"); if (list.Count > 0 && list[0].Name != null) { msg.Append($": {list[0]}"); } return Exceptions.RaiseTypeError(msg.ToString()); } Binding? binding = Bind(inst, args, kw, info, methodinfo); object result; IntPtr ts = IntPtr.Zero; if (binding == null) { var value = new StringBuilder("No method matches given arguments"); if (methodinfo != null && methodinfo.Length > 0) { value.Append($" for {methodinfo[0].DeclaringType?.Name}.{methodinfo[0].Name}"); } else if (list.Count > 0 && list[0].Valid) { value.Append($" for {list[0].Value.DeclaringType?.Name}.{list[0].Value.Name}"); } value.Append(": "); Runtime.PyErr_Fetch(out var errType, out var errVal, out var errTrace); AppendArgumentTypes(to: value, args); Runtime.PyErr_Restore(errType.StealNullable(), errVal.StealNullable(), errTrace.StealNullable()); return Exceptions.RaiseTypeError(value.ToString()); } if (allow_threads) { ts = PythonEngine.BeginAllowThreads(); } try { result = binding.info.Invoke(binding.inst, BindingFlags.Default, null, binding.args, null); } catch (Exception e) { if (e.InnerException != null) { e = e.InnerException; } if (allow_threads) { PythonEngine.EndAllowThreads(ts); } Exceptions.SetError(e); return default; } if (allow_threads) { PythonEngine.EndAllowThreads(ts); } // If there are out parameters, we return a tuple containing // the result, if any, followed by the out parameters. If there is only // one out parameter and the return type of the method is void, // we return the out parameter as the result to Python (for // code compatibility with ironpython). var returnType = binding.info.IsConstructor ? typeof(void) : ((MethodInfo)binding.info).ReturnType; if (binding.outs > 0) { ParameterInfo[] pi = binding.info.GetParameters(); int c = pi.Length; var n = 0; bool isVoid = returnType == typeof(void); int tupleSize = binding.outs + (isVoid ? 0 : 1); using var t = Runtime.PyTuple_New(tupleSize); if (!isVoid) { using var v = Converter.ToPython(result, returnType); Runtime.PyTuple_SetItem(t.Borrow(), n, v.Steal()); n++; } for (var i = 0; i < c; i++) { Type pt = pi[i].ParameterType; if (pt.IsByRef) { using var v = Converter.ToPython(binding.args[i], pt.GetElementType()); Runtime.PyTuple_SetItem(t.Borrow(), n, v.Steal()); n++; } } if (binding.outs == 1 && returnType == typeof(void)) { BorrowedReference item = Runtime.PyTuple_GetItem(t.Borrow(), 0); return new NewReference(item); } return new NewReference(t.Borrow()); } return Converter.ToPython(result, returnType); } } /// <summary> /// Utility class to sort method info by parameter type precedence. /// </summary> internal class MethodSorter : IComparer<MaybeMethodBase> { int IComparer<MaybeMethodBase>.Compare(MaybeMethodBase m1, MaybeMethodBase m2) { MethodBase me1 = m1.UnsafeValue; MethodBase me2 = m2.UnsafeValue; if (me1 == null && me2 == null) { return 0; } else if (me1 == null) { return -1; } else if (me2 == null) { return 1; } if (me1.DeclaringType != me2.DeclaringType) { // m2's type derives from m1's type, favor m2 if (me1.DeclaringType.IsAssignableFrom(me2.DeclaringType)) return 1; // m1's type derives from m2's type, favor m1 if (me2.DeclaringType.IsAssignableFrom(me1.DeclaringType)) return -1; } int p1 = MethodBinder.GetPrecedence(me1); int p2 = MethodBinder.GetPrecedence(me2); if (p1 < p2) { return -1; } if (p1 > p2) { return 1; } return 0; } } /// <summary> /// A Binding is a utility instance that bundles together a MethodInfo /// representing a method to call, a (possibly null) target instance for /// the call, and the arguments for the call (all as managed values). /// </summary> internal class Binding { public MethodBase info; public object?[] args; public object? inst; public int outs; internal Binding(MethodBase info, object? inst, object?[] args, int outs) { this.info = info; this.inst = inst; this.args = args; this.outs = outs; } } static internal class ParameterInfoExtensions { public static object? GetDefaultValue(this ParameterInfo parameterInfo) { // parameterInfo.HasDefaultValue is preferable but doesn't exist in .NET 4.0 bool hasDefaultValue = (parameterInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault; if (hasDefaultValue) { return parameterInfo.DefaultValue; } else { // [OptionalAttribute] was specified for the parameter. // See https://stackoverflow.com/questions/3416216/optionalattribute-parameters-default-value // for rules on determining the value to pass to the parameter var type = parameterInfo.ParameterType; if (type == typeof(object)) return Type.Missing; else if (type.IsValueType) return Activator.CreateInstance(type); else return 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Win32.SafeHandles { [System.Security.SecurityCriticalAttribute] public sealed partial class SafeAccessTokenHandle : System.Runtime.InteropServices.SafeHandle { public SafeAccessTokenHandle(System.IntPtr handle) : base(default(System.IntPtr), default(bool)) { } public static Microsoft.Win32.SafeHandles.SafeAccessTokenHandle InvalidHandle {[System.Security.SecurityCriticalAttribute]get { return default(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle); } } public override bool IsInvalid {[System.Security.SecurityCriticalAttribute]get { return default(bool); } } [System.Security.SecurityCriticalAttribute] protected override bool ReleaseHandle() { return default(bool); } } } namespace System.Security.Principal { public sealed partial class IdentityNotMappedException : System.Exception { public IdentityNotMappedException() { } public IdentityNotMappedException(string message) { } public IdentityNotMappedException(string message, System.Exception inner) { } public System.Security.Principal.IdentityReferenceCollection UnmappedIdentities { get { return default(System.Security.Principal.IdentityReferenceCollection); } } } public abstract partial class IdentityReference { internal IdentityReference() { } public abstract string Value { get; } public abstract override bool Equals(object o); public abstract override int GetHashCode(); public abstract bool IsValidTargetType(System.Type targetType); public static bool operator ==(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { return default(bool); } public static bool operator !=(System.Security.Principal.IdentityReference left, System.Security.Principal.IdentityReference right) { return default(bool); } public abstract override string ToString(); public abstract System.Security.Principal.IdentityReference Translate(System.Type targetType); } public partial class IdentityReferenceCollection : System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>, System.Collections.Generic.IEnumerable<System.Security.Principal.IdentityReference>, System.Collections.IEnumerable { public IdentityReferenceCollection() { } public IdentityReferenceCollection(int capacity) { } public int Count { get { return default(int); } } public System.Security.Principal.IdentityReference this[int index] { get { return default(System.Security.Principal.IdentityReference); } set { } } bool System.Collections.Generic.ICollection<System.Security.Principal.IdentityReference>.IsReadOnly { get { return default(bool); } } public void Add(System.Security.Principal.IdentityReference identity) { } public void Clear() { } public bool Contains(System.Security.Principal.IdentityReference identity) { return default(bool); } public void CopyTo(System.Security.Principal.IdentityReference[] array, int offset) { } public System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Security.Principal.IdentityReference>); } public bool Remove(System.Security.Principal.IdentityReference identity) { return default(bool); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReferenceCollection); } public System.Security.Principal.IdentityReferenceCollection Translate(System.Type targetType, bool forceSuccess) { return default(System.Security.Principal.IdentityReferenceCollection); } } public sealed partial class NTAccount : System.Security.Principal.IdentityReference { public NTAccount(string name) { } public NTAccount(string domainName, string accountName) { } public override string Value { get { return default(string); } } public override bool Equals(object o) { return default(bool); } public override int GetHashCode() { return default(int); } public override bool IsValidTargetType(System.Type targetType) { return default(bool); } public static bool operator ==(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { return default(bool); } public static bool operator !=(System.Security.Principal.NTAccount left, System.Security.Principal.NTAccount right) { return default(bool); } public override string ToString() { return default(string); } public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReference); } } public sealed partial class SecurityIdentifier : System.Security.Principal.IdentityReference, System.IComparable<System.Security.Principal.SecurityIdentifier> { public static readonly int MaxBinaryLength; public static readonly int MinBinaryLength; public SecurityIdentifier(byte[] binaryForm, int offset) { } public SecurityIdentifier(System.IntPtr binaryForm) { } public SecurityIdentifier(System.Security.Principal.WellKnownSidType sidType, System.Security.Principal.SecurityIdentifier domainSid) { } public SecurityIdentifier(string sddlForm) { } public System.Security.Principal.SecurityIdentifier AccountDomainSid { get { return default(System.Security.Principal.SecurityIdentifier); } } public int BinaryLength { get { return default(int); } } public override string Value { get { return default(string); } } public int CompareTo(System.Security.Principal.SecurityIdentifier sid) { return default(int); } public override bool Equals(object o) { return default(bool); } public bool Equals(System.Security.Principal.SecurityIdentifier sid) { return default(bool); } public void GetBinaryForm(byte[] binaryForm, int offset) { } public override int GetHashCode() { return default(int); } public bool IsAccountSid() { return default(bool); } public bool IsEqualDomainSid(System.Security.Principal.SecurityIdentifier sid) { return default(bool); } public override bool IsValidTargetType(System.Type targetType) { return default(bool); } public bool IsWellKnown(System.Security.Principal.WellKnownSidType type) { return default(bool); } public static bool operator ==(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { return default(bool); } public static bool operator !=(System.Security.Principal.SecurityIdentifier left, System.Security.Principal.SecurityIdentifier right) { return default(bool); } public override string ToString() { return default(string); } public override System.Security.Principal.IdentityReference Translate(System.Type targetType) { return default(System.Security.Principal.IdentityReference); } } [System.FlagsAttribute] public enum TokenAccessLevels { AdjustDefault = 128, AdjustGroups = 64, AdjustPrivileges = 32, AdjustSessionId = 256, AllAccess = 983551, AssignPrimary = 1, Duplicate = 2, Impersonate = 4, MaximumAllowed = 33554432, Query = 8, QuerySource = 16, Read = 131080, Write = 131296, } public enum WellKnownSidType { AccountAdministratorSid = 38, AccountCertAdminsSid = 46, AccountComputersSid = 44, AccountControllersSid = 45, AccountDomainAdminsSid = 41, AccountDomainGuestsSid = 43, AccountDomainUsersSid = 42, AccountEnterpriseAdminsSid = 48, AccountGuestSid = 39, AccountKrbtgtSid = 40, AccountPolicyAdminsSid = 49, AccountRasAndIasServersSid = 50, AccountSchemaAdminsSid = 47, AnonymousSid = 13, AuthenticatedUserSid = 17, BatchSid = 10, BuiltinAccountOperatorsSid = 30, BuiltinAdministratorsSid = 26, BuiltinAuthorizationAccessSid = 59, BuiltinBackupOperatorsSid = 33, BuiltinDomainSid = 25, BuiltinGuestsSid = 28, BuiltinIncomingForestTrustBuildersSid = 56, BuiltinNetworkConfigurationOperatorsSid = 37, BuiltinPerformanceLoggingUsersSid = 58, BuiltinPerformanceMonitoringUsersSid = 57, BuiltinPowerUsersSid = 29, BuiltinPreWindows2000CompatibleAccessSid = 35, BuiltinPrintOperatorsSid = 32, BuiltinRemoteDesktopUsersSid = 36, BuiltinReplicatorSid = 34, BuiltinSystemOperatorsSid = 31, BuiltinUsersSid = 27, CreatorGroupServerSid = 6, CreatorGroupSid = 4, CreatorOwnerServerSid = 5, CreatorOwnerSid = 3, DialupSid = 8, DigestAuthenticationSid = 52, EnterpriseControllersSid = 15, InteractiveSid = 11, LocalServiceSid = 23, LocalSid = 2, LocalSystemSid = 22, LogonIdsSid = 21, MaxDefined = 60, NetworkServiceSid = 24, NetworkSid = 9, NTAuthoritySid = 7, NtlmAuthenticationSid = 51, NullSid = 0, OtherOrganizationSid = 55, ProxySid = 14, RemoteLogonIdSid = 20, RestrictedCodeSid = 18, SChannelAuthenticationSid = 53, SelfSid = 16, ServiceSid = 12, TerminalServerSid = 19, ThisOrganizationSid = 54, WinBuiltinTerminalServerLicenseServersSid = 60, WorldSid = 1, } public enum WindowsBuiltInRole { AccountOperator = 548, Administrator = 544, BackupOperator = 551, Guest = 546, PowerUser = 547, PrintOperator = 550, Replicator = 552, SystemOperator = 549, User = 545, } public partial class WindowsIdentity : System.Security.Claims.ClaimsIdentity, System.IDisposable { public new const string DefaultIssuer = "AD AUTHORITY"; public WindowsIdentity(System.IntPtr userToken) { } public WindowsIdentity(System.IntPtr userToken, string type) { } public WindowsIdentity(string sUserPrincipalName) { } public Microsoft.Win32.SafeHandles.SafeAccessTokenHandle AccessToken {[System.Security.SecurityCriticalAttribute]get { return default(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle); } } public sealed override string AuthenticationType { get { return default(string); } } public override System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims { get { return default(System.Collections.Generic.IEnumerable<System.Security.Claims.Claim>); } } public System.Security.Principal.IdentityReferenceCollection Groups { get { return default(System.Security.Principal.IdentityReferenceCollection); } } public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get { return default(System.Security.Principal.TokenImpersonationLevel); } } public virtual bool IsAnonymous { get { return default(bool); } } public override bool IsAuthenticated { get { return default(bool); } } public virtual bool IsGuest { get { return default(bool); } } public virtual bool IsSystem { get { return default(bool); } } public override string Name { get { return default(string); } } public System.Security.Principal.SecurityIdentifier Owner { get { return default(System.Security.Principal.SecurityIdentifier); } } public System.Security.Principal.SecurityIdentifier User { get { return default(System.Security.Principal.SecurityIdentifier); } } public override System.Security.Claims.ClaimsIdentity Clone() { return default(System.Security.Claims.ClaimsIdentity); } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public static System.Security.Principal.WindowsIdentity GetAnonymous() { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent() { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent(bool ifImpersonating) { return default(System.Security.Principal.WindowsIdentity); } public static System.Security.Principal.WindowsIdentity GetCurrent(System.Security.Principal.TokenAccessLevels desiredAccess) { return default(System.Security.Principal.WindowsIdentity); } public static void RunImpersonated(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Action action) { } public static T RunImpersonated<T>(Microsoft.Win32.SafeHandles.SafeAccessTokenHandle safeAccessTokenHandle, System.Func<T> func) { return default(T); } } public partial class WindowsPrincipal : System.Security.Claims.ClaimsPrincipal { public WindowsPrincipal(System.Security.Principal.WindowsIdentity ntIdentity) { } public override System.Security.Principal.IIdentity Identity { get { return default(System.Security.Principal.IIdentity); } } public virtual bool IsInRole(int rid) { return default(bool); } public virtual bool IsInRole(System.Security.Principal.SecurityIdentifier sid) { return default(bool); } public virtual bool IsInRole(System.Security.Principal.WindowsBuiltInRole role) { return default(bool); } public override bool IsInRole(string role) { return default(bool); } } }
// 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 CommandLine; using CommandLine.Text; using Microsoft.Xunit.Performance.Api; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Http; using System.Reflection; using System.Text.RegularExpressions; namespace JitBench { class Program { static void Main(string[] args) { var options = JitBenchHarnessOptions.Parse(args); SetupStatics(options); using (var h = new XunitPerformanceHarness(args)) { ProcessStartInfo startInfo = options.UseExistingSetup ? UseExistingSetup() : CreateNewSetup(); string scenarioName = "MusicStore"; if (options.EnableTiering) { startInfo.Environment.Add("COMPlus_EXPERIMENTAL_TieredCompilation", "1"); scenarioName += " Tiering"; } if (options.Minopts) { startInfo.Environment.Add("COMPlus_JITMinOpts", "1"); scenarioName += " Minopts"; } if (options.DisableR2R) { startInfo.Environment.Add("COMPlus_ReadyToRun", "0"); scenarioName += " NoR2R"; } if (options.DisableNgen) { startInfo.Environment.Add("COMPlus_ZapDisable", "1"); scenarioName += " NoNgen"; } var scenarioConfiguration = CreateScenarioConfiguration(); h.RunScenario(startInfo, () => { PrintHeader(scenarioName); }, PostIteration, PostProcessing, scenarioConfiguration); } } private static ScenarioConfiguration CreateScenarioConfiguration() { var config = new ScenarioConfiguration(TimeSpan.FromMilliseconds(60000)) { Iterations = (int)s_iterations }; return config; } private static void SetupStatics(JitBenchHarnessOptions options) { // Set variables we will need to store results. s_iterations = options.Iterations; s_iteration = 0; s_startupTimes = new double[s_iterations]; s_requestTimes = new double[s_iterations]; s_steadystateTimes = new double[s_iterations]; s_temporaryDirectory = options.IntermediateOutputDirectory; s_targetArchitecture = options.TargetArchitecture; if (string.IsNullOrWhiteSpace(s_targetArchitecture)) throw new ArgumentNullException("Unspecified target architecture."); // J == JitBench folder. By reducing the length of the directory // name we attempt to reduce the chances of hitting PATH length // problems we have been hitting in the lab. // The changes we have done have reduced it in this way: // C:\Jenkins\workspace\perf_scenario---5b001a46\bin\sandbox\JitBench\JitBench-dev // C:\j\workspace\perf_scenario---5b001a46\bin\sandbox\JitBench\JitBench-dev // C:\j\w\perf_scenario---5b001a46\bin\sandbox\JitBench\JitBench-dev // C:\j\w\perf_scenario---5b001a46\bin\sandbox\J s_jitBenchDevDirectory = Path.Combine(s_temporaryDirectory, "J"); s_dotnetProcessFileName = Path.Combine(s_jitBenchDevDirectory, ".dotnet", "dotnet.exe"); s_musicStoreDirectory = Path.Combine(s_jitBenchDevDirectory, "src", "MusicStore"); } private static void DownloadAndExtractJitBenchRepo() { using (var client = new HttpClient()) { var archiveName = $"{JitBenchCommitSha1Id}.zip"; var url = $"{JitBenchRepoUrl}/archive/{archiveName}"; var zipFile = Path.Combine(s_temporaryDirectory, archiveName); using (FileStream tmpzip = File.Create(zipFile)) { using (Stream stream = client.GetStreamAsync(url).Result) stream.CopyTo(tmpzip); tmpzip.Flush(); } // If the repo already exists, we delete it and extract it again. if (Directory.Exists(s_jitBenchDevDirectory)) Directory.Delete(s_jitBenchDevDirectory, true); // This step will create s_JitBenchDevDirectory. ZipFile.ExtractToDirectory(zipFile, s_temporaryDirectory); Directory.Move(Path.Combine(s_temporaryDirectory, $"JitBench-{JitBenchCommitSha1Id}"), s_jitBenchDevDirectory); } } private static void InstallSharedRuntime() { var psi = new ProcessStartInfo() { WorkingDirectory = s_jitBenchDevDirectory, FileName = @"powershell.exe", Arguments = $".\\Dotnet-Install.ps1 -SharedRuntime -InstallDir .dotnet -Channel master -Architecture {s_targetArchitecture}" }; LaunchProcess(psi, 180000); } private static IDictionary<string, string> InstallDotnet() { var psi = new ProcessStartInfo() { WorkingDirectory = s_jitBenchDevDirectory, FileName = @"powershell.exe", Arguments = $".\\Dotnet-Install.ps1 -InstallDir .dotnet -Channel master -Architecture {s_targetArchitecture}" }; LaunchProcess(psi, 180000); return GetInitialEnvironment(); } private static void ModifySharedFramework() { // Current working directory is the <coreclr repo root>/sandbox directory. Console.WriteLine($"Modifying the shared framework."); var sourcedi = new DirectoryInfo(Directory.GetCurrentDirectory()); var targetdi = new DirectoryInfo( new DirectoryInfo(Path.Combine(s_jitBenchDevDirectory, ".dotnet", "shared", "Microsoft.NETCore.App")) .GetDirectories("*") .OrderBy(s => s.Name) .Last() .FullName); Console.WriteLine($" Source : {sourcedi.FullName}"); Console.WriteLine($" Target : {targetdi.FullName}"); var compiledBinariesOfInterest = new string[] { "clretwrc.dll", "clrjit.dll", "coreclr.dll", "mscordaccore.dll", "mscordbi.dll", "mscorrc.debug.dll", "mscorrc.dll", "sos.dll", "SOS.NETCore.dll", "System.Private.CoreLib.dll" }; foreach (var compiledBinaryOfInterest in compiledBinariesOfInterest) { foreach (FileInfo fi in targetdi.GetFiles(compiledBinaryOfInterest)) { var sourceFilePath = Path.Combine(sourcedi.FullName, fi.Name); var targetFilePath = Path.Combine(targetdi.FullName, fi.Name); if (File.Exists(sourceFilePath)) { File.Copy(sourceFilePath, targetFilePath, true); Console.WriteLine($" Copied file - '{targetFilePath}'"); } } } } private static IDictionary<string, string> GenerateStore(IDictionary<string, string> environment) { // This step generates some environment variables needed later. var psi = new ProcessStartInfo() { WorkingDirectory = s_jitBenchDevDirectory, FileName = "powershell.exe", Arguments = $"-Command \".\\AspNet-GenerateStore.ps1 -InstallDir .store -Architecture {s_targetArchitecture} -Runtime win7-{s_targetArchitecture}; gi env:JITBENCH_*, env:DOTNET_SHARED_STORE | %{{ \\\"$($_.Name)=$($_.Value)\\\" }} 1>>{EnvironmentFileName}\"" }; LaunchProcess(psi, 1800000, environment); // Return the generated environment variables. return GetEnvironment(environment, Path.Combine(s_jitBenchDevDirectory, EnvironmentFileName)); } private static IDictionary<string, string> GetEnvironment(IDictionary<string, string> environment, string fileName) { foreach (var line in File.ReadLines(fileName)) { if (string.IsNullOrWhiteSpace(line)) continue; string[] pair = line.Split(new char[] { '=' }, 2); if (pair.Length != 2) throw new InvalidOperationException($"AspNet-GenerateStore.ps1 did not generate the expected environment variable {pair}"); if (!environment.ContainsKey(pair[0])) environment.Add(pair[0], pair[1]); else environment[pair[0]] = pair[1]; } return environment; } private static void RestoreMusicStore(string workingDirectory, string dotnetFileName, IDictionary<string, string> environment) { var psi = new ProcessStartInfo() { WorkingDirectory = workingDirectory, FileName = dotnetFileName, Arguments = "restore" }; LaunchProcess(psi, 300000, environment); } private static void PublishMusicStore(string workingDirectory, string dotnetFileName, IDictionary<string, string> environment) { var psi = new ProcessStartInfo() { WorkingDirectory = workingDirectory, FileName = "cmd.exe", Arguments = $"/C \"{dotnetFileName} publish -c Release -f {JitBenchTargetFramework} --manifest %JITBENCH_ASPNET_MANIFEST% /p:MvcRazorCompileOnPublish=false\"" }; LaunchProcess(psi, 300000, environment); } // Return an environment with the downloaded dotnet on the path. private static IDictionary<string, string> GetInitialEnvironment() { // TODO: This is currently hardcoded, but we could probably pull it from the powershell cmdlet call. var environment = new Dictionary<string, string> { { "PATH", $"{Path.Combine(s_jitBenchDevDirectory, ".dotnet")};{Environment.GetEnvironmentVariable("PATH")}" } }; return environment; } private static ProcessStartInfo UseExistingSetup() { PrintHeader("Using existing SETUP"); var environment = GetInitialEnvironment(); environment = GetEnvironment(environment, Path.Combine(s_jitBenchDevDirectory, EnvironmentFileName)); ValidateEnvironment(environment); var psi = new ProcessStartInfo() { FileName = "cmd.exe", Arguments = $"/C \"{s_dotnetProcessFileName} MusicStore.dll 1>{MusicStoreRedirectedStandardOutputFileName}\"", WorkingDirectory = Path.Combine(s_musicStoreDirectory, "bin", "Release", JitBenchTargetFramework, "publish") }; foreach (KeyValuePair<string, string> pair in environment) psi.Environment.Add(pair.Key, pair.Value); return psi; } private static ProcessStartInfo CreateNewSetup() { PrintHeader("Starting SETUP"); DownloadAndExtractJitBenchRepo(); InstallSharedRuntime(); IDictionary<string, string> environment = InstallDotnet(); if (new string[] { "PATH" }.Except(environment.Keys, StringComparer.OrdinalIgnoreCase).Any()) throw new Exception("Missing expected environment variable PATH."); environment = GenerateStore(environment); ValidateEnvironment(environment); ModifySharedFramework(); RestoreMusicStore(s_musicStoreDirectory, s_dotnetProcessFileName, environment); PublishMusicStore(s_musicStoreDirectory, s_dotnetProcessFileName, environment); var psi = new ProcessStartInfo() { FileName = "cmd.exe", Arguments = $"/C \"{s_dotnetProcessFileName} MusicStore.dll 1>{MusicStoreRedirectedStandardOutputFileName}\"", WorkingDirectory = Path.Combine(s_musicStoreDirectory, "bin", "Release", JitBenchTargetFramework, "publish") }; foreach (KeyValuePair<string, string> pair in environment) psi.Environment.Add(pair.Key, pair.Value); return psi; } private static void ValidateEnvironment(IDictionary<string, string> environment) { var expectedVariables = new string[] { "PATH", "JITBENCH_ASPNET_MANIFEST", "JITBENCH_FRAMEWORK_VERSION", "JITBENCH_ASPNET_VERSION", "DOTNET_SHARED_STORE" }; if (expectedVariables.Except(environment.Keys, StringComparer.OrdinalIgnoreCase).Any()) throw new Exception("Missing expected environment variables."); } private const string MusicStoreRedirectedStandardOutputFileName = "measures.txt"; private const string JitBenchRepoUrl = "https://github.com/aspnet/JitBench"; private const string JitBenchCommitSha1Id = "b7e7b786c60daa255aacaea85006afe4d4ec8306"; private const string JitBenchTargetFramework = "netcoreapp2.1"; private const string EnvironmentFileName = "JitBenchEnvironment.txt"; private static void PostIteration() { var path = Path.Combine(s_jitBenchDevDirectory, "src", "MusicStore", "bin", "Release", JitBenchTargetFramework, "publish"); path = Path.Combine(path, MusicStoreRedirectedStandardOutputFileName); double? startupTime = null; double? requestTime = null; double? steadyStateAverageTime = null; foreach (string line in File.ReadLines(path)) { Match match = Regex.Match(line, @"^Server started in (\d+)ms$"); if (match.Success && match.Groups.Count == 2) { startupTime = Convert.ToDouble(match.Groups[1].Value); continue; } match = Regex.Match(line, @"^Request took (\d+)ms$"); if (match.Success && match.Groups.Count == 2) { requestTime = Convert.ToDouble(match.Groups[1].Value); continue; } match = Regex.Match(line, @"^Steadystate average response time: (\d+)ms$"); if (match.Success && match.Groups.Count == 2) { steadyStateAverageTime = Convert.ToDouble(match.Groups[1].Value); break; } } if (!startupTime.HasValue) throw new Exception("Startup time was not found."); if (!requestTime.HasValue) throw new Exception("First Request time was not found."); if (!steadyStateAverageTime.HasValue) throw new Exception("Steady state average response time not found."); s_startupTimes[s_iteration] = startupTime.Value; s_requestTimes[s_iteration] = requestTime.Value; s_steadystateTimes[s_iteration] = steadyStateAverageTime.Value; PrintRunningStepInformation($"{s_iteration} Server started in {s_startupTimes[s_iteration]}ms"); PrintRunningStepInformation($"{s_iteration} Request took {s_requestTimes[s_iteration]}ms"); PrintRunningStepInformation($"{s_iteration} Cold start time (server start + first request time): {s_startupTimes[s_iteration] + s_requestTimes[s_iteration]}ms"); PrintRunningStepInformation($"{s_iteration} Average steady state response {s_steadystateTimes[s_iteration]}ms"); ++s_iteration; } private static ScenarioBenchmark PostProcessing() { PrintHeader("Starting POST"); var scenarioBenchmark = new ScenarioBenchmark("MusicStore") { Namespace = "JitBench" }; // Create (measured) test entries for this scenario. var startup = new ScenarioTestModel("Startup"); scenarioBenchmark.Tests.Add(startup); var request = new ScenarioTestModel("First Request"); scenarioBenchmark.Tests.Add(request); // TODO: add response time once jit bench is updated to // report more reasonable numbers. // Add measured metrics to each test. startup.Performance.Metrics.Add(new MetricModel { Name = "Duration", DisplayName = "Duration", Unit = "ms" }); request.Performance.Metrics.Add(new MetricModel { Name = "Duration", DisplayName = "Duration", Unit = "ms" }); for (int i = 0; i < s_iterations; ++i) { var startupIteration = new IterationModel { Iteration = new Dictionary<string, double>() }; startupIteration.Iteration.Add("Duration", s_startupTimes[i]); startup.Performance.IterationModels.Add(startupIteration); var requestIteration = new IterationModel { Iteration = new Dictionary<string, double>() }; requestIteration.Iteration.Add("Duration", s_requestTimes[i]); request.Performance.IterationModels.Add(requestIteration); } return scenarioBenchmark; } private static void LaunchProcess(ProcessStartInfo processStartInfo, int timeoutMilliseconds, IDictionary<string, string> environment = null) { Console.WriteLine(); Console.WriteLine($"{System.Security.Principal.WindowsIdentity.GetCurrent().Name}@{Environment.MachineName} \"{processStartInfo.WorkingDirectory}\""); Console.WriteLine($"[{DateTime.Now}] $ {processStartInfo.FileName} {processStartInfo.Arguments}"); if (environment != null) { foreach (KeyValuePair<string, string> pair in environment) { if (!processStartInfo.Environment.ContainsKey(pair.Key)) processStartInfo.Environment.Add(pair.Key, pair.Value); else processStartInfo.Environment[pair.Key] = pair.Value; } } using (var p = new Process() { StartInfo = processStartInfo }) { p.Start(); if (p.WaitForExit(timeoutMilliseconds) == false) { // FIXME: What about clean/kill child processes? p.Kill(); throw new TimeoutException($"The process '{processStartInfo.FileName} {processStartInfo.Arguments}' timed out."); } if (p.ExitCode != 0) throw new Exception($"{processStartInfo.FileName} exited with error code {p.ExitCode}"); } } private static void PrintHeader(string message) { Console.WriteLine(); Console.WriteLine("**********************************************************************"); Console.WriteLine($"** {message}"); Console.WriteLine("**********************************************************************"); } private static void PrintRunningStepInformation(string message) { Console.WriteLine($"-- {message}"); } private static uint s_iterations; private static uint s_iteration; private static double[] s_startupTimes; private static double[] s_requestTimes; private static double[] s_steadystateTimes; private static string s_temporaryDirectory; private static string s_jitBenchDevDirectory; private static string s_dotnetProcessFileName; private static string s_musicStoreDirectory; private static string s_targetArchitecture; /// <summary> /// Provides an interface to parse the command line arguments passed to the JitBench harness. /// </summary> private sealed class JitBenchHarnessOptions { public JitBenchHarnessOptions() { _tempDirectory = Directory.GetCurrentDirectory(); _iterations = 11; } [Option("use-existing-setup", Required = false, HelpText = "Use existing setup.")] public Boolean UseExistingSetup { get; set; } [Option("tiering", Required = false, HelpText = "Enable tiered jit.")] public Boolean EnableTiering { get; set; } [Option("minopts", Required = false, HelpText = "Force jit to use minopt codegen.")] public Boolean Minopts { get; set; } [Option("disable-r2r", Required = false, HelpText = "Disable loading of R2R images.")] public Boolean DisableR2R { get; set; } [Option("disable-ngen", Required = false, HelpText = "Disable loading of ngen images.")] public Boolean DisableNgen { get; set; } [Option("iterations", Required = false, HelpText = "Number of iterations to run.")] public uint Iterations { get { return _iterations; } set { _iterations = value; } } [Option('o', Required = false, HelpText = "Specifies the intermediate output directory name.")] public string IntermediateOutputDirectory { get { return _tempDirectory; } set { if (string.IsNullOrWhiteSpace(value)) throw new InvalidOperationException("The intermediate output directory name cannot be null, empty or white space."); if (value.Any(c => Path.GetInvalidPathChars().Contains(c))) throw new InvalidOperationException("Specified intermediate output directory name contains invalid path characters."); _tempDirectory = Path.IsPathRooted(value) ? value : Path.GetFullPath(value); Directory.CreateDirectory(_tempDirectory); } } [Option("target-architecture", Required = true, HelpText = "JitBench target architecture (It must match the built product that was copied into sandbox).")] public string TargetArchitecture { get; set; } public static JitBenchHarnessOptions Parse(string[] args) { using (var parser = new Parser((settings) => { settings.CaseInsensitiveEnumValues = true; settings.CaseSensitive = false; settings.HelpWriter = new StringWriter(); settings.IgnoreUnknownArguments = true; })) { JitBenchHarnessOptions options = null; parser.ParseArguments<JitBenchHarnessOptions>(args) .WithParsed(parsed => options = parsed) .WithNotParsed(errors => { foreach (Error error in errors) { switch (error.Tag) { case ErrorType.MissingValueOptionError: throw new ArgumentException( $"Missing value option for command line argument '{(error as MissingValueOptionError).NameInfo.NameText}'"); case ErrorType.HelpRequestedError: Console.WriteLine(Usage()); Environment.Exit(0); break; case ErrorType.VersionRequestedError: Console.WriteLine(new AssemblyName(typeof(JitBenchHarnessOptions).GetTypeInfo().Assembly.FullName).Version); Environment.Exit(0); break; case ErrorType.BadFormatTokenError: case ErrorType.UnknownOptionError: case ErrorType.MissingRequiredOptionError: throw new ArgumentException( $"Missing required command line argument '{(error as MissingRequiredOptionError).NameInfo.NameText}'"); case ErrorType.MutuallyExclusiveSetError: case ErrorType.BadFormatConversionError: case ErrorType.SequenceOutOfRangeError: case ErrorType.RepeatedOptionError: case ErrorType.NoVerbSelectedError: case ErrorType.BadVerbSelectedError: case ErrorType.HelpVerbRequestedError: break; } } }); return options; } } public static string Usage() { var parser = new Parser((parserSettings) => { parserSettings.CaseInsensitiveEnumValues = true; parserSettings.CaseSensitive = false; parserSettings.EnableDashDash = true; parserSettings.HelpWriter = new StringWriter(); parserSettings.IgnoreUnknownArguments = true; }); var helpTextString = new HelpText { AddDashesToOption = true, AddEnumValuesToHelpText = true, AdditionalNewLineAfterOption = false, Heading = "JitBenchHarness", MaximumDisplayWidth = 80, }.AddOptions(parser.ParseArguments<JitBenchHarnessOptions>(new string[] { "--help" })).ToString(); return helpTextString; } private string _tempDirectory; private uint _iterations; } } }
// <copyright file="AutoResetEvent.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using IX.StandardExtensions.ComponentModel; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Extensions; using JetBrains.Annotations; using GlobalThreading = System.Threading; namespace IX.System.Threading; /// <summary> /// A set/reset event class that implements methods to block threads and unblock automatically. /// </summary> /// <seealso cref="IX.System.Threading.ISetResetEvent" /> [PublicAPI] public class AutoResetEvent : DisposableBase, ISetResetEvent { #region Internal state private readonly bool eventLocal; /// <summary> /// The auto-reset event. /// </summary> [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP006:Implement IDisposable.", Justification = "IDisposable is correctly implemented in base class.")] private readonly GlobalThreading.AutoResetEvent sre; #endregion #region Constructors and destructors /// <summary> /// Initializes a new instance of the <see cref="AutoResetEvent" /> class. /// </summary> public AutoResetEvent() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="AutoResetEvent" /> class. /// </summary> /// <param name="initialState">The initial signal state.</param> public AutoResetEvent(bool initialState) { this.sre = new GlobalThreading.AutoResetEvent(initialState); this.eventLocal = true; } /// <summary> /// Initializes a new instance of the <see cref="AutoResetEvent" /> class. /// </summary> /// <param name="autoResetEvent">The automatic reset event to wrap around.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="autoResetEvent" /> is <see langword="null" /> ( /// <see langword="Nothing" /> in Visual Basic). /// </exception> [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP003:Dispose previous before re-assigning.", Justification = "This is a constructor, the analyzer is thrown off.")] public AutoResetEvent(GlobalThreading.AutoResetEvent autoResetEvent) { Requires.NotNull( out this.sre, autoResetEvent, nameof(autoResetEvent)); } #endregion #region Methods #region Operators /// <summary> /// Performs an implicit conversion from <see cref="GlobalThreading.AutoResetEvent" /> to /// <see cref="AutoResetEvent" />. /// </summary> /// <param name="autoResetEvent">The automatic reset event.</param> /// <returns>The result of the conversion.</returns> public static implicit operator AutoResetEvent(GlobalThreading.AutoResetEvent autoResetEvent) => new(autoResetEvent); /// <summary> /// Performs an implicit conversion from <see cref="AutoResetEvent" /> to /// <see cref="GlobalThreading.AutoResetEvent" />. /// </summary> /// <param name="autoResetEvent">The automatic reset event.</param> /// <returns>The result of the conversion.</returns> public static implicit operator GlobalThreading.AutoResetEvent(AutoResetEvent autoResetEvent) => Requires.NotNull( autoResetEvent, nameof(autoResetEvent)) .sre; #endregion #region Interface implementations /// <summary> /// Gets the awaiter for this event, so that it can be awaited on using &quot;await mre;&quot;. /// </summary> /// <returns>An awaiter that works the same as <see cref="WaitOne()" />, continuing on a different thread.</returns> public SetResetEventAwaiter GetAwaiter() => new(this); /// <summary> /// Sets the state of this event instance to non-signaled. Any thread entering a wait from this point will block. /// </summary> /// <returns><see langword="true" /> if the signal has been reset, <see langword="false" /> otherwise.</returns> public bool Reset() => this.sre.Reset(); /// <summary> /// Sets the state of this event instance to signaled. Any waiting thread will unblock. /// </summary> /// <returns><see langword="true" /> if the signal has been set, <see langword="false" /> otherwise.</returns> public bool Set() => this.sre.Set(); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> public void WaitOne() => this.sre.WaitOne(); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne(int millisecondsTimeout) => this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout)); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne(double millisecondsTimeout) => this.sre.WaitOne(TimeSpan.FromMilliseconds(millisecondsTimeout)); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="timeout">The timeout period.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne(TimeSpan timeout) => this.sre.WaitOne(timeout); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne( int millisecondsTimeout, bool exitSynchronizationDomain) => this.sre.WaitOne( TimeSpan.FromMilliseconds(millisecondsTimeout), exitSynchronizationDomain); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne( double millisecondsTimeout, bool exitSynchronizationDomain) => this.sre.WaitOne( TimeSpan.FromMilliseconds(millisecondsTimeout), exitSynchronizationDomain); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="timeout">The timeout period.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public bool WaitOne( TimeSpan timeout, bool exitSynchronizationDomain) => this.sre.WaitOne( timeout, exitSynchronizationDomain); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns>A potentially awaitable value task.</returns> [SuppressMessage( "Performance", "HAA0603:Delegate allocation from a method group", Justification = "Unavoidable.")] public async ValueTask WaitOneAsync(GlobalThreading.CancellationToken cancellationToken = default) => _ = await this.sre.WaitOneAsync( GlobalThreading.Timeout.InfiniteTimeSpan, cancellationToken); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public ValueTask<bool> WaitOneAsync( int millisecondsTimeout, GlobalThreading.CancellationToken cancellationToken = default) => this.sre.WaitOneAsync( millisecondsTimeout, cancellationToken); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public ValueTask<bool> WaitOneAsync( double millisecondsTimeout, GlobalThreading.CancellationToken cancellationToken = default) => this.sre.WaitOneAsync( millisecondsTimeout, cancellationToken); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="timeout">The timeout period.</param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public ValueTask<bool> WaitOneAsync( TimeSpan timeout, GlobalThreading.CancellationToken cancellationToken = default) => this.sre.WaitOneAsync( timeout, cancellationToken); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public ValueTask<bool> WaitOneAsync( int millisecondsTimeout, bool exitSynchronizationDomain, GlobalThreading.CancellationToken cancellationToken = default) => this.sre.WaitOneAsync( millisecondsTimeout, cancellationToken); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="millisecondsTimeout">The timeout period, in milliseconds.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public ValueTask<bool> WaitOneAsync( double millisecondsTimeout, bool exitSynchronizationDomain, GlobalThreading.CancellationToken cancellationToken = default) => this.sre.WaitOneAsync( millisecondsTimeout, cancellationToken); /// <summary> /// Enters a wait period and, should there be no signal set, blocks the thread calling. /// </summary> /// <param name="timeout">The timeout period.</param> /// <param name="exitSynchronizationDomain"> /// If set to <see langword="true" />, the synchronization domain is exited before /// the call. /// </param> /// <param name="cancellationToken">The cancellation token for this operation.</param> /// <returns> /// <see langword="true" /> if the event is set within the timeout period, <see langword="false" /> if the timeout /// is reached. /// </returns> public ValueTask<bool> WaitOneAsync( TimeSpan timeout, bool exitSynchronizationDomain, GlobalThreading.CancellationToken cancellationToken = default) => this.sre.WaitOneAsync( timeout, cancellationToken); /// <summary> /// Gets the awaiter for this event, with a timeout. /// </summary> /// <param name="timeout">The timeout to wait until expiring.</param> /// <returns>An awaiter that works the same as <see cref="WaitOne(TimeSpan)" />, continuing on a different thread.</returns> public SetResetEventAwaiterWithTimeout WithTimeout(TimeSpan timeout) => new( this, timeout); /// <summary> /// Gets the awaiter for this event, with a timeout. /// </summary> /// <param name="timeout">The timeout to wait until expiring.</param> /// <returns>An awaiter that works the same as <see cref="WaitOne(double)" />, continuing on a different thread.</returns> public SetResetEventAwaiterWithTimeout WithTimeout(double timeout) => new( this, timeout); /// <summary> /// Gets the awaiter for this event, with a timeout. /// </summary> /// <param name="timeout">The timeout to wait until expiring.</param> /// <returns>An awaiter that works the same as <see cref="WaitOne(int)" />, continuing on a different thread.</returns> public SetResetEventAwaiterWithTimeout WithTimeout(int timeout) => new( this, timeout); #endregion /// <summary> /// Converts to a <see cref="GlobalThreading.ManualResetEvent" />. /// </summary> /// <returns>The <see cref="GlobalThreading.ManualResetEvent" /> that is encapsulated in this instance.</returns> public GlobalThreading.AutoResetEvent ToAutoResetEvent() => this.sre; #region Disposable /// <summary> /// Disposes in the managed context. /// </summary> protected override void DisposeManagedContext() { base.DisposeManagedContext(); if (this.eventLocal) { this.sre.Dispose(); } } #endregion #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Match is the result class for a regex search. // It returns the location, length, and substring for // the entire match as well as every captured group. // Match is also used during the search to keep track of each capture for each group. This is // done using the "_matches" array. _matches[x] represents an array of the captures for group x. // This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x] // stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid // values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the // Length of the last capture // // For example, if group 2 has one capture starting at position 4 with length 6, // _matchcount[2] == 1 // _matches[2][0] == 4 // _matches[2][1] == 6 // // Values in the _matches array can also be negative. This happens when using the balanced match // construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start" // and "end" groups. The capture added for "start" receives the negative values, and these values point to // the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative // values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms. // using System; using System.Collections; using System.Globalization; namespace Flatbox.RegularExpressions { /// <summary> /// Represents the results from a single regular expression match. /// </summary> public class Match : Group { internal static readonly Match s_empty = new Match(null, 1, string.Empty, 0, 0, 0); internal GroupCollection _groupcoll; // input to the match internal Regex _regex; internal int _textbeg; internal int _textpos; internal int _textend; internal int _textstart; // output from the match internal int[][] _matches; internal int[] _matchcount; internal bool _balancing; // whether we've done any balancing with this match. If we // have done balancing, we'll need to do extra work in Tidy(). /// <summary> /// Returns an empty Match object. /// </summary> public static Match Empty { get { return s_empty; } } internal Match(Regex regex, int capcount, string text, int begpos, int len, int startpos) : base(text, new int[2], 0, "0") { _regex = regex; _matchcount = new int[capcount]; _matches = new int[capcount][]; _matches[0] = _caps; _textbeg = begpos; _textend = begpos + len; _textstart = startpos; _balancing = false; // No need for an exception here. This is only called internally, so we'll use an Assert instead System.Diagnostics.Debug.Assert(!(_textbeg < 0 || _textstart < _textbeg || _textend < _textstart || _text.Length < _textend), "The parameters are out of range."); } /* * Nonpublic set-text method */ internal virtual void Reset(Regex regex, string text, int textbeg, int textend, int textstart) { _regex = regex; _text = text; _textbeg = textbeg; _textend = textend; _textstart = textstart; for (int i = 0; i < _matchcount.Length; i++) { _matchcount[i] = 0; } _balancing = false; } public virtual GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, null); return _groupcoll; } } /// <summary> /// Returns a new Match with the results for the next match, starting /// at the position at which the last match ended (at the character beyond the last /// matched character). /// </summary> public Match NextMatch() { if (_regex == null) return this; return _regex.Run(false, _length, _text, _textbeg, _textend - _textbeg, _textpos); } /// <summary> /// Returns the expansion of the passed replacement pattern. For /// example, if the replacement pattern is ?$1$2?, Result returns the concatenation /// of Group(1).ToString() and Group(2).ToString(). /// </summary> public virtual string Result(string replacement) { RegexReplacement repl; if (replacement == null) throw new ArgumentNullException(nameof(replacement)); if (_regex == null) throw new NotSupportedException(""); repl = (RegexReplacement)_regex._replref.Get(); if (repl == null || !repl.Pattern.Equals(replacement)) { repl = RegexParser.ParseReplacement(replacement, _regex.caps, _regex.capsize, _regex.capnames, _regex.roptions); _regex._replref.Cache(repl); } return repl.Replacement(this); } /* * Used by the replacement code */ internal virtual string GroupToStringImpl(int groupnum) { int c = _matchcount[groupnum]; if (c == 0) return string.Empty; int[] matches = _matches[groupnum]; return _text.Substring(matches[(c - 1) * 2], matches[(c * 2) - 1]); } /* * Used by the replacement code */ internal string LastGroupToStringImpl() { return GroupToStringImpl(_matchcount.Length - 1); } /* * Convert to a thread-safe object by precomputing cache contents */ /// <summary> /// Returns a Match instance equivalent to the one supplied that is safe to share /// between multiple threads. /// </summary> public static Match Synchronized(Match inner) { if (inner == null) throw new ArgumentNullException(nameof(inner)); int numgroups = inner._matchcount.Length; // Populate all groups by looking at each one for (int i = 0; i < numgroups; i++) { Group group = inner.Groups[i]; // Depends on the fact that Group.Synchronized just // operates on and returns the same instance Group.Synchronized(group); } return inner; } /* * Nonpublic builder: add a capture to the group specified by "cap" */ internal virtual void AddMatch(int cap, int start, int len) { int capcount; if (_matches[cap] == null) _matches[cap] = new int[2]; capcount = _matchcount[cap]; if (capcount * 2 + 2 > _matches[cap].Length) { int[] oldmatches = _matches[cap]; int[] newmatches = new int[capcount * 8]; for (int j = 0; j < capcount * 2; j++) newmatches[j] = oldmatches[j]; _matches[cap] = newmatches; } _matches[cap][capcount * 2] = start; _matches[cap][capcount * 2 + 1] = len; _matchcount[cap] = capcount + 1; } /* * Nonpublic builder: Add a capture to balance the specified group. This is used by the balanced match construct. (?<foo-foo2>...) If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap). However, since we have backtracking, we need to keep track of everything. */ internal virtual void BalanceMatch(int cap) { int capcount; int target; _balancing = true; // we'll look at the last capture first capcount = _matchcount[cap]; target = capcount * 2 - 2; // first see if it is negative, and therefore is a reference to the next available // capture group for balancing. If it is, we'll reset target to point to that capture. if (_matches[cap][target] < 0) target = -3 - _matches[cap][target]; // move back to the previous capture target -= 2; // if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it. if (target >= 0 && _matches[cap][target] < 0) AddMatch(cap, _matches[cap][target], _matches[cap][target + 1]); else AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ ); } /* * Nonpublic builder: removes a group match by capnum */ internal virtual void RemoveMatch(int cap) { _matchcount[cap]--; } /* * Nonpublic: tells if a group was matched by capnum */ internal virtual bool IsMatched(int cap) { return cap < _matchcount.Length && _matchcount[cap] > 0 && _matches[cap][_matchcount[cap] * 2 - 1] != (-3 + 1); } /* * Nonpublic: returns the index of the last specified matched group by capnum */ internal virtual int MatchIndex(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 2]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /* * Nonpublic: returns the length of the last specified matched group by capnum */ internal virtual int MatchLength(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 1]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /* * Nonpublic: tidy the match so that it can be used as an immutable result */ internal virtual void Tidy(int textpos) { int[] interval; interval = _matches[0]; _index = interval[0]; _length = interval[1]; _textpos = textpos; _capcount = _matchcount[0]; if (_balancing) { // The idea here is that we want to compact all of our unbalanced captures. To do that we // use j basically as a count of how many unbalanced captures we have at any given time // (really j is an index, but j/2 is the count). First we skip past all of the real captures // until we find a balance captures. Then we check each subsequent entry. If it's a balance // capture (it's negative), we decrement j. If it's a real capture, we increment j and copy // it down to the last free position. for (int cap = 0; cap < _matchcount.Length; cap++) { int limit; int[] matcharray; limit = _matchcount[cap] * 2; matcharray = _matches[cap]; int i = 0; int j; for (i = 0; i < limit; i++) { if (matcharray[i] < 0) break; } for (j = i; i < limit; i++) { if (matcharray[i] < 0) { // skip negative values j--; } else { // but if we find something positive (an actual capture), copy it back to the last // unbalanced position. if (i != j) matcharray[j] = matcharray[i]; j++; } } _matchcount[cap] = j / 2; } _balancing = false; } } #if DEBUG internal bool Debug { get { if (_regex == null) return false; return _regex.Debug; } } internal virtual void Dump() { int i, j; for (i = 0; i < _matchcount.Length; i++) { System.Diagnostics.Debug.WriteLine("Capnum " + i.ToString(CultureInfo.InvariantCulture) + ":"); for (j = 0; j < _matchcount[i]; j++) { string text = ""; if (_matches[i][j * 2] >= 0) text = _text.Substring(_matches[i][j * 2], _matches[i][j * 2 + 1]); System.Diagnostics.Debug.WriteLine(" (" + _matches[i][j * 2].ToString(CultureInfo.InvariantCulture) + "," + _matches[i][j * 2 + 1].ToString(CultureInfo.InvariantCulture) + ") " + text); } } } #endif } /* * MatchSparse is for handling the case where slots are * sparsely arranged (e.g., if somebody says use slot 100000) */ internal class MatchSparse : Match { // the lookup hashtable new internal Hashtable _caps; /* * Nonpublic constructor */ internal MatchSparse(Regex regex, Hashtable caps, int capcount, string text, int begpos, int len, int startpos) : base(regex, capcount, text, begpos, len, startpos) { _caps = caps; } public override GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, _caps); return _groupcoll; } } #if DEBUG internal override void Dump() { if (_caps != null) { foreach (DictionaryEntry kvp in _caps) { System.Diagnostics.Debug.WriteLine("Slot " + kvp.Key.ToString() + " -> " + kvp.Value.ToString()); } } base.Dump(); } #endif } }
namespace Macabresoft.Macabre2D.Framework; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using Macabresoft.Core; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; /// <summary> /// An entity which will render the specified text. /// </summary> [Display(Name = "Text Renderer")] public class TextRenderer : RenderableEntity, IRotatable { private readonly ResettableLazy<BoundingArea> _boundingArea; private readonly ResettableLazy<Transform> _pixelTransform; private readonly ResettableLazy<Transform> _rotatableTransform; private Color _color = Color.Black; private float _rotation; private bool _snapToPixels; private string _text = string.Empty; /// <summary> /// Initializes a new instance of the <see cref="TextRenderer" /> class. /// </summary> public TextRenderer() { this._boundingArea = new ResettableLazy<BoundingArea>(this.CreateBoundingArea); this._pixelTransform = new ResettableLazy<Transform>(this.CreatePixelTransform); this._rotatableTransform = new ResettableLazy<Transform>(this.CreateRotatableTransform); } /// <inheritdoc /> public override BoundingArea BoundingArea => this._boundingArea.Value; /// <summary> /// Gets the font reference. /// </summary> [DataMember(Order = 0)] public AssetReference<FontAsset> FontReference { get; } = new(); /// <summary> /// Gets or sets the color. /// </summary> /// <value>The color.</value> [DataMember(Order = 1)] public Color Color { get => this._color; set => this.Set(ref this._color, value); } /// <summary> /// Gets the render settings. /// </summary> /// <value>The render settings.</value> [DataMember(Order = 4, Name = "Render Settings")] public RenderSettings RenderSettings { get; private set; } = new(); /// <inheritdoc /> [DataMember(Order = 5)] public float Rotation { get => this._snapToPixels ? 0f : this._rotation; set { if (this.Set(ref this._rotation, value.NormalizeAngle()) && !this._snapToPixels) { this._boundingArea.Reset(); this._rotatableTransform.Reset(); } } } /// <summary> /// Gets or sets a value indicating whether this text renderer should snap to the pixel /// ratio defined in <see cref="IGameSettings" />. /// </summary> /// <remarks>Snapping to pixels will disable rotations on this renderer.</remarks> /// <value><c>true</c> if this should snap to pixels; otherwise, <c>false</c>.</value> [DataMember(Order = 3)] public bool SnapToPixels { get => this._snapToPixels; set { if (this.Set(ref this._snapToPixels, value)) { if (!this._snapToPixels) { this._rotatableTransform.Reset(); } else { this._pixelTransform.Reset(); } this._boundingArea.Reset(); } } } /// <summary> /// Gets or sets the text. /// </summary> /// <value>The text.</value> [DataMember(Order = 2)] public string Text { get => this._text; set { if (this.Set(ref this._text, value)) { this._boundingArea.Reset(); this.RenderSettings.InvalidateSize(); } } } /// <inheritdoc /> public override void Initialize(IScene scene, IEntity entity) { base.Initialize(scene, entity); this.Scene.Assets.ResolveAsset<FontAsset, SpriteFont>(this.FontReference); this.RenderSettings.PropertyChanged += this.RenderSettings_PropertyChanged; this.RenderSettings.Initialize(this.CreateSize); } /// <inheritdoc /> public override void Render(FrameTime frameTime, BoundingArea viewBoundingArea) { if (!string.IsNullOrEmpty(this.Text) && this.FontReference.Asset is FontAsset font && this.Scene.Game.SpriteBatch is SpriteBatch spriteBatch) { spriteBatch.Draw( this.Scene.Game.Project.Settings.PixelsPerUnit, font, this.Text, this.SnapToPixels ? this._pixelTransform.Value : this._rotatableTransform.Value, this.Color, this.RenderSettings.Orientation); } } /// <inheritdoc /> protected override void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) { base.OnPropertyChanged(sender, e); if (e.PropertyName == nameof(IEntity.Transform)) { this.Reset(); } } private BoundingArea CreateBoundingArea() { BoundingArea result; if (this.LocalScale.X != 0f && this.LocalScale.Y != 0f) { var inversePixelsPerUnit = this.Scene.Game.Project.Settings.InversePixelsPerUnit; var (x, y) = this.RenderSettings.Size; var width = x * inversePixelsPerUnit; var height = y * inversePixelsPerUnit; var offset = this.RenderSettings.Offset * inversePixelsPerUnit; var points = new List<Vector2> { this.GetWorldTransform(offset, this.Rotation).Position, this.GetWorldTransform(offset + new Vector2(width, 0f), this.Rotation).Position, this.GetWorldTransform(offset + new Vector2(width, height), this.Rotation).Position, this.GetWorldTransform(offset + new Vector2(0f, height), this.Rotation).Position }; var minimumX = points.Min(point => point.X); var minimumY = points.Min(point => point.Y); var maximumX = points.Max(point => point.X); var maximumY = points.Max(point => point.Y); if (this.SnapToPixels) { minimumX = minimumX.ToPixelSnappedValue(this.Scene.Game.Project.Settings); minimumY = minimumY.ToPixelSnappedValue(this.Scene.Game.Project.Settings); maximumX = maximumX.ToPixelSnappedValue(this.Scene.Game.Project.Settings); maximumY = maximumY.ToPixelSnappedValue(this.Scene.Game.Project.Settings); } result = new BoundingArea(new Vector2(minimumX, minimumY), new Vector2(maximumX, maximumY)); } else { result = new BoundingArea(); } return result; } private Transform CreatePixelTransform() { var worldTransform = this.GetWorldTransform(this.RenderSettings.Offset * this.Scene.Game.Project.Settings.InversePixelsPerUnit); return worldTransform.ToPixelSnappedValue(this.Scene.Game.Project.Settings); } private Transform CreateRotatableTransform() { return this.GetWorldTransform(this.RenderSettings.Offset * this.Scene.Game.Project.Settings.InversePixelsPerUnit, this.Rotation); } private Vector2 CreateSize() { return this.FontReference.Asset?.Content?.MeasureString(this.Text) ?? Vector2.Zero; } private void RenderSettings_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(this.RenderSettings.Offset)) { this.Reset(); } } private void Reset() { this._pixelTransform.Reset(); this._rotatableTransform.Reset(); this._boundingArea.Reset(); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using Hammock.Model; using Newtonsoft.Json; namespace TweetSharp { #if !SILVERLIGHT [Serializable] #endif #if !Smartphone && !NET20 [DataContract] [DebuggerDisplay("{Type}:{Coordinates.Latitude},{Coordinates.Longitude}")] #endif [JsonObject(MemberSerialization.OptIn)] public class TwitterGeoLocation : PropertyChangedBase, IEquatable<TwitterGeoLocation>, ITwitterModel { #if !SILVERLIGHT /// <summary> /// The inner spatial coordinates for this location. /// </summary> [Serializable] #endif public class GeoCoordinates { /// <summary> /// Gets or sets the latitude. /// </summary> /// <value>The latitude.</value> public virtual double Latitude{ get; set; } /// <summary> /// Gets or sets the longitude. /// </summary> /// <value>The longitude.</value> public virtual double Longitude { get; set; } /// <summary> /// Performs an explicit conversion from <see cref="TwitterGeoLocation.GeoCoordinates"/> to array of <see cref="System.Double"/>. /// </summary> /// <param name="location">The location.</param> /// <returns>The result of the conversion.</returns> public static explicit operator double[](GeoCoordinates location) { return new[] { location.Latitude, location.Longitude }; } /// <summary> /// Performs an implicit conversion from <see cref="double"/> to <see cref="TwitterGeoLocation.GeoCoordinates"/>. /// </summary> /// <param name="values">The values.</param> /// <returns>The result of the conversion.</returns> public static implicit operator GeoCoordinates(List<double> values) { return FromEnumerable(values); } /// <summary> /// Performs an implicit conversion from array of <see cref="System.Double"/> to <see cref="TwitterGeoLocation.GeoCoordinates"/>. /// </summary> /// <param name="values">The values.</param> /// <returns>The result of the conversion.</returns> public static implicit operator GeoCoordinates(double[] values) { return FromEnumerable(values); } /// <summary> /// Froms the enumerable. /// </summary> /// <param name="values">The values.</param> /// <returns></returns> private static GeoCoordinates FromEnumerable(IEnumerable<double> values) { if (values == null) { throw new ArgumentNullException("values"); } var latitude = values.First(); var longitude = values.Skip(1).Take(1).Single(); return new GeoCoordinates {Latitude = latitude, Longitude = longitude}; } } private static readonly TwitterGeoLocation _none = new TwitterGeoLocation(); private GeoCoordinates _coordinates; private string _type; /// <summary> /// Initializes a new instance of the <see cref="TwitterGeoLocation"/> struct. /// </summary> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> public TwitterGeoLocation(double latitude, double longitude) { _coordinates = new GeoCoordinates { Latitude = latitude, Longitude = longitude }; } /// <summary> /// Initializes a new instance of the <see cref="TwitterGeoLocation"/> struct. /// </summary> public TwitterGeoLocation() { } /// <summary> /// Gets or sets the inner spatial coordinates. /// </summary> /// <value>The coordinates.</value> [JsonProperty("coordinates")] public virtual GeoCoordinates Coordinates { get { return _coordinates; } set { _coordinates = value; OnPropertyChanged("Coordinates"); } } /// <summary> /// Gets or sets the type of location. /// </summary> /// <value>The type.</value> [JsonProperty("type")] public virtual string Type { get { return _type; } set { _type = value; OnPropertyChanged("Type"); } } /// <summary> /// Gets an instance of <see cref="TwitterGeoLocation" /> /// that represents nowhere. /// </summary> /// <value>The none.</value> public static TwitterGeoLocation None { get { return _none; } } #region IEquatable<TwitterGeoLocation> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public virtual bool Equals(TwitterGeoLocation other) { if (ReferenceEquals(null, other)) { return false; } return other.Coordinates.Latitude == Coordinates.Latitude && other.Coordinates.Longitude == Coordinates.Longitude; } #endregion /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="instance">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object instance) { if (ReferenceEquals(null, instance)) { return false; } return instance.GetType() == typeof (TwitterGeoLocation) && Equals((TwitterGeoLocation) instance); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(TwitterGeoLocation left, TwitterGeoLocation right) { if ( ReferenceEquals(left,right)) { return true; } if ( ReferenceEquals(null, left)) { return false; } return left.Equals(right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(TwitterGeoLocation left, TwitterGeoLocation right) { if (ReferenceEquals(left, right)) { return false; } if (ReferenceEquals(null, left)) { return true; } return !left.Equals(right); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { unchecked { return (Coordinates.Latitude.GetHashCode() * 397) ^ Coordinates.Longitude.GetHashCode(); } } public override string ToString() { return string.Format("{0},{1}", Coordinates.Latitude, Coordinates.Longitude); } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RawSource { get; set; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveWriteRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <value> /// Used to select all inventory nodes in a folder but not the folder itself /// </value> private const string STAR_WILDCARD = "*"; private InventoryArchiverModule m_module; private CachedUserInfo m_userInfo; private string m_invPath; protected TarArchiveWriter m_archiveWriter; protected UuidGatherer m_assetGatherer; /// <value> /// Used to collect the uuids of the assets that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_assetUuids = new Dictionary<UUID, int>(); /// <value> /// Used to collect the uuids of the users that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>(); /// <value> /// The stream to which the inventory archive will be saved. /// </value> private Stream m_saveStream; /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( InventoryArchiverModule module, CachedUserInfo userInfo, string invPath, string savePath) : this( module, userInfo, invPath, new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress)) { } /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( InventoryArchiverModule module, CachedUserInfo userInfo, string invPath, Stream saveStream) { m_module = module; m_userInfo = userInfo; m_invPath = invPath; m_saveStream = saveStream; m_assetGatherer = new UuidGatherer(m_module.AssetService); } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids) { Exception reportedException = null; bool succeeded = true; try { m_archiveWriter.Close(); } catch (IOException e) { m_saveStream.Close(); reportedException = e; succeeded = false; } m_module.TriggerInventoryArchiveSaved(succeeded, m_userInfo, m_invPath, m_saveStream, reportedException); } protected void SaveInvItem(InventoryItemBase inventoryItem, string path) { string filename = string.Format("{0}{1}_{2}.xml", path, inventoryItem.Name, inventoryItem.ID); // Record the creator of this item for user record purposes (which might go away soon) m_userUuids[inventoryItem.CreatorIdAsUuid] = 1; InventoryItemBase saveItem = (InventoryItemBase)inventoryItem.Clone(); saveItem.CreatorId = OspResolver.MakeOspa(saveItem.CreatorIdAsUuid, m_module.CommsManager); string serialization = UserInventoryItemSerializer.Serialize(saveItem); m_archiveWriter.WriteFile(filename, serialization); m_assetGatherer.GatherAssetUuids(saveItem.AssetID, (AssetType)saveItem.AssetType, m_assetUuids); } /// <summary> /// Save an inventory folder /// </summary> /// <param name="inventoryFolder">The inventory folder to save</param> /// <param name="path">The path to which the folder should be saved</param> /// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param> protected void SaveInvFolder(InventoryFolderImpl inventoryFolder, string path, bool saveThisFolderItself) { if (saveThisFolderItself) { path += string.Format( "{0}{1}{2}/", inventoryFolder.Name, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, inventoryFolder.ID); // We need to make sure that we record empty folders m_archiveWriter.WriteDir(path); } List<InventoryFolderImpl> childFolders = inventoryFolder.RequestListOfFolderImpls(); List<InventoryItemBase> items = inventoryFolder.RequestListOfItems(); /* Dictionary identicalFolderNames = new Dictionary<string, int>(); foreach (InventoryFolderImpl folder in inventories) { if (!identicalFolderNames.ContainsKey(folder.Name)) identicalFolderNames[folder.Name] = 0; else identicalFolderNames[folder.Name] = identicalFolderNames[folder.Name]++; int folderNameNumber = identicalFolderName[folder.Name]; SaveInvDir( folder, string.Format( "{0}{1}{2}/", path, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, folderNameNumber)); } */ foreach (InventoryFolderImpl childFolder in childFolders) { SaveInvFolder(childFolder, path, true); } foreach (InventoryItemBase item in items) { SaveInvItem(item, path); } } /// <summary> /// Execute the inventory write request /// </summary> public void Execute() { InventoryFolderImpl inventoryFolder = null; InventoryItemBase inventoryItem = null; if (!m_userInfo.HasReceivedInventory) { // If the region server has access to the user admin service (by which users are created), // then we'll assume that it's okay to fiddle with the user's inventory even if they are not on the // server. // // FIXME: FetchInventory should probably be assumed to by async anyway, since even standalones might // use a remote inventory service, though this is vanishingly rare at the moment. if (null == m_module.CommsManager.UserAdminService) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Have not yet received inventory info for user {0} {1}", m_userInfo.UserProfile.Name, m_userInfo.UserProfile.ID); return; } else { m_userInfo.FetchInventory(); } } bool foundStar = false; // Eliminate double slashes and any leading / on the path. This might be better done within InventoryFolderImpl // itself (possibly at a small loss in efficiency). string[] components = m_invPath.Split(new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries); int maxComponentIndex = components.Length - 1; // If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the // folder itself. This may get more sophisicated later on if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD) { foundStar = true; maxComponentIndex--; } m_invPath = String.Empty; for (int i = 0; i <= maxComponentIndex; i++) { m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER; } // Annoyingly Split actually returns the original string if the input string consists only of delimiters // Therefore if we still start with a / after the split, then we need the root folder if (m_invPath.Length == 0) { inventoryFolder = m_userInfo.RootFolder; } else { m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); inventoryFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath); } // The path may point to an item instead if (inventoryFolder == null) { inventoryItem = m_userInfo.RootFolder.FindItemByPath(m_invPath); } m_archiveWriter = new TarArchiveWriter(m_saveStream); if (null == inventoryFolder) { if (null == inventoryItem) { // We couldn't find the path indicated m_saveStream.Close(); m_module.TriggerInventoryArchiveSaved( false, m_userInfo, m_invPath, m_saveStream, new Exception(string.Format("Could not find inventory entry at path {0}", m_invPath))); return; } else { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, m_invPath); SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH); } } else { m_log.DebugFormat( "[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}", inventoryFolder.Name, inventoryFolder.ID, m_invPath); //recurse through all dirs getting dirs and files SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !foundStar); } SaveUsers(); new AssetsRequest( new AssetsArchiver(m_archiveWriter), m_assetUuids.Keys, m_module.AssetService, ReceivedAllAssets).Execute(); } /// <summary> /// Save information for the users that we've collected. /// </summary> protected void SaveUsers() { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count); foreach (UUID creatorId in m_userUuids.Keys) { // Record the creator of this item CachedUserInfo creator = m_module.CommsManager.UserProfileCacheService.GetUserDetails(creatorId); if (creator != null) { m_archiveWriter.WriteFile( ArchiveConstants.USERS_PATH + creator.UserProfile.Name + ".xml", UserProfileSerializer.Serialize(creator.UserProfile)); } else { m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId); } } } } }
#pragma warning disable SA1515 // Single-line comment should be preceded by blank line using System.Net; using System.Net.Security; using System.Security.Authentication; using System.Text; using MySqlConnector.Core; using MySqlConnector.Utilities; namespace MySqlConnector.Protocol.Serialization; internal static class NegotiateStreamConstants { public const int HeaderLength = 5; public const byte MajorVersion = 1; public const byte MinorVersion = 0; public const byte HandshakeDone = 0x14; public const byte HandshakeError = 0x15; public const byte HandshakeInProgress = 0x16; public const ushort MaxPayloadLength = ushort.MaxValue; } #pragma warning disable CA1844 // Provide memory-based overrides of async methods when subclassing 'Stream' /// <summary> /// Helper class to translate NegotiateStream framing for SPNEGO token /// into MySQL protocol packets. /// /// Serves as underlying stream for System.Net.NegotiateStream /// to perform MariaDB's auth_gssapi_client authentication. /// /// NegotiateStream protocol is described in e.g here /// https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-NNS/[MS-NNS].pdf /// We only use Handshake Messages for authentication. /// </summary> internal class NegotiateToMySqlConverterStream : Stream { private readonly MemoryStream m_writeBuffer; private readonly ServerSession m_serverSession; private readonly IOBehavior m_ioBehavior; private readonly CancellationToken m_cancellationToken; private MemoryStream m_readBuffer; private int m_writePayloadLength; private bool m_clientHandshakeDone; public PayloadData? MySQLProtocolPayload { get; private set; } public NegotiateToMySqlConverterStream(ServerSession serverSession, IOBehavior ioBehavior, CancellationToken cancellationToken) { m_serverSession = serverSession; m_readBuffer = new(); m_writeBuffer = new(); m_ioBehavior = ioBehavior; m_cancellationToken = cancellationToken; } private static void CreateNegotiateStreamMessageHeader(byte[] buffer, int offset, byte messageId, long payloadLength) { buffer[offset] = messageId; buffer[offset+1] = NegotiateStreamConstants.MajorVersion; buffer[offset+2] = NegotiateStreamConstants.MinorVersion; buffer[offset+3] = (byte) (payloadLength >> 8); buffer[offset+4] = (byte) (payloadLength & 0xff); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var bytesRead = 0; if (m_readBuffer.Length == m_readBuffer.Position) { if (count < NegotiateStreamConstants.HeaderLength) throw new InvalidDataException("Unexpected call to read less then NegotiateStream header"); if (m_clientHandshakeDone) { // NegotiateStream protocol expects server to send "handshake done" // empty message at the end of handshake. CreateNegotiateStreamMessageHeader(buffer, offset, NegotiateStreamConstants.HandshakeDone, 0); return NegotiateStreamConstants.HeaderLength; } // Read and cache packet from server. var payload = await m_serverSession.ReceiveReplyAsync(m_ioBehavior, cancellationToken).ConfigureAwait(false); var payloadMemory = payload.Memory; if (payloadMemory.Length > NegotiateStreamConstants.MaxPayloadLength) throw new InvalidDataException("Payload too big for NegotiateStream - {0} bytes".FormatInvariant(payloadMemory.Length)); // Check the first byte of the incoming packet. // It can be an OK packet indicating end of server processing, // or it can be 0x01 prefix we must strip off - 0x01 server masks special bytes, e.g 0xff, 0xfe in the payload // during pluggable authentication packet exchanges. switch (payloadMemory.Span[0]) { case 0x0: MySQLProtocolPayload = payload; CreateNegotiateStreamMessageHeader(buffer, offset, NegotiateStreamConstants.HandshakeDone, 0); return NegotiateStreamConstants.HeaderLength; case 0x1: payloadMemory = payloadMemory.Slice(1); break; } m_readBuffer = new(payloadMemory.ToArray()); CreateNegotiateStreamMessageHeader(buffer, offset, NegotiateStreamConstants.HandshakeInProgress, m_readBuffer.Length); bytesRead = NegotiateStreamConstants.HeaderLength; offset += bytesRead; count -= bytesRead; } if (count > 0) { // Return cached data. bytesRead += m_readBuffer.Read(buffer, offset, count); } return bytesRead; } public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, m_cancellationToken).GetAwaiter().GetResult(); public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (m_writePayloadLength == 0) { // The message header was not read yet. if (count < NegotiateStreamConstants.HeaderLength) // For simplicity, we expect header to be written in one go throw new InvalidDataException("Cannot parse NegotiateStream handshake message header"); // Parse NegotiateStream handshake header var messageId = buffer[offset+0]; var majorProtocolVersion = buffer[offset+1]; var minorProtocolVersion = buffer[offset+2]; var payloadSizeLow = buffer[offset+4]; var payloadSizeHigh = buffer[offset+3]; if (majorProtocolVersion != NegotiateStreamConstants.MajorVersion || minorProtocolVersion != NegotiateStreamConstants.MinorVersion) { throw new FormatException( "Unknown version of NegotiateStream protocol {0}.{1}, expected {2}.{3}".FormatInvariant( majorProtocolVersion, minorProtocolVersion, NegotiateStreamConstants.MajorVersion, NegotiateStreamConstants.MinorVersion)); } if (messageId != NegotiateStreamConstants.HandshakeDone && messageId != NegotiateStreamConstants.HandshakeError && messageId != NegotiateStreamConstants.HandshakeInProgress) { throw new FormatException("Invalid NegotiateStream MessageId 0x{0:X2}".FormatInvariant(messageId)); } m_writePayloadLength = (int) payloadSizeLow + ((int) payloadSizeHigh << 8); if (messageId == NegotiateStreamConstants.HandshakeDone) m_clientHandshakeDone = true; count -= NegotiateStreamConstants.HeaderLength; } if (count == 0) return; if (count + m_writeBuffer.Length > m_writePayloadLength) throw new InvalidDataException("Attempt to write more than a single message"); PayloadData payload; if (count < m_writePayloadLength) { m_writeBuffer.Write(buffer, offset, count); if (m_writeBuffer.Length < m_writePayloadLength) // The message is only partially written return; var payloadBytes = m_writeBuffer.ToArray(); payload = new(new ArraySegment<byte>(payloadBytes, 0, (int) m_writeBuffer.Length)); m_writeBuffer.SetLength(0); } else { // full payload provided payload = new(new ArraySegment<byte>(buffer, offset, m_writePayloadLength)); } await m_serverSession.SendReplyAsync(payload, m_ioBehavior, cancellationToken).ConfigureAwait(false); // Need to parse NegotiateStream header next time m_writePayloadLength = 0; } public override void Write(byte[] buffer, int offset, int count) => WriteAsync(buffer, offset, count, m_cancellationToken).GetAwaiter().GetResult(); public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); public override void SetLength(long value) => throw new NotImplementedException(); } internal static class AuthGSSAPI { private static string GetServicePrincipalName(byte[] switchRequest) { var reader = new ByteArrayReader(switchRequest.AsSpan()); return Encoding.UTF8.GetString(reader.ReadNullOrEofTerminatedByteString()); } public static async Task<PayloadData> AuthenticateAsync(ConnectionSettings cs, byte[] switchRequestPayloadData, ServerSession session, IOBehavior ioBehavior, CancellationToken cancellationToken) { using var innerStream = new NegotiateToMySqlConverterStream(session, ioBehavior, cancellationToken); using var negotiateStream = new NegotiateStream(innerStream); var targetName = cs.ServerSPN.Length == 0 ? GetServicePrincipalName(switchRequestPayloadData) : cs.ServerSPN; if (ioBehavior == IOBehavior.Synchronous) { negotiateStream.AuthenticateAsClient(CredentialCache.DefaultNetworkCredentials, targetName); } else { await negotiateStream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, targetName).ConfigureAwait(false); } if (cs.ServerSPN.Length != 0 && !negotiateStream.IsMutuallyAuthenticated) { // Negotiate used NTLM fallback, server name cannot be verified. throw new AuthenticationException("GSSAPI : Unable to verify server principal name using authentication type {0}".FormatInvariant(negotiateStream.RemoteIdentity?.AuthenticationType)); } if (innerStream.MySQLProtocolPayload is PayloadData payload) // return already pre-read OK packet. return payload; // Read final OK packet from server return await session.ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } }
#region Apache Notice /***************************************************************************** * $Revision: 575913 $ * $LastChangedDate: 2007-09-15 06:43:08 -0600 (Sat, 15 Sep 2007) $ * $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 #region Using using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using IBatisNet.Common.Exceptions; using IBatisNet.Common.Logging; using IBatisNet.Common.Utilities; using IBatisNet.DataMapper.Exceptions; using IBatisNet.DataMapper.MappedStatements; #endregion namespace IBatisNet.DataMapper.Configuration.Cache { /// <summary> /// Summary description for CacheModel. /// </summary> [Serializable] [XmlRoot("cacheModel", Namespace="http://ibatis.apache.org/mapping")] public class CacheModel { #region Fields private static IDictionary _lockMap = new HybridDictionary(); [NonSerialized] private static readonly ILog _logger = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType ); /// <summary> /// This is used to represent null objects that are returned from the cache so /// that they can be cached, too. /// </summary> [NonSerialized] public readonly static object NULL_OBJECT = new Object(); /// <summary> /// Constant to turn off periodic cache flushes /// </summary> [NonSerialized] public const long NO_FLUSH_INTERVAL = -99999; [NonSerialized] private object _statLock = new Object(); [NonSerialized] private int _requests = 0; [NonSerialized] private int _hits = 0; [NonSerialized] private string _id = string.Empty; [NonSerialized] private ICacheController _controller = null; [NonSerialized] private FlushInterval _flushInterval = null; [NonSerialized] private long _lastFlush = 0; [NonSerialized] private HybridDictionary _properties = new HybridDictionary(); [NonSerialized] private string _implementation = string.Empty; [NonSerialized] private bool _isReadOnly = true; [NonSerialized] private bool _isSerializable = false; #endregion #region Properties /// <summary> /// Identifier used to identify the CacheModel amongst the others. /// </summary> [XmlAttribute("id")] public string Id { get { return _id; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The id attribute is mandatory in a cacheModel tag."); _id = value; } } /// <summary> /// Cache controller implementation name. /// </summary> [XmlAttribute("implementation")] public string Implementation { get { return _implementation; } set { if ((value == null) || (value.Length < 1)) throw new ArgumentNullException("The implementation attribute is mandatory in a cacheModel tag."); _implementation = value; } } /// <summary> /// Set the cache controller /// </summary> public ICacheController CacheController { set{ _controller =value; } } /// <summary> /// Set or get the flushInterval (in Ticks) /// </summary> [XmlElement("flushInterval",typeof(FlushInterval))] public FlushInterval FlushInterval { get { return _flushInterval; } set { _flushInterval = value; } } /// <summary> /// Specifie how the cache content should be returned. /// If true a deep copy is returned. /// </summary> /// <remarks> /// Combinaison /// IsReadOnly=true/IsSerializable=false : Returned instance of cached object /// IsReadOnly=false/IsSerializable=true : Returned coopy of cached object /// </remarks> public bool IsSerializable { get { return _isSerializable; } set { _isSerializable = value; } } /// <summary> /// Determines if the cache will be used as a read-only cache. /// Tells the cache model that is allowed to pass back a reference to the object /// existing in the cache. /// </summary> /// <remarks> /// The IsReadOnly properties works in conjonction with the IsSerializable propertie. /// </remarks> public bool IsReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; } } #endregion #region Constructor (s) / Destructor /// <summary> /// Constructor /// </summary> public CacheModel() { _lastFlush = DateTime.Now.Ticks; } #endregion #region Methods /// <summary> /// /// </summary> public void Initialize() { // Initialize FlushInterval _flushInterval.Initialize(); try { if (_implementation == null) { throw new DataMapperException ("Error instantiating cache controller for cache named '"+_id+"'. Cause: The class for name '"+_implementation+"' could not be found."); } // Build the CacheController Type type = TypeUtils.ResolveType(_implementation); object[] arguments = new object[0]; _controller = (ICacheController)Activator.CreateInstance(type, arguments); } catch (Exception e) { throw new ConfigurationException("Error instantiating cache controller for cache named '"+_id+". Cause: " + e.Message, e); } //------------ configure Controller--------------------- try { _controller.Configure(_properties); } catch (Exception e) { throw new ConfigurationException ("Error configuring controller named '"+_id+"'. Cause: " + e.Message, e); } } /// <summary> /// Event listener /// </summary> /// <param name="mappedStatement">A MappedStatement on which we listen ExecuteEventArgs event.</param> public void RegisterTriggerStatement(IMappedStatement mappedStatement) { mappedStatement.Execute +=new ExecuteEventHandler(FlushHandler); } /// <summary> /// FlushHandler which clear the cache /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FlushHandler(object sender, ExecuteEventArgs e) { if (_logger.IsDebugEnabled) { _logger.Debug("Flush cacheModel named "+_id+" for statement '"+e.StatementName+"'"); } Flush(); } /// <summary> /// Clears all elements from the cache. /// </summary> public void Flush() { _lastFlush = DateTime.Now.Ticks; _controller.Flush(); } /// <summary> /// Adds an item with the specified key and value into cached data. /// Gets a cached object with the specified key. /// </summary> /// <value>The cached object or <c>null</c></value> /// <remarks> /// A side effect of this method is that is may clear the cache /// if it has not been cleared in the flushInterval. /// </remarks> public object this [CacheKey key] { get { lock(this) { if (_lastFlush != NO_FLUSH_INTERVAL && (DateTime.Now.Ticks - _lastFlush > _flushInterval.Interval)) { Flush(); } } object value = null; lock (GetLock(key)) { value = _controller[key]; } if(_isSerializable && !_isReadOnly && (value != NULL_OBJECT && value != null)) { try { MemoryStream stream = new MemoryStream((byte[]) value); stream.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); value = formatter.Deserialize( stream ); } catch(Exception ex) { throw new IBatisNetException("Error caching serializable object. Be sure you're not attempting to use " + "a serialized cache for an object that may be taking advantage of lazy loading. Cause: "+ex.Message, ex); } } lock(_statLock) { _requests++; if (value != null) { _hits++; } } if (_logger.IsDebugEnabled) { if (value != null) { _logger.Debug(String.Format("Retrieved cached object '{0}' using key '{1}' ", value, key)); } else { _logger.Debug(String.Format("Cache miss using key '{0}' ", key)); } } return value; } set { if (null == value) {value = NULL_OBJECT;} if(_isSerializable && !_isReadOnly && value != NULL_OBJECT) { try { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, value); value = stream.ToArray(); } catch(Exception ex) { throw new IBatisNetException("Error caching serializable object. Cause: "+ex.Message, ex); } } _controller[key] = value; if (_logger.IsDebugEnabled) { _logger.Debug(String.Format("Cache object '{0}' using key '{1}' ", value, key)); } } } /// <summary> /// /// </summary> public double HitRatio { get { if (_requests!=0) { return (double)_hits/(double)_requests; } else { return 0; } } } /// <summary> /// Add a property /// </summary> /// <param name="name">The name of the property</param> /// <param name="value">The value of the property</param> public void AddProperty(string name, string value) { _properties.Add(name, value); } #endregion /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> [MethodImpl(MethodImplOptions.Synchronized)] public object GetLock(CacheKey key) { int controllerId = HashCodeProvider.GetIdentityHashCode(_controller); int keyHash = key.GetHashCode(); int lockKey = 29 * controllerId + keyHash; object lok =_lockMap[lockKey]; if (lok == null) { lok = lockKey; //might as well use the same object _lockMap[lockKey] = lok; } return lok; } } }
using System; using System.IO; using System.Collections; using Franson.BlueTools; namespace Chat { /// <summary> /// The ChatManager manages the spontanuous networks that occure when devices locate /// eachother. /// </summary> public class ChatManager { /// <summary> /// Raised whenever a message is received from a device. /// </summary> public event MessageReceivedHandler MessageReceived; /// <summary> /// Fired whenever the profile of a device changes. /// </summary> public event ProfileChangedHandler ProfileChanged; /// <summary> /// List of all participants. /// </summary> private ArrayList participants = new ArrayList(); /// <summary> /// The profile of this device. /// </summary> private Profile profile = new Profile(); /// <summary> /// The ChatService that allows devices to connect to this device. /// </summary> private ChatService chatService = new ChatService(); private ArrayList newDevices = new ArrayList(); /// <summary> /// Creates /// </summary> public ChatManager() { // Initialize the profile // profile.Name = "Unnamed"; Network[] networks = Manager.GetManager().Networks; foreach(Network network in networks) { network.DeviceDiscovered += new BlueToolsEventHandler(network_DeviceDiscovered); network.DeviceLost += new BlueToolsEventHandler(network_DeviceLost); network.Server.Advertise(chatService); //network.AutoDiscovery = true; network.DiscoverDevicesAsync(); network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(network_DeviceDiscoveryCompleted); } chatService.ParticipantConnected += new ParticipantConnectedHandler(chatService_ParticipantConnected); } /// <summary> /// Closes the ChatManager and all connections managed by it. /// </summary> public void Close() { while(participants.Count > 0) { Participant participant = (Participant)participants[0]; participants.RemoveAt(0); participant.Close(); } } /// <summary> /// Gets or sets the local profile. Whenever this is set, the new profile will be /// sent to all participants. /// </summary> public Profile Profile { get { return profile; } set { profile = value; SendProfile(); } } /// <summary> /// Returns a list of all participants connected to this device. /// </summary> public Participant[] Participants { get { return (Participant[])participants.ToArray(typeof(Participant)); } } /// <summary> /// Adds a participant to the network. /// </summary> /// <param name="participant">The participant to add.</param> public void AddParticipant(Participant participant) { lock(this) { // This is the only negogation we have. Should be sufficient. // foreach(Participant other in participants) { if(other.Address.Equals(participant.Address)) { participant.Close(); return; } } participants.Add(participant); participant.MessageReceived += new MessageReceivedHandler(participant_MessageReceived); participant.ProfileChanged += new ProfileChangedHandler(participant_ProfileChanged); participant.Lost += new ParticipantLostHandler(participant_Lost); participant.SendProfile(profile); } } /// <summary> /// Sends the local profile to all participants. /// </summary> public void SendProfile() { foreach(Participant participant in participants) { participant.SendProfile(profile); } } /// <summary> /// Sets a message to all participants. /// </summary> /// <param name="message">The message to send.</param> public void SendMessage(String message) { foreach(Participant participant in participants) { participant.SendMessage(message); } } #region Events private void participant_MessageReceived(Participant participant, String message) { if(MessageReceived != null) { MessageReceived(participant, message); } } private void participant_ProfileChanged(Participant participant) { if(ProfileChanged != null) { ProfileChanged(participant); } } private void chatService_ParticipantConnected(Participant participant) { AddParticipant(participant); } private void network_DeviceDiscovered(object sender, BlueToolsEventArgs eventArgs) { RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; newDevices.Add(device); } private void network_DeviceLost(object sender, BlueToolsEventArgs eventArgs) { RemoteDevice device = (RemoteDevice)((DiscoveryEventArgs)eventArgs).Discovery; device.ServiceDiscovered -= new BlueToolsEventHandler(device_ServiceDiscovered); System.Windows.Forms.MessageBox.Show("Lost " + device.Name); } private void device_ServiceDiscovered(object sender, BlueToolsEventArgs eventArgs) { Device device = (Device)sender; RemoteService service = (RemoteService)((DiscoveryEventArgs)eventArgs).Discovery; if(service.ServiceType.Equals(ChatService.ChatServiceServiceType)) { // Check if we're already connected to the device AddParticipant(new Participant(device.Address, service.Stream)); } } private void participant_Lost(Participant participant) { participants.Remove(participant); participant.MessageReceived -= new MessageReceivedHandler(participant_MessageReceived); participant.ProfileChanged -= new ProfileChangedHandler(participant_ProfileChanged); participant.Lost -= new ParticipantLostHandler(participant_Lost); } private void network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { while(newDevices.Count > 0) { RemoteDevice device = (RemoteDevice)newDevices[0]; newDevices.RemoveAt(0); device.ServiceDiscovered += new BlueToolsEventHandler(device_ServiceDiscovered); try { device.DiscoverServicesAsync(ServiceType.RFCOMM); } catch (Exception exc) { System.Windows.Forms.MessageBox.Show(exc.Message); } } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Tor.Http.Models; using static WalletWasabi.Tor.Http.Constants; namespace WalletWasabi.Tor.Http.Helpers { public static class HttpMessageHelper { public static async Task<string> ReadStartLineAsync(Stream stream, CancellationToken ctsToken = default) { // https://tools.ietf.org/html/rfc7230#section-3 // A recipient MUST parse an HTTP message as a sequence of octets in an // encoding that is a superset of US-ASCII[USASCII]. // Read until the first CRLF // the CRLF is part of the startLine // https://tools.ietf.org/html/rfc7230#section-3.5 // Although the line terminator for the start-line and header fields is // the sequence CRLF, a recipient MAY recognize a single LF as a line // terminator and ignore any preceding CR. var bab = new ByteArrayBuilder(); int read = 0; while (read >= 0) { read = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); bab.Append((byte)read); if (LF == (byte)read) { break; } } var startLine = bab.ToString(Encoding.ASCII); if (string.IsNullOrEmpty(startLine)) { throw new FormatException($"{nameof(startLine)} cannot be null or empty."); } return startLine; } public static async Task<string> ReadHeadersAsync(Stream stream, CancellationToken ctsToken = default) { var headers = ""; var firstRead = true; var builder = new StringBuilder(); builder.Append(headers); while (true) { string header = await ReadCRLFLineAsync(stream, Encoding.ASCII, ctsToken).ConfigureAwait(false); if (header is null) { throw new FormatException("Malformed HTTP message: End of headers must be CRLF."); } if (header.Length == 0) { // 2 CRLF was read in row so it's the end of the headers break; } if (firstRead) { // https://tools.ietf.org/html/rfc7230#section-3 // A recipient that receives whitespace between the // start - line and the first header field MUST either reject the message // as invalid or consume each whitespace-preceded line without further // processing of it(i.e., ignore the entire line, along with any // subsequent lines preceded by whitespace, until a properly formed // header field is received or the header section is terminated). if (char.IsWhiteSpace(header[0])) { throw new FormatException("Invalid HTTP message: Cannot be whitespace between the start line and the headers."); } firstRead = false; } builder.Append(header + CRLF); // CRLF is part of the headerstring } headers = builder.ToString(); if (string.IsNullOrEmpty(headers)) { headers = ""; } return headers; } private static async Task<string> ReadCRLFLineAsync(Stream stream, Encoding encoding, CancellationToken ctsToken = default) { var bab = new ByteArrayBuilder(); while (true) { int ch = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); if (ch == -1) { break; } if (ch == '\r') { var ch2 = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); if (ch2 == '\n') { return bab.ToString(encoding); } bab.Append(new byte[] { (byte)ch, (byte)ch2 }); continue; } bab.Append((byte)ch); } return bab.Length > 0 ? bab.ToString(encoding) : null; } public static byte[]? HandleGzipCompression(HttpContentHeaders contentHeaders, byte[]? decodedBodyArray) { if (decodedBodyArray is null || !decodedBodyArray.Any()) { return decodedBodyArray; } if (contentHeaders?.ContentEncoding is { } && contentHeaders.ContentEncoding.Contains("gzip")) { using (var src = new MemoryStream(decodedBodyArray)) using (var unzipStream = new GZipStream(src, CompressionMode.Decompress)) { using var targetStream = new MemoryStream(); unzipStream.CopyTo(targetStream); decodedBodyArray = targetStream.ToArray(); } contentHeaders.ContentEncoding.Remove("gzip"); if (!contentHeaders.ContentEncoding.Any()) { contentHeaders.Remove("Content-Encoding"); } } return decodedBodyArray; } public static async Task<byte[]?> GetContentBytesAsync(Stream stream, HttpRequestContentHeaders headerStruct, CancellationToken ctsToken = default) { if (headerStruct.RequestHeaders is { } && headerStruct.RequestHeaders.Contains("Transfer-Encoding")) { // https://tools.ietf.org/html/rfc7230#section-4 // All transfer-coding names are case-insensitive if ("chunked".Equals(headerStruct.RequestHeaders.TransferEncoding.Last().Value, StringComparison.OrdinalIgnoreCase)) { return await GetDecodedChunkedContentBytesAsync(stream, headerStruct, ctsToken).ConfigureAwait(false); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // If a Transfer - Encoding header field is present in a response and // the chunked transfer coding is not the final encoding, the // message body length is determined by reading the connection until // it is closed by the server. If a Transfer - Encoding header field // is present in a request and the chunked transfer coding is not // the final encoding, the message body length cannot be determined // reliably; the server MUST respond with the 400(Bad Request) // status code and then close the connection. return await GetBytesTillEndAsync(stream, ctsToken).ConfigureAwait(false); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // 5.If a valid Content - Length header field is present without // Transfer - Encoding, its decimal value defines the expected message // body length in octets.If the sender closes the connection or // the recipient times out before the indicated number of octets are // received, the recipient MUST consider the message to be // incomplete and close the connection. if (headerStruct.ContentHeaders.Contains("Content-Length")) { long? contentLength = headerStruct.ContentHeaders?.ContentLength; return await ReadBytesTillLengthAsync(stream, contentLength, ctsToken).ConfigureAwait(false); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // 6.If this is a request message and none of the above are true, then // the message body length is zero (no message body is present). // 7. Otherwise, this is a response message without a declared message // body length, so the message body length is determined by the // number of octets received prior to the server closing the // connection. return GetDummyOrNullContentBytes(headerStruct.ContentHeaders); } public static async Task<byte[]?> GetContentBytesAsync(Stream stream, HttpResponseContentHeaders headerStruct, HttpMethod requestMethod, StatusLine statusLine, CancellationToken ctsToken = default) { // https://tools.ietf.org/html/rfc7230#section-3.3.3 // The length of a message body is determined by one of the following // (in order of precedence): // 1.Any response to a HEAD request and any response with a 1xx // (Informational), 204(No Content), or 304(Not Modified) status // code is always terminated by the first empty line after the // header fields, regardless of the header fields present in the // message, and thus cannot contain a message body. if (requestMethod == HttpMethod.Head || HttpStatusCodeHelper.IsInformational(statusLine.StatusCode) || statusLine.StatusCode == HttpStatusCode.NoContent || statusLine.StatusCode == HttpStatusCode.NotModified) { return GetDummyOrNullContentBytes(headerStruct.ContentHeaders); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // 2.Any 2xx(Successful) response to a CONNECT request implies that // the connection will become a tunnel immediately after the empty // line that concludes the header fields.A client MUST ignore any // Content - Length or Transfer-Encoding header fields received in // such a message. if (requestMethod == new HttpMethod("CONNECT")) { if (HttpStatusCodeHelper.IsSuccessful(statusLine.StatusCode)) { return null; } } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // 3.If a Transfer-Encoding header field is present and the chunked // transfer coding(Section 4.1) is the final encoding, the message // body length is determined by reading and decoding the chunked // data until the transfer coding indicates the data is complete. if (headerStruct?.ResponseHeaders is { } && headerStruct.ResponseHeaders.Contains("Transfer-Encoding")) { // https://tools.ietf.org/html/rfc7230#section-4 // All transfer-coding names are case-insensitive if ("chunked".Equals(headerStruct.ResponseHeaders.TransferEncoding.Last().Value, StringComparison.OrdinalIgnoreCase)) { return await GetDecodedChunkedContentBytesAsync(stream, headerStruct, ctsToken).ConfigureAwait(false); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // If a Transfer - Encoding header field is present in a response and // the chunked transfer coding is not the final encoding, the // message body length is determined by reading the connection until // it is closed by the server. If a Transfer - Encoding header field // is present in a request and the chunked transfer coding is not // the final encoding, the message body length cannot be determined // reliably; the server MUST respond with the 400(Bad Request) // status code and then close the connection. return await GetBytesTillEndAsync(stream, ctsToken).ConfigureAwait(false); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // 5.If a valid Content - Length header field is present without // Transfer - Encoding, its decimal value defines the expected message // body length in octets.If the sender closes the connection or // the recipient times out before the indicated number of octets are // received, the recipient MUST consider the message to be // incomplete and close the connection. if (headerStruct.ContentHeaders.Contains("Content-Length")) { long? contentLength = headerStruct.ContentHeaders?.ContentLength; return await ReadBytesTillLengthAsync(stream, contentLength, ctsToken).ConfigureAwait(false); } // https://tools.ietf.org/html/rfc7230#section-3.3.3 // 6.If this is a request message and none of the above are true, then // the message body length is zero (no message body is present). // 7. Otherwise, this is a response message without a declared message // body length, so the message body length is determined by the // number of octets received prior to the server closing the // connection. return await GetBytesTillEndAsync(stream, ctsToken).ConfigureAwait(false); } private static async Task<byte[]> GetDecodedChunkedContentBytesAsync(Stream stream, HttpRequestContentHeaders headerStruct, CancellationToken ctsToken = default) { return await GetDecodedChunkedContentBytesAsync(stream, headerStruct, null, ctsToken).ConfigureAwait(false); } private static async Task<byte[]> GetDecodedChunkedContentBytesAsync(Stream stream, HttpResponseContentHeaders headerStruct, CancellationToken ctsToken = default) { return await GetDecodedChunkedContentBytesAsync(stream, null, headerStruct, ctsToken).ConfigureAwait(false); } private static async Task<byte[]> GetDecodedChunkedContentBytesAsync(Stream stream, HttpRequestContentHeaders requestHeaders, HttpResponseContentHeaders responseHeaders, CancellationToken ctsToken = default) { if (responseHeaders is null && requestHeaders is null) { throw new ArgumentException("Response and request headers cannot be both null."); } else if (responseHeaders is { } && requestHeaders is { }) { throw new ArgumentException("Either response or request headers has to be null."); } // https://tools.ietf.org/html/rfc7230#section-4.1.3 // 4.1.3.Decoding Chunked // A process for decoding the chunked transfer coding can be represented // in pseudo - code as: // length := 0 // read chunk - size, chunk - ext(if any), and CRLF // while (chunk - size > 0) // { // read chunk-data and CRLF // append chunk-data to decoded-body // length:= length + chunk - size // read chunk-size, chunk - ext(if any), and CRLF // } // read trailer field // while (trailer field is not empty) { // if (trailer field is allowed to be sent in a trailer) { // append trailer field to existing header fields // } // read trailer-field // } // Content - Length := length // Remove "chunked" from Transfer-Encoding // Remove Trailer from existing header fields long length = 0; var firstChunkLine = await ReadCRLFLineAsync(stream, Encoding.ASCII, ctsToken: ctsToken).ConfigureAwait(false); ParseFistChunkLine(firstChunkLine, out long chunkSize, out _); // We will not do anything with the chunk extensions, because: // https://tools.ietf.org/html/rfc7230#section-4.1.1 // A recipient MUST ignore unrecognized chunk extensions. var decodedBody = new List<byte>(); // https://tools.ietf.org/html/rfc7230#section-4.1 // The chunked transfer coding is complete // when a chunk with a chunk-size of zero is received, possibly followed // by a trailer, and finally terminated by an empty line. while (chunkSize > 0) { var chunkData = await ReadBytesTillLengthAsync(stream, chunkSize, ctsToken).ConfigureAwait(false); string crlfLine = await ReadCRLFLineAsync(stream, Encoding.ASCII, ctsToken).ConfigureAwait(false); if (crlfLine.Length != 0) { throw new FormatException("Chunk does not end with CRLF."); } decodedBody.AddRange(chunkData); length += chunkSize; firstChunkLine = await ReadCRLFLineAsync(stream, Encoding.ASCII, ctsToken: ctsToken).ConfigureAwait(false); ParseFistChunkLine(firstChunkLine, out long cs, out _); chunkSize = cs; } // https://tools.ietf.org/html/rfc7230#section-4.1.2 // A trailer allows the sender to include additional fields at the end // of a chunked message in order to supply metadata that might be // dynamically generated while the message body is sent string trailerHeaders = await ReadHeadersAsync(stream, ctsToken).ConfigureAwait(false); var trailerHeaderSection = await HeaderSection.CreateNewAsync(trailerHeaders).ConfigureAwait(false); RemoveInvalidTrailers(trailerHeaderSection); if (responseHeaders is { }) { var trailerHeaderStruct = trailerHeaderSection.ToHttpResponseHeaders(); AssertValidHeaders(trailerHeaderStruct.ResponseHeaders, trailerHeaderStruct.ContentHeaders); // https://tools.ietf.org/html/rfc7230#section-4.1.2 // When a chunked message containing a non-empty trailer is received, // the recipient MAY process the fields(aside from those forbidden // above) as if they were appended to the message's header section. CopyHeaders(trailerHeaderStruct.ResponseHeaders, responseHeaders.ResponseHeaders); responseHeaders.ResponseHeaders.Remove("Transfer-Encoding"); responseHeaders.ContentHeaders.TryAddWithoutValidation("Content-Length", length.ToString()); responseHeaders.ResponseHeaders.Remove("Trailer"); } if (requestHeaders is { }) { var trailerHeaderStruct = trailerHeaderSection.ToHttpRequestHeaders(); AssertValidHeaders(trailerHeaderStruct.RequestHeaders, trailerHeaderStruct.ContentHeaders); // https://tools.ietf.org/html/rfc7230#section-4.1.2 // When a chunked message containing a non-empty trailer is received, // the recipient MAY process the fields(aside from those forbidden // above) as if they were appended to the message's header section. CopyHeaders(trailerHeaderStruct.RequestHeaders, requestHeaders.RequestHeaders); requestHeaders.RequestHeaders.Remove("Transfer-Encoding"); requestHeaders.ContentHeaders.TryAddWithoutValidation("Content-Length", length.ToString()); requestHeaders.RequestHeaders.Remove("Trailer"); } return decodedBody.ToArray(); } public static void RemoveInvalidTrailers(HeaderSection trailerHeaderSection) { // https://tools.ietf.org/html/rfc7230#section-4.1.2 // A sender MUST NOT generate a trailer that contains a field necessary // for message framing (e.g., Transfer - Encoding and Content - Length), trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Transfer-Encoding"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Content-Length"); // routing (e.g., Host) // request modifiers(e.g., controls and // https://tools.ietf.org/html/rfc7231#section-5.1 trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Cache-Control"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Expect"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Host"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Max-Forwards"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Pragma"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Range"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "TE"); // conditionals in Section 5 of[RFC7231]), // https://tools.ietf.org/html/rfc7231#section-5.2 trailerHeaderSection.Fields.RemoveAll(x => x.Name == "If-Match"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "If-None-Match"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "If-Modified-Since"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "If-Unmodified-Since"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "If-Range"); // authentication(e.g., see [RFC7235] // https://tools.ietf.org/html/rfc7235#section-5.3 trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Authorization"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Proxy-Authenticate"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Proxy-Authorization"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "WWW-Authenticate"); // and[RFC6265]), // https://tools.ietf.org/html/rfc6265 trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Set-Cookie"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Cookie"); // response control data(e.g., see Section 7.1 of[RFC7231]), // https://tools.ietf.org/html/rfc7231#section-7.1 trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Age"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Cache-Control"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Expires"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Date"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Location"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Retry-After"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Vary"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Warning"); // or determining how to process the payload(e.g., // Content - Encoding, Content - Type, Content - Range, and Trailer). trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Content-Encoding"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Content-Type"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Content-Range"); trailerHeaderSection.Fields.RemoveAll(x => x.Name == "Trailer"); } public static void ParseFistChunkLine(string firstChunkLine, out long chunkSize, out IEnumerable<string> chunkExtensions) { // https://tools.ietf.org/html/rfc7230#section-4.1 // chunk = chunk-size [ chunk-ext ] CRLF // https://tools.ietf.org/html/rfc7230#section-4.1.1 // chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] ) var parts = firstChunkLine.Split(";", StringSplitOptions.RemoveEmptyEntries); // https://tools.ietf.org/html/rfc7230#section-4.1 // The chunk-size field is a string of hex digits indicating the size of // the chunk-data in octets. chunkSize = Convert.ToInt64(parts.First().Trim(), 16); chunkExtensions = null; if (parts.Length > 1) { chunkExtensions = parts.Skip(1); } } private static async Task<byte[]> GetBytesTillEndAsync(Stream stream, CancellationToken ctsToken) { var bab = new ByteArrayBuilder(); while (true) { int read = await stream.ReadByteAsync(ctsToken).ConfigureAwait(false); if (read == -1) { return bab.ToArray(); } else { bab.Append((byte)read); } } } private static async Task<byte[]> ReadBytesTillLengthAsync(Stream stream, long? length, CancellationToken ctsToken) { try { Convert.ToInt32(length); } catch (OverflowException ex) { throw new NotSupportedException($"Content-Length too long: {length}.", ex); } var allData = new byte[(int)length]; var num = await stream.ReadBlockAsync(allData, (int)length, ctsToken).ConfigureAwait(false); if (num < (int)length) { // https://tools.ietf.org/html/rfc7230#section-3.3.3 // If the sender closes the connection or // the recipient times out before the indicated number of octets are // received, the recipient MUST consider the message to be // incomplete and close the connection. // https://tools.ietf.org/html/rfc7230#section-3.4 // A client that receives an incomplete response message, which can // occur when a connection is closed prematurely or when decoding a // supposedly chunked transfer coding fails, MUST record the message as // incomplete.Cache requirements for incomplete responses are defined // in Section 3 of[RFC7234]. throw new NotSupportedException($"Incomplete message. Expected length: {length}. Actual: {num}."); } return allData; } public static void AssertValidHeaders(HttpHeaders messageHeaders, HttpContentHeaders contentHeaders) { if (messageHeaders is { } && messageHeaders.Contains("Transfer-Encoding")) { if (contentHeaders is { } && contentHeaders.Contains("Content-Length")) { contentHeaders.Remove("Content-Length"); } } // Any Content-Length field value greater than or equal to zero is valid. if (contentHeaders is { } && contentHeaders.Contains("Content-Length")) { if (contentHeaders.ContentLength < 0) { throw new HttpRequestException("Content-Length MUST be greater than or equal to zero."); } } } public static byte[]? GetDummyOrNullContentBytes(HttpContentHeaders contentHeaders) { if (contentHeaders.NotNullAndNotEmpty()) { return Array.Empty<byte>(); // dummy empty content } return null; } public static void CopyHeaders(HttpHeaders source, HttpHeaders destination) { if (!source.NotNullAndNotEmpty()) { return; } foreach (var header in source) { destination.TryAddWithoutValidation(header.Key, header.Value); } } } }
/*=================================\ * PlotterControl\Form_Macros.cs * * The Coestaris licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. * * Created: 27.11.2017 14:04 * Last Edited: 27.11.2017 14:04:46 *=================================*/ using CWA; using CWA.Printing.Macro; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Globalization; using System.Linq; using System.Windows.Forms; namespace CnC_WFA { public partial class Form_Macro : Form { private const int scrw = 1180; private const int scrh = 720; private PointF LastPoint; private bool IsUpped; private bool ForcePaint; private PointF ForcePaintPoint; private Macro main; private Pen PenRectangle; private GraphicsPath[] GrUpped, GrNormal; private Matrix Matrix; private float Zoom; private bool IsLoad; private string LastFilePath; public Form_Macro(string filename) { InitializeComponent(); main = new Macro(filename); if (main.CreatedVersion < new Version(GlobalOptions.Ver)) { var h = MessageBox.Show( TB.L.Phrase["Form_Macro.OlderVersionOfFile"], TB.L.Phrase["Form_Macro.Warning"], MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (h == DialogResult.Yes) { main.CreatedVersion = new Version(GlobalOptions.Ver); main.Save(filename); } } radioButton_elt_none.Checked = true; Form_macroses_Resize(null, null); PenRectangle = new Pen(Color.Black, 1) { DashStyle = DashStyle.Dash }; Zoom = (float)trackBar_zoom.Value / 100; label_zoom.Text = trackBar_zoom.Value + "%"; IsLoad = true; LastFilePath = filename; RenderGR(); Render(); UpDateListBox(); } public Form_Macro() { InitializeComponent(); main = new Macro(TB.L.Phrase["Form_MacroPack.NoName"], TB.L.Phrase["Form_MacroPack.NoDiscr"]); } private void RenderGR() { List<GraphicsPath> grUpped = new List<GraphicsPath>(); List<GraphicsPath> grNormal = new List<GraphicsPath>(); if (main.Elems.Count == 0) { GrUpped = new GraphicsPath[0]; GrNormal = new GraphicsPath[0]; return; } float CurXPos = 0, CurYPos = 0; MacroElem b; try { b = main.Elems.FindAll(a => a.Type == MacroElemType.MoveToPoint || a.Type == MacroElemType.MoveToPointAndDelay)[0]; } catch(ArgumentOutOfRangeException) { return; } if (b == null) return; CurXPos = b.MoveToPoint.X; CurYPos = b.MoveToPoint.Y; bool isUpped = true; grUpped.Add(new GraphicsPath()); foreach (var a in main.Elems) { if(a.Type == MacroElemType.Tool || a.Type == MacroElemType.ToolAndDelay) { if (a.ToolMove > 50) { isUpped = true; grUpped.Add(new GraphicsPath()); } if (a.ToolMove < -50) { grNormal.Add(new GraphicsPath()); isUpped = false; } } if (a.Type == MacroElemType.MoveRelative || a.Type == MacroElemType.MoveRelativeAndDelay) { if (isUpped) grUpped.Last().AddLine(CurXPos, CurYPos, CurXPos + a.MoveRelative.X, CurYPos + a.MoveRelative.Y); else grNormal.Last().AddLine(CurXPos, CurYPos, CurXPos + a.MoveRelative.X, CurYPos + a.MoveRelative.Y); CurXPos += a.MoveRelative.X; CurYPos += a.MoveRelative.Y; } if (a.Type == MacroElemType.MoveToPoint || a.Type == MacroElemType.MoveToPointAndDelay) { if (isUpped) grUpped.Last().AddLine(CurXPos, CurYPos, a.MoveToPoint.X, a.MoveToPoint.Y); else grNormal.Last().AddLine(CurXPos, CurYPos, a.MoveToPoint.X, a.MoveToPoint.Y); CurXPos = a.MoveToPoint.X; CurYPos = a.MoveToPoint.Y; } } LastPoint = new PointF(CurXPos, CurYPos); GrUpped = grUpped.ToArray(); GrNormal = grNormal.ToArray(); } private Bitmap MacroBmp; private void Render() { float height = scrh * Zoom; float wight = scrw * Zoom; Bitmap bmp = new Bitmap((int)(scrw * Zoom), (int)(scrh * Zoom)); Matrix = new Matrix(); Matrix.Scale(Zoom, Zoom); List<GraphicsPath> grUp = new List<GraphicsPath>(); GrUpped.ToList().ForEach(p=> grUp.Add((GraphicsPath)p.Clone())); List<GraphicsPath> grNo = new List<GraphicsPath>(); GrNormal.ToList().ForEach(p => grNo.Add((GraphicsPath)p.Clone())); foreach (var item in grUp) item.Transform(Matrix); foreach (var item in grNo) item.Transform(Matrix); using (Graphics gr = Graphics.FromImage(bmp)) { gr.FillRectangle(Brushes.White, new RectangleF(0, 0, wight, height)); if(MacroBmp != null) gr.DrawImage(MacroBmp, 0, 0, main.PicSize.Width * Zoom / .013f, main.PicSize.Height * Zoom / .013f); gr.DrawRectangle(PenRectangle, 2, 2, wight - 4, height - 4); foreach (var item in grUp) gr.DrawPath(new Pen(Color.Gray, 1 * Zoom) { DashStyle = DashStyle.Dash }, item); foreach (var item in grNo) gr.DrawPath(new Pen(Color.Black, 1 * Zoom), item); } Image img = pictureBox1.Image; pictureBox1.Image = bmp; if (img != null) img.Dispose(); } private void UpDateListBox() { if (IsLoad) toolStripMenuItem_saveas.Enabled = true; Text = string.Format(TB.L.Phrase["Form_Macro.Macro"], main.Name); listBox_elements.Items.Clear(); toolStripTextBox_discr.Text = main.Discr; toolStripTextBox_name.Text = main.Name; foreach (var a in main.Elems) listBox_elements.Items.Add(a.StringType); label_elements.Text = string.Format(TB.L.Phrase["Form_MacroPack.Elements"], listBox_elements.Items.Count); } private void Form_macroses_Load(object sender, EventArgs e) { radioButton_move_vetr.Checked = true; radioButton_elt_none.Checked = true; Form_macroses_Resize(null, null); PenRectangle = new Pen(Color.Black, 1) { DashStyle = DashStyle.Dash }; Zoom = 1; RenderGR(); Render(); UpDateListBox(); } private void trackBar1_Scroll(object sender, EventArgs e) { Zoom = (float)trackBar_zoom.Value / 100; Render(); label_zoom.Text = trackBar_zoom.Value + "%"; } private void button_addel_Click(object sender, EventArgs e) { IsUpped = CheckIsUpped(); if (radioButton_elt_move.Checked) { if (tabControl1.SelectedIndex == 0) { if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPoint, MoveToPoint = new PointF(float.Parse(textBox_move_topointx.Text, CultureInfo.InvariantCulture), float.Parse(textBox_move_topointy.Text, CultureInfo.InvariantCulture)) }); else main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPointAndDelay, Delay = (float)numericUpDown_delay.Value ,MoveToPoint = new PointF(float.Parse(textBox_move_topointx.Text, CultureInfo.InvariantCulture), float.Parse(textBox_move_topointy.Text, CultureInfo.InvariantCulture)) }); } if(tabControl1.SelectedIndex == 3) { int x = pictureBox1.PointToClient(MousePosition).X; int y = pictureBox1.PointToClient(MousePosition).Y; float locx = (x / Zoom); float locy = (y / Zoom); if (LastPoint.X == 0&& LastPoint.Y == 0) { if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPoint, MoveToPoint = new PointF(locx, locy) }); else if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPointAndDelay, MoveToPoint = new PointF(locx, locy) , Delay = (float)numericUpDown_delay.Value}); } else { if (!radioButton_move_hor.Checked) { if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPoint, MoveToPoint = new PointF(LastPoint.X - float.Parse(textBox_move_offhorvertlength.Text, CultureInfo.InvariantCulture), LastPoint.Y) }); else if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPointAndDelay, MoveToPoint = new PointF(LastPoint.X - float.Parse(textBox_move_offhorvertlength.Text, CultureInfo.InvariantCulture), LastPoint.Y), Delay = (float)numericUpDown_delay.Value }); } else { if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPoint, MoveToPoint = new PointF(LastPoint.X, LastPoint.Y - float.Parse(textBox_move_offhorvertlength.Text, CultureInfo.InvariantCulture)) }); else if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.MoveToPointAndDelay, MoveToPoint = new PointF(LastPoint.X, LastPoint.Y - float.Parse(textBox_move_offhorvertlength.Text, CultureInfo.InvariantCulture)), Delay = (float)numericUpDown_delay.Value }); } } } } else if(radioButton_elt_none.Checked) { if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.None }); else main.Elems.Add(new MacroElem() { Type = MacroElemType.Delay, Delay = (float)numericUpDown_delay.Value }); } else if(radioButton_elt_tup.Checked) { if(IsUpped) { MessageBox.Show( TB.L.Phrase["Form_Macro.AlreadyUpped"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } IsUpped = false; if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.Tool, ToolMove = GlobalOptions.StepHeightConst }); else main.Elems.Add(new MacroElem() { Type = MacroElemType.ToolAndDelay, ToolMove = GlobalOptions.StepHeightConst , Delay = (float)numericUpDown_delay.Value}); } else if(radioButton_elt_tdown.Checked) { if(!IsUpped) { MessageBox.Show( TB.L.Phrase["Form_Macro.AlreadyDown"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); return; } IsUpped = true; if (numericUpDown_delay.Value == 0) main.Elems.Add(new MacroElem() { Type = MacroElemType.Tool, ToolMove = - GlobalOptions.StepHeightConst }); else main.Elems.Add(new MacroElem() { Type = MacroElemType.ToolAndDelay, ToolMove = - GlobalOptions.StepHeightConst, Delay = (float)numericUpDown_delay.Value }); } RenderGR(); Render(); UpDateListBox(); } private bool CheckIsUpped() { bool isUpped = true; foreach (var a in main.Elems) { if (a.Type == MacroElemType.Tool || a.Type == MacroElemType.ToolAndDelay) { if (a.ToolMove > 50) isUpped = true; if (a.ToolMove < -50) isUpped = false; } } return isUpped; } private void Form_macroses_Resize(object sender, EventArgs e) { groupBox_addel.Location = new Point(Width - groupBox_addel.Width - 30, groupBox_addel.Location.Y); groupBox_main.Location = new Point(Width - groupBox_main.Width - 30, groupBox_main.Location.Y); groupBox_zoom.Location = new Point(Width - groupBox_zoom.Width - 30, groupBox_zoom.Location.Y); panel1.Width = Width - groupBox_zoom.Width - 30 - 20; panel1.Height = Height - 80; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (radioButton_elt_move.Checked) { pictureBox1.Refresh(); } string s = TB.L.Phrase["Form_Macro.Status"]; float locx = (pictureBox1.PointToClient(MousePosition).X / Zoom); float locy = (pictureBox1.PointToClient(MousePosition).Y / Zoom); float xmm = locx * GlobalOptions.MaxHeightSteps / scrw; float ymm = locy * GlobalOptions.MaxWidthSteps / scrh; toolStripStatusLabel_xglobal.Text = string.Format(s, (e == null ? "-" : e.X.ToString()), (e == null ? "-" : e.Y.ToString()), locx, locy, xmm * 0.01323f, ymm * 0.01323f, xmm, ymm); } private void Form_macroses_MouseMove(object sender, MouseEventArgs e) { pictureBox1_MouseMove(null, null); } private void radioButton_elt_move_CheckedChanged(object sender, EventArgs e) { tabControl1.Enabled = radioButton_elt_move.Checked; Render(); } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if(ForcePaint) { e.Graphics.DrawLine(Pens.Gray, LastPoint.X * Zoom, LastPoint.Y * Zoom, ForcePaintPoint.X, ForcePaintPoint.Y); } else if (PointToClient(MousePosition).X < Width - 240) { if (radioButton_elt_move.Checked) { int x = pictureBox1.PointToClient(MousePosition).X; int y = pictureBox1.PointToClient(MousePosition).Y; float locx = (x / Zoom); float locy = (y / Zoom); if(tabControl1.SelectedIndex == 3) { if (LastPoint.X != 0 && LastPoint.Y != 0) { if (radioButton_move_vetr.Checked) { textBox_move_offhorvertlength.Text = (LastPoint.X - locx).ToString(CultureInfo.InvariantCulture); e.Graphics.DrawLine(Pens.Gray, LastPoint.X * Zoom, LastPoint.Y * Zoom, x, LastPoint.Y * Zoom); } else { textBox_move_offhorvertlength.Text = (LastPoint.Y - locy).ToString(CultureInfo.InvariantCulture); e.Graphics.DrawLine(Pens.Gray, LastPoint.X * Zoom, LastPoint.Y * Zoom, LastPoint.X * Zoom, y); } } } else if (tabControl1.SelectedIndex == 0) { textBox_move_topointx.Text = locx.ToString(CultureInfo.InvariantCulture); textBox_move_topointy.Text = locy.ToString(CultureInfo.InvariantCulture); if (LastPoint.X != 0 && LastPoint.Y != 0) { if(IsUpped) e.Graphics.DrawLine(new Pen(Color.Blue, 1) { DashStyle = DashStyle.Dash }, LastPoint.X * Zoom, LastPoint.Y * Zoom, x, y); else e.Graphics.DrawLine(new Pen(Color.Blue, 1), LastPoint.X * Zoom, LastPoint.Y * Zoom, x, y); } } } } } private void pictureBox1_MouseDoubleClick(object sender, MouseEventArgs e) { button_addel_Click(null, null); } private void button_save_Click(object sender, EventArgs e) { if(IsLoad) { main.Save(LastFilePath); } else if(saveFileDialog1.ShowDialog() == DialogResult.OK) { main.Save(saveFileDialog1.FileName); } } private void button_load_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { main = new Macro(openFileDialog1.FileName); if (main.CreatedVersion < new Version(GlobalOptions.Ver)) { var h = MessageBox.Show( TB.L.Phrase["Form_Macro.OlderVersionOfFile"], TB.L.Phrase["Form_Macro.Warning"], MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (h == DialogResult.Yes) { main.CreatedVersion = new Version(GlobalOptions.Ver); main.Save(openFileDialog1.FileName); } } radioButton_elt_none.Checked = true; Form_macroses_Resize(null, null); MacroBmp = new Bitmap(main.PicFileName); PenRectangle = new Pen(Color.Black, 1) { DashStyle = DashStyle.Dash }; Zoom = 1; IsLoad = true; LastFilePath = openFileDialog1.FileName; Zoom = (float)trackBar_zoom.Value / 100; label_zoom.Text = trackBar_zoom.Value + "%"; RenderGR(); Render(); UpDateListBox(); } } private void listBox_elements_MouseClick(object sender, MouseEventArgs e) { string strTip = ""; int nIdx = listBox_elements.IndexFromPoint(e.Location); if ((nIdx >= 0) && (nIdx < listBox_elements.Items.Count)) strTip = listBox_elements.Items[nIdx].ToString(); toolTip1.SetToolTip(listBox_elements, strTip); } private void ToCorner() { float minx = scrw; float miny = scrh; foreach (var a in main.Elems) { if(a.Type == MacroElemType.MoveToPoint || a.Type == MacroElemType.MoveToPointAndDelay) { minx = Math.Min(minx, a.MoveToPoint.X); miny = Math.Min(miny, a.MoveToPoint.Y); } } for (int i = 0; i <= main.Elems.Count - 1; i++) { if (main.Elems[i].Type == MacroElemType.MoveToPoint || main.Elems[i].Type == MacroElemType.MoveToPointAndDelay) { main.Elems[i] = new MacroElem() { Type = main.Elems[i].Type, Delay = main.Elems[i].Delay, MoveToPoint = new PointF(main.Elems[i].MoveToPoint.X - minx, main.Elems[i].MoveToPoint.Y - miny) }; } } RenderGR(); Render(); UpDateListBox(); } private void button_100percent_Click_1(object sender, EventArgs e) { button_100percent_Click(null, null); } private void textBox_move_topointx_TextChanged(object sender, EventArgs e) { if (PointToClient(MousePosition).X > Width - 240) { ForcePaint = true; float a, b; string s1 = textBox_move_topointx.Text; if (!float.TryParse(s1, out a)) MessageBox.Show( "'" + s1 + TB.L.Phrase["Connection.WrongFloatInput"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); string s2 = textBox_move_topointy.Text; if (!float.TryParse(s2, out b)) MessageBox.Show( "'" + s2 + TB.L.Phrase["Connection.WrongFloatInput"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); ForcePaintPoint = new PointF(a, b); pictureBox1.Refresh(); } } private void textBox_move_topointy_TextChanged(object sender, EventArgs e) { if (PointToClient(MousePosition).X > Width - 240) { ForcePaint = true; float a, b; string s1 = textBox_move_topointx.Text; if (!float.TryParse(s1, out a)) MessageBox.Show( "'" + s1 + TB.L.Phrase["Connection.WrongFloatInput"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); string s2 = textBox_move_topointy.Text; if (!float.TryParse(s2, out b)) MessageBox.Show( "'" + s2 + TB.L.Phrase["Connection.WrongFloatInput"], TB.L.Phrase["Connection.Error"], MessageBoxButtons.OK, MessageBoxIcon.Error); ForcePaintPoint = new PointF(a, b); pictureBox1.Refresh(); } } private void pictureBox1_MouseEnter(object sender, EventArgs e) { ForcePaint = false; } private void tabControl1_MouseEnter(object sender, EventArgs e) { ForcePaint = true; } private void textBox_move_topointx_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) button_addel_Click(null, null); } private void textBox_move_topointy_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) button_addel_Click(null, null); } private void pictureBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if(e.KeyCode == Keys.Shift && PointToClient(MousePosition).X < Width - 240 && radioButton_elt_move.Checked && tabControl1.SelectedIndex == 3) radioButton_move_vetr.Checked = !radioButton_move_vetr.Checked; } private void Form_macroses_KeyDown(object sender, KeyEventArgs e) { pictureBox1_PreviewKeyDown(null, null); } private void tabControl1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && PointToClient(MousePosition).X < Width - 240 && radioButton_elt_move.Checked && tabControl1.SelectedIndex == 3) { radioButton_move_vetr.Checked = !radioButton_move_vetr.Checked; radioButton_move_hor.Checked = !radioButton_move_vetr.Checked; } } private void button_clear_Click(object sender, EventArgs e) { main = new Macro("noname", "nodiscr"); main.Elems = new List<MacroElem>(); UpDateListBox(); radioButton_elt_none.Checked = true; Form_macroses_Resize(null, null); PenRectangle = new Pen(Color.Black, 1); PenRectangle.DashStyle = DashStyle.Dash; Zoom = 1; Zoom = (float)trackBar_zoom.Value / 100; label_zoom.Text = trackBar_zoom.Value + "%"; RenderGR(); Render(); UpDateListBox(); } private void textBox_name_TextChanged(object sender, EventArgs e) { main.Name = toolStripTextBox_name.Text; Text = string.Format(TB.L.Phrase["Form_Macro.Macro"], main.Name); } private void textBox_descr_TextChanged(object sender, EventArgs e) { main.Discr = toolStripTextBox_discr.Text; Text = string.Format(TB.L.Phrase["Form_Macro.Macro"], main.Name); } private void button3_Click(object sender, EventArgs e) { Close(); } private void toolStripMenuItem_saveas_Click(object sender, EventArgs e) { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { main.Save(saveFileDialog1.FileName); } } private void toolStripMenuItem_tocorner_Click(object sender, EventArgs e) { } private void toolStripMenuItem_addimg_Click(object sender, EventArgs e) { if(string.IsNullOrEmpty(main.PicFileName)) { var f = FormTranslator.Translate(new Form_Dialog_MacroAddImage()); if (f.ShowDialog() == DialogResult.OK) { main.PicFileName = f.Path; main.PicSize = new SizeF(f.XSize, f.YSize); MacroBmp = new Bitmap(f.Path); }; } else { var f = FormTranslator.Translate(new Form_Dialog_MacroAddImage() { Path = main.PicFileName, XSize = main.PicSize.Width, YSize = main.PicSize.Height }); if (f.ShowDialog() == DialogResult.OK) { main.PicFileName = f.Path; main.PicSize = new SizeF(f.XSize, f.YSize); MacroBmp = new Bitmap(f.Path); }; } } private void button_100percent_Click(object sender, EventArgs e) { trackBar_zoom.Value = 100; trackBar1_Scroll(null, null); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading; using System.Windows.Forms; using DeOps.Services; using DeOps.Services.Board; using DeOps.Services.Mail; using DeOps.Services.Profile; using DeOps.Services.Storage; using DeOps.Services.Transfer; using DeOps.Services.Trust; using DeOps.Implementation; using DeOps.Implementation.Dht; using DeOps.Implementation.Protocol; using DeOps.Implementation.Protocol.Net; using DeOps.Implementation.Transport; using DeOps.Interface; namespace DeOps.Simulator { public partial class NetView : CustomIconForm { SimForm Main; InternetSim Sim; ulong OpID; Bitmap DisplayBuffer; bool Redraw; bool ReInitBuffer; Pen BluePen = new Pen(Color.LightBlue, 1); Pen TrafficPen = new Pen(Color.WhiteSmoke, 1); Pen BlackPen = new Pen(Color.Black, 1); SolidBrush GreenBrush = new SolidBrush(Color.Green); SolidBrush RedBrush = new SolidBrush(Color.Red); SolidBrush OrangeBrush = new SolidBrush(Color.Orange); SolidBrush BlackBrush = new SolidBrush(Color.Black); SolidBrush BlueBrush = new SolidBrush(Color.Blue); SolidBrush PurpleBrush = new SolidBrush(Color.Purple); Font TahomaFont = new Font("Tahoma", 8); ulong SelectedID; bool ShowInbound; Dictionary<ulong, Rectangle> NodeBoxes = new Dictionary<ulong, Rectangle>(); Dictionary<ulong, Point> NodePoints = new Dictionary<ulong, Point>(); List<Point> TrackPoints = new List<Point>(); List<Point> TransferPoints = new List<Point>(); Dictionary<ulong, BitArray> NodeBitfields = new Dictionary<ulong, BitArray>(); G2Protocol Protocol = new G2Protocol(); public string TrackString; public byte[] TrackHash; public ulong TrackHashID; ToolTip NodeTip = new ToolTip(); LegendForm Legend = new LegendForm(); public NetView(SimForm main, ulong id) { Main = main; Sim = Main.Sim; OpID = id; Redraw = true; SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); Sim.UpdateView += new UpdateViewHandler(OnUpdateView); InitializeComponent(); NodeTip.ShowAlways = true; } private void NetView_Load(object sender, EventArgs e) { string name = "Unknown"; if (Sim.OpNames.ContainsKey(OpID)) name = Sim.OpNames[OpID]; else if (OpID == 0) name = "Lookup"; Text = name + " Network"; } private void NetView_FormClosing(object sender, FormClosingEventArgs e) { Sim.UpdateView -= new UpdateViewHandler(OnUpdateView); Main.NetViews.Remove(OpID); } public void OnUpdateView() { if (Thread.CurrentThread.ManagedThreadId != Main.UiThreadId) { BeginInvoke(Sim.UpdateView); return; } Redraw = true; Invalidate(); } private void NetView_Paint(object sender, PaintEventArgs e) { int width = ClientRectangle.Width; int height = ClientRectangle.Height; if (width == 0 || height == 0) return; if (DisplayBuffer == null || ReInitBuffer) { DisplayBuffer = new Bitmap(width, height); ReInitBuffer = false; } if (!Redraw) { e.Graphics.DrawImage(DisplayBuffer, 0, 0); return; } Redraw = false; // background Graphics buffer = Graphics.FromImage(DisplayBuffer); buffer.Clear(Color.White); buffer.SmoothingMode = SmoothingMode.AntiAlias; // calc radii Point centerPoint = new Point(width / 2, height / 2); int maxRadius = (height > width) ? width / 2 : height / 2; maxRadius -= 15; // get node points NodePoints.Clear(); TrackPoints.Clear(); TransferPoints.Clear(); Dictionary<ulong, DhtNetwork> networks = new Dictionary<ulong, DhtNetwork>(); Sim.Instances.SafeForEach(instance => { if (OpID == 0) { if (instance.Context.Lookup != null) networks[instance.Context.Lookup.UserID] = instance.Context.Lookup.Network; } else instance.Context.Cores.LockReading(delegate() { foreach (OpCore core in instance.Context.Cores) if (OpID == core.Network.OpID) networks[core.UserID] = core.Network; }); }); NodeBitfields.Clear(); foreach (DhtNetwork network in networks.Values) { ulong userID = network.Core.UserID; int nodeRadius = (network.Core.Firewall == FirewallType.Open) ? maxRadius - 30 : maxRadius; NodePoints[userID] = GetCircumPoint(centerPoint, nodeRadius, IDto32(userID)); if (TrackHash != null) { if (IsTracked(network.Core)) TrackPoints.Add(GetCircumPoint(centerPoint, nodeRadius + 7, IDto32(userID))); foreach (OpTransfer transfer in network.Core.Transfers.Transfers.Values) if (Utilities.MemCompare(transfer.Details.Hash, TrackHash)) { TransferPoints.Add(GetCircumPoint(centerPoint, nodeRadius + 7, IDto32(userID))); if(transfer.LocalBitfield != null) NodeBitfields[userID] = transfer.LocalBitfield; } } } // draw lines for tcp between points foreach(DhtNetwork network in networks.Values) lock(network.TcpControl.SocketList) foreach(TcpConnect connect in network.TcpControl.SocketList) if(connect.State == TcpState.Connected && NodePoints.ContainsKey(connect.UserID)) buffer.DrawLine(BluePen, NodePoints[network.Local.UserID], NodePoints[connect.UserID]); // draw traffic lines DrawTraffic(buffer); // draw nodes NodeBoxes.Clear(); foreach (ulong id in NodePoints.Keys) { SolidBrush brush = null; FirewallType firewall = networks[id].Core.Firewall; if(firewall == FirewallType.Open) brush = GreenBrush; if(firewall == FirewallType.NAT) brush = OrangeBrush; if(firewall == FirewallType.Blocked) brush = RedBrush; NodeBoxes[id] = GetBoundingBox(NodePoints[id], 4); buffer.FillEllipse(brush, NodeBoxes[id]); } // draw tracked foreach (Point point in TrackPoints) buffer.FillEllipse(BlueBrush, GetBoundingBox(point, 3)); foreach (Point point in TransferPoints) buffer.FillEllipse(PurpleBrush, GetBoundingBox(point, 3)); int barwidth = 150; MissingBrush.Color = Color.White; int[] popularity = null; // popularity is nodes who have the transfer loaded (up/down) foreach(ulong user in NodeBitfields.Keys) { BitArray bitfield = NodeBitfields[user]; Rectangle box = NodeBoxes[user]; // determine popularity if (popularity == null) popularity = new int[bitfield.Length]; for (int i = 0; i < bitfield.Length; i++) if (bitfield[i]) popularity[i]++; // draw bar int x = (box.X < width / 2) ? box.X + box.Width + 1 : // right sie box.X - 1 - barwidth; // right side Rectangle bar = new Rectangle(x, box.Y, barwidth, box.Height); DrawBitfield(buffer, bar, bitfield); } // draw total completed bar in bottom right if (popularity != null) { int max = popularity.Max(); Rectangle totalBox = new Rectangle(width - 300 - 5, height - 16 - 5, 300, 16); buffer.FillRectangle(CompletedBrush, totalBox); for (int i = 0; i < popularity.Length; i++) { int brightness = 255 - popularity[i] * 255 / max; // high brighness -> white -> less people have file MissingBrush.Color = Color.FromArgb(brightness, brightness, 255); DrawPiece(buffer, popularity.Length, totalBox, i, i + 1); } buffer.DrawRectangle(BorderPen, totalBox); } // mark selected if (SelectedID != 0 && NodeBoxes.ContainsKey(SelectedID)) { Rectangle selectBox = NodeBoxes[SelectedID]; selectBox.Inflate(2,2); buffer.DrawEllipse(BlackPen, selectBox); string name = networks[SelectedID].Core.User.Settings.UserName; name += " " + Utilities.IDtoBin(networks[SelectedID].Local.UserID); name += ShowInbound ? " Inbound Traffic" : " Outbound Traffic"; buffer.DrawString(name, TahomaFont, BlackBrush, new PointF(3, 37)); } // write hits for global if(OpID == 0) buffer.DrawString(Sim.WebCacheHits + " WebCache Hits", TahomaFont, BlackBrush, new PointF(3, 25)); if (TrackString != null) buffer.DrawString("Tracking: " + TrackString, TahomaFont, BlackBrush, 3, height - 20); // Copy buffer to display e.Graphics.DrawImage(DisplayBuffer, ClientRectangle.X, ClientRectangle.Y); } SolidBrush CompletedBrush = new SolidBrush(Color.CornflowerBlue); SolidBrush MissingBrush = new SolidBrush(Color.White); Pen BorderPen = new Pen(Color.Black); private void DrawBitfield(Graphics buffer, Rectangle bar, BitArray bitfield) { buffer.FillRectangle(CompletedBrush, bar); // cut out missing pieces, so worst case they are visible // opposed to other way where they'd be hidden int start = -1; for (int i = 0; i < bitfield.Length; i++) // has if (bitfield[i]) { if (start != -1) { DrawPiece(buffer, bitfield.Length, bar, start, i); start = -1; } } // missing else if (start == -1) start = i; // draw last missing piece if (start != -1) DrawPiece(buffer, bitfield.Length, bar, start, bitfield.Length); buffer.DrawRectangle(BorderPen, bar); } private void DrawPiece(Graphics buffer, int bits, Rectangle box, float start, float end) { float scale = (float)box.Width / (float)bits; int x1 = (int)(start * scale); int x2 = (int)(end * scale); buffer.FillRectangle(MissingBrush, box.X + x1, box.Y, x2 - x1, box.Height); } private bool IsTracked(OpCore core) { bool found = false; // storage StorageService storage = core.GetService(ServiceIDs.Storage) as StorageService; if (!found && storage != null) if (storage.FileMap.SafeContainsKey(TrackHashID)) found = true; // link if(!found) core.Trust.TrustMap.LockReading(delegate() { foreach (OpTrust trust in core.Trust.TrustMap.Values) if (trust.Loaded && Utilities.MemCompare(trust.File.Header.FileHash, TrackHash)) { found = true; break; } }); // profile ProfileService profiles = core.GetService(ServiceIDs.Profile) as ProfileService; if (!found && profiles != null) profiles.ProfileMap.LockReading(delegate() { foreach (OpProfile profile in profiles.ProfileMap.Values) if (Utilities.MemCompare(profile.File.Header.FileHash, TrackHash)) { found = true; break; } }); // mail MailService mail = core.GetService(ServiceIDs.Mail) as MailService; if (!found && mail != null) { foreach (CachedPending pending in mail.PendingMap.Values) if (Utilities.MemCompare(pending.Header.FileHash, TrackHash)) return true; foreach (List<CachedMail> list in mail.MailMap.Values) foreach (CachedMail cached in list) if (Utilities.MemCompare(cached.Header.FileHash, TrackHash)) { found = true; break; } } // board BoardService boards = core.GetService(ServiceIDs.Board) as BoardService; if (!found && boards != null) boards.BoardMap.LockReading(delegate() { foreach (OpBoard board in boards.BoardMap.Values) if (!found) board.Posts.LockReading(delegate() { foreach (OpPost post in board.Posts.Values) if (Utilities.MemCompare(post.Header.FileHash, TrackHash)) { found = true; break; } }); }); return found; } Point GetCircumPoint(Point center, int rad, uint position) { double fraction = (double)position / (double)uint.MaxValue; int xPos = (int)((double)rad * Math.Cos(fraction * 2 * Math.PI)) + center.X; int yPos = (int)((double)rad * Math.Sin(fraction * 2 * Math.PI)) + center.Y; return new Point(xPos, yPos); } private void NetView_Resize(object sender, EventArgs e) { if (Width > 0 && Height > 0) { ReInitBuffer = true; Redraw = true; Invalidate(); } } uint IDto32(UInt64 id) { return (uint)(id >> 32); } Rectangle GetBoundingBox(Point center, int rad) { return new Rectangle(center.X - rad, center.Y - rad, rad * 2, rad * 2); } private void NetView_MouseClick(object sender, MouseEventArgs e) { bool set = false; foreach(ulong id in NodeBoxes.Keys) if (NodeBoxes[id].Contains(e.Location)) { if (id == SelectedID) ShowInbound = !ShowInbound; else SelectedID = id; set = true; break; } if (!set) SelectedID = 0; Redraw = true; Invalidate(); } void DrawTraffic(Graphics buffer) { Dictionary<ulong, Dictionary<ulong, PacketGroup>> UdpTraffic = new Dictionary<ulong, Dictionary<ulong, PacketGroup>>(); Dictionary<ulong, Dictionary<ulong, PacketGroup>> TcpTraffic = new Dictionary<ulong, Dictionary<ulong, PacketGroup>>(); for (int i = 0; i < Sim.OutPackets.Length; i++) lock (Sim.OutPackets[i]) foreach (SimPacket packet in Sim.OutPackets[i]) if (SelectedID == 0 || (!ShowInbound && SelectedID == packet.SenderID) || (ShowInbound && SelectedID == packet.Dest.Local.UserID)) if ((packet.Dest.IsLookup && OpID == 0) || (!packet.Dest.IsLookup && packet.Dest.OpID == OpID)) { Dictionary<ulong, Dictionary<ulong, PacketGroup>> TrafficGroup = packet.Tcp != null ? TcpTraffic : UdpTraffic; if (!TrafficGroup.ContainsKey(packet.SenderID)) TrafficGroup[packet.SenderID] = new Dictionary<ulong, PacketGroup>(); if (!TrafficGroup[packet.SenderID].ContainsKey(packet.Dest.Local.UserID)) TrafficGroup[packet.SenderID][packet.Dest.Local.UserID] = new PacketGroup(packet.SenderID, packet.Dest.Local.UserID); TrafficGroup[packet.SenderID][packet.Dest.Local.UserID].Add(packet); } DrawGroup(buffer, UdpTraffic, false); DrawGroup(buffer, TcpTraffic, true); } private void DrawGroup(Graphics buffer, Dictionary<ulong, Dictionary<ulong, PacketGroup>> TrafficGroup, bool tcp) { foreach (Dictionary<ulong, PacketGroup> destination in TrafficGroup.Values) foreach (PacketGroup group in destination.Values) { if (!NodePoints.ContainsKey(group.SourceID) || !NodePoints.ContainsKey(group.DestID)) continue; group.SetPoints(NodePoints[group.SourceID], NodePoints[group.DestID]); TrafficPen.Width = 1; group.LineSize = 200 + 20; if (group.TotalSize > 200) { TrafficPen.Width = 2; group.LineSize = 1000 + 100; } if (group.TotalSize > 1000) { TrafficPen.Width = 3; group.LineSize = group.TotalSize + 500; } // calc break size double breakSize = (group.LineSize - group.TotalSize) / (group.Packets.Count + 1); double pos = breakSize; Color bgColor = Color.WhiteSmoke; //if (SelectedID != 0) // bgColor = group.SourceID == SelectedID ? Color.LightCoral : Color.LightBlue; //else // bgColor = tcp ? Color.LightBlue : Color.WhiteSmoke; TrafficPen.Color = bgColor; buffer.DrawLine(TrafficPen, group.GetPoint(0), group.GetPoint(pos)); foreach (byte[] packet in group.Packets) { if (Sim.TestEncryption || Sim.TestTcpFullBuffer) { TrafficPen.Color = Legend.PicUnk.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + packet.Length)); } else { G2Header root = new G2Header(packet); G2Protocol.ReadPacket(root); double controlLen = (root.InternalPos > 0) ? root.InternalPos - root.PacketPos : packet.Length; // net packet if (root.Name == RootPacket.Network) { TrafficPen.Color = Legend.PicNet.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + controlLen)); NetworkPacket netPacket = NetworkPacket.Decode(root); G2Header internalRoot = new G2Header(netPacket.InternalData); G2Protocol.ReadPacket(internalRoot); G2ReceivedPacket recvedPacket = new G2ReceivedPacket(); recvedPacket.Root = internalRoot; // draw internal TrafficPen.Color = Legend.PicUnk.BackColor; if (internalRoot.Name == NetworkPacket.SearchRequest) { SearchReq req = SearchReq.Decode(recvedPacket); int paramLen = req.Parameters == null ? 10 : req.Parameters.Length; TrafficPen.Color = Legend.PicSrchReq.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize - paramLen)); TrafficPen.Color = GetComponentColor(req.Service); buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen + internalRoot.PacketSize - paramLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize)); } else if (internalRoot.Name == NetworkPacket.SearchAck) { SearchAck ack = SearchAck.Decode(recvedPacket); int valLen = 10; if (ack.ValueList.Count > 0) { valLen = 0; foreach (byte[] val in ack.ValueList) valLen += val.Length; } TrafficPen.Color = Legend.PicSrchAck.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize - valLen)); TrafficPen.Color = GetComponentColor(ack.Service); buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen + internalRoot.PacketSize - valLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize)); } else if (internalRoot.Name == NetworkPacket.StoreRequest) { StoreReq req = StoreReq.Decode(recvedPacket); int dataLen = req.Data == null ? 10 : req.Data.Length; TrafficPen.Color = Legend.PicStore.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize - dataLen)); TrafficPen.Color = GetComponentColor(req.Service); buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen + internalRoot.PacketSize - dataLen), group.GetPoint(pos + controlLen + internalRoot.PacketSize)); } else { if (internalRoot.Name == NetworkPacket.Ping) TrafficPen.Color = Legend.PicPing.BackColor; else if (internalRoot.Name == NetworkPacket.Pong) TrafficPen.Color = Legend.PicPong.BackColor; else if (internalRoot.Name == NetworkPacket.ProxyRequest) TrafficPen.Color = Legend.PicPxyReq.BackColor; else if (internalRoot.Name == NetworkPacket.ProxyAck) TrafficPen.Color = Legend.PicPxyAck.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + packet.Length)); } } // comm packet if (root.Name == RootPacket.Comm) { TrafficPen.Color = Legend.PicComm.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + controlLen)); TrafficPen.Color = Legend.PicUnk.BackColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos + controlLen), group.GetPoint(pos + packet.Length)); } } if (SelectedID != 0) buffer.DrawString(group.TotalSize.ToString(), TahomaFont, BlackBrush, group.GetPoint(group.LineSize / 4)); pos += packet.Length; TrafficPen.Color = bgColor; buffer.DrawLine(TrafficPen, group.GetPoint(pos), group.GetPoint(pos + breakSize)); pos += breakSize; } } } private Color GetComponentColor(uint id) { switch (id) { case 0://ServiceID.DHT: return Legend.PicNode.BackColor; case 1://ServiceID.Trust: return Legend.PicLink.BackColor; case 2://ServiceID.Location: return Legend.PicLoc.BackColor; case 3://ServiceID.Transfer: return Legend.PicTransfer.BackColor; case 4://ServiceID.Profile: return Legend.PicProfile.BackColor; case 8://ServiceID.Board: return Legend.PicBoard.BackColor; case 7: //ServiceID.Mail: return Legend.PicMail.BackColor; } return Legend.PicUnk.BackColor; } ulong CurrentTip; private void NetView_MouseMove(object sender, MouseEventArgs e) { Point client = PointToClient(Cursor.Position); foreach (ulong id in NodeBoxes.Keys) if (NodeBoxes[id].Contains(client)) { if(CurrentTip != id) { string name = "Unknown"; Sim.Instances.SafeForEach(instance => { if (instance.Context.Lookup != null && instance.Context.Lookup.UserID == id) name = instance.Context.Lookup.LocalIP.ToString(); else instance.Context.Cores.LockReading(delegate() { foreach (OpCore core in instance.Context.Cores) if (core.UserID == id) { name = core.User.Settings.UserName; break; } }); }); NodeTip.Show(name, this, client.X, client.Y); CurrentTip = id; } return; } CurrentTip = 0; NodeTip.Hide(this); } private void LegendMenu_Click(object sender, EventArgs e) { LegendForm form = new LegendForm(); form.Show(); } private void TrackMenuItem_Click(object sender, EventArgs e) { TrackFile form = new TrackFile(this); form.Show(); } } public class PacketGroup { public ulong SourceID; public ulong DestID; public Point SourcePoint; public Point DestPoint; public int TotalSize; public double LineSize; public List<byte[]> Packets = new List<byte[]>(); // trig double Opp; double Adj; double Hyp; double Ang; public PacketGroup(ulong source, ulong dest) { SourceID = source; DestID = dest; } public void Add(SimPacket wrap) { if (wrap.Packet == null) return; TotalSize += wrap.Packet.Length; Packets.Add(wrap.Packet); } public void SetPoints(Point source, Point dest) { SourcePoint = source; DestPoint = dest; // get width and height between two lines Opp = dest.Y - source.Y; Adj = dest.X - source.X; // figure length of hypotenuse Hyp = Math.Sqrt(Math.Pow(Adj, 2) + Math.Pow(Opp, 2)); Ang = Math.Abs(Math.Asin(Opp / Hyp)); } public Point GetPoint(double pos) { double frac = pos / LineSize; double newHyp = Hyp * frac; double newOpp = newHyp * Math.Sin(Ang); double newAdj = newHyp * Math.Cos(Ang); if (Opp < 0) newOpp *= -1; if (Adj < 0) newAdj *= -1; return new Point(SourcePoint.X + (int)newAdj, SourcePoint.Y + (int)newOpp); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableMultiplyTests { #region Test methods [Fact] public static void CheckNullableByteMultiplyTest() { byte?[] array = { 0, 1, byte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteMultiply(array[i], array[j]); } } } [Fact] public static void CheckNullableSByteMultiplyTest() { sbyte?[] array = { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteMultiply(array[i], array[j]); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortMultiplyTest(bool useInterpreter) { ushort?[] array = { 0, 1, ushort.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortMultiply(array[i], array[j], useInterpreter); VerifyNullableUShortMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortMultiplyTest(bool useInterpreter) { short?[] array = { 0, 1, -1, short.MinValue, short.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortMultiply(array[i], array[j], useInterpreter); VerifyNullableShortMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntMultiplyTest(bool useInterpreter) { uint?[] array = { 0, 1, uint.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntMultiply(array[i], array[j], useInterpreter); VerifyNullableUIntMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntMultiplyTest(bool useInterpreter) { int?[] array = { 0, 1, -1, int.MinValue, int.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntMultiply(array[i], array[j], useInterpreter); VerifyNullableIntMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongMultiplyTest(bool useInterpreter) { ulong?[] array = { 0, 1, ulong.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongMultiply(array[i], array[j], useInterpreter); VerifyNullableULongMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongMultiplyTest(bool useInterpreter) { long?[] array = { 0, 1, -1, long.MinValue, long.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongMultiply(array[i], array[j], useInterpreter); VerifyNullableLongMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableFloatMultiplyTest(bool useInterpreter) { float?[] array = { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableFloatMultiply(array[i], array[j], useInterpreter); VerifyNullableFloatMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDoubleMultiplyTest(bool useInterpreter) { double?[] array = { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDoubleMultiply(array[i], array[j], useInterpreter); VerifyNullableDoubleMultiplyOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableDecimalMultiplyTest(bool useInterpreter) { decimal?[] array = { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue, null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableDecimalMultiply(array[i], array[j], useInterpreter); VerifyNullableDecimalMultiplyOvf(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckNullableCharMultiplyTest() { char?[] array = { '\0', '\b', 'A', '\uffff', null }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableCharMultiply(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyNullableByteMultiply(byte? a, byte? b) { Expression aExp = Expression.Constant(a, typeof(byte?)); Expression bExp = Expression.Constant(b, typeof(byte?)); Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp)); Assert.Throws<InvalidOperationException>(() => Expression.MultiplyChecked(aExp, bExp)); } private static void VerifyNullableSByteMultiply(sbyte? a, sbyte? b) { Expression aExp = Expression.Constant(a, typeof(sbyte?)); Expression bExp = Expression.Constant(b, typeof(sbyte?)); Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp)); Assert.Throws<InvalidOperationException>(() => Expression.MultiplyChecked(aExp, bExp)); } private static void VerifyNullableUShortMultiply(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Multiply( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort?)(a * b)), f()); } private static void VerifyNullableUShortMultiplyOvf(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); ushort? expected; try { expected = checked((ushort?)(a * b)); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableShortMultiply(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Multiply( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); Assert.Equal(unchecked((short?)(a * b)), f()); } private static void VerifyNullableShortMultiplyOvf(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); short? expected; try { expected = checked((short?)(a * b)); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableUIntMultiply(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Multiply( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a * b), f()); } private static void VerifyNullableUIntMultiplyOvf(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); uint? expected; try { expected = checked(a * b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableIntMultiply(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Multiply( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a * b), f()); } private static void VerifyNullableIntMultiplyOvf(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); int? expected; try { expected = checked(a * b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableULongMultiply(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Multiply( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a * b), f()); } private static void VerifyNullableULongMultiplyOvf(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); ulong? expected; try { expected = checked(a * b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableLongMultiply(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Multiply( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a * b), f()); } private static void VerifyNullableLongMultiplyOvf(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); long? expected; try { expected = checked(a * b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableFloatMultiply(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Multiply( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a * b, f()); } private static void VerifyNullableFloatMultiplyOvf(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a * b, f()); } private static void VerifyNullableDoubleMultiply(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Multiply( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a * b, f()); } private static void VerifyNullableDoubleMultiplyOvf(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a * b, f()); } private static void VerifyNullableDecimalMultiply(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Multiply( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); decimal? expected; try { expected = a * b; } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableDecimalMultiplyOvf(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.MultiplyChecked( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); decimal? expected; try { expected = a * b; } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyNullableCharMultiply(char? a, char? b) { Expression aExp = Expression.Constant(a, typeof(char?)); Expression bExp = Expression.Constant(b, typeof(char?)); Assert.Throws<InvalidOperationException>(() => Expression.Multiply(aExp, bExp)); Assert.Throws<InvalidOperationException>(() => Expression.MultiplyChecked(aExp, bExp)); } #endregion } }
using System; using System.Collections.Generic; using DevExpress.XtraBars; using DevExpress.XtraNavBar; using DevExpress.XtraPrinting; using DevExpress.XtraPrinting.Preview; using DevExpress.XtraReports.UI; using EIDSS.RAM.Components; using EIDSS.RAM.Presenters; using EIDSS.RAM.Presenters.Base; using EIDSS.RAM_DB.Common.CommandProcessing.Commands.Layout; using EIDSS.RAM_DB.Common.EventHandlers; using EIDSS.RAM_DB.Views; using EIDSS.Reports.BaseControls; using bv.common; using bv.common.Core; using bv.winclient.Core; using eidss.model.Core; using eidss.model.Enums; using eidss.model.Resources; namespace EIDSS.RAM.Layout { public partial class PivotReportForm : BaseLayoutForm, IPivotReportView { private PivotReport m_Report; private readonly PivotReportPresenter m_ReportPresenter; private RamPivotGrid m_CustomSummarySource; public PivotReportForm() { Trace.WriteLine(Trace.Kind.Info, "PivotReportForm creating..."); InitializeComponent(); m_ReportPresenter = (PivotReportPresenter) BaseRamPresenter; if (IsDesignMode()) { return; } m_Report = new PivotReport(); // Note: ScaleFactor resetting after document created first time // it needs to create empty document and when real document will be created, it will be second, not first time creation m_Report.CreateDocument(true); nbControlReport_GroupExpanded(this, new NavBarGroupEventArgs(nbGroupSettings)); ApplyExportPermission(); AjustToolbar(); } /// <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 (m_CustomSummarySource != null) { m_Report.PivotGrid.CustomCellDisplayText -= m_CustomSummarySource.OnCustomCellDisplayText; m_Report.PivotGrid.FieldValueDisplayText -= m_CustomSummarySource.OnFieldValueDisplayText; m_Report.PivotGrid.CustomSummary -= m_CustomSummarySource.OnCustomSummary; m_CustomSummarySource = null; } if (m_Report != null) { ResetReportData(); m_Report.Dispose(); m_Report = null; } eventManager.ClearAllReferences(); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); nbContainerSettings = null; } public string FilterText { get { return memFilter.Text; } set { memFilter.Text = value; } } public string PivotName { get { return tbPivotName.Text; } set { tbPivotName.Text = value; } } public PrintingSystemBase PrintingSystem { get { return m_Report.PrintingSystem; } } private ReportPrintTool m_ReportPrintTool; public ReportPrintTool ReportPrintTool { //get { return new ReportPrintTool(m_Report); } get { return m_ReportPrintTool ?? (m_ReportPrintTool = new ReportPrintTool(m_Report)); } } public PivotReportPresenter ReportPresenter { get { return m_ReportPresenter; } } public ExportDelegate GetExportDelegate(ExportType exportType) { switch (exportType) { case ExportType.PDF: return m_Report.ExportToPdf; case ExportType.XLS: return m_Report.ExportToXls; case ExportType.RTF: return m_Report.ExportToRtf; case ExportType.Html: return m_Report.ExportToHtml; case ExportType.Image: return m_Report.ExportToImage; } throw new RamException("Not supported export type: " + exportType); } public void ResetReportData() { if (m_Report != null) { m_Report.PivotGrid.Clear(); } } public void OnPivotDataLoaded(PivotDataEventArgs e) { Utils.CheckNotNull(e, "e"); var sourceGrid = e.PivotGrid as RamPivotGrid; if (sourceGrid == null) { throw new ArgumentException("e.PivotGrid should have type RamPivotGrid."); } Utils.CheckNotNull(sourceGrid, "e.PivotGrid"); using (m_Report.PivotGrid.BeginTransaction()) { PrintingSystem.ClearContent(); // check that complexity of the pivot grid is not very big if (sourceGrid.Complexity > RamPivotGrid.MaxLayoutComplexity) { MessageForm.Show(EidssMessages.Get("msgTooComplexLayout")); return; } // check that total cells count in the pivot grid is not very big if (sourceGrid.TotalCells > RamPivotGrid.MaxLayoutCellCount) { string msg = EidssMessages.Get("msgTooComplexLayout"); msg = string.Format(msg, RamPivotGrid.MaxLayoutCellCount); MessageForm.Show(msg); return; } m_Report.PivotGrid.CreateReportGridFrom(sourceGrid); m_Report.HeaderText = m_ReportPresenter.GetPivotNameFromDataSource(); m_Report.Footer = string.Empty; m_Report.FilterText = FilterText; int pageWidth = PrintingSystem.PageSettings.Bounds.Width - PrintingSystem.PageSettings.LeftMargin - PrintingSystem.PageSettings.RightMargin; //magic number :) const float coeff = 1.05f; float totalWidth = sourceGrid.TotalWidth * coeff; float scaleFactor = (pageWidth >= totalWidth) ? 1 : (pageWidth) / (totalWidth); PrintingSystem.Document.ScaleFactor = scaleFactor; PrintingSystem.ClearContent(); printControlReport.PrintingSystem = PrintingSystem; m_Report.CreateDocument(true); m_Report.Visible = true; m_Report.PivotGrid.Visible = true; if (m_CustomSummarySource == null) { m_CustomSummarySource = sourceGrid; m_Report.PivotGrid.CustomCellDisplayText += m_CustomSummarySource.OnCustomCellDisplayText; m_Report.PivotGrid.FieldValueDisplayText += m_CustomSummarySource.OnFieldValueDisplayText; m_Report.PivotGrid.CustomSummary += m_CustomSummarySource.OnCustomSummary; } } } private void memFilter_Leave(object sender, EventArgs e) { if (m_Report.FilterText == FilterText) { return; } m_Report.FilterText = FilterText; m_Report.CreateDocument(true); } private void tbPivotName_Leave(object sender, EventArgs e) { if ((m_Report.HeaderText == PivotName) || ((m_Report.HeaderText == EidssMessages.Get("msgNoReportHeader", "[Untitled]")) && string.IsNullOrEmpty(PivotName))) { return; } m_Report.HeaderText = PivotName; m_Report.CreateDocument(true); } private void biFilter_ItemClick(object sender, ItemClickEventArgs e) { RaiseSendCommand(new LayoutCommand(this, LayoutOperation.Filter)); } private void biSave_ItemClick(object sender, ItemClickEventArgs e) { RaiseSendCommand(new LayoutCommand(this, LayoutOperation.Save)); } private void biCancelChanges_ItemClick(object sender, ItemClickEventArgs e) { RaiseSendCommand(new LayoutCommand(this, LayoutOperation.Cancel)); } protected override void DefineBinding() { Trace.WriteLine(Trace.Kind.Undefine, "ReportForm.DefineBinding() call"); using (SharedPresenter.ContextKeeper.CreateNewContext("DefineBinding")) { m_ReportPresenter.BindPivotName(tbPivotName); } } private void ApplyExportPermission() { if (!EidssUserContext.User.HasPermission( PermissionHelper.ExecutePermission(EIDSSPermissionObject.CanImportExportData))) { //printBarManager.Items.Remove(biExportFile); LinkPersistInfo linkToRemove = null; foreach (LinkPersistInfo linksInfo in previewBar1.LinksPersistInfo) { if (biExportFile == linksInfo.Item) { linkToRemove = linksInfo; } } if (linkToRemove != null) { previewBar1.LinksPersistInfo.Remove(linkToRemove); } } } private void AjustToolbar() { var itemsToRemove = new List<BarItem>(); itemsToRemove.AddRange(new BarItem[] {biExportHtm, biExportMht, biExportCsv, biExportTxt}); foreach (BarItem item in printBarManager.Items) { if ((item is PrintPreviewBarItem) && (string.IsNullOrEmpty(item.Name))) { itemsToRemove.Add(item); } } ReportView.RemoveFromToolbar(itemsToRemove, printBarManager, previewBar1); } #region Nav Bar Layout private void nbControlReport_GroupCollapsed(object sender, NavBarGroupEventArgs e) { if (e.Group == nbGroupSettings) { nbControlReport.Height = BaseRamPresenter.NavBarGroupHeaderHeight; } } private void nbControlReport_GroupExpanded(object sender, NavBarGroupEventArgs e) { if (e.Group == nbGroupSettings) { nbControlReport.Height = nbGroupSettings.ControlContainer.Height + BaseRamPresenter.NavBarGroupHeaderHeight; } } #endregion } }
/*************************************************************************** * LinkLabel.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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 Gtk; using Hyena.Gui; namespace Banshee.Widgets { public class LinkLabel : EventBox { public delegate bool UriOpenHandler(string uri); private static UriOpenHandler default_open_handler; private static Gdk.Cursor hand_cursor = new Gdk.Cursor(Gdk.CursorType.Hand1); private Label label; private Uri uri; private bool act_as_link; private bool is_pressed; private bool is_hovering; private bool selectable; private UriOpenHandler open_handler; private Gdk.RGBA link_color; private bool interior_focus; private int focus_width; private int focus_padding; private int padding; public event EventHandler Clicked; public LinkLabel() : this(null, null) { Open = DefaultOpen; } public LinkLabel(string text, Uri uri) { CanFocus = true; AppPaintable = true; this.uri = uri; label = new Label(text); label.Show(); link_color = label.StyleContext.GetBackgroundColor (StateFlags.Selected); ActAsLink = true; Add(label); } protected override void OnStyleUpdated () { base.OnStyleUpdated (); CheckButton check = new CheckButton (); interior_focus = GtkUtilities.StyleGetProperty<bool> (check, "interior-focus", false); focus_width = GtkUtilities.StyleGetProperty<int> (check, "focus-line-width", -1); focus_padding = GtkUtilities.StyleGetProperty<int> (check, "focus-padding", -1); padding = interior_focus ? focus_width + focus_padding : 0; } protected virtual void OnClicked() { if(uri != null && Open != null) { Open(uri.AbsoluteUri); } EventHandler handler = Clicked; if(handler != null) { handler(this, new EventArgs()); } } protected override bool OnDrawn (Cairo.Context cr) { if(!IsDrawable) { return false; } if(CairoHelper.ShouldDrawWindow (cr, Window) && HasFocus) { int layout_width = 0, layout_height = 0; label.Layout.GetPixelSize(out layout_width, out layout_height); StyleContext.Save (); StyleContext.AddClass ("check"); StyleContext.RenderFocus (cr, 0, 0, layout_width + 2 * padding, layout_height + 2 * padding); StyleContext.Restore (); } if(Child != null) { PropagateDraw(Child, cr); } return false; } protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { base.OnGetPreferredHeight (out minimum_height, out natural_height); if (label == null) { return; } minimum_height = natural_height = 0; int label_min_height, label_natural_height; label.GetPreferredHeight (out label_min_height, out label_natural_height); minimum_height += label_min_height; natural_height += label_natural_height; natural_height += ((int)BorderWidth + padding) * 2; minimum_height += ((int)BorderWidth + padding) * 2; } protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width) { base.OnGetPreferredWidth (out minimum_width, out natural_width); if (label == null) { return; } minimum_width = natural_width = 0; int label_min_width, label_natural_width; label.GetPreferredWidth (out label_min_width, out label_natural_width); minimum_width = Math.Max (minimum_width, label_min_width); natural_width = Math.Max (natural_width, label_natural_width); minimum_width += ((int)BorderWidth + padding) * 2; natural_width += ((int)BorderWidth + padding) * 2; } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); Gdk.Rectangle child_allocation = new Gdk.Rectangle (); if (label == null || !label.Visible) { return; } int total_padding = (int)BorderWidth + padding; child_allocation.X = total_padding; child_allocation.Y = total_padding; child_allocation.Width = (int)Math.Max (1, Allocation.Width - 2 * total_padding); child_allocation.Height = (int)Math.Max (1, Allocation.Height - 2 * total_padding); label.SizeAllocate (child_allocation); } protected override bool OnButtonPressEvent(Gdk.EventButton evnt) { if(evnt.Button == 1) { HasFocus = true; is_pressed = true; } return false; } protected override bool OnButtonReleaseEvent(Gdk.EventButton evnt) { if(evnt.Button == 1 && is_pressed && is_hovering) { OnClicked(); is_pressed = false; } return false; } protected override bool OnKeyReleaseEvent(Gdk.EventKey evnt) { if(evnt.Key != Gdk.Key.KP_Enter && evnt.Key != Gdk.Key.Return && evnt.Key != Gdk.Key.space) { return false; } OnClicked(); return false; } protected override bool OnEnterNotifyEvent(Gdk.EventCrossing evnt) { is_hovering = true; Window.Cursor = hand_cursor; return false; } protected override bool OnLeaveNotifyEvent(Gdk.EventCrossing evnt) { is_hovering = false; Window.Cursor = null; return false; } public Pango.EllipsizeMode Ellipsize { get { return label.Ellipsize; } set { label.Ellipsize = value; } } public string Text { get { return label.Text; } set { label.Text = value; } } public string Markup { set { label.Markup = value; } } public Label Label { get { return label; } } public float Xalign { get { return label.Xalign; } set { label.Xalign = value; } } public float Yalign { get { return label.Yalign; } set { label.Yalign = value; } } public bool Selectable { get { return selectable; } set { if((value && !ActAsLink) || !value) { label.Selectable = value; } selectable = value; } } public Uri Uri { get { return uri; } set { uri = value; } } public string UriString { get { return uri == null ? null : uri.AbsoluteUri; } set { uri = value == null ? null : new Uri(value); } } public UriOpenHandler Open { get { return open_handler; } set { open_handler = value; } } public bool ActAsLink { get { return act_as_link; } set { if(act_as_link == value) { return; } act_as_link = value; if(act_as_link) { label.Selectable = false; label.OverrideColor (StateFlags.Normal, link_color); } else { label.Selectable = selectable; label.OverrideColor (StateFlags.Normal, label.StyleContext.GetColor (StateFlags.Normal)); } label.QueueDraw(); } } public static UriOpenHandler DefaultOpen { get { return default_open_handler; } set { default_open_handler = value; } } } }
// 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.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Reflection.Tests { public unsafe class PointerHolder { public int* field; public char* Property { get; set; } public void Method(byte* ptr, int expected) { Assert.Equal(expected, unchecked((int)ptr)); } public bool* Return(int expected) { return unchecked((bool*)expected); } } public unsafe class PointerTests { [Fact] public void Box_TypeNull() { ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => { Pointer.Box((void*)0, null); }); } [Fact] public void Box_NonPointerType() { Assert.Throws<ArgumentException>(() => { Pointer.Box((void*)0, typeof(int)); }); } [Fact] public void Unbox_Null() { Assert.Throws<ArgumentException>(() => { Pointer.Unbox(null); }); } [Fact] public void Unbox_NotPointer() { Assert.Throws<ArgumentException>(() => { Pointer.Unbox(new object()); }); } [Theory] [MemberData(nameof(Pointers))] public void PointerValueRoundtrips(int value) { void* ptr = unchecked((void*)value); void* result = Pointer.Unbox(Pointer.Box(ptr, typeof(int*))); Assert.Equal((IntPtr)ptr, (IntPtr)result); } public static IEnumerable<object[]> Pointers => new[] { new object[] { 0 }, new object[] { 1 }, new object[] { -1 }, new object[] { int.MaxValue }, new object[] { int.MinValue }, }; [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerFieldSetValue(int value) { var obj = new PointerHolder(); FieldInfo field = typeof(PointerHolder).GetField("field"); field.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(int*))); Assert.Equal(value, unchecked((int)obj.field)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void IntPtrFieldSetValue(int value) { var obj = new PointerHolder(); FieldInfo field = typeof(PointerHolder).GetField("field"); field.SetValue(obj, (IntPtr)value); Assert.Equal(value, unchecked((int)obj.field)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerFieldSetValue_InvalidType(int value) { var obj = new PointerHolder(); FieldInfo field = typeof(PointerHolder).GetField("field"); Assert.Throws<ArgumentException>(() => { field.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(long*))); }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Issue https://github.com/dotnet/corefx/issues/17450")] public void PointerFieldGetValue(int value) { var obj = new PointerHolder(); obj.field = unchecked((int*)value); FieldInfo field = typeof(PointerHolder).GetField("field"); object actualValue = field.GetValue(obj); Assert.IsType<Pointer>(actualValue); void* actualPointer = Pointer.Unbox(actualValue); Assert.Equal(value, unchecked((int)actualPointer)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerPropertySetValue(int value) { var obj = new PointerHolder(); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); property.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(char*))); Assert.Equal(value, unchecked((int)obj.Property)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void IntPtrPropertySetValue(int value) { var obj = new PointerHolder(); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); property.SetValue(obj, (IntPtr)value); Assert.Equal(value, unchecked((int)obj.Property)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerPropertySetValue_InvalidType(int value) { var obj = new PointerHolder(); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); Assert.Throws<ArgumentException>(() => { property.SetValue(obj, Pointer.Box(unchecked((void*)value), typeof(long*))); }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerPropertyGetValue(int value) { var obj = new PointerHolder(); obj.Property = unchecked((char*)value); PropertyInfo property = typeof(PointerHolder).GetProperty("Property"); object actualValue = property.GetValue(obj); Assert.IsType<Pointer>(actualValue); void* actualPointer = Pointer.Unbox(actualValue); Assert.Equal(value, unchecked((int)actualPointer)); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerMethodParameter(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Method"); method.Invoke(obj, new[] { Pointer.Box(unchecked((void*)value), typeof(byte*)), value }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void IntPtrMethodParameter(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Method"); method.Invoke(obj, new object[] { (IntPtr)value, value }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerMethodParameter_InvalidType(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Method"); Assert.Throws<ArgumentException>(() => { method.Invoke(obj, new[] { Pointer.Box(unchecked((void*)value), typeof(long*)), value }); }); } [Theory] [MemberData(nameof(Pointers))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Pointers through Invoke not implemented: https://github.com/dotnet/corert/issues/2113")] public void PointerMethodReturn(int value) { var obj = new PointerHolder(); MethodInfo method = typeof(PointerHolder).GetMethod("Return"); object actualValue = method.Invoke(obj, new object[] { value }); Assert.IsType<Pointer>(actualValue); void* actualPointer = Pointer.Unbox(actualValue); Assert.Equal(value, unchecked((int)actualPointer)); } [Theory] [MemberData(nameof(Pointers))] public void PointerSerializes(int value) { object pointer = Pointer.Box(unchecked((void*)value), typeof(int*)); Pointer cloned = BinaryFormatterHelpers.Clone((Pointer)pointer); Assert.Equal((ulong)Pointer.Unbox(pointer), (ulong)Pointer.Unbox(cloned)); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BinaryReader ** ** ** Purpose: Wraps a stream and provides convenient read functionality ** for strings and primitive types. ** ** ============================================================*/ namespace System.IO { using System; using System.Text; using System.Globalization; ////[System.Runtime.InteropServices.ComVisible( true )] public class BinaryReader : IDisposable { private const int MaxCharBytesSize = 128; private Stream m_stream; private byte[] m_buffer; private Decoder m_decoder; private byte[] m_charBytes; private char[] m_singleChar; private char[] m_charBuffer; private int m_maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% private bool m_2BytesPerChar; private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf public BinaryReader( Stream input ) : this( input, new UTF8Encoding() ) { } public BinaryReader( Stream input, Encoding encoding ) { if(input == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "input" ); #else throw new ArgumentNullException(); #endif } if(encoding == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "encoding" ); #else throw new ArgumentNullException(); #endif } if(!input.CanRead) #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_StreamNotReadable" ) ); #else throw new ArgumentException(); #endif m_stream = input; m_decoder = encoding.GetDecoder(); m_maxCharsSize = encoding.GetMaxCharCount( MaxCharBytesSize ); int minBufferSize = encoding.GetMaxByteCount( 1 ); // max bytes per one char if(minBufferSize < 16) minBufferSize = 16; m_buffer = new byte[minBufferSize]; m_charBuffer = null; m_charBytes = null; // For Encodings that always use 2 bytes per char (or more), // special case them here to make Read() & Peek() faster. m_2BytesPerChar = encoding is UnicodeEncoding; // check if BinaryReader is based on MemoryStream, and keep this for it's life // we cannot use "as" operator, since derived classes are not allowed m_isMemoryStream = (m_stream.GetType() == typeof( MemoryStream )); BCLDebug.Assert( m_decoder != null, "[BinaryReader.ctor]m_decoder!=null" ); } public virtual Stream BaseStream { get { return m_stream; } } public virtual void Close() { Dispose( true ); } protected virtual void Dispose( bool disposing ) { if(disposing) { Stream copyOfStream = m_stream; m_stream = null; if(copyOfStream != null) copyOfStream.Close(); } m_stream = null; m_buffer = null; m_decoder = null; m_charBytes = null; m_singleChar = null; m_charBuffer = null; } /// <internalonly/> void IDisposable.Dispose() { Dispose( true ); } public virtual int PeekChar() { if(m_stream == null) __Error.FileNotOpen(); if(!m_stream.CanSeek) return -1; long origPos = m_stream.Position; int ch = Read(); m_stream.Position = origPos; return ch; } public virtual int Read() { if(m_stream == null) { __Error.FileNotOpen(); } return InternalReadOneChar(); } public virtual bool ReadBoolean() { FillBuffer( 1 ); return (m_buffer[0] != 0); } public virtual byte ReadByte() { // Inlined to avoid some method call overhead with FillBuffer. if(m_stream == null) __Error.FileNotOpen(); int b = m_stream.ReadByte(); if(b == -1) __Error.EndOfFile(); return (byte)b; } [CLSCompliant( false )] public virtual sbyte ReadSByte() { FillBuffer( 1 ); return (sbyte)(m_buffer[0]); } public virtual char ReadChar() { int value = Read(); if(value == -1) { __Error.EndOfFile(); } return (char)value; } public virtual short ReadInt16() { FillBuffer( 2 ); return (short)(m_buffer[0] | m_buffer[1] << 8); } [CLSCompliant( false )] public virtual ushort ReadUInt16() { FillBuffer( 2 ); return (ushort)(m_buffer[0] | m_buffer[1] << 8); } public virtual int ReadInt32() { if(m_isMemoryStream) { // read directly from MemoryStream buffer MemoryStream mStream = m_stream as MemoryStream; BCLDebug.Assert( mStream != null, "m_stream as MemoryStream != null" ); return mStream.InternalReadInt32(); } else { FillBuffer( 4 ); return (int)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } } [CLSCompliant( false )] public virtual uint ReadUInt32() { FillBuffer( 4 ); return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); } public virtual long ReadInt64() { FillBuffer( 8 ); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return (long)((ulong)hi) << 32 | lo; } [CLSCompliant( false )] public virtual ulong ReadUInt64() { FillBuffer( 8 ); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); return ((ulong)hi) << 32 | lo; } public virtual unsafe float ReadSingle() { FillBuffer( 4 ); uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); return *((float*)&tmpBuffer); } public virtual unsafe double ReadDouble() { FillBuffer( 8 ); uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24); uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 | m_buffer[6] << 16 | m_buffer[7] << 24); ulong tmpBuffer = ((ulong)hi) << 32 | lo; return *((double*)&tmpBuffer); } public virtual decimal ReadDecimal() { FillBuffer( 16 ); return Decimal.ToDecimal( m_buffer ); } public virtual String ReadString() { int currPos = 0; int n; int stringLength; int readLength; int charsRead; if(m_stream == null) __Error.FileNotOpen(); // Length of the string in bytes, not chars stringLength = Read7BitEncodedInt(); if(stringLength < 0) { #if EXCEPTION_STRINGS throw new IOException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "IO.IO_InvalidStringLen_Len" ), stringLength ) ); #else throw new IOException(); #endif } if(stringLength == 0) { return String.Empty; } if(m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } if(m_charBuffer == null) { m_charBuffer = new char[m_maxCharsSize]; } StringBuilder sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); n = m_stream.Read( m_charBytes, 0, readLength ); if(n == 0) { __Error.EndOfFile(); } charsRead = m_decoder.GetChars( m_charBytes, 0, n, m_charBuffer, 0 ); if(currPos == 0 && n == stringLength) return new String( m_charBuffer, 0, charsRead ); if(sb == null) sb = new StringBuilder( stringLength ); // Actual string length in chars may be smaller. sb.Append( m_charBuffer, 0, charsRead ); currPos += n; } while(currPos < stringLength); return sb.ToString(); } public virtual int Read( char[] buffer, int index, int count ) { if(buffer == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(buffer.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif } if(m_stream == null) __Error.FileNotOpen(); return InternalReadChars( buffer, index, count ); } private int InternalReadChars( char[] buffer, int index, int count ) { int charsRead = 0; int numBytes = 0; int charsRemaining = count; if(m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; } while(charsRemaining > 0) { // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. numBytes = charsRemaining; if(m_2BytesPerChar) numBytes <<= 1; if(numBytes > MaxCharBytesSize) numBytes = MaxCharBytesSize; if(m_isMemoryStream) { MemoryStream mStream = m_stream as MemoryStream; BCLDebug.Assert( mStream != null, "m_stream as MemoryStream != null" ); int position = mStream.InternalGetPosition(); numBytes = mStream.InternalEmulateRead( numBytes ); if(numBytes == 0) { return (count - charsRemaining); } charsRead = m_decoder.GetChars( mStream.InternalGetBuffer(), position, numBytes, buffer, index ); } else { numBytes = m_stream.Read( m_charBytes, 0, numBytes ); if(numBytes == 0) { // Console.WriteLine("Found no bytes. We're outta here."); return (count - charsRemaining); } charsRead = m_decoder.GetChars( m_charBytes, 0, numBytes, buffer, index ); } charsRemaining -= charsRead; index += charsRead; // Console.WriteLine("That became: " + charsRead + " characters."); } BCLDebug.Assert( charsRemaining == 0, "We didn't read all the chars we thought we would." ); return count; } private int InternalReadOneChar() { // I know having a separate InternalReadOneChar method seems a little // redundant, but this makes a scenario like the security parser code // 20% faster, in addition to the optimizations for UnicodeEncoding I // put in InternalReadChars. int charsRead = 0; int numBytes = 0; long posSav = posSav = 0; if(m_stream.CanSeek) posSav = m_stream.Position; if(m_charBytes == null) { m_charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need atmost 2 bytes/char here? } if(m_singleChar == null) { m_singleChar = new char[1]; } while(charsRead == 0) { // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. // Assume 1 byte can be 1 char unless m_2BytesPerChar is true. numBytes = m_2BytesPerChar ? 2 : 1; int r = m_stream.ReadByte(); m_charBytes[0] = (byte)r; if(r == -1) numBytes = 0; if(numBytes == 2) { r = m_stream.ReadByte(); m_charBytes[1] = (byte)r; if(r == -1) numBytes = 1; } if(numBytes == 0) { // Console.WriteLine("Found no bytes. We're outta here."); return -1; } BCLDebug.Assert( numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only." ); try { charsRead = m_decoder.GetChars( m_charBytes, 0, numBytes, m_singleChar, 0 ); } catch { // Handle surrogate char if(m_stream.CanSeek) m_stream.Seek( (posSav - m_stream.Position), SeekOrigin.Current ); // else - we can't do much here throw; } BCLDebug.Assert( charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!" ); // Console.WriteLine("That became: " + charsRead + " characters."); } if(charsRead == 0) return -1; return m_singleChar[0]; } public virtual char[] ReadChars( int count ) { if(m_stream == null) { __Error.FileNotOpen(); } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } char[] chars = new char[count]; int n = InternalReadChars( chars, 0, count ); if(n != count) { char[] copy = new char[n]; Buffer.InternalBlockCopy( chars, 0, copy, 0, 2 * n ); // sizeof(char) chars = copy; } return chars; } public virtual int Read( byte[] buffer, int index, int count ) { if(buffer == null) #if EXCEPTION_STRINGS throw new ArgumentNullException( "buffer", Environment.GetResourceString( "ArgumentNull_Buffer" ) ); #else throw new ArgumentNullException(); #endif if(index < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "index", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(count < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(buffer.Length - index < count) #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) ); #else throw new ArgumentException(); #endif if(m_stream == null) __Error.FileNotOpen(); return m_stream.Read( buffer, index, count ); } public virtual byte[] ReadBytes( int count ) { if(count < 0) #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif if(m_stream == null) __Error.FileNotOpen(); byte[] result = new byte[count]; int numRead = 0; do { int n = m_stream.Read( result, numRead, count ); if(n == 0) break; numRead += n; count -= n; } while(count > 0); if(numRead != result.Length) { // Trim array. This should happen on EOF & possibly net streams. byte[] copy = new byte[numRead]; Buffer.InternalBlockCopy( result, 0, copy, 0, numRead ); result = copy; } return result; } protected virtual void FillBuffer( int numBytes ) { BCLDebug.Assert( m_buffer == null || (numBytes > 0 && numBytes <= m_buffer.Length), "[FillBuffer]numBytes>0 && numBytes<=m_buffer.Length" ); int bytesRead = 0; int n = 0; if(m_stream == null) __Error.FileNotOpen(); // Need to find a good threshold for calling ReadByte() repeatedly // vs. calling Read(byte[], int, int) for both buffered & unbuffered // streams. if(numBytes == 1) { n = m_stream.ReadByte(); if(n == -1) __Error.EndOfFile(); m_buffer[0] = (byte)n; return; } do { n = m_stream.Read( m_buffer, bytesRead, numBytes - bytesRead ); if(n == 0) { __Error.EndOfFile(); } bytesRead += n; } while(bytesRead < numBytes); } internal protected int Read7BitEncodedInt() { // Read out an Int32 7 bits at a time. The high bit // of the byte when on means to continue reading more bytes. int count = 0; int shift = 0; byte b; do { // Check for a corrupted stream. Read a max of 5 bytes. // In a future version, add a DataFormatException. if(shift == 5 * 7) // 5 bytes max per Int32, shift += 7 #if EXCEPTION_STRINGS throw new FormatException( Environment.GetResourceString( "Format_Bad7BitInt32" ) ); #else throw new FormatException(); #endif // ReadByte handles end of stream cases for us. b = ReadByte(); count |= (b & 0x7F) << shift; shift += 7; } while((b & 0x80) != 0); return count; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace System.Data.SqlClient.ManualTesting.Tests { /// <summary> /// represents table with random column types and values in it /// </summary> public class SqlRandomTable { // "Row-Overflow Data Exceeding 8 KB" private const int MaxBytesPerRow = 8060; // however, with sparse columns the limit drops to 8018 private const int MaxBytesPerRowWithSparse = 8018; // SQL Server uses 6 bytes per-row to store row info (null-bitmap overhead is calculated based on column size) private const int ConstantOverhead = 6; // SQL does not allow table creation with more than 1024 non-sparse columns private const int MaxNonSparseColumns = 1024; // cannot send more than 2100 parameters in one command private const int MaxParameterCount = 2100; /// <summary> /// column types /// </summary> private readonly SqlRandomTableColumn[] _columns; private readonly string[] _columnNames; public readonly IList<SqlRandomTableColumn> Columns; public readonly IList<string> ColumnNames; public readonly int? PrimaryKeyColumnIndex; public readonly bool HasSparseColumns; public readonly double NonSparseValuesTotalSize; /// <summary> /// maximum size of the row allowed for this column (depends if it has sparse columns or not) /// </summary> public int MaxRowSize { get { if (HasSparseColumns) return MaxBytesPerRowWithSparse; else return MaxBytesPerRow; } } /// <summary> /// rows and their values /// </summary> private readonly List<object[]> _rows; public IList<object> this[int row] { get { return new List<object>(_rows[row]).AsReadOnly(); } } public SqlRandomTable(SqlRandomTableColumn[] columns, int? primaryKeyColumnIndex = null, int estimatedRowCount = 0) { if (columns == null || columns.Length == 0) throw new ArgumentException("non-empty type array is required"); if (estimatedRowCount < 0) throw new ArgumentOutOfRangeException("non-negative row count is required, use 0 for default"); if (primaryKeyColumnIndex.HasValue && (primaryKeyColumnIndex.Value < 0 || primaryKeyColumnIndex.Value >= columns.Length)) throw new ArgumentOutOfRangeException("primaryColumnIndex"); PrimaryKeyColumnIndex = primaryKeyColumnIndex; _columns = (SqlRandomTableColumn[])columns.Clone(); _columnNames = new string[columns.Length]; if (estimatedRowCount == 0) _rows = new List<object[]>(); else _rows = new List<object[]>(estimatedRowCount); Columns = new List<SqlRandomTableColumn>(_columns).AsReadOnly(); ColumnNames = new List<string>(_columnNames).AsReadOnly(); bool hasSparse = false; double totalNonSparse = 0; foreach (var c in _columns) { if (c.IsSparse) { hasSparse = true; } else { totalNonSparse += c.GetInRowSize(null); // for non-sparse columns size does not depend on the value } } HasSparseColumns = hasSparse; NonSparseValuesTotalSize = totalNonSparse; } public string GetColumnName(int c) { if (_columnNames[c] == null) { AutoGenerateColumnNames(); } return _columnNames[c]; } public string GetColumnTSqlType(int c) { return _columns[c].GetTSqlTypeDefinition(); } /// <summary> /// adds new row with random values, each column has 50% chance to have null value /// </summary> public void AddRow(SqlRandomizer rand) { BitArray nullBitmap = rand.NextBitmap(_columns.Length); AddRow(rand, nullBitmap); } private bool IsPrimaryKey(int c) { return PrimaryKeyColumnIndex.HasValue && PrimaryKeyColumnIndex.Value == c; } /// <summary> /// adds a new row with random values and specified null bitmap /// </summary> public void AddRow(SqlRandomizer rand, BitArray nullBitmap) { object[] row = new object[_columns.Length]; // non-sparse columns will always take fixed size, must add them now double rowSize = NonSparseValuesTotalSize; double maxRowSize = MaxRowSize; if (PrimaryKeyColumnIndex.HasValue) { // make sure pkey is set first // ignore the null bitmap in this case object pkeyValue = _rows.Count; row[PrimaryKeyColumnIndex.Value] = pkeyValue; } for (int c = 0; c < row.Length; c++) { if (IsPrimaryKey(c)) { // handled above continue; } if (SkipOnInsert(c)) { row[c] = null; // this null value should not be used, assert triggered if it is } else if (rowSize >= maxRowSize) { // reached the limit, cannot add more for this row row[c] = DBNull.Value; } else if (nullBitmap[c]) { row[c] = DBNull.Value; } else { object value = _columns[c].CreateRandomValue(rand); if (value == null || value == DBNull.Value) { row[c] = DBNull.Value; } else if (IsSparse(c)) { // check if the value fits double newRowSize = rowSize + _columns[c].GetInRowSize(value); if (newRowSize > maxRowSize) { // cannot fit it, zero this one and try to fit next column row[c] = DBNull.Value; } else { // the value is OK, keep it row[c] = value; rowSize = newRowSize; } } else { // non-sparse values are already counted in NonSparseValuesTotalSize row[c] = value; } } } _rows.Add(row); } public void AddRows(SqlRandomizer rand, int rowCount) { for (int i = 0; i < rowCount; i++) AddRow(rand); } public string GenerateCreateTableTSql(string tableName) { StringBuilder tsql = new StringBuilder(); tsql.AppendFormat("CREATE TABLE {0} (", tableName); for (int c = 0; c < _columns.Length; c++) { if (c != 0) tsql.Append(", "); tsql.AppendFormat("[{0}] {1}", GetColumnName(c), GetColumnTSqlType(c)); if (IsPrimaryKey(c)) { tsql.Append(" PRIMARY KEY"); } else if (IsSparse(c)) { tsql.Append(" SPARSE NULL"); } else if (IsColumnSet(c)) { tsql.Append(" COLUMN_SET FOR ALL_SPARSE_COLUMNS NULL"); } else { tsql.Append(" NULL"); } } tsql.AppendFormat(") ON [PRIMARY]"); return tsql.ToString(); } public void DumpColumnsInfo(TextWriter output) { for (int i = 0; i < _columnNames.Length - 1; i++) { output.Write(_columnNames[i]); if (_columns[i].StorageSize.HasValue) output.Write(", [StorageSize={0}]", _columns[i].StorageSize.Value); if (_columns[i].Precision.HasValue) output.Write(", [Precision={0}]", _columns[i].Precision.Value); if (_columns[i].Scale.HasValue) output.Write(", [Scale={0}]", _columns[i].Scale.Value); output.WriteLine(); } } public void DumpRow(TextWriter output, object[] row) { if (row == null || row.Length != _columns.Length) throw new ArgumentException("Row length does not match the columns"); for (int i = 0; i < _columnNames.Length - 1; i++) { object val = row[i]; string type; if (val == null) { val = "<dbnull>"; type = ""; } else { type = val.GetType().Name; if (val is Array) { val = string.Format("[Length={0}]", ((Array)val).Length); } else if (val is string) { val = string.Format("[Length={0}]", ((string)val).Length); } else { val = string.Format("[{0}]", val); } } output.WriteLine("[{0}] = {1}", _columnNames[i], val); } } private bool SkipOnInsert(int c) { if (_columns[c].Type == SqlDbType.Timestamp) { // cannot insert timestamp return true; } if (IsColumnSet(c)) { // skip column set, using sparse columns themselves return true; } // OK to insert value return false; } public void GenerateTableOnServer(SqlConnection con, string tableName) { // create table SqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = GenerateCreateTableTSql(tableName); try { cmd.ExecuteNonQuery(); } catch (Exception e) { StringWriter output = new StringWriter(); output.WriteLine("(START)"); output.WriteLine(cmd.CommandText); output.WriteLine("- Columns:"); DumpColumnsInfo(output); output.WriteLine("(END)"); output.WriteLine(e.Message); output.WriteLine("---------"); lock (Console.Out) Console.WriteLine(output); throw; } InsertRows(con, tableName, 0, _rows.Count); } public void InsertRows(SqlConnection con, string tableName, int rowFrom, int rowToExclusive) { if (con == null || tableName == null) { throw new ArgumentNullException("connection and table name must be valid"); } if (rowToExclusive > _rows.Count) { throw new ArgumentOutOfRangeException("rowToExclusive", rowToExclusive, "cannot be greater than the row count"); } if (rowFrom < 0 || rowFrom > rowToExclusive) { throw new ArgumentOutOfRangeException("rowFrom", rowFrom, "cannot be less than 0 or greater than rowToExclusive"); } SqlCommand cmd = null; SqlParameter[] parameters = null; for (int r = rowFrom; r < rowToExclusive; r++) { InsertRowInternal(con, ref cmd, ref parameters, tableName, r); } } public void InsertRow(SqlConnection con, string tableName, int row) { if (con == null || tableName == null) { throw new ArgumentNullException("connection and table name must be valid"); } if (row < 0 || row >= _rows.Count) { throw new ArgumentOutOfRangeException("row", row, "cannot be less than 0 or greater than or equal to row count"); } SqlCommand cmd = null; SqlParameter[] parameters = null; InsertRowInternal(con, ref cmd, ref parameters, tableName, row); } private void InsertRowInternal(SqlConnection con, ref SqlCommand cmd, ref SqlParameter[] parameters, string tableName, int row) { // cannot use DataTable: it does not handle well char[] values and variant and also does not support sparse/column set ones StringBuilder columnsText = new StringBuilder(); StringBuilder valuesText = new StringBuilder(); // create the command and parameters on first call, reuse afterwards (to reduces table creation overhead) if (cmd == null) { cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; } else { // need to unbind existing parameters and re-add the next set of values cmd.Parameters.Clear(); } if (parameters == null) { parameters = new SqlParameter[_columns.Length]; } object[] rowValues = _rows[row]; // there is a limit of parameters to be sent (2010) for (int ci = 0; ci < _columns.Length; ci++) { if (cmd.Parameters.Count >= MaxParameterCount) { // reached the limit of max parameters, cannot continue // theoretically, we could do INSERT + UPDATE. practically, chances for this to happen are almost none since nulls are skipped rowValues[ci] = DBNull.Value; continue; } if (SkipOnInsert(ci)) { // cannot insert timestamp // insert of values into columnset columns are also not supported (use sparse columns themselves) continue; } bool isNull = (rowValues[ci] == DBNull.Value || rowValues[ci] == null); if (isNull) { // columns such as sparse cannot have DEFAULT constraint, thus it is safe to ignore the value of the column when inserting new row // this also significantly reduces number of columns updated during insert, to prevent "The number of target // columns that are specified in an INSERT, UPDATE, or MERGE statement exceeds the maximum of 4096." continue; } SqlParameter p = parameters[ci]; // construct column list if (columnsText.Length > 0) { columnsText.Append(", "); valuesText.Append(", "); } columnsText.AppendFormat("[{0}]", _columnNames[ci]); if (p == null) { p = cmd.CreateParameter(); p.ParameterName = "@p" + ci; p.SqlDbType = _columns[ci].Type; parameters[ci] = p; } p.Value = rowValues[ci] ?? DBNull.Value; cmd.Parameters.Add(p); valuesText.Append(p.ParameterName); } Debug.Assert(columnsText.Length > 0, "Table that have only TIMESTAMP, ColumnSet or Sparse columns are not allowed - use primary key in this case"); cmd.CommandText = string.Format("INSERT INTO {0} ( {1} ) VALUES ( {2} )", tableName, columnsText, valuesText); try { cmd.ExecuteNonQuery(); } catch (SqlException e) { StringWriter output = new StringWriter(); output.WriteLine("(START)"); output.WriteLine(cmd.CommandText); output.WriteLine("- Columns:"); DumpColumnsInfo(output); output.WriteLine("- Row[{0}]:", row); DumpRow(output, _rows[row]); output.WriteLine("- INSERT Command:"); output.WriteLine(cmd.CommandText); output.WriteLine("(END)"); output.WriteLine(e.Message); output.WriteLine("---------"); lock (Console.Out) Console.WriteLine(output); throw; } } /// <summary> /// generates SELECT statement; if columnIndices is null the statement will include all the columns /// </summary> public int GenerateSelectFromTableTSql(string tableName, StringBuilder selectBuilder, int[] columnIndices = null, int indicesOffset = -1, int indicesCount = -1) { if (tableName == null || selectBuilder == null) throw new ArgumentNullException("tableName == null || selectBuilder == null"); int maxIndicesLength = (columnIndices == null) ? _columns.Length : columnIndices.Length; if (indicesOffset == -1) { indicesOffset = 0; } else if (indicesOffset < 0 || indicesOffset >= maxIndicesLength) { throw new ArgumentOutOfRangeException("indicesOffset"); } if (indicesCount == -1) { indicesCount = maxIndicesLength; } else if (indicesCount < 1 || (indicesCount + indicesOffset) > maxIndicesLength) { // at least one index required throw new ArgumentOutOfRangeException("indicesCount"); } double totalRowSize = 0; int countAdded = 0; // append the first int columnIndex = (columnIndices == null) ? indicesOffset : columnIndices[indicesOffset]; selectBuilder.AppendFormat("SELECT [{0}]", _columnNames[columnIndex]); totalRowSize += _columns[columnIndex].GetInRowSize(null); countAdded++; // append the rest, if any int end = indicesOffset + indicesCount; for (int c = indicesOffset + 1; c < end; c++) { columnIndex = (columnIndices == null) ? c : columnIndices[c]; totalRowSize += _columns[columnIndex].GetInRowSize(null); if (totalRowSize > MaxRowSize) { // overflow - stop now break; } selectBuilder.AppendFormat(", [{0}]", _columnNames[columnIndex]); countAdded++; } selectBuilder.AppendFormat(" FROM {0}", tableName); if (PrimaryKeyColumnIndex.HasValue) selectBuilder.AppendFormat(" ORDER BY [{0}]", _columnNames[PrimaryKeyColumnIndex.Value]); return countAdded; } #region static helper methods private static int GetRowOverhead(int columnSize) { int nullBitmapSize = (columnSize + 7) / 8; return ConstantOverhead + nullBitmapSize; } // once we have only this size left on the row, column set column is forced // 40 is an XML and variant size private static readonly int s_columnSetSafetyRange = SqlRandomTypeInfo.XmlRowUsage * 3; /// <summary> /// Creates random list of columns from the given source collection. The rules are: /// * table cannot contain more than 1024 non-sparse columns /// * total row size of non-sparse columns should not exceed 8060 or 8018 (with sparse) /// * column set column must be added if number of columns in total exceeds 1024 /// </summary> public static SqlRandomTableColumn[] CreateRandTypes(SqlRandomizer rand, SqlRandomTypeInfoCollection sourceCollection, int maxColumnsCount, bool createIdColumn) { var retColumns = new List<SqlRandomTableColumn>(maxColumnsCount); bool hasTimestamp = false; double totalRowSize = 0; int totalRegularColumns = 0; bool hasColumnSet = false; bool hasSparseColumns = false; int maxRowSize = MaxBytesPerRow; // set to MaxBytesPerRowWithSparse when sparse column is first added int i = 0; if (createIdColumn) { SqlRandomTypeInfo keyType = sourceCollection[SqlDbType.Int]; SqlRandomTableColumn keyColumn = keyType.CreateDefaultColumn(SqlRandomColumnOptions.None); retColumns.Add(keyColumn); totalRowSize += keyType.GetInRowSize(keyColumn, null); i++; totalRegularColumns++; } for (; i < maxColumnsCount; i++) { // select column options (sparse/column-set) bool isSparse; // must be set in the if/else flow below bool isColumnSet = false; if (totalRegularColumns >= MaxNonSparseColumns) { // reached the limit for regular columns if (!hasColumnSet) { // no column-set yet, stop unconditionally // this can happen if large char/binary value brought the row size total to a limit leaving no space for column-set break; } // there is a column set, enforce sparse from this point isSparse = true; } else if (i == (MaxNonSparseColumns - 1) && hasSparseColumns && !hasColumnSet) { // we almost reached the limit of regular & sparse columns with, but no column set added // to increase chances for >1024 columns, enforce column set now isColumnSet = true; isSparse = false; } else if (totalRowSize > MaxBytesPerRowWithSparse) { Debug.Assert(totalRowSize <= MaxBytesPerRow, "size over the max limit"); Debug.Assert(!hasSparseColumns, "should not have sparse columns after MaxBytesPerRowWithSparse (check maxRowSize)"); // cannot insert sparse from this point isSparse = false; isColumnSet = false; } else { // check how close we are to the limit of the row size int sparseProbability; if (totalRowSize < 100) { sparseProbability = 2; } else if (totalRowSize < MaxBytesPerRowWithSparse / 2) { sparseProbability = 10; } else if (totalRowSize < (MaxBytesPerRowWithSparse - s_columnSetSafetyRange)) { sparseProbability = 50; } else { // close to the row size limit, special case if (!hasColumnSet) { // if we have not added column set column yet // column-set is a regular column and its size counts towards row size, so time to add it isColumnSet = true; sparseProbability = -1; // not used } else { sparseProbability = 90; } } if (!isColumnSet) { isSparse = (rand.Next(100) < sparseProbability); if (!isSparse && !hasColumnSet) { // if decided to add regular column, give it a (low) chance to inject a column set at any position isColumnSet = rand.Next(100) < 1; } } else { isSparse = false; } } // select the type SqlRandomTypeInfo ti; SqlRandomColumnOptions options = SqlRandomColumnOptions.None; if (isSparse) { Debug.Assert(!isColumnSet, "should not have both sparse and column set flags set"); ti = sourceCollection.NextSparse(rand); Debug.Assert(ti.CanBeSparseColumn, "NextSparse must return only types that can be sparse"); options |= SqlRandomColumnOptions.Sparse; } else if (isColumnSet) { Debug.Assert(!hasColumnSet, "there is already a column set, we should not set isColumnSet again above"); ti = sourceCollection[SqlDbType.Xml]; options |= SqlRandomColumnOptions.ColumnSet; } else { // regular column ti = sourceCollection.Next(rand); if (ti.Type == SqlDbType.Timestamp) { // while table can contain single timestamp column only, there is no way to insert values into it. // thus, do not allow this if (hasTimestamp || maxColumnsCount == 1) { ti = sourceCollection[SqlDbType.Int]; } else { // table cannot have two timestamp columns hasTimestamp = true; } } } SqlRandomTableColumn col = ti.CreateRandomColumn(rand, options); if (!isSparse) { double rowSize = ti.GetInRowSize(col, DBNull.Value); int overhead = GetRowOverhead(retColumns.Count + 1); // +1 for this column if (totalRowSize + rowSize + overhead > maxRowSize) { // cannot use this column // note that if this column is a column set column continue; } totalRowSize += rowSize; totalRegularColumns++; } // else - sparse columns are not counted towards row size when table is created (they are when inserting new row with non-null value in the sparse column)... retColumns.Add(col); // after adding the column, update the state if (isColumnSet) { hasColumnSet = true; } if (isSparse) { hasSparseColumns = true; maxRowSize = MaxBytesPerRowWithSparse; // reduce the max row size } } return retColumns.ToArray(); } public static SqlRandomTable Create(SqlRandomizer rand, SqlRandomTypeInfoCollection sourceCollection, int maxColumnsCount, int rowCount, bool createPrimaryKeyColumn) { SqlRandomTableColumn[] testTypes = CreateRandTypes(rand, sourceCollection, maxColumnsCount, createPrimaryKeyColumn); SqlRandomTable table = new SqlRandomTable(testTypes, primaryKeyColumnIndex: createPrimaryKeyColumn ? (Nullable<int>)0 : null, estimatedRowCount: rowCount); table.AddRows(rand, rowCount); return table; } private void AutoGenerateColumnNames() { Dictionary<string, int> nameMap = new Dictionary<string, int>(_columns.Length); for (int c = 0; c < _columns.Length; c++) { if (_columnNames[c] == null) { // pick name that is not in table yet string name = GenerateColumnName(nameMap, c); nameMap[name] = c; _columnNames[c] = name; } else { // check for dups if (nameMap.ContainsKey(_columnNames[c])) { // should not happen now since column names are auto-generated only throw new InvalidOperationException("duplicate column names detected"); } } } } private string GenerateColumnName(Dictionary<string, int> nameMap, int c) { string baseName; if (IsPrimaryKey(c)) baseName = "PKEY"; else baseName = string.Format("C{0}_{1}", _columns[c].Type, c); string name = baseName; int extraSuffix = 1; while (nameMap.ContainsKey(name)) { name = string.Format("{0}_{1}", baseName, extraSuffix); ++extraSuffix; } return name; } private bool IsSparse(int c) { return _columns[c].IsSparse; } private bool IsColumnSet(int c) { return _columns[c].IsColumnSet; } #endregion static helper methods } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Dynamic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using PMKS; using Silverlight_PMKS; namespace PMKS_Silverlight_App { public class JointData : DependencyObject, INotifyPropertyChanged { public double X = double.NaN; public double Y = double.NaN; public double AngleDegrees = double.NaN; public JointType TypeOfJoint; private string _linkNames; public string LinkNames { get { return _linkNames; } set { _linkNames = value.ToLower(); _linkNames = _linkNames.Replace("gnd", "ground"); _linkNames = _linkNames.Replace("grnd", "ground"); _linkNames = _linkNames.Replace("grond", "ground"); _linkNames = _linkNames.Replace("gound", "ground"); _linkNames = _linkNames.Replace("groud", "ground"); if (Regex.Match(_linkNames[0].ToString(), @"[0,1]").Success && Regex.Match(_linkNames[1].ToString(), @"[^a-z,^0-9]").Success) { _linkNames = _linkNames.Remove(0, 1); _linkNames = "ground" + _linkNames; } var lastIndex = _linkNames.Length - 1; if (Regex.Match(_linkNames[lastIndex].ToString(), @"[0,1]").Success && Regex.Match(_linkNames[lastIndex - 1].ToString(), @"[^a-z,^0-9]").Success) { _linkNames = _linkNames.Remove(lastIndex); _linkNames += "ground"; } _linkNames = Regex.Replace(_linkNames, @"[^a-z,^0-9][0,1][^a-z,^0-9]", " ground "); } } public string JointTypeString { get { if (TypeOfJoint == JointType.unspecified) return ""; return TypeOfJoint.ToString(); } set { string jointTypeString; if (string.IsNullOrWhiteSpace(value)) jointTypeString = ""; else jointTypeString = value.Split(',', ' ')[0]; Enum.TryParse(jointTypeString, true, out TypeOfJoint); } } public string[] LinkNamesList { set { var tempList = ""; foreach (var s in value) { tempList += s; tempList += ","; } _linkNames = tempList.Remove(tempList.Length - 1); if (Application.Current.RootVisual != null) App.main.linkInputTable.UpdateLinksTable(); } get { if (_linkNames == null || string.IsNullOrWhiteSpace(_linkNames)) return new string[0]; return _linkNames.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); //var tempList = _linkNames.Split(new [] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); //for (int i = 0; i < tempList.Length; i++) //{ // var s = tempList[i]; // if (s.Equals("0") || s.Equals("1")) tempList[i] = "ground"; //} //return tempList; } } public string XPos { get { return (double.IsNaN(X)) ? "" : X.ToString("F3", CultureInfo.InvariantCulture); } set { if (!double.TryParse(value, out X)) X = GetRandomNewXCoord(Y); } } public string YPos { get { return (double.IsNaN(Y)) ? "" : Y.ToString("F3", CultureInfo.InvariantCulture); } set { if (!double.TryParse(value, out Y)) Y = GetRandomNewYCoord(X); } } // Declare the PropertyChanged event public event PropertyChangedEventHandler PropertyChanged; // OnPropertyChanged will raise the PropertyChanged event passing the // source property that is being updated. private void onPropertyChanged(object sender, string propertyName) { if (this.PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs(propertyName)); } } public string Angle { get { if (double.IsNaN(AngleDegrees)) { if (TypeOfJoint == JointType.R || TypeOfJoint == JointType.G || TypeOfJoint == JointType.unspecified) return ""; return "required"; } return AngleDegrees.ToString("F3", CultureInfo.InvariantCulture); } set { if (!double.TryParse(value, out AngleDegrees)) { AngleDegrees = double.NaN; } while (AngleDegrees > 90) AngleDegrees -= 180.0; while (AngleDegrees < -90) AngleDegrees += 180.0; } } public Boolean PosVisible { get { return (Boolean)GetValue(PosVisibleProperty); } set { SetValue(PosVisibleProperty, value); } } public static readonly DependencyProperty PosVisibleProperty = DependencyProperty.Register("PosVisible", typeof(Boolean), typeof(JointData), new PropertyMetadata(true)); public Boolean VelocityVisible { get { return (Boolean)GetValue(VelVisibleProperty); } set { SetValue(VelVisibleProperty, value); } } public static readonly DependencyProperty VelVisibleProperty = DependencyProperty.Register("VelVisible", typeof(Boolean), typeof(JointData), new PropertyMetadata(false)); public Boolean AccelerationVisible { get { return (Boolean)GetValue(AccelVisibleProperty); } set { SetValue(AccelVisibleProperty, value); } } public static readonly DependencyProperty AccelVisibleProperty = DependencyProperty.Register("AccelVisible", typeof(Boolean), typeof(JointData), new PropertyMetadata(false)); public Boolean DrivingInput { get { return (Boolean)GetValue(DrivingInputProperty); } set { SetValue(DrivingInputProperty, value); } } public static readonly DependencyProperty DrivingInputProperty = DependencyProperty.Register("DrivingInput", typeof(Boolean), typeof(JointData), new PropertyMetadata(false)); public Boolean CanBeDriver { get { return ((TypeOfJoint == JointType.R || TypeOfJoint == JointType.P) && LinkNamesList != null && LinkNamesList.Count() > 1); } } public double CanPlotStateVars { get { if (LinkNames.Contains("ground")) return 0.0; else return 1.0; } } internal static string ConvertDataToText(char jointSepChar) { var nameTrimChars = new[] { ' ', ',', ';', ':', '.', '|' }; var text = ""; foreach (var jInfo in App.main.JointsInfo.Data) { if (string.IsNullOrWhiteSpace(jInfo.LinkNames) || (string.IsNullOrWhiteSpace(jInfo.JointTypeString))) continue; var linkNames = jInfo.LinkNames; var linkNamesList = linkNames.Split(nameTrimChars); linkNames = ""; foreach (var name in linkNamesList) { var trimmedName = name.Trim(nameTrimChars); if (!string.IsNullOrWhiteSpace(trimmedName)) linkNames += name.Trim(nameTrimChars) + ","; } text += linkNames; text += jInfo.JointTypeString + ","; text += jInfo.XPos + ","; text += jInfo.YPos; text += (!string.IsNullOrWhiteSpace(jInfo.Angle)) ? "," + jInfo.Angle : ""; var boolStr = "," + (jInfo.PosVisible ? 't' : 'f') + (jInfo.VelocityVisible ? 't' : 'f') + (jInfo.AccelerationVisible ? 't' : 'f') + (jInfo.DrivingInput ? 't' : 'f'); text += boolStr + jointSepChar; } return text; } public void RefreshTablePositions() { //if (App.main != null) // App.main.fileAndEditPanel.dataGrid.InvalidateMeasure(); onPropertyChanged(this, "XPos"); onPropertyChanged(this, "YPos"); onPropertyChanged(this, "Angle"); } private static double xRangeCenter, yRangeCenter, radiusRange; private static Random random = new Random(); private static double GetRandomNewXCoord(double yCoord = double.NaN) { if (double.IsNaN(yCoord)) return xRangeCenter + random.NextDouble() * radiusRange; else { var angle = Math.Asin((yCoord - yRangeCenter) / radiusRange); if (random.NextDouble() > 0.5) return xRangeCenter + radiusRange * Math.Cos(angle); else return xRangeCenter - radiusRange * Math.Cos(angle); } } private static double GetRandomNewYCoord(double xCoord = double.NaN) { if (double.IsNaN(xCoord)) return yRangeCenter + random.NextDouble() * radiusRange; else { var angle = Math.Acos((xCoord - xRangeCenter) / radiusRange); if (random.NextDouble() > 0.5) return yRangeCenter + radiusRange * Math.Sin(angle); else return yRangeCenter - radiusRange * Math.Sin(angle); } } internal static void UpdateRandomRange(List<double[]> initPositions) { var xMin = initPositions.Min(coord => coord[0]); var xMax = initPositions.Max(coord => coord[0]); var yMin = initPositions.Min(coord => coord[1]); var yMax = initPositions.Max(coord => coord[1]); xRangeCenter = (xMax + xMin) / 2; yRangeCenter = (yMax + yMin) / 2; radiusRange = Math.Max((xMax - xMin), (yMax - yMin)) / 2; } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI41; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.LowLevelAPI41 { /// <summary> /// C_DigestInit, C_Digest, C_DigestUpdate, C_DigestFinal and C_DigestKey tests. /// </summary> [TestFixture()] public class _12_DigestTest { /// <summary> /// C_DigestInit and C_Digest test. /// </summary> [Test()] public void _01_DigestSinglePartTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs41); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1); // Initialize digesting operation rv = pkcs11.C_DigestInit(session, ref mechanism); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of digest value in first call uint digestLen = 0; rv = pkcs11.C_Digest(session, sourceData, Convert.ToUInt32(sourceData.Length), null, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(digestLen > 0); // Allocate array for digest value byte[] digest = new byte[digestLen]; // Get digest value in second call rv = pkcs11.C_Digest(session, sourceData, Convert.ToUInt32(sourceData.Length), digest, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with digest value rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_DigestInit, C_DigestUpdate and C_DigestFinal test. /// </summary> [Test()] public void _02_DigestMultiPartTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs41); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] digest = null; // Multipart digesting functions C_DigestUpdate and C_DigestFinal can be used i.e. for digesting of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize digesting operation rv = pkcs11.C_DigestInit(session, ref mechanism); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Digest each individual source data part rv = pkcs11.C_DigestUpdate(session, part, Convert.ToUInt32(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Get length of digest value in first call uint digestLen = 0; rv = pkcs11.C_DigestFinal(session, null, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(digestLen > 0); // Allocate array for digest value digest = new byte[digestLen]; // Get digest value in second call rv = pkcs11.C_DigestFinal(session, digest, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with digest value rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_DigestInit, C_DigestKey and C_DigestFinal test. /// </summary> [Test()] public void _03_DigestKeyTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs41); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key uint keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify digesting mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1); // Initialize digesting operation rv = pkcs11.C_DigestInit(session, ref mechanism); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Digest key rv = pkcs11.C_DigestKey(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of digest value in first call uint digestLen = 0; rv = pkcs11.C_DigestFinal(session, null, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(digestLen > 0); // Allocate array for digest value byte[] digest = new byte[digestLen]; // Get digest value in second call rv = pkcs11.C_DigestFinal(session, digest, ref digestLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with digest value rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_811 : MapLoop { public M_811() : base(null) { Content.AddRange(new MapBaseEntity[] { new BIG() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 100 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new ITD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_FA1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_HL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, new TDS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_ITA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_BAL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CTT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } //1000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 12 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2000 public class L_FA1 : MapLoop { public L_FA1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3000 public class L_HL : MapLoop { public L_HL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NM1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_ITA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_IT1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SLN(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_TCD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_USD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_III(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_FA1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3100 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new VEH() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 8 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 8 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_QTY(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, }); } } //3110 public class L_QTY : MapLoop { public L_QTY(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3200 public class L_NM1 : MapLoop { public L_NM1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3300 public class L_ITA : MapLoop { public L_ITA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3400 public class L_IT1 : MapLoop { public L_IT1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new IT1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 8 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_QTY_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ITA_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new L_NM1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3410 public class L_QTY_1 : MapLoop { public L_QTY_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3420 public class L_ITA_1 : MapLoop { public L_ITA_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3430 public class L_NM1_1 : MapLoop { public L_NM1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3500 public class L_SLN : MapLoop { public L_SLN(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SLN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 200 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 20 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new INC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 15 }, new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_QTY_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NM1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3510 public class L_QTY_2 : MapLoop { public L_QTY_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3520 public class L_NM1_2 : MapLoop { public L_NM1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 8 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 3 }, new DMG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3600 public class L_TCD : MapLoop { public L_TCD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new TCD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TXI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_QTY_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3610 public class L_QTY_3 : MapLoop { public L_QTY_3(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3700 public class L_USD : MapLoop { public L_USD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new USD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new ITA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new TRF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 18 }, new L_QTY_4(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3710 public class L_QTY_4 : MapLoop { public L_QTY_4(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new QTY() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //3800 public class L_III : MapLoop { public L_III(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new III() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new L_LQ(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3810 public class L_LQ : MapLoop { public L_LQ(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //3900 public class L_FA1_1 : MapLoop { public L_FA1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4000 public class L_ITA_2 : MapLoop { public L_ITA_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, }); } } //5000 public class L_BAL : MapLoop { public L_BAL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new BAL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6000 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_BAL_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ITA_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LX_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6100 public class L_BAL_1 : MapLoop { public L_BAL_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new BAL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6200 public class L_ITA_3 : MapLoop { public L_ITA_3(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new SI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6300 public class L_LX_1 : MapLoop { public L_LX_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_ITA_4(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //6310 public class L_AMT : MapLoop { public L_AMT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //6320 public class L_ITA_4 : MapLoop { public L_ITA_4(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new ITA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using System.Text.RegularExpressions; namespace Jubjubnest.Style.DotNet { /// <summary> /// Analyzes the XML documentation. /// </summary> [ DiagnosticAnalyzer( LanguageNames.CSharp ) ] public class DocumentationAnalyzer : DiagnosticAnalyzer { /// <summary>Require documentation on all elements.</summary> public static RuleDescription XmlDocumentEverythingWithSummary { get; } = new RuleDescription( nameof( XmlDocumentEverythingWithSummary ), "Documentation" ); /// <summary>Require documentation on all method parameters.</summary> public static RuleDescription XmlDocumentAllMethodParams { get; } = new RuleDescription( nameof( XmlDocumentAllMethodParams ), "Documentation" ); /// <summary>Require documentation on return values.</summary> public static RuleDescription XmlDocumentReturnValues { get; } = new RuleDescription( nameof( XmlDocumentReturnValues ), "Documentation" ); /// <summary>Check that each documented parameter exists on the method.</summary> public static RuleDescription XmlDocumentationNoMismatchedParam { get; } = new RuleDescription( nameof( XmlDocumentationNoMismatchedParam ), "Documentation" ); /// <summary>Check that the documentation XML elements are not empty.</summary> public static RuleDescription XmlDocumentationNoEmptyContent { get; } = new RuleDescription( nameof( XmlDocumentationNoEmptyContent ), "Documentation" ); /// <summary>Check that the documentation XML elements are not empty.</summary> public static RuleDescription XmlNoMultipleXmlDocumentationSegments { get; } = new RuleDescription( nameof( XmlNoMultipleXmlDocumentationSegments ), "Documentation" ); /// <summary>Check that the documentation XML elements are not empty.</summary> public static RuleDescription XmlNoMultipleParamsWithSameName { get; } = new RuleDescription( nameof( XmlNoMultipleParamsWithSameName ), "Documentation" ); /// <summary>Check that the documentation XML elements are not empty.</summary> public static RuleDescription XmlEnableDocumentationGeneration { get; } = new RuleDescription( nameof( XmlEnableDocumentationGeneration ), "Documentation" ); /// <summary> /// Supported diagnostic rules. /// </summary> public override ImmutableArray< DiagnosticDescriptor > SupportedDiagnostics => ImmutableArray.Create( XmlEnableDocumentationGeneration.Rule, XmlDocumentEverythingWithSummary.Rule, XmlDocumentAllMethodParams.Rule, XmlDocumentReturnValues.Rule, XmlDocumentationNoMismatchedParam.Rule, XmlDocumentationNoEmptyContent.Rule, XmlNoMultipleXmlDocumentationSegments.Rule, XmlNoMultipleParamsWithSameName.Rule ); /// <summary> /// Initialize the analyzer. /// </summary> /// <param name="context">Analysis context the analysis actions are registered on.</param> public override void Initialize( AnalysisContext context ) { // Ignore generated files. context.ConfigureGeneratedCodeAnalysis( GeneratedCodeAnalysisFlags.None ); // Register the actions. context.RegisterSyntaxTreeAction( CheckDocumentationMode ); context.RegisterSyntaxNodeAction( CheckXmlDocumentation, SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.EnumDeclaration, SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.FieldDeclaration, SyntaxKind.EnumMemberDeclaration ); } /// <summary> /// Check the documentation mode. /// </summary> /// <param name="context">Analysis context.</param> private void CheckDocumentationMode( SyntaxTreeAnalysisContext context ) { // Check whether the documentation mode is set. if( context.Tree.Options.DocumentationMode == DocumentationMode.None ) { // Documentation is not being processed. Raise an error. var diagnostic = Diagnostic.Create( XmlEnableDocumentationGeneration.Rule, null ); context.ReportDiagnostic( diagnostic ); } } /// <summary> /// Check for the XML documentation. /// </summary> /// <param name="context">Analysis context.</param> private static void CheckXmlDocumentation( SyntaxNodeAnalysisContext context ) { // Skip the XML checks if the Xml documentation isn't being processed. // These checks would fail even if XML documentation was present. if( context.Node.SyntaxTree.Options.DocumentationMode == DocumentationMode.None ) return; // Get all the documentation trivia. var documentationTrivias = context.Node.GetLeadingTrivia() .Where( trivia => trivia.IsKind( SyntaxKind.SingleLineDocumentationCommentTrivia ) || trivia.IsKind( SyntaxKind.MultiLineDocumentationCommentTrivia ) ) .Select( trivia => trivia.GetStructure() ) .OfType< DocumentationCommentTriviaSyntax >() .ToList(); // Ensure there's only one doc-block at most. if( documentationTrivias.Count > 1 ) { // Multiple blocks. Report and stop processing until the dev fixes this issue. // Remove the last trivia. The last trivia is considered "okay". // We'll report issues for only the preceding ones. documentationTrivias.RemoveAt( documentationTrivias.Count - 1 ); // Report all preceding blocks. foreach( var trivia in documentationTrivias ) { // Report. var diagnostic = Diagnostic.Create( XmlNoMultipleXmlDocumentationSegments.Rule, trivia.GetLocation() ); context.ReportDiagnostic( diagnostic ); } // Stop processing further. return; } // [Test], [TestCase] and [TestMethod] methods do not need XML documentation. // These methods should have a name that is descriptive enough. bool requiresDocumentation = true; if( context.Node.IsKind( SyntaxKind.MethodDeclaration ) ) { // Check for the attributes on the method. var method = ( MethodDeclarationSyntax )context.Node; var attributes = method.AttributeLists.SelectMany( list => list.Attributes ); // Check for the aforementioned attributes. var isTestMethod = attributes.Any( attr => { // Compare the name. var attrName = attr.Name.ToString(); return attrName == "Test" || attrName == "TestCase" || attrName == "TestMethod"; } ); // Set the require-value. requiresDocumentation = !isTestMethod; } // The remaining tests involve checking the documentation. // If there is no documentation and none is required we can stop here. if( !requiresDocumentation && documentationTrivias.Count == 0 ) return; // Ensure the documentation exists. if( documentationTrivias.Count == 0 ) { // No documentation. // Create the diagnostic message and report it. var identifier = SyntaxHelper.GetIdentifier( context.Node ); var diagnostic = Diagnostic.Create( XmlDocumentEverythingWithSummary.Rule, identifier?.GetLocation() ?? context.Node.GetLocation(), SyntaxHelper.GetItemType( context.Node ), identifier.ToString() ); context.ReportDiagnostic( diagnostic ); // Stop processing further here. // If there is no XML documentation tag, there's no real reason to // report missing parameters etc. either. return; } // Validate the individual XML elements. var xmlElements = documentationTrivias[ 0 ] .ChildNodes() .OfType< XmlElementSyntax >() .ToList(); ValidateXmlElements( context, xmlElements ); } /// <summary> /// Validates the XML-elements in the documentation block. /// </summary> /// <param name="context">Analysis context.</param> /// <param name="xmlElements">XML elements contained in the XML-documentation.</param> private static void ValidateXmlElements( SyntaxNodeAnalysisContext context, List< XmlElementSyntax > xmlElements ) { // Ensure a summary exists. var summaries = xmlElements.Where( xml => xml.StartTag.Name.ToString() == "summary" ); if( !summaries.Any() ) { // No summary. // Create the diagnostic message and report it. var identifier = SyntaxHelper.GetIdentifier( context.Node ); var diagnostic = Diagnostic.Create( XmlDocumentEverythingWithSummary.Rule, identifier?.GetLocation() ?? context.Node.GetLocation(), SyntaxHelper.GetItemType( context.Node ), identifier.ToString() ); context.ReportDiagnostic( diagnostic ); } // If this is a method declaration, we'll need to check for "param" and "return" docs. if( context.Node.IsKind( SyntaxKind.MethodDeclaration ) ) { // This is a method declaration. Check for additional XML elements. // Get the method and gather the method params by name. var method = (MethodDeclarationSyntax)context.Node; var paramNodes = method.ParameterList.Parameters.ToDictionary( p => p.Identifier.ToString() ); // Gather all <param> elements. var paramElements = xmlElements.Where( xml => xml.StartTag.Name.ToString() == "param" ).ToList(); // Go through all param XML elements. // Keep gathering the ones matching real parameters into a by-name dictionary while doing so. Dictionary< string, string > paramDocs = new Dictionary< string, string >(); foreach( var paramElement in paramElements ) { // Get the name for the element. var nameAttribute = paramElement.StartTag.Attributes .OfType< XmlNameAttributeSyntax >() .Single(); // Check whether a parameter exists with that name. var paramName = nameAttribute.Identifier.ToString(); if( !paramNodes.ContainsKey( paramName ) ) { // No parameter with the name found. // Create the diagnostic message and report it. var diagnostic = Diagnostic.Create( XmlDocumentationNoMismatchedParam.Rule, nameAttribute.GetLocation(), paramName ); context.ReportDiagnostic( diagnostic ); // Continue to the next element without adding this // one to the param docs dictionary as it doesn't // match an existing element. continue; } // Ensure there are no duplicate 'name' attributes. if( paramDocs.ContainsKey( nameAttribute.Identifier.ToString() ) ) { // Duplicate attribute. // Create the diagnostic message and report it. var diagnostic = Diagnostic.Create( XmlNoMultipleParamsWithSameName.Rule, nameAttribute.GetLocation(), paramName ); context.ReportDiagnostic( diagnostic ); continue; } // Store the element by name in the dictionary. paramDocs.Add( nameAttribute.Identifier.ToString(), paramElement.Content.ToString() ); } // Check all existing parameters against the <param> elements. foreach( var paramPair in paramNodes ) { // Check if there is a <param> element for the parameter. var paramName = paramPair.Key; if( !paramDocs.ContainsKey( paramName ) ) { // No element exists. // Create the diagnostic message and report it. var diagnostic = Diagnostic.Create( XmlDocumentAllMethodParams.Rule, paramPair.Value.Identifier.GetLocation(), paramPair.Key ); context.ReportDiagnostic( diagnostic ); } } // If the method is non-void, ensure it has a <returns> element. if( method.ReturnType.ToString() != "void" && xmlElements.All( xml => xml.StartTag.Name.ToString() != "returns" ) ) { // Non-void without <returns>. // Create the diagnostic message and report it. var diagnostic = Diagnostic.Create( XmlDocumentReturnValues.Rule, method.Identifier.GetLocation(), method.Identifier.ToString() ); context.ReportDiagnostic( diagnostic ); } } // Ensure all XML elements have proper content. foreach( var element in xmlElements ) EnsureNonEmptyContent( context, element ); } /// <summary> /// Checks that the XML element has valid content. /// </summary> /// <param name="context">Analysis context.</param> /// <param name="element">XML documentation element.</param> private static void EnsureNonEmptyContent( SyntaxNodeAnalysisContext context, XmlElementSyntax element ) { // Check whether the content exists. if( string.IsNullOrWhiteSpace( element.Content.ToString() ) ) { // Empty element. // Create the diagnostic message and report it. var diagnostic = Diagnostic.Create( XmlDocumentationNoEmptyContent.Rule, element.GetLocation(), element.StartTag.Name.ToString() ); context.ReportDiagnostic( diagnostic ); } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; namespace TheArtOfDev.HtmlRenderer.Core.Dom { /// <summary> /// Helps on CSS Layout. /// </summary> internal static class CssLayoutEngine { /// <summary> /// Measure image box size by the width\height set on the box and the actual rendered image size.<br/> /// If no image exists for the box error icon will be set. /// </summary> /// <param name="imageWord">the image word to measure</param> public static void MeasureImageSize(CssRectImage imageWord) { ArgChecker.AssertArgNotNull(imageWord, "imageWord"); ArgChecker.AssertArgNotNull(imageWord.OwnerBox, "imageWord.OwnerBox"); var width = new CssLength(imageWord.OwnerBox.Width); var height = new CssLength(imageWord.OwnerBox.Height); bool hasImageTagWidth = width.Number > 0 && width.Unit == CssUnit.Pixels; bool hasImageTagHeight = height.Number > 0 && height.Unit == CssUnit.Pixels; bool scaleImageHeight = false; if (hasImageTagWidth) { imageWord.Width = width.Number; } else if (width.Number > 0 && width.IsPercentage) { imageWord.Width = width.Number * imageWord.OwnerBox.ContainingBlock.Size.Width; scaleImageHeight = true; } else if (imageWord.Image != null) { imageWord.Width = imageWord.ImageRectangle == RRect.Empty ? imageWord.Image.Width : imageWord.ImageRectangle.Width; } else { imageWord.Width = hasImageTagHeight ? height.Number / 1.14f : 20; } var maxWidth = new CssLength(imageWord.OwnerBox.MaxWidth); if (maxWidth.Number > 0) { double maxWidthVal = -1; if (maxWidth.Unit == CssUnit.Pixels) { maxWidthVal = maxWidth.Number; } else if (maxWidth.IsPercentage) { maxWidthVal = maxWidth.Number * imageWord.OwnerBox.ContainingBlock.Size.Width; } if (maxWidthVal > -1 && imageWord.Width > maxWidthVal) { imageWord.Width = maxWidthVal; scaleImageHeight = !hasImageTagHeight; } } if (hasImageTagHeight) { imageWord.Height = height.Number; } else if (imageWord.Image != null) { imageWord.Height = imageWord.ImageRectangle == RRect.Empty ? imageWord.Image.Height : imageWord.ImageRectangle.Height; } else { imageWord.Height = imageWord.Width > 0 ? imageWord.Width * 1.14f : 22.8f; } if (imageWord.Image != null) { // If only the width was set in the html tag, ratio the height. if ((hasImageTagWidth && !hasImageTagHeight) || scaleImageHeight) { // Divide the given tag width with the actual image width, to get the ratio. double ratio = imageWord.Width / imageWord.Image.Width; imageWord.Height = imageWord.Image.Height * ratio; } // If only the height was set in the html tag, ratio the width. else if (hasImageTagHeight && !hasImageTagWidth) { // Divide the given tag height with the actual image height, to get the ratio. double ratio = imageWord.Height / imageWord.Image.Height; imageWord.Width = imageWord.Image.Width * ratio; } } imageWord.Height += imageWord.OwnerBox.ActualBorderBottomWidth + imageWord.OwnerBox.ActualBorderTopWidth + imageWord.OwnerBox.ActualPaddingTop + imageWord.OwnerBox.ActualPaddingBottom; } /// <summary> /// Creates line boxes for the specified blockbox /// </summary> /// <param name="g"></param> /// <param name="blockBox"></param> public static void CreateLineBoxes(RGraphics g, CssBox blockBox) { ArgChecker.AssertArgNotNull(g, "g"); ArgChecker.AssertArgNotNull(blockBox, "blockBox"); blockBox.LineBoxes.Clear(); double limitRight = blockBox.ActualRight - blockBox.ActualPaddingRight - blockBox.ActualBorderRightWidth; //Get the start x and y of the blockBox double startx = blockBox.Location.X + blockBox.ActualPaddingLeft - 0 + blockBox.ActualBorderLeftWidth; double starty = blockBox.Location.Y + blockBox.ActualPaddingTop - 0 + blockBox.ActualBorderTopWidth; double curx = startx + blockBox.ActualTextIndent; double cury = starty; //Reminds the maximum bottom reached double maxRight = startx; double maxBottom = starty; //First line box CssLineBox line = new CssLineBox(blockBox); //Flow words and boxes FlowBox(g, blockBox, blockBox, limitRight, 0, startx, ref line, ref curx, ref cury, ref maxRight, ref maxBottom); // if width is not restricted we need to lower it to the actual width if (blockBox.ActualRight >= 90999) { blockBox.ActualRight = maxRight + blockBox.ActualPaddingRight + blockBox.ActualBorderRightWidth; } //Gets the rectangles for each line-box foreach (var linebox in blockBox.LineBoxes) { ApplyHorizontalAlignment(g, linebox); ApplyRightToLeft(blockBox, linebox); BubbleRectangles(blockBox, linebox); ApplyVerticalAlignment(g, linebox); linebox.AssignRectanglesToBoxes(); } blockBox.ActualBottom = maxBottom + blockBox.ActualPaddingBottom + blockBox.ActualBorderBottomWidth; // handle limiting block height when overflow is hidden if (blockBox.Height != null && blockBox.Height != CssConstants.Auto && blockBox.Overflow == CssConstants.Hidden && blockBox.ActualBottom - blockBox.Location.Y > blockBox.ActualHeight) { blockBox.ActualBottom = blockBox.Location.Y + blockBox.ActualHeight; } } /// <summary> /// Applies special vertical alignment for table-cells /// </summary> /// <param name="g"></param> /// <param name="cell"></param> public static void ApplyCellVerticalAlignment(RGraphics g, CssBox cell) { ArgChecker.AssertArgNotNull(g, "g"); ArgChecker.AssertArgNotNull(cell, "cell"); if (cell.VerticalAlign == CssConstants.Top || cell.VerticalAlign == CssConstants.Baseline) return; double cellbot = cell.ClientBottom; double bottom = cell.GetMaximumBottom(cell, 0f); double dist = 0f; if (cell.VerticalAlign == CssConstants.Bottom) { dist = cellbot - bottom; } else if (cell.VerticalAlign == CssConstants.Middle) { dist = (cellbot - bottom) / 2; } foreach (CssBox b in cell.Boxes) { b.OffsetTop(dist); } //float top = cell.ClientTop; //float bottom = cell.ClientBottom; //bool middle = cell.VerticalAlign == CssConstants.Middle; //foreach (LineBox line in cell.LineBoxes) //{ // for (int i = 0; i < line.RelatedBoxes.Count; i++) // { // double diff = bottom - line.RelatedBoxes[i].Rectangles[line].Bottom; // if (middle) diff /= 2f; // RectangleF r = line.RelatedBoxes[i].Rectangles[line]; // line.RelatedBoxes[i].Rectangles[line] = new RectangleF(r.X, r.Y + diff, r.Width, r.Height); // } // foreach (BoxWord word in line.Words) // { // double gap = word.Top - top; // word.Top = bottom - gap - word.Height; // } //} } #region Private methods /// <summary> /// Recursively flows the content of the box using the inline model /// </summary> /// <param name="g">Device Info</param> /// <param name="blockbox">Blockbox that contains the text flow</param> /// <param name="box">Current box to flow its content</param> /// <param name="limitRight">Maximum reached right</param> /// <param name="linespacing">Space to use between rows of text</param> /// <param name="startx">x starting coordinate for when breaking lines of text</param> /// <param name="line">Current linebox being used</param> /// <param name="curx">Current x coordinate that will be the left of the next word</param> /// <param name="cury">Current y coordinate that will be the top of the next word</param> /// <param name="maxRight">Maximum right reached so far</param> /// <param name="maxbottom">Maximum bottom reached so far</param> private static void FlowBox(RGraphics g, CssBox blockbox, CssBox box, double limitRight, double linespacing, double startx, ref CssLineBox line, ref double curx, ref double cury, ref double maxRight, ref double maxbottom) { var startX = curx; var startY = cury; box.FirstHostingLineBox = line; var localCurx = curx; var localMaxRight = maxRight; var localmaxbottom = maxbottom; foreach (CssBox b in box.Boxes) { double leftspacing = (b.Position != CssConstants.Absolute && b.Position != CssConstants.Fixed) ? b.ActualMarginLeft + b.ActualBorderLeftWidth + b.ActualPaddingLeft : 0; double rightspacing = (b.Position != CssConstants.Absolute && b.Position != CssConstants.Fixed) ? b.ActualMarginRight + b.ActualBorderRightWidth + b.ActualPaddingRight : 0; b.RectanglesReset(); b.MeasureWordsSize(g); curx += leftspacing; if (b.Words.Count > 0) { bool wrapNoWrapBox = false; if (b.WhiteSpace == CssConstants.NoWrap && curx > startx) { var boxRight = curx; foreach (var word in b.Words) boxRight += word.FullWidth; if (boxRight > limitRight) wrapNoWrapBox = true; } if (DomUtils.IsBoxHasWhitespace(b)) curx += box.ActualWordSpacing; foreach (var word in b.Words) { if (maxbottom - cury < box.ActualLineHeight) maxbottom += box.ActualLineHeight - (maxbottom - cury); if ((b.WhiteSpace != CssConstants.NoWrap && b.WhiteSpace != CssConstants.Pre && curx + word.Width + rightspacing > limitRight && (b.WhiteSpace != CssConstants.PreWrap || !word.IsSpaces)) || word.IsLineBreak || wrapNoWrapBox) { wrapNoWrapBox = false; curx = startx; // handle if line is wrapped for the first text element where parent has left margin\padding if (b == box.Boxes[0] && !word.IsLineBreak && (word == b.Words[0] || (box.ParentBox != null && box.ParentBox.IsBlock))) curx += box.ActualMarginLeft + box.ActualBorderLeftWidth + box.ActualPaddingLeft; cury = maxbottom + linespacing; line = new CssLineBox(blockbox); if (word.IsImage || word.Equals(b.FirstWord)) { curx += leftspacing; } } line.ReportExistanceOf(word); word.Left = curx; word.Top = cury; if (!box.IsFixed) { word.BreakPage(); } curx = word.Left + word.FullWidth; maxRight = Math.Max(maxRight, word.Right); maxbottom = Math.Max(maxbottom, word.Bottom); if (b.Position == CssConstants.Absolute) { word.Left += box.ActualMarginLeft; word.Top += box.ActualMarginTop; } } } else { FlowBox(g, blockbox, b, limitRight, linespacing, startx, ref line, ref curx, ref cury, ref maxRight, ref maxbottom); } curx += rightspacing; } // handle height setting if (maxbottom - startY < box.ActualHeight) { maxbottom += box.ActualHeight - (maxbottom - startY); } // handle width setting if (box.IsInline && 0 <= curx - startX && curx - startX < box.ActualWidth) { // hack for actual width handling curx += box.ActualWidth - (curx - startX); line.Rectangles.Add(box, new RRect(startX, startY, box.ActualWidth, box.ActualHeight)); } // handle box that is only a whitespace if (box.Text != null && box.Text.IsWhitespace() && !box.IsImage && box.IsInline && box.Boxes.Count == 0 && box.Words.Count == 0) { curx += box.ActualWordSpacing; } // hack to support specific absolute position elements if (box.Position == CssConstants.Absolute) { curx = localCurx; maxRight = localMaxRight; maxbottom = localmaxbottom; AdjustAbsolutePosition(box, 0, 0); } box.LastHostingLineBox = line; } /// <summary> /// Adjust the position of absolute elements by letf and top margins. /// </summary> private static void AdjustAbsolutePosition(CssBox box, double left, double top) { left += box.ActualMarginLeft; top += box.ActualMarginTop; if (box.Words.Count > 0) { foreach (var word in box.Words) { word.Left += left; word.Top += top; } } else { foreach (var b in box.Boxes) AdjustAbsolutePosition(b, left, top); } } /// <summary> /// Recursively creates the rectangles of the blockBox, by bubbling from deep to outside of the boxes /// in the rectangle structure /// </summary> private static void BubbleRectangles(CssBox box, CssLineBox line) { if (box.Words.Count > 0) { double x = Single.MaxValue, y = Single.MaxValue, r = Single.MinValue, b = Single.MinValue; List<CssRect> words = line.WordsOf(box); if (words.Count > 0) { foreach (CssRect word in words) { // handle if line is wrapped for the first text element where parent has left margin\padding var left = word.Left; if (box == box.ParentBox.Boxes[0] && word == box.Words[0] && word == line.Words[0] && line != line.OwnerBox.LineBoxes[0] && !word.IsLineBreak) left -= box.ParentBox.ActualMarginLeft + box.ParentBox.ActualBorderLeftWidth + box.ParentBox.ActualPaddingLeft; x = Math.Min(x, left); r = Math.Max(r, word.Right); y = Math.Min(y, word.Top); b = Math.Max(b, word.Bottom); } line.UpdateRectangle(box, x, y, r, b); } } else { foreach (CssBox b in box.Boxes) { BubbleRectangles(b, line); } } } /// <summary> /// Applies vertical and horizontal alignment to words in lineboxes /// </summary> /// <param name="g"></param> /// <param name="lineBox"></param> private static void ApplyHorizontalAlignment(RGraphics g, CssLineBox lineBox) { switch (lineBox.OwnerBox.TextAlign) { case CssConstants.Right: ApplyRightAlignment(g, lineBox); break; case CssConstants.Center: ApplyCenterAlignment(g, lineBox); break; case CssConstants.Justify: ApplyJustifyAlignment(g, lineBox); break; default: ApplyLeftAlignment(g, lineBox); break; } } /// <summary> /// Applies right to left direction to words /// </summary> /// <param name="blockBox"></param> /// <param name="lineBox"></param> private static void ApplyRightToLeft(CssBox blockBox, CssLineBox lineBox) { if (blockBox.Direction == CssConstants.Rtl) { ApplyRightToLeftOnLine(lineBox); } else { foreach (var box in lineBox.RelatedBoxes) { if (box.Direction == CssConstants.Rtl) { ApplyRightToLeftOnSingleBox(lineBox, box); } } } } /// <summary> /// Applies RTL direction to all the words on the line. /// </summary> /// <param name="line">the line to apply RTL to</param> private static void ApplyRightToLeftOnLine(CssLineBox line) { if (line.Words.Count > 0) { double left = line.Words[0].Left; double right = line.Words[line.Words.Count - 1].Right; foreach (CssRect word in line.Words) { double diff = word.Left - left; double wright = right - diff; word.Left = wright - word.Width; } } } /// <summary> /// Applies RTL direction to specific box words on the line. /// </summary> /// <param name="lineBox"></param> /// <param name="box"></param> private static void ApplyRightToLeftOnSingleBox(CssLineBox lineBox, CssBox box) { int leftWordIdx = -1; int rightWordIdx = -1; for (int i = 0; i < lineBox.Words.Count; i++) { if (lineBox.Words[i].OwnerBox == box) { if (leftWordIdx < 0) leftWordIdx = i; rightWordIdx = i; } } if (leftWordIdx > -1 && rightWordIdx > leftWordIdx) { double left = lineBox.Words[leftWordIdx].Left; double right = lineBox.Words[rightWordIdx].Right; for (int i = leftWordIdx; i <= rightWordIdx; i++) { double diff = lineBox.Words[i].Left - left; double wright = right - diff; lineBox.Words[i].Left = wright - lineBox.Words[i].Width; } } } /// <summary> /// Applies vertical alignment to the linebox /// </summary> /// <param name="g"></param> /// <param name="lineBox"></param> private static void ApplyVerticalAlignment(RGraphics g, CssLineBox lineBox) { double baseline = Single.MinValue; foreach (var box in lineBox.Rectangles.Keys) { baseline = Math.Max(baseline, lineBox.Rectangles[box].Top); } var boxes = new List<CssBox>(lineBox.Rectangles.Keys); foreach (CssBox box in boxes) { //Important notes on http://www.w3.org/TR/CSS21/tables.html#height-layout switch (box.VerticalAlign) { case CssConstants.Sub: lineBox.SetBaseLine(g, box, baseline + lineBox.Rectangles[box].Height * .5f); break; case CssConstants.Super: lineBox.SetBaseLine(g, box, baseline - lineBox.Rectangles[box].Height * .2f); break; case CssConstants.TextTop: break; case CssConstants.TextBottom: break; case CssConstants.Top: break; case CssConstants.Bottom: break; case CssConstants.Middle: break; default: //case: baseline lineBox.SetBaseLine(g, box, baseline); break; } } } /// <summary> /// Applies centered alignment to the text on the linebox /// </summary> /// <param name="g"></param> /// <param name="lineBox"></param> private static void ApplyJustifyAlignment(RGraphics g, CssLineBox lineBox) { if (lineBox.Equals(lineBox.OwnerBox.LineBoxes[lineBox.OwnerBox.LineBoxes.Count - 1])) return; double indent = lineBox.Equals(lineBox.OwnerBox.LineBoxes[0]) ? lineBox.OwnerBox.ActualTextIndent : 0f; double textSum = 0f; double words = 0f; double availWidth = lineBox.OwnerBox.ClientRectangle.Width - indent; // Gather text sum foreach (CssRect w in lineBox.Words) { textSum += w.Width; words += 1f; } if (words <= 0f) return; //Avoid Zero division double spacing = (availWidth - textSum) / words; //Spacing that will be used double curx = lineBox.OwnerBox.ClientLeft + indent; foreach (CssRect word in lineBox.Words) { word.Left = curx; curx = word.Right + spacing; if (word == lineBox.Words[lineBox.Words.Count - 1]) { word.Left = lineBox.OwnerBox.ClientRight - word.Width; } } } /// <summary> /// Applies centered alignment to the text on the linebox /// </summary> /// <param name="g"></param> /// <param name="line"></param> private static void ApplyCenterAlignment(RGraphics g, CssLineBox line) { if (line.Words.Count == 0) return; CssRect lastWord = line.Words[line.Words.Count - 1]; double right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth; double diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight; diff /= 2; if (diff > 0) { foreach (CssRect word in line.Words) { word.Left += diff; } if (line.Rectangles.Count > 0) { foreach (CssBox b in ToList(line.Rectangles.Keys)) { RRect r = line.Rectangles[b]; line.Rectangles[b] = new RRect(r.X + diff, r.Y, r.Width, r.Height); } } } } /// <summary> /// Applies right alignment to the text on the linebox /// </summary> /// <param name="g"></param> /// <param name="line"></param> private static void ApplyRightAlignment(RGraphics g, CssLineBox line) { if (line.Words.Count == 0) return; CssRect lastWord = line.Words[line.Words.Count - 1]; double right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth; double diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight; if (diff > 0) { foreach (CssRect word in line.Words) { word.Left += diff; } if (line.Rectangles.Count > 0) { foreach (CssBox b in ToList(line.Rectangles.Keys)) { RRect r = line.Rectangles[b]; line.Rectangles[b] = new RRect(r.X + diff, r.Y, r.Width, r.Height); } } } } /// <summary> /// Simplest alignment, just arrange words. /// </summary> /// <param name="g"></param> /// <param name="line"></param> private static void ApplyLeftAlignment(RGraphics g, CssLineBox line) { //No alignment needed. //foreach (LineBoxRectangle r in line.Rectangles) //{ // double curx = r.Left + (r.Index == 0 ? r.OwnerBox.ActualPaddingLeft + r.OwnerBox.ActualBorderLeftWidth / 2 : 0); // if (r.SpaceBefore) curx += r.OwnerBox.ActualWordSpacing; // foreach (BoxWord word in r.Words) // { // word.Left = curx; // word.Top = r.Top;// +r.OwnerBox.ActualPaddingTop + r.OwnerBox.ActualBorderTopWidth / 2; // curx = word.Right + r.OwnerBox.ActualWordSpacing; // } //} } /// <summary> /// todo: optimizate, not creating a list each time /// </summary> private static List<T> ToList<T>(IEnumerable<T> collection) { List<T> result = new List<T>(); foreach (T item in collection) { result.Add(item); } return result; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MinByte() { var test = new SimpleBinaryOpTest__MinByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinByte testClass) { var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinByte testClass) { fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<Byte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); } public SimpleBinaryOpTest__MinByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Min( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Min( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Min( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Byte>* pClsVar1 = &_clsVar1) fixed (Vector256<Byte>* pClsVar2 = &_clsVar2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pClsVar1)), Avx.LoadVector256((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinByte(); var result = Avx2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MinByte(); fixed (Vector256<Byte>* pFld1 = &test._fld1) fixed (Vector256<Byte>* pFld2 = &test._fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<Byte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Min( Avx.LoadVector256((Byte*)(&test._fld1)), Avx.LoadVector256((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Byte> op1, Vector256<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != Math.Min(left[0], right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Min(left[i], right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Min)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Statements { using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using System.Transactions; using System.Workflow.ComponentModel; using System.Workflow.Runtime; [DataContract] class InteropExecutor : IWorkflowCoreRuntime, ISupportInterop { Dictionary<int, Activity> contextActivityMap; Activity currentActivity; Activity currentAtomicActivity; Activity internalCurrentActivity; bool trackingEnabled; bool hasCheckedForTrackingParticipant; [DataMember] Dictionary<Bookmark, IComparable> bookmarkQueueMap; [DataMember] int currentContextId; [DataMember] Guid instanceId; [DataMember] int eventCounter; IList<PropertyInfo> outputProperties; IDictionary<string, object> outputs; Exception outstandingException; [DataMember] byte[] persistedActivityData; Activity rootActivity; Scheduler scheduler; WorkflowQueuingService workflowQueuingService; TimerSchedulerService timerSchedulerSerivce; TimerEventSubscriptionCollection timerQueue; VolatileResourceManager resourceManager; ServiceEnvironment serviceEnvironment; [DataMember(EmitDefaultValue = false)] int atomicActivityContextId; [DataMember(EmitDefaultValue = false)] int internalCurrentActivityContextId; [DataMember(EmitDefaultValue = false)] string atomicActivityName; [DataMember(EmitDefaultValue = false)] string internalCurrentActivityName; Exception lastExceptionThrown; bool abortTransaction; public InteropExecutor(Guid instanceId, Activity rootActivity, IList<PropertyInfo> outputProperties, Activity activityDefinition) { this.PrivateInitialize(rootActivity, instanceId, outputProperties, activityDefinition); } public Activity CurrentActivity { get { return this.currentActivity; } set { this.currentActivity = value; } } public IDictionary<string, object> Outputs { get { return this.outputs; } } public IEnumerable<IComparable> Queues { get { return this.workflowQueuingService.QueueNames; } } public Dictionary<System.Activities.Bookmark, IComparable> BookmarkQueueMap { get { if (this.bookmarkQueueMap == null) { this.bookmarkQueueMap = new Dictionary<System.Activities.Bookmark, IComparable>(); } return this.bookmarkQueueMap; } } public InteropEnvironment ServiceProvider { get; set; } public Activity CurrentAtomicActivity { get { return this.currentAtomicActivity; } } public Guid InstanceID { get { return this.instanceId; } } public bool IsDynamicallyUpdated { get { return false; } } public Activity RootActivity { get { return this.rootActivity; } } TimerEventSubscriptionCollection TimerQueue { get { if (this.timerQueue == null) { this.timerQueue = (TimerEventSubscriptionCollection)this.rootActivity.GetValue(TimerEventSubscriptionCollection.TimerCollectionProperty); Debug.Assert(this.timerQueue != null, "TimerEventSubscriptionCollection on root activity should never be null, but it was"); } return this.timerQueue; } set { this.timerQueue = value; this.rootActivity.SetValue(TimerEventSubscriptionCollection.TimerCollectionProperty, this.timerQueue); } } public WaitCallback ProcessTimersCallback { get { return new WaitCallback(this.ProcessTimers); } } public WorkBatchCollection BatchCollection { get { return this.resourceManager.BatchCollection; } } public bool TrackingEnabled { get { return this.trackingEnabled; } set { this.trackingEnabled = value; } } public bool HasCheckedForTrackingParticipant { get { return this.hasCheckedForTrackingParticipant; } set { this.hasCheckedForTrackingParticipant = value; } } public ActivityExecutionStatus EnqueueEvent(IComparable queueName, object item) { if (queueName == null) { throw new ArgumentNullException("queueName"); } this.workflowQueuingService.EnqueueEvent(queueName, item); Guid timerId = Guid.Empty; if (Guid.TryParse(queueName.ToString(), out timerId)) { // This is a no-op if this is not a timer event. this.TimerQueue.Remove(timerId); } scheduler.Run(); return TranslateExecutionStatus(); } public ActivityExecutionStatus Resume() { scheduler.Run(); return TranslateExecutionStatus(); } public void SetAmbientTransactionAndServiceEnvironment(Transaction transaction) { this.serviceEnvironment = new ServiceEnvironment(this.RootActivity); if (transaction != null && this.currentAtomicActivity != null) { TransactionalProperties transactionalProperties = (TransactionalProperties)this.currentAtomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); Debug.Assert(transactionalProperties != null, "The current atomic activity is missing transactional properties"); transactionalProperties.Transaction = transaction; transactionalProperties.TransactionScope = new System.Transactions.TransactionScope(transactionalProperties.Transaction, TimeSpan.Zero, EnterpriseServicesInteropOption.Full); } } public void ClearAmbientTransactionAndServiceEnvironment() { try { if (this.resourceManager.IsBatchDirty) { this.ServiceProvider.AddResourceManager(this.resourceManager); } if (this.currentAtomicActivity != null) { TransactionalProperties transactionalProperties = (TransactionalProperties)this.currentAtomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); Debug.Assert(transactionalProperties != null, "The current atomic activity is missing transactional properties"); transactionalProperties.Transaction = null; if (transactionalProperties.TransactionScope != null) { transactionalProperties.TransactionScope.Complete(); transactionalProperties.TransactionScope.Dispose(); transactionalProperties.TransactionScope = null; } } } finally { ((IDisposable)this.serviceEnvironment).Dispose(); this.serviceEnvironment = null; } } public bool CheckAndProcessTransactionAborted(TransactionalProperties transactionalProperties) { if (transactionalProperties.Transaction != null && transactionalProperties.Transaction.TransactionInformation.Status != TransactionStatus.Aborted) { return false; } if (transactionalProperties.TransactionState != TransactionProcessState.AbortProcessed) { // The transaction has aborted. The WF3 runtime throws a TransactionAborted exception here, which then propagates as fault. // But WF4 aborts the workflow, so pause the scheduler and return. this.scheduler.Pause(); transactionalProperties.TransactionState = TransactionProcessState.AbortProcessed; } return true; } public bool IsActivityInAtomicContext(Activity activity, out Activity atomicActivity) { atomicActivity = null; while (activity != null) { if (activity == this.currentAtomicActivity) { atomicActivity = activity; return true; } activity = activity.Parent; } return false; } public ActivityExecutionStatus Execute() { using (ActivityExecutionContext activityExecutionContext = new ActivityExecutionContext(this.rootActivity, true)) { activityExecutionContext.ExecuteActivity(this.rootActivity); } scheduler.Run(); return TranslateExecutionStatus(); } public ActivityExecutionStatus Cancel() { using (ActivityExecutionContext activityExecutionContext = new ActivityExecutionContext(this.rootActivity, true)) { if (this.rootActivity.ExecutionStatus == ActivityExecutionStatus.Executing) { activityExecutionContext.CancelActivity(this.rootActivity); } } scheduler.Run(); return TranslateExecutionStatus(); } public void Initialize(Activity definition, IDictionary<string, object> inputs, bool hasNameCollision) { this.rootActivity.SetValue(Activity.ActivityExecutionContextInfoProperty, new ActivityExecutionContextInfo(this.rootActivity.QualifiedName, this.GetNewContextActivityId(), instanceId, -1)); this.rootActivity.SetValue(Activity.ActivityContextGuidProperty, instanceId); SetInputParameters(definition, this.rootActivity, inputs, hasNameCollision); ((IDependencyObjectAccessor)this.rootActivity).InitializeActivatingInstanceForRuntime( null, this); this.rootActivity.FixUpMetaProperties(definition); TimerQueue = new TimerEventSubscriptionCollection(this, this.instanceId); using (new ServiceEnvironment(this.rootActivity)) { using (SetCurrentActivity(this.rootActivity)) { RegisterContextActivity(this.rootActivity); using (ActivityExecutionContext executionContext = new ActivityExecutionContext(this.rootActivity, true)) { executionContext.InitializeActivity(this.rootActivity); } } } } internal void EnsureReload(Interop activity) { if (this.rootActivity == null) { this.Reload( activity.ComponentModelActivity, activity.OutputPropertyDefinitions); } } [OnSerializing] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "required signature for serialization")] void OnSerializing(StreamingContext context) { // If the Interop activity is serialized twice without a EnsureReload call in between, then the root activity is null. if (this.rootActivity == null) { // The root activity has already been serialized and saved in this.persistedActivityData so there is nothing to do. return; } using (MemoryStream stream = new MemoryStream(10240)) { stream.Position = 0; this.rootActivity.Save(stream); this.persistedActivityData = stream.GetBuffer(); Array.Resize<byte>(ref this.persistedActivityData, Convert.ToInt32(stream.Length)); } if (this.internalCurrentActivity != null) { this.internalCurrentActivityContextId = this.internalCurrentActivity.ContextId; this.internalCurrentActivityName = this.internalCurrentActivity.QualifiedName; } if (this.CurrentAtomicActivity != null) { this.atomicActivityContextId = this.CurrentAtomicActivity.ContextId; this.atomicActivityName = this.CurrentAtomicActivity.QualifiedName; } } public void Reload(Activity definitionActivity, IList<PropertyInfo> outputProperties) { MemoryStream stream = new MemoryStream(this.persistedActivityData); Activity activity = null; stream.Position = 0; using (new ActivityDefinitionResolution(definitionActivity)) { activity = Activity.Load(stream, null); } this.PrivateInitialize(activity, instanceId, outputProperties, definitionActivity); // register all dynamic activities for loading Queue<Activity> dynamicActivitiesQueue = new Queue<Activity>(); dynamicActivitiesQueue.Enqueue(activity); while (dynamicActivitiesQueue.Count > 0) { Activity dynamicActivity = dynamicActivitiesQueue.Dequeue(); ((IDependencyObjectAccessor)dynamicActivity).InitializeInstanceForRuntime(this); this.RegisterContextActivity(dynamicActivity); IList<Activity> nestedDynamicActivities = (IList<Activity>)dynamicActivity.GetValue(Activity.ActiveExecutionContextsProperty); if (nestedDynamicActivities != null) { foreach (Activity nestedDynamicActivity in nestedDynamicActivities) { dynamicActivitiesQueue.Enqueue(nestedDynamicActivity); } } } if (!string.IsNullOrEmpty(this.internalCurrentActivityName)) { this.internalCurrentActivity = this.GetContextActivityForId(this.internalCurrentActivityContextId).GetActivityByName(this.internalCurrentActivityName); } if (!string.IsNullOrEmpty(this.atomicActivityName)) { this.currentAtomicActivity = this.GetContextActivityForId(this.atomicActivityContextId).GetActivityByName(this.atomicActivityName); } this.TimerQueue.Executor = this; } void PrivateInitialize(Activity rootActivity, Guid instanceId, IList<PropertyInfo> outputProperties, Activity workflowDefinition) { this.instanceId = instanceId; this.rootActivity = rootActivity; this.contextActivityMap = new Dictionary<int, Activity>(); this.scheduler = new Scheduler(this); this.workflowQueuingService = new WorkflowQueuingService(this); this.outputProperties = outputProperties; this.resourceManager = new VolatileResourceManager(); this.rootActivity.SetValue(System.Workflow.ComponentModel.Activity.WorkflowDefinitionProperty, workflowDefinition); this.rootActivity.SetValue(WorkflowExecutor.WorkflowExecutorProperty, this); } static void SetInputParameters(Activity definition, Activity rootActivity, IDictionary<string, object> inputs, bool hasNameCollision) { if (inputs != null) { int suffixLength = Interop.InArgumentSuffix.Length; foreach (KeyValuePair<string, object> input in inputs) { PropertyInfo propertyInfo; //If there was a naming collision, we renamed the InArguments and need to strip "In" from the end of the property name if (hasNameCollision) { string truncatedName = input.Key.Substring(0, input.Key.Length - suffixLength); propertyInfo = definition.GetType().GetProperty(truncatedName); } else { propertyInfo = definition.GetType().GetProperty(input.Key); } if (propertyInfo != null && propertyInfo.CanWrite) { propertyInfo.SetValue(rootActivity, input.Value, null); } } } } ActivityExecutionStatus TranslateExecutionStatus() { if (this.abortTransaction) { WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 1127, string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropExceptionTraceMessage, this.ServiceProvider.Activity.DisplayName, this.lastExceptionThrown.ToString())); throw this.lastExceptionThrown; } if (this.rootActivity.ExecutionStatus == ActivityExecutionStatus.Closed) { //Extract Outputs from V1Activity. if (this.outputProperties.Count != 0) { this.outputs = new Dictionary<string, object>(this.outputProperties.Count); foreach (PropertyInfo property in this.outputProperties) { //We renamed the OutArgument half of the pair. Don't attempt to populate if there is no Get method. if (property.CanRead && (property.GetGetMethod() != null)) { this.outputs.Add(property.Name + Interop.OutArgumentSuffix, property.GetValue(this.rootActivity, null)); } } } if (this.outstandingException != null) { WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 1127, string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropExceptionTraceMessage, this.ServiceProvider.Activity.DisplayName, this.outstandingException.ToString())); throw this.outstandingException; } } return this.rootActivity.ExecutionStatus; } public void ActivityStatusChanged(Activity activity, bool transacted, bool committed) { if (!committed) { // Forward to 4.0 tracking mechanism, AEC.Track if (this.trackingEnabled) { this.ServiceProvider.TrackActivityStatusChange(activity, this.eventCounter++); } if (activity.ExecutionStatus == ActivityExecutionStatus.Closed) { this.ScheduleDelayedItems(activity); } } if (activity.ExecutionStatus == ActivityExecutionStatus.Closed) { if (!(activity is ICompensatableActivity) || ((activity is ICompensatableActivity) && activity.CanUninitializeNow)) { CorrelationTokenCollection.UninitializeCorrelationTokens(activity); } } } public void CheckpointInstanceState(Activity atomicActivity) { // Note that the WF4 runtime does not create checkpoints. If the transaction aborts, the workflow aborts. // We are following the WF4 behavior and not creating a checkpoint. TransactionOptions tranOpts = new TransactionOptions(); WorkflowTransactionOptions atomicTxn = TransactedContextFilter.GetTransactionOptions(atomicActivity); tranOpts.IsolationLevel = atomicTxn.IsolationLevel; if (tranOpts.IsolationLevel == IsolationLevel.Unspecified) { tranOpts.IsolationLevel = IsolationLevel.Serializable; } tranOpts.Timeout = atomicTxn.TimeoutDuration; TransactionalProperties transactionProperties = new TransactionalProperties(); atomicActivity.SetValue(WorkflowExecutor.TransactionalPropertiesProperty, transactionProperties); this.ServiceProvider.CreateTransaction(tranOpts); this.currentAtomicActivity = atomicActivity; this.scheduler.Pause(); } public void DisposeCheckpointState() { // Nothing to do. The interop activity executor doesn't create checkpoints. } public Activity GetContextActivityForId(int id) { return this.contextActivityMap[id]; } public int GetNewContextActivityId() { return this.currentContextId++; } public object GetService(Activity currentActivity, Type serviceType) { if (serviceType == typeof(IWorkflowCoreRuntime)) { return this; } if (serviceType == typeof(WorkflowQueuingService)) { this.workflowQueuingService.CallingActivity = ContextActivity(currentActivity); return this.workflowQueuingService; } if (serviceType == typeof(ITimerService)) { if (this.timerSchedulerSerivce == null) { this.timerSchedulerSerivce = new TimerSchedulerService(this); } return this.timerSchedulerSerivce; } return ((IServiceProvider)this.ServiceProvider).GetService(serviceType); } public Activity LoadContextActivity(ActivityExecutionContextInfo contextInfo, Activity outerContextActivity) { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } public void OnAfterDynamicChange(bool updateSucceeded, System.Collections.Generic.IList<WorkflowChangeAction> changes) { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } public bool OnBeforeDynamicChange(System.Collections.Generic.IList<WorkflowChangeAction> changes) { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } public void PersistInstanceState(Activity activity) { this.lastExceptionThrown = null; this.abortTransaction = false; this.ScheduleDelayedItems(activity); if (this.currentAtomicActivity == null) { if (activity == this.rootActivity && !activity.PersistOnClose) { // This method is called when the root activity completes. We shouldn't perist unless the root has [PersistOnClose] return; } this.ServiceProvider.Persist(); } else { TransactionalProperties transactionalProperties = null; transactionalProperties = (TransactionalProperties)activity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); if (this.CheckAndProcessTransactionAborted(transactionalProperties)) { return; } // Complete and dispose transaction scope transactionalProperties.TransactionScope.Complete(); transactionalProperties.TransactionScope.Dispose(); transactionalProperties.TransactionScope = null; this.ServiceProvider.CommitTransaction(); transactionalProperties.Transaction = null; this.currentAtomicActivity = null; } this.internalCurrentActivity = activity; this.scheduler.Pause(); } public void RaiseActivityExecuting(Activity activity) { // No tracking needed since no tracking was done here in V1 } public void RaiseException(Exception e, Activity activity, string responsibleActivity) { // No tracking needed using (SetCurrentActivity(activity)) { using (ActivityExecutionContext executionContext = new ActivityExecutionContext(activity, true)) { executionContext.FaultActivity(e); } } } public void RaiseHandlerInvoked() { } public void RaiseHandlerInvoking(Delegate delegateHandler) { } void ProcessTimers(object ignored) { // No-op in V2. Timers are managed by TimerExtension. } public void RegisterContextActivity(Activity activity) { int contextId = ContextId(activity); this.contextActivityMap.Add(contextId, activity); activity.OnActivityExecutionContextLoad(this); } static int ContextId(Activity activity) { return ((ActivityExecutionContextInfo)ContextActivity(activity).GetValue(Activity.ActivityExecutionContextInfoProperty)).ContextId; } static Activity ContextActivity(Activity activity) { Activity contextActivity = activity; while (contextActivity != null && contextActivity.GetValue(Activity.ActivityExecutionContextInfoProperty) == null) { contextActivity = contextActivity.Parent; } return contextActivity; } public void RequestRevertToCheckpointState(Activity currentActivity, EventHandler<EventArgs> callbackHandler, EventArgs callbackData, bool suspendOnRevert, string suspendReason) { if (this.lastExceptionThrown != null) { // Transaction scope activity is trying to abort the transaction due to an exception. // Pause the scheduler and throw the exception to the V2 runtime. // The V2 runtime will abort the workflow. this.abortTransaction = true; this.scheduler.Pause(); } } bool IWorkflowCoreRuntime.Resume() { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } public void SaveContextActivity(Activity contextActivity) { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = @"The transacted parameter represents items that should not be processed if the ambient transction rolls back. Since the Interop activity just aborts the workflow on rollback, this parameter is not applicable here.")] public void ScheduleItem(SchedulableItem item, bool isInAtomicTransaction, bool transacted, bool queueInTransaction) { if (queueInTransaction) { this.AddItemToBeScheduledLater(this.CurrentActivity, item); } else { this.scheduler.ScheduleItem(item, isInAtomicTransaction); } } void AddItemToBeScheduledLater(Activity atomicActivity, SchedulableItem item) { if (atomicActivity == null) { return; } // Activity may not be atomic and is an activity which is not // yet scheduled for execution (typically receive case) if (!atomicActivity.SupportsTransaction) { return; } TransactionalProperties transactionalProperties = (TransactionalProperties)atomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); if (transactionalProperties != null) { lock (transactionalProperties) { List<SchedulableItem> notifications = null; notifications = transactionalProperties.ItemsToBeScheduledAtCompletion; if (notifications == null) { notifications = new List<SchedulableItem>(); transactionalProperties.ItemsToBeScheduledAtCompletion = notifications; } notifications.Add(item); } } } void ScheduleDelayedItems(Activity atomicActivity) { List<SchedulableItem> items = null; TransactionalProperties transactionalProperties = (TransactionalProperties)atomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); if (transactionalProperties == null) { return; } lock (transactionalProperties) { items = transactionalProperties.ItemsToBeScheduledAtCompletion; if (items == null) { return; } foreach (SchedulableItem item in items) { this.scheduler.ScheduleItem(item, false); } items.Clear(); transactionalProperties.ItemsToBeScheduledAtCompletion = null; } } public IDisposable SetCurrentActivity(Activity activity) { Activity oldCurrentActivity = this.CurrentActivity; this.CurrentActivity = activity; return new ResetCurrentActivity(this, oldCurrentActivity); } public Guid StartWorkflow(Type workflowType, Dictionary<string, object> namedArgumentValues) { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } public bool SuspendInstance(string suspendDescription) { throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.InteropNonSupportedBehavior, this.ServiceProvider.Activity.DisplayName)); } public void TerminateInstance(Exception e) { this.outstandingException = e; } public void Track(string key, object data) { // Forward to 4.0 tracking mechanism, AEC.Track if (this.trackingEnabled) { this.ServiceProvider.TrackData(this.CurrentActivity, this.eventCounter++, key, data); } } public void UnregisterContextActivity(Activity activity) { int contextId = ContextId(activity); this.contextActivityMap.Remove(contextId); activity.OnActivityExecutionContextUnload(this); } object IServiceProvider.GetService(Type serviceType) { return this.GetService(this.rootActivity, serviceType); } class ActivityDefinitionResolution : IDisposable { [ThreadStatic] static Activity definitionActivity; static ActivityResolveEventHandler activityResolveEventHandler = new ActivityResolveEventHandler(OnActivityResolve); [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "This is a bogus validation; registration to event cannot be done using field initializers")] static ActivityDefinitionResolution() { Activity.ActivityResolve += ActivityDefinitionResolution.activityResolveEventHandler; } public ActivityDefinitionResolution(Activity definitionActivity) { ActivityDefinitionResolution.definitionActivity = definitionActivity; } static Activity OnActivityResolve(object sender, ActivityResolveEventArgs e) { return ActivityDefinitionResolution.definitionActivity; } void IDisposable.Dispose() { ActivityDefinitionResolution.definitionActivity = null; } } class ResetCurrentActivity : IDisposable { InteropExecutor activityExecutor; Activity oldCurrentActivity = null; internal ResetCurrentActivity(InteropExecutor activityExecutor, Activity oldCurrentActivity) { this.activityExecutor = activityExecutor; this.oldCurrentActivity = oldCurrentActivity; } void IDisposable.Dispose() { this.activityExecutor.CurrentActivity = oldCurrentActivity; } } class Scheduler { // State to be persisted for the scheduler internal static DependencyProperty SchedulerQueueProperty = DependencyProperty.RegisterAttached("SchedulerQueue", typeof(Queue<SchedulableItem>), typeof(Scheduler)); internal static DependencyProperty AtomicActivityQueueProperty = DependencyProperty.RegisterAttached("AtomicActivityQueue", typeof(Queue<SchedulableItem>), typeof(Scheduler)); // The atomic activity queue contains items related to the currently executing atomic activity. // While the atomic activity is executing, execution of the items that are not in the atomic context is deferred until the atomic activity completes. // We need two queues to separate the items associated with the atomic activity from the other items. Queue<SchedulableItem> schedulerQueue; Queue<SchedulableItem> atomicActivityQueue; InteropExecutor owner; bool pause; public Scheduler(InteropExecutor owner) { this.owner = owner; this.schedulerQueue = (Queue<SchedulableItem>)owner.RootActivity.GetValue(Scheduler.SchedulerQueueProperty); if (this.schedulerQueue == null) { this.schedulerQueue = new Queue<SchedulableItem>(); owner.RootActivity.SetValue(Scheduler.SchedulerQueueProperty, this.schedulerQueue); } this.atomicActivityQueue = (Queue<SchedulableItem>)owner.RootActivity.GetValue(Scheduler.AtomicActivityQueueProperty); if (this.atomicActivityQueue == null) { this.atomicActivityQueue = new Queue<SchedulableItem>(); owner.RootActivity.SetValue(Scheduler.AtomicActivityQueueProperty, this.atomicActivityQueue); } } public void ScheduleItem(SchedulableItem item, bool isInAtomicTransaction) { Queue<SchedulableItem> queue = isInAtomicTransaction ? this.atomicActivityQueue : this.schedulerQueue; queue.Enqueue(item); } public void Pause() { this.pause = true; } public void Run() { this.pause = false; while (!this.pause) { SchedulableItem item; // atomicActivityQueue has higher priority if (this.atomicActivityQueue.Count > 0) { item = this.atomicActivityQueue.Dequeue(); } // The execution of the items in the scheduler queue is deferred until the atomic activity completes. else if (owner.CurrentAtomicActivity == null && this.schedulerQueue.Count > 0) { item = schedulerQueue.Dequeue(); } else { break; } Activity itemActivity = owner.GetContextActivityForId(item.ContextId).GetActivityByName(item.ActivityId); Activity atomicActivity; TransactionalProperties transactionalProperties = null; if (owner.IsActivityInAtomicContext(itemActivity, out atomicActivity)) { transactionalProperties = (TransactionalProperties)atomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty); // If we've aborted for any reason stop now! if (owner.CheckAndProcessTransactionAborted(transactionalProperties)) { return; } } try { item.Run(owner); } catch (Exception e) { if (WorkflowExecutor.IsIrrecoverableException(e)) { throw; } if (transactionalProperties != null) { transactionalProperties.TransactionState = TransactionProcessState.AbortProcessed; owner.lastExceptionThrown = e; } owner.RaiseException(e, itemActivity, null); } } } } class TimerSchedulerService : ITimerService { IWorkflowCoreRuntime executor; public TimerSchedulerService(IWorkflowCoreRuntime executor) : base() { this.executor = executor; } public void ScheduleTimer(WaitCallback callback, Guid workflowInstanceId, DateTime whenUtc, Guid timerId) { if (timerId == Guid.Empty) { throw new ArgumentException(ExecutionStringManager.InteropTimerIdCantBeEmpty, "timerId"); } TimeSpan timerDuration = whenUtc - DateTime.UtcNow; if (timerDuration < TimeSpan.Zero) { timerDuration = TimeSpan.Zero; } GetTimerExtension().RegisterTimer(timerDuration, new Bookmark(timerId.ToString())); } public void CancelTimer(Guid timerId) { if (timerId == Guid.Empty) { throw new ArgumentException(ExecutionStringManager.InteropTimerIdCantBeEmpty, "timerId"); } GetTimerExtension().CancelTimer(new Bookmark(timerId.ToString())); } TimerExtension GetTimerExtension() { TimerExtension timerExtension = this.executor.GetService(typeof(TimerExtension)) as TimerExtension; if (timerExtension == null) { throw new InvalidOperationException(ExecutionStringManager.InteropCantFindTimerExtension); } return timerExtension; } } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security.Permissions; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.Project { internal enum tagDVASPECT { DVASPECT_CONTENT = 1, DVASPECT_THUMBNAIL = 2, DVASPECT_ICON = 4, DVASPECT_DOCPRINT = 8 } internal enum tagTYMED { TYMED_HGLOBAL = 1, TYMED_FILE = 2, TYMED_ISTREAM = 4, TYMED_ISTORAGE = 8, TYMED_GDI = 16, TYMED_MFPICT = 32, TYMED_ENHMF = 64, TYMED_NULL = 0 } internal sealed class DataCacheEntry : IDisposable { #region fields /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); private FORMATETC format; private long data; private DATADIR dataDir; private bool isDisposed; #endregion #region properties internal FORMATETC Format { get { return this.format; } } internal long Data { get { return this.data; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal DATADIR DataDir { get { return this.dataDir; } } #endregion /// <summary> /// The IntPtr is data allocated that should be removed. It is allocated by the ProcessSelectionData method. /// </summary> internal DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir) { this.format = fmt; this.data = (long)data; this.dataDir = dir; } #region Dispose ~DataCacheEntry() { Dispose(false); } /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> private void Dispose(bool disposing) { // Everybody can go here. if(!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock(Mutex) { if(disposing && this.data != 0) { Marshal.FreeHGlobal((IntPtr)this.data); this.data = 0; } this.isDisposed = true; } } } #endregion } /// <summary> /// Unfortunately System.Windows.Forms.IDataObject and /// Microsoft.VisualStudio.OLE.Interop.IDataObject are different... /// </summary> internal sealed class DataObject : IDataObject { #region fields internal const int DATA_S_SAMEFORMATETC = 0x00040130; EventSinkCollection map; ArrayList entries; #endregion internal DataObject() { this.map = new EventSinkCollection(); this.entries = new ArrayList(); } internal void SetData(FORMATETC format, IntPtr data) { this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET)); } #region IDataObject methods int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie) { if (e == null) { throw new ArgumentNullException("e"); } STATDATA sdata = new STATDATA(); sdata.ADVF = adv; sdata.FORMATETC = e[0]; sdata.pAdvSink = sink; cookie = this.map.Add(sdata); sdata.dwConnection = cookie; return 0; } void IDataObject.DUnadvise(uint cookie) { this.map.RemoveAt(cookie); } int IDataObject.EnumDAdvise(out IEnumSTATDATA e) { e = new EnumSTATDATA((IEnumerable)this.map); return 0; //?? } int IDataObject.EnumFormatEtc(uint direction, out IEnumFORMATETC penum) { penum = new EnumFORMATETC((DATADIR)direction, (IEnumerable)this.entries); return 0; } int IDataObject.GetCanonicalFormatEtc(FORMATETC[] format, FORMATETC[] fmt) { throw new System.Runtime.InteropServices.COMException("", DATA_S_SAMEFORMATETC); } void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m) { STGMEDIUM retMedium = new STGMEDIUM(); if(fmt == null || fmt.Length < 1) return; foreach(DataCacheEntry e in this.entries) { if(e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) { retMedium.tymed = e.Format.tymed; // Caller must delete the memory. retMedium.unionmember = DragDropHelper.CopyHGlobal(new IntPtr(e.Data)); break; } } if(m != null && m.Length > 0) m[0] = retMedium; } void IDataObject.GetDataHere(FORMATETC[] fmt, STGMEDIUM[] m) { } int IDataObject.QueryGetData(FORMATETC[] fmt) { if(fmt == null || fmt.Length < 1) return VSConstants.S_FALSE; foreach(DataCacheEntry e in this.entries) { if(e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/) return VSConstants.S_OK; } return VSConstants.S_FALSE; } void IDataObject.SetData(FORMATETC[] fmt, STGMEDIUM[] m, int fRelease) { } #endregion } [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] internal static class DragDropHelper { #pragma warning disable 414 internal static readonly ushort CF_VSREFPROJECTITEMS; internal static readonly ushort CF_VSSTGPROJECTITEMS; internal static readonly ushort CF_VSPROJECTCLIPDESCRIPTOR; #pragma warning restore 414 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static DragDropHelper() { CF_VSREFPROJECTITEMS = UnsafeNativeMethods.RegisterClipboardFormat("CF_VSREFPROJECTITEMS"); CF_VSSTGPROJECTITEMS = UnsafeNativeMethods.RegisterClipboardFormat("CF_VSSTGPROJECTITEMS"); CF_VSPROJECTCLIPDESCRIPTOR = UnsafeNativeMethods.RegisterClipboardFormat("CF_PROJECTCLIPBOARDDESCRIPTOR"); } public static FORMATETC CreateFormatEtc(ushort iFormat) { FORMATETC fmt = new FORMATETC(); fmt.cfFormat = iFormat; fmt.ptd = IntPtr.Zero; fmt.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = (uint)TYMED.TYMED_HGLOBAL; return fmt; } public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) { int returnValue = VSConstants.E_FAIL; FORMATETC[] af = new FORMATETC[1]; af[0] = fmtetc; try { int result = ErrorHandler.ThrowOnFailure(pDataObject.QueryGetData(af)); if(result == VSConstants.S_OK) { fmtetc = af[0]; returnValue = VSConstants.S_OK; } } catch(COMException e) { Trace.WriteLine("COMException : " + e.Message); returnValue = e.ErrorCode; } return returnValue; } public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc) { FORMATETC[] af = new FORMATETC[1]; af[0] = fmtetc; STGMEDIUM[] sm = new STGMEDIUM[1]; pDataObject.GetData(af, sm); fmtetc = af[0]; return sm[0]; } /// <summary> /// Retrives data from a VS format. /// </summary> public static List<string> GetDroppedFiles(ushort format, Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject, out DropDataType ddt) { ddt = DropDataType.None; List<string> droppedFiles = new List<string>(); // try HDROP FORMATETC fmtetc = CreateFormatEtc(format); if(QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) { STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc); if(stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) { // We are releasing the cloned hglobal here. IntPtr dropInfoHandle = stgmedium.unionmember; if(dropInfoHandle != IntPtr.Zero) { ddt = DropDataType.Shell; try { uint numFiles = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, 0xFFFFFFFF, null, 0); // We are a directory based project thus a projref string is placed on the clipboard. // We assign the maximum length of a projref string. // The format of a projref is : <Proj Guid>|<project rel path>|<file path> uint lenght = (uint)Guid.Empty.ToString().Length + 2 * NativeMethods.MAX_PATH + 2; char[] moniker = new char[lenght + 1]; for(uint fileIndex = 0; fileIndex < numFiles; fileIndex++) { uint queryFileLength = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, fileIndex, moniker, lenght); string filename = new String(moniker, 0, (int)queryFileLength); droppedFiles.Add(filename); } } finally { Marshal.FreeHGlobal(dropInfoHandle); } } } } return droppedFiles; } public static string GetSourceProjectPath(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject) { string projectPath = null; FORMATETC fmtetc = CreateFormatEtc(CF_VSPROJECTCLIPDESCRIPTOR); if(QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK) { STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc); if(stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL) { // We are releasing the cloned hglobal here. IntPtr dropInfoHandle = stgmedium.unionmember; if(dropInfoHandle != IntPtr.Zero) { try { string path = GetData(dropInfoHandle); // Clone the path that we can release our memory. if(!String.IsNullOrEmpty(path)) { projectPath = String.Copy(path); } } finally { Marshal.FreeHGlobal(dropInfoHandle); } } } } return projectPath; } /// <summary> /// Returns the data packed after the DROPFILES structure. /// </summary> /// <param name="dropHandle"></param> /// <returns></returns> internal static string GetData(IntPtr dropHandle) { IntPtr data = UnsafeNativeMethods.GlobalLock(dropHandle); try { _DROPFILES df = (_DROPFILES)Marshal.PtrToStructure(data, typeof(_DROPFILES)); if(df.fWide != 0) { IntPtr pdata = new IntPtr((long)data + df.pFiles); return Marshal.PtrToStringUni(pdata); } } finally { if(data != null) { UnsafeNativeMethods.GlobalUnLock(data); } } return null; } internal static IntPtr CopyHGlobal(IntPtr data) { IntPtr src = UnsafeNativeMethods.GlobalLock(data); int size = UnsafeNativeMethods.GlobalSize(data); IntPtr ptr = Marshal.AllocHGlobal(size); IntPtr buffer = UnsafeNativeMethods.GlobalLock(ptr); try { for(int i = 0; i < size; i++) { byte val = Marshal.ReadByte(new IntPtr((long)src + i)); Marshal.WriteByte(new IntPtr((long)buffer + i), val); } } finally { if(buffer != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnLock(buffer); } if(src != IntPtr.Zero) { UnsafeNativeMethods.GlobalUnLock(src); } } return ptr; } internal static void CopyStringToHGlobal(string s, IntPtr data, int bufferSize) { Int16 nullTerminator = 0; int dwSize = Marshal.SizeOf(nullTerminator); if((s.Length + 1) * Marshal.SizeOf(s[0]) > bufferSize) throw new System.IO.InternalBufferOverflowException(); // IntPtr memory already locked... for(int i = 0, len = s.Length; i < len; i++) { Marshal.WriteInt16(data, i * dwSize, s[i]); } // NULL terminate it Marshal.WriteInt16(new IntPtr((long)data + (s.Length * dwSize)), nullTerminator); } } // end of dragdrophelper internal class EnumSTATDATA : IEnumSTATDATA { IEnumerable i; IEnumerator e; public EnumSTATDATA(IEnumerable i) { this.i = i; this.e = i.GetEnumerator(); } void IEnumSTATDATA.Clone(out IEnumSTATDATA clone) { clone = new EnumSTATDATA(i); } int IEnumSTATDATA.Next(uint celt, STATDATA[] d, out uint fetched) { uint rc = 0; //uint size = (fetched != null) ? fetched[0] : 0; for(uint i = 0; i < celt; i++) { if(e.MoveNext()) { STATDATA sdata = (STATDATA)e.Current; rc++; if(d != null && d.Length > i) { d[i] = sdata; } } } fetched = rc; return 0; } int IEnumSTATDATA.Reset() { e.Reset(); return 0; } int IEnumSTATDATA.Skip(uint celt) { for(uint i = 0; i < celt; i++) { e.MoveNext(); } return 0; } } internal class EnumFORMATETC : IEnumFORMATETC { IEnumerable cache; // of DataCacheEntrys. DATADIR dir; IEnumerator e; public EnumFORMATETC(DATADIR dir, IEnumerable cache) { this.cache = cache; this.dir = dir; e = cache.GetEnumerator(); } void IEnumFORMATETC.Clone(out IEnumFORMATETC clone) { clone = new EnumFORMATETC(dir, cache); } int IEnumFORMATETC.Next(uint celt, FORMATETC[] d, uint[] fetched) { uint rc = 0; //uint size = (fetched != null) ? fetched[0] : 0; for(uint i = 0; i < celt; i++) { if(e.MoveNext()) { DataCacheEntry entry = (DataCacheEntry)e.Current; rc++; if(d != null && d.Length > i) { d[i] = entry.Format; } } else { return VSConstants.S_FALSE; } } if(fetched != null && fetched.Length > 0) fetched[0] = rc; return VSConstants.S_OK; } int IEnumFORMATETC.Reset() { e.Reset(); return 0; } int IEnumFORMATETC.Skip(uint celt) { for(uint i = 0; i < celt; i++) { e.MoveNext(); } return 0; } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using Fluent.Extensibility; using Fluent.Internal; /// <summary> /// Represents adorner for KeyTips. /// KeyTipAdorners is chained to produce one from another. /// Detaching root adorner couses detaching all adorners in the chain /// </summary> public class KeyTipAdorner : Adorner { #region Events /// <summary> /// This event is occured when adorner is /// detached and is not able to be attached again /// </summary> public event EventHandler<KeyTipPressedResult> Terminated; #endregion #region Fields // KeyTips that have been // found on this element private readonly List<KeyTipInformation> keyTipInformations = new List<KeyTipInformation>(); private readonly FrameworkElement oneOfAssociatedElements; // Parent adorner private readonly KeyTipAdorner parentAdorner; private KeyTipAdorner childAdorner; private readonly FrameworkElement keyTipElementContainer; // Is this adorner attached to the adorned element? private bool attached; private bool isAttaching; // Designate that this adorner is terminated private bool terminated; private AdornerLayer adornerLayer; #endregion #region Properties /// <summary> /// Determines whether at least one on the adorners in the chain is alive /// </summary> public bool IsAdornerChainAlive { get { return this.isAttaching || this.attached || (this.childAdorner != null && this.childAdorner.IsAdornerChainAlive); } } /// <summary> /// Returns whether any key tips are visibile. /// </summary> public bool AreAnyKeyTipsVisible { get { return this.keyTipInformations.Any(x => x.IsVisible) || (this.childAdorner != null && this.childAdorner.AreAnyKeyTipsVisible); } } /// <summary> /// Gets the currently active <see cref="KeyTipAdorner"/> by following eventually present child adorners. /// </summary> public KeyTipAdorner ActiveKeyTipAdorner { get { return this.childAdorner != null && this.childAdorner.IsAdornerChainAlive ? this.childAdorner.ActiveKeyTipAdorner : this; } } /// <summary> /// Gets a copied list of the currently available <see cref="KeyTipInformation"/>. /// </summary> public IReadOnlyList<KeyTipInformation> KeyTipInformations { get { return this.keyTipInformations.ToList(); } } #endregion #region Intialization /// <summary> /// Construcotor /// </summary> /// <param name="adornedElement">Element to adorn.</param> /// <param name="parentAdorner">Parent adorner or null.</param> /// <param name="keyTipElementContainer">The element which is container for elements.</param> public KeyTipAdorner(FrameworkElement adornedElement, FrameworkElement keyTipElementContainer, KeyTipAdorner parentAdorner) : base(adornedElement) { this.parentAdorner = parentAdorner; this.keyTipElementContainer = keyTipElementContainer; // Try to find supported elements this.FindKeyTips(this.keyTipElementContainer, false); this.oneOfAssociatedElements = this.keyTipInformations.Count != 0 ? this.keyTipInformations[0].AssociatedElement : adornedElement // Maybe here is bug, coz we need keytipped item here... ; } // Find key tips on the given element private void FindKeyTips(FrameworkElement container, bool hide) { var children = GetVisibleChildren(container); foreach (var child in children) { var groupBox = child as RibbonGroupBox; var keys = KeyTip.GetKeys(child); if (keys != null || child is IKeyTipInformationProvider) { if (groupBox is null) { this.GenerateAndAddRegularKeyTipInformations(keys, child, hide); // Do not search deeper in the tree continue; } this.GenerateAndAddGroupBoxKeyTipInformation(hide, keys, child, groupBox); } var innerHide = hide || groupBox?.State == RibbonGroupBoxState.Collapsed; this.FindKeyTips(child, innerHide); } } private void GenerateAndAddGroupBoxKeyTipInformation(bool hide, string keys, FrameworkElement child, RibbonGroupBox groupBox) { var keyTipInformation = new KeyTipInformation(keys, child, hide || groupBox.State != RibbonGroupBoxState.Collapsed); // Add to list & visual children collections this.AddKeyTipInformationElement(keyTipInformation); this.LogDebug("Found KeyTipped RibbonGroupBox \"{0}\" with keys \"{1}\".", keyTipInformation.AssociatedElement, keyTipInformation.Keys); } private void GenerateAndAddRegularKeyTipInformations(string keys, FrameworkElement child, bool hide) { IEnumerable<KeyTipInformation> informations; if (child is IKeyTipInformationProvider keyTipInformationProvider) { informations = keyTipInformationProvider.GetKeyTipInformations(hide); } else { informations = new[] { new KeyTipInformation(keys, child, hide) }; } if (informations != null) { foreach (var keyTipInformation in informations) { // Add to list & visual children collections this.AddKeyTipInformationElement(keyTipInformation); this.LogDebug("Found KeyTipped element \"{0}\" with keys \"{1}\".", keyTipInformation.AssociatedElement, keyTipInformation.Keys); } } } private void AddKeyTipInformationElement(KeyTipInformation keyTipInformation) { this.keyTipInformations.Add(keyTipInformation); this.AddVisualChild(keyTipInformation.KeyTip); } private static IList<FrameworkElement> GetVisibleChildren(FrameworkElement element) { var logicalChildren = LogicalTreeHelper.GetChildren(element) .OfType<FrameworkElement>(); var children = logicalChildren; // Always using the visual tree is very expensive, so we only search through it when we got specific control types. // Using the visual tree here, in addition to the logical, partially fixes #244. if (element is ContentPresenter || element is ContentControl) { children = children .Concat(UIHelper.GetVisualChildren(element)) .OfType<FrameworkElement>(); } else if (element is ItemsControl itemsControl) { children = children.Concat(UIHelper.GetAllItemContainers<FrameworkElement>(itemsControl)); } // Don't show key tips for the selected content too early if (element is RibbonTabControl ribbonTabControl && ribbonTabControl.SelectedContent is FrameworkElement selectedContent) { children = children.Except(new[] { selectedContent }); } return children .Where(x => x.Visibility == Visibility.Visible) .Distinct() .ToList(); } #endregion #region Attach & Detach /// <summary> /// Attaches this adorner to the adorned element /// </summary> public void Attach() { if (this.attached) { return; } this.isAttaching = true; this.oneOfAssociatedElements.UpdateLayout(); this.LogDebug("Attach begin {0}", this.Visibility); if (this.oneOfAssociatedElements.IsLoaded == false) { // Delay attaching this.LogDebug("Delaying attach"); this.oneOfAssociatedElements.Loaded += this.OnDelayAttach; return; } this.adornerLayer = GetAdornerLayer(this.oneOfAssociatedElements); if (this.adornerLayer is null) { this.LogDebug("No adorner layer found"); this.isAttaching = false; return; } this.FilterKeyTips(string.Empty); // Show this adorner this.adornerLayer.Add(this); this.isAttaching = false; this.attached = true; this.LogDebug("Attach end"); } private void OnDelayAttach(object sender, EventArgs args) { this.LogDebug("Delay attach (control loaded)"); this.oneOfAssociatedElements.Loaded -= this.OnDelayAttach; this.Attach(); } /// <summary> /// Detaches this adorner from the adorned element /// </summary> public void Detach() { this.childAdorner?.Detach(); if (!this.attached) { return; } this.LogDebug("Detach Begin"); // Maybe adorner awaiting attaching, cancel it this.oneOfAssociatedElements.Loaded -= this.OnDelayAttach; // Show this adorner this.adornerLayer.Remove(this); this.attached = false; this.LogDebug("Detach End"); } #endregion #region Termination /// <summary> /// Terminate whole key tip's adorner chain /// </summary> public void Terminate(KeyTipPressedResult keyTipPressedResult) { if (this.terminated) { return; } this.terminated = true; this.Detach(); this.parentAdorner?.Terminate(keyTipPressedResult); this.childAdorner?.Terminate(keyTipPressedResult); this.Terminated?.Invoke(this, keyTipPressedResult); this.LogDebug("Termination"); } #endregion #region Static Methods private static AdornerLayer GetAdornerLayer(UIElement element) { var current = element; while (true) { if (current is null) { return null; } var parent = (UIElement)VisualTreeHelper.GetParent(current) ?? (UIElement)LogicalTreeHelper.GetParent(current); current = parent; if (current is AdornerDecorator) { return AdornerLayer.GetAdornerLayer((UIElement)VisualTreeHelper.GetChild(current, 0)); } } } private static UIElement GetTopLevelElement(UIElement element) { while (true) { var current = VisualTreeHelper.GetParent(element) as UIElement; if (current is null) { return element; } element = current; } } #endregion #region Methods /// <summary> /// Back to the previous adorner. /// </summary> public void Back() { this.LogTrace("Invoking back."); var control = this.keyTipElementContainer as IKeyTipedControl; control?.OnKeyTipBack(); if (this.parentAdorner != null) { this.LogDebug("Back"); this.Detach(); this.parentAdorner.Attach(); } else { this.Terminate(KeyTipPressedResult.Empty); } } /// <summary> /// Forwards to the elements with the given keys /// </summary> /// <param name="keys">Keys</param> /// <param name="click">If true the element will be clicked</param> /// <returns>If the element will be found the function will return true</returns> public bool Forward(string keys, bool click) { this.LogTrace("Trying to forward keys \"{0}\"...", keys); var keyTipInformation = this.TryGetKeyTipInformation(keys); if (keyTipInformation is null) { this.LogTrace("Found no element for keys \"{0}\".", keys); return false; } this.Forward(keys, keyTipInformation.AssociatedElement, click); return true; } // Forward to the next element private void Forward(string keys, FrameworkElement element, bool click) { this.LogTrace("Forwarding keys \"{0}\" to element \"{1}\".", keys, GetControlLogText(element)); this.Detach(); var keyTipPressedResult = KeyTipPressedResult.Empty; if (click) { this.LogTrace("Invoking click."); var control = element as IKeyTipedControl; keyTipPressedResult = control?.OnKeyTipPressed() ?? KeyTipPressedResult.Empty; } var children = GetVisibleChildren(element); if (children.Count == 0) { this.Terminate(keyTipPressedResult); return; } // Panels aren't good elements to adorn. For example, trying to display KeyTips on MenuItems in SplitButton fails if using a panel. var validChild = children.FirstOrDefault(x => x is Panel == false) ?? children[0]; this.childAdorner = ReferenceEquals(GetTopLevelElement(validChild), GetTopLevelElement(element)) == false ? new KeyTipAdorner(validChild, element, this) : new KeyTipAdorner(element, element, this); // Stop if no further KeyTips can be displayed. if (this.childAdorner.keyTipInformations.Any() == false) { this.Terminate(keyTipPressedResult); return; } this.childAdorner.Attach(); } /// <summary> /// Gets <see cref="KeyTipInformation"/> by keys. /// </summary> /// <param name="keys">The keys to look for.</param> /// <returns>The <see cref="KeyTipInformation"/> associated with <paramref name="keys"/>.</returns> private KeyTipInformation TryGetKeyTipInformation(string keys) { return this.keyTipInformations.FirstOrDefault(x => x.IsEnabled && x.Visibility == Visibility.Visible && keys.Equals(x.Keys, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Determines if an of the keytips contained in this adorner start with <paramref name="keys"/> /// </summary> /// <returns><c>true</c> if any keytip start with <paramref name="keys"/>. Otherwise <c>false</c>.</returns> public bool ContainsKeyTipStartingWith(string keys) { foreach (var keyTipInformation in this.keyTipInformations.Where(x => x.IsEnabled)) { var content = keyTipInformation.Keys; if (content.StartsWith(keys, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } // Hide / unhide keytips relative matching to entered keys internal void FilterKeyTips(string keys) { this.LogDebug("FilterKeyTips with \"{0}\"", keys); // Reset visibility if filter is empty if (string.IsNullOrEmpty(keys)) { foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.Visibility = keyTipInformation.DefaultVisibility; } } // Backup current visibility of key tips foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.BackupVisibility = keyTipInformation.Visibility; } // Hide / unhide keytips relative matching to entered keys foreach (var keyTipInformation in this.keyTipInformations) { var content = keyTipInformation.Keys; if (string.IsNullOrEmpty(keys)) { keyTipInformation.Visibility = keyTipInformation.BackupVisibility; } else { keyTipInformation.Visibility = content.StartsWith(keys, StringComparison.OrdinalIgnoreCase) ? keyTipInformation.BackupVisibility : Visibility.Collapsed; } } this.LogDebug("Filtered key tips: {0}", this.keyTipInformations.Count(x => x.Visibility == Visibility.Visible)); } #endregion #region Layout & Visual Children /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) { this.LogDebug("ArrangeOverride"); foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.KeyTip.Arrange(new Rect(keyTipInformation.Position, keyTipInformation.KeyTip.DesiredSize)); } return finalSize; } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { this.LogDebug("MeasureOverride"); foreach (var keyTipInformation in this.keyTipInformations) { keyTipInformation.KeyTip.Measure(SizeConstants.Infinite); } this.UpdateKeyTipPositions(); var result = new Size(0, 0); foreach (var keyTipInformation in this.keyTipInformations) { var cornerX = keyTipInformation.KeyTip.DesiredSize.Width + keyTipInformation.Position.X; var cornerY = keyTipInformation.KeyTip.DesiredSize.Height + keyTipInformation.Position.Y; if (cornerX > result.Width) { result.Width = cornerX; } if (cornerY > result.Height) { result.Height = cornerY; } } return result; } private void UpdateKeyTipPositions() { this.LogDebug("UpdateKeyTipPositions"); if (this.keyTipInformations.Count == 0) { return; } double[] rows = null; var groupBox = this.oneOfAssociatedElements as RibbonGroupBox ?? UIHelper.GetParent<RibbonGroupBox>(this.oneOfAssociatedElements); var panel = groupBox?.GetPanel(); if (panel != null) { var height = groupBox.GetLayoutRoot().DesiredSize.Height; rows = new[] { groupBox.GetLayoutRoot().TranslatePoint(new Point(0, 0), this.AdornedElement).Y, groupBox.GetLayoutRoot().TranslatePoint(new Point(0, panel.DesiredSize.Height / 2.0), this.AdornedElement).Y, groupBox.GetLayoutRoot().TranslatePoint(new Point(0, panel.DesiredSize.Height), this.AdornedElement).Y, groupBox.GetLayoutRoot().TranslatePoint(new Point(0, height + 1), this.AdornedElement).Y }; } foreach (var keyTipInformation in this.keyTipInformations) { // Skip invisible keytips if (keyTipInformation.Visibility != Visibility.Visible) { continue; } // Update KeyTip Visibility var visualTargetIsVisible = keyTipInformation.VisualTarget.IsVisible; var visualTargetInVisualTree = VisualTreeHelper.GetParent(keyTipInformation.VisualTarget) != null; keyTipInformation.Visibility = visualTargetIsVisible && visualTargetInVisualTree ? Visibility.Visible : Visibility.Collapsed; keyTipInformation.KeyTip.Margin = KeyTip.GetMargin(keyTipInformation.AssociatedElement); if (IsWithinQuickAccessToolbar(keyTipInformation.AssociatedElement)) { var x = (keyTipInformation.VisualTarget.DesiredSize.Width / 2.0) - (keyTipInformation.KeyTip.DesiredSize.Width / 2.0); var y = keyTipInformation.VisualTarget.DesiredSize.Height - (keyTipInformation.KeyTip.DesiredSize.Height / 2.0); if (KeyTip.GetAutoPlacement(keyTipInformation.AssociatedElement) == false) { switch (KeyTip.GetHorizontalAlignment(keyTipInformation.AssociatedElement)) { case HorizontalAlignment.Left: x = 0; break; case HorizontalAlignment.Right: x = keyTipInformation.VisualTarget.DesiredSize.Width - keyTipInformation.KeyTip.DesiredSize.Width; break; } } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point(x, y), this.AdornedElement); } else if (keyTipInformation.AssociatedElement.Name == "PART_DialogLauncherButton") { // Dialog Launcher Button Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; if (rows is null) { continue; } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point( (elementSize.Width / 2.0) - (keyTipSize.Width / 2.0), 0), this.AdornedElement); keyTipInformation.Position = new Point(keyTipInformation.Position.X, rows[3]); } else if (KeyTip.GetAutoPlacement(keyTipInformation.AssociatedElement) == false) { var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; double x = 0, y = 0; switch (KeyTip.GetHorizontalAlignment(keyTipInformation.AssociatedElement)) { case HorizontalAlignment.Left: break; case HorizontalAlignment.Right: x = elementSize.Width - keyTipSize.Width; break; case HorizontalAlignment.Center: case HorizontalAlignment.Stretch: x = (elementSize.Width / 2.0) - (keyTipSize.Width / 2.0); break; } switch (KeyTip.GetVerticalAlignment(keyTipInformation.AssociatedElement)) { case VerticalAlignment.Top: break; case VerticalAlignment.Bottom: y = elementSize.Height - keyTipSize.Height; break; case VerticalAlignment.Center: case VerticalAlignment.Stretch: y = (elementSize.Height / 2.0) - (keyTipSize.Height / 2.0); break; } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point(x, y), this.AdornedElement); } else if (keyTipInformation.AssociatedElement is InRibbonGallery gallery && gallery.IsCollapsed == false) { // InRibbonGallery Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; if (rows is null) { continue; } keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point( elementSize.Width - (keyTipSize.Width / 2.0), 0), this.AdornedElement); keyTipInformation.Position = new Point(keyTipInformation.Position.X, rows[2] - (keyTipSize.Height / 2)); } else if (keyTipInformation.AssociatedElement is RibbonTabItem || keyTipInformation.AssociatedElement is Backstage) { // Ribbon Tab Item Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.RenderSize; keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint(new Point( (elementSize.Width / 2.0) - (keyTipSize.Width / 2.0), elementSize.Height - (keyTipSize.Height / 2.0)), this.AdornedElement); } else if (keyTipInformation.AssociatedElement is MenuItem) { // MenuItem Exclusive Placement var elementSize = keyTipInformation.VisualTarget.DesiredSize; keyTipInformation.Position = keyTipInformation.VisualTarget.TranslatePoint( new Point( (elementSize.Height / 3.0) + 2, (elementSize.Height / 4.0) + 2), this.AdornedElement); } else if (keyTipInformation.AssociatedElement.Parent is BackstageTabControl) { // Backstage Items Exclusive Placement var keyTipSize = keyTipInformation.KeyTip.DesiredSize; var elementSize = keyTipInformation.VisualTarget.DesiredSize; var parent = (UIElement)keyTipInformation.VisualTarget.Parent; var positionInParent = keyTipInformation.VisualTarget.TranslatePoint(default, parent); keyTipInformation.Position = parent.TranslatePoint( new Point( 5, positionInParent.Y + ((elementSize.Height / 2.0) - keyTipSize.Height)), this.AdornedElement); } else { if (RibbonProperties.GetSize(keyTipInformation.AssociatedElement) != RibbonControlSize.Large || IsTextBoxShapedControl(keyTipInformation.AssociatedElement)) { var x = keyTipInformation.KeyTip.DesiredSize.Width / 2.0; var y = keyTipInformation.KeyTip.DesiredSize.Height / 2.0; var point = new Point(x, y); var translatedPoint = keyTipInformation.VisualTarget.TranslatePoint(point, this.AdornedElement); // Snapping to rows if it present SnapToRowsIfPresent(rows, keyTipInformation, translatedPoint); keyTipInformation.Position = translatedPoint; } else { var x = (keyTipInformation.VisualTarget.DesiredSize.Width / 2.0) - (keyTipInformation.KeyTip.DesiredSize.Width / 2.0); var y = keyTipInformation.VisualTarget.DesiredSize.Height - 8; var point = new Point(x, y); var translatedPoint = keyTipInformation.VisualTarget.TranslatePoint(point, this.AdornedElement); // Snapping to rows if it present SnapToRowsIfPresent(rows, keyTipInformation, translatedPoint); keyTipInformation.Position = translatedPoint; } } } } private static bool IsTextBoxShapedControl(FrameworkElement element) { return element is Spinner || element is System.Windows.Controls.ComboBox || element is System.Windows.Controls.TextBox || element is System.Windows.Controls.CheckBox; } // Determines whether the element is children to RibbonToolBar private static bool IsWithinRibbonToolbarInTwoLine(DependencyObject element) { var ribbonToolBar = UIHelper.GetParent<RibbonToolBar>(element); var definition = ribbonToolBar?.GetCurrentLayoutDefinition(); if (definition is null) { return false; } if (definition.RowCount == 2 || definition.Rows.Count == 2) { return true; } return false; } // Determines whether the element is children to quick access toolbar private static bool IsWithinQuickAccessToolbar(DependencyObject element) { return UIHelper.GetParent<QuickAccessToolBar>(element) != null; } private static void SnapToRowsIfPresent(double[] rows, KeyTipInformation keyTipInformation, Point translatedPoint) { if (rows is null) { return; } var withinRibbonToolbar = IsWithinRibbonToolbarInTwoLine(keyTipInformation.VisualTarget); var index = 0; var mindistance = Math.Abs(rows[0] - translatedPoint.Y); for (var j = 1; j < rows.Length; j++) { if (withinRibbonToolbar && j == 1) { continue; } var distance = Math.Abs(rows[j] - translatedPoint.Y); if (distance < mindistance) { mindistance = distance; index = j; } } translatedPoint.Y = rows[index] - (keyTipInformation.KeyTip.DesiredSize.Height / 2.0); } /// <inheritdoc /> protected override int VisualChildrenCount => this.keyTipInformations.Count; /// <inheritdoc /> protected override Visual GetVisualChild(int index) { return this.keyTipInformations[index].KeyTip; } #endregion #region Logging [Conditional("DEBUG")] private void LogDebug(string format, params object[] args) { var message = this.GetMessageLog(format, args); Debug.WriteLine(message, "KeyTipAdorner"); } [Conditional("TRACE")] private void LogTrace(string format, params object[] args) { var message = this.GetMessageLog(format, args); Trace.WriteLine(message, "KeyTipAdorner"); } private string GetMessageLog(string format, object[] args) { var name = GetControlLogText(this.AdornedElement); var message = $"[{name}] {string.Format(format, args)}"; return message; } private static string GetControlLogText(UIElement control) { var name = control.GetType().Name; if (control is IHeaderedControl headeredControl) { name += $" ({headeredControl.Header})"; } return name; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; using BlogTemplate._1.Models; using BlogTemplate._1.Tests.Fakes; using Microsoft.AspNetCore.Http; using Xunit; using static BlogTemplate._1.Pages.EditModel; namespace BlogTemplate._1.Tests.Model { public class BlogDataStoreTests { [Fact] public void SavePost_SetIdTwoPosts_UniqueIds() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); Post testPost1 = new Post { Slug = "Test-Post-Slug", Title = "Test Title", Body = "Test contents", IsPublic = true, PubDate = DateTime.UtcNow }; Post testPost2 = new Post { Slug = "Test-Post-Slug", Title = "Test Title", Body = "Test contents", IsPublic = true, PubDate = DateTime.UtcNow }; testDataStore.SavePost(testPost1); testDataStore.SavePost(testPost2); Assert.NotNull(testPost1.Id); Assert.NotNull(testPost2.Id); Assert.NotEqual(testPost1.Id, testPost2.Id); } [Fact] public void SavePost_SaveSimplePost() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); Post testPost = new Post { Slug = "Test-Post-Slug", Title = "Test Title", Body = "Test contents", IsPublic = true }; testPost.PubDate = DateTime.UtcNow; testDataStore.SavePost(testPost); Assert.True(testFileSystem.FileExists($"BlogFiles\\Posts\\{testPost.PubDate.UtcDateTime.ToString("s").Replace(":","-")}_{testPost.Id.ToString("N")}.xml")); Post result = testDataStore.GetPost(testPost.Id.ToString("N")); Assert.Equal("Test-Post-Slug", result.Slug); Assert.Equal("Test Title", result.Title); Assert.Equal("Test contents", result.Body); } [Fact] public void SaveComment_SaveSimpleComment() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); Post testPost = new Post { Slug = "Test-slug", Title = "Test title", Body = "Test body", PubDate = DateTimeOffset.Now, LastModified = DateTimeOffset.Now, IsPublic = true, Excerpt = "Test excerpt" }; Comment testComment = new Comment { AuthorName = "Test name", Body = "Test body", PubDate = DateTimeOffset.Now, IsPublic = true }; testPost.Comments.Add(testComment); testDataStore.SavePost(testPost); string filePath = $"BlogFiles\\Posts\\{testPost.PubDate.UtcDateTime.ToString("s").Replace(":", "-")}_{testPost.Id.ToString("N")}.xml"; Assert.True(testFileSystem.FileExists(filePath)); StringReader xmlFileContents = new StringReader(testFileSystem.ReadFileText(filePath)); XDocument doc = XDocument.Load(xmlFileContents); Assert.True(doc.Root.Elements("Comments").Any()); } [Fact] public void GetPost_FindPostBySlug_ReturnsPost() { BlogDataStore testDataStore = new BlogDataStore(new FakeFileSystem()); var comment = new Comment { AuthorName = "Test name", Body = "test body", PubDate = DateTimeOffset.Now, IsPublic = true }; Post test = new Post { Slug = "Test-Title", Title = "Test Title", Body = "Test body", PubDate = DateTimeOffset.Now, LastModified = DateTimeOffset.Now, IsPublic = true, Excerpt = "Test excerpt", }; test.Comments.Add(comment); testDataStore.SavePost(test); Post result = testDataStore.GetPost(test.Id.ToString("N")); Assert.NotNull(result); Assert.Equal(result.Slug, "Test-Title"); Assert.Equal(result.Body, "Test body"); Assert.Equal(result.Title, "Test Title"); Assert.NotNull(result.PubDate); Assert.NotNull(result.LastModified); Assert.True(result.IsPublic); Assert.Equal(result.Excerpt, "Test excerpt"); } [Fact] public void GetPost_PostDNE_ReturnsNull() { BlogDataStore testDataStore = new BlogDataStore(new FakeFileSystem()); Assert.Null(testDataStore.GetPost("12345")); } [Fact] public void GetAllComments_ReturnsList() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); Post testPost = new Post { Slug = "Test-slug", Title = "Test title", Body = "Test body", PubDate = DateTimeOffset.Now, LastModified = DateTimeOffset.Now, IsPublic = true, Excerpt = "Test excerpt" }; var comment1 = new Comment { AuthorName = "Test name", Body = "test body", PubDate = DateTimeOffset.Now, IsPublic = true }; var comment2 = new Comment { AuthorName = "Test name", Body = "test body", PubDate = DateTimeOffset.Now, IsPublic = true }; testPost.Comments.Add(comment1); testPost.Comments.Add(comment2); testDataStore.SavePost(testPost); string text = testFileSystem.ReadFileText($"BlogFiles\\Posts\\{testPost.PubDate.UtcDateTime.ToString("s").Replace(":","-")}_{testPost.Id.ToString("N")}.xml"); StringReader reader = new StringReader(text); XDocument doc = XDocument.Load(reader); List<Comment> comments = testDataStore.GetAllComments(doc); Assert.NotEmpty(comments); } [Fact] public void GetAllPosts_ReturnsList() { BlogDataStore testDataStore = new BlogDataStore(new FakeFileSystem()); Post post1 = new Post { Slug = "Test-slug", Title = "Test title", Body = "Test body", PubDate = DateTimeOffset.Now, LastModified = DateTimeOffset.Now, IsPublic = true, Excerpt = "Test excerpt" }; Post post2 = new Post { Slug = "Test-slug", Title = "Test title", Body = "Test body", PubDate = DateTimeOffset.Now, LastModified = DateTimeOffset.Now, IsPublic = true, Excerpt = "Test excerpt" }; testDataStore.SavePost(post1); testDataStore.SavePost(post2); List<Post> posts = testDataStore.GetAllPosts(); Assert.NotEmpty(posts); } [Fact] public void FindComment_SwitchIsPublicValue() { BlogDataStore testDataStore = new BlogDataStore(new FakeFileSystem()); Post testPost = new Post { Slug = "Test-slug", Title = "Test title", Body = "Test body", PubDate = DateTimeOffset.Now, LastModified = DateTimeOffset.Now, IsPublic = true, Excerpt = "Test excerpt" }; var comment1 = new Comment { AuthorName = "Test name", Body = "test body", PubDate = DateTimeOffset.Now, IsPublic = true }; var comment2 = new Comment { AuthorName = "Test name", Body = "test body", PubDate = DateTimeOffset.Now, IsPublic = true }; testPost.Comments.Add(comment1); testPost.Comments.Add(comment2); testDataStore.SavePost(testPost); Comment newcom = testDataStore.FindComment(comment1.UniqueId, testPost); Assert.Equal(testPost.Comments.Count, 2); Assert.Equal(newcom.UniqueId, comment1.UniqueId); } [Fact] public void UpdatePost_TitleIsUpdated_UpdateSlug() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); Post oldPost = new Post { Slug = "Old-Title", IsPublic = true, PubDate = DateTimeOffset.Now }; Post newPost = new Post { Slug = "New-Title", IsPublic = true, PubDate = oldPost.PubDate }; testDataStore.SavePost(oldPost); newPost.Id = oldPost.Id; testDataStore.UpdatePost(newPost, true); Post result = testDataStore.CollectPostInfo($"BlogFiles\\Posts\\{newPost.PubDate.UtcDateTime.ToString("s").Replace(":","-")}_{newPost.Id.ToString("N")}.xml"); Assert.Equal("New-Title", result.Slug); } [Fact] public void SaveFiles_CreatesFilesInUploadsFolder() { FakeFormFile file1 = new FakeFormFile(); file1.FileName = "file1"; file1.Length = 5; FakeFormFile file2 = new FakeFormFile(); file2.FileName = "file2"; file2.Length = 5; List<IFormFile> files = new List<IFormFile>(); files.Add(file1); files.Add(file2); IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); testDataStore.SaveFiles(files); Assert.True(testFileSystem.FileExists("wwwroot\\Uploads\\file1")); Assert.True(testFileSystem.FileExists("wwwroot\\Uploads\\file2")); } [Fact] public void CollectPostInfo_EmptyFile_HasPostNode_SetDefaultValues() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); testFileSystem.WriteFileText($"BlogFiles\\Posts\\empty_file.xml", "<Post/>"); Post testPost = testDataStore.CollectPostInfo($"BlogFiles\\Posts\\empty_file.xml"); Assert.NotEqual(default(Guid), testPost.Id); Assert.Equal("", testPost.Slug); Assert.Equal("", testPost.Title); Assert.Equal("", testPost.Body); Assert.Equal(default(DateTimeOffset), testPost.PubDate); Assert.Equal(default(DateTimeOffset), testPost.LastModified); Assert.Equal(true, testPost.IsPublic); Assert.Equal(false, testPost.IsDeleted); Assert.Equal("", testPost.Excerpt); } [Fact] public void CollectPostInfo_EmptyFile_DoesNotHavePostNode_SetDefaultValues() { IFileSystem testFileSystem = new FakeFileSystem(); BlogDataStore testDataStore = new BlogDataStore(testFileSystem); testFileSystem.WriteFileText($"BlogFiles\\Posts\\empty_file.xml", ""); Assert.Null(testDataStore.CollectPostInfo($"BlogFiles\\Posts\\empty_file.xml")); } } }
// 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.ApplicationInsights.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApplicationInsights; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ComponentCurrentBillingFeaturesOperations operations. /// </summary> internal partial class ComponentCurrentBillingFeaturesOperations : IServiceOperations<ApplicationInsightsManagementClient>, IComponentCurrentBillingFeaturesOperations { /// <summary> /// Initializes a new instance of the ComponentCurrentBillingFeaturesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ComponentCurrentBillingFeaturesOperations(ApplicationInsightsManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApplicationInsightsManagementClient /// </summary> public ApplicationInsightsManagementClient Client { get; private set; } /// <summary> /// Returns current billing features for an Application Insights component. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ApplicationInsightsComponentBillingFeatures>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/currentbillingfeatures").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ApplicationInsightsComponentBillingFeatures>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationInsightsComponentBillingFeatures>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update current billing features for an Application Insights component. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='resourceName'> /// The name of the Application Insights component resource. /// </param> /// <param name='billingFeaturesProperties'> /// Properties that need to be specified to update billing features for an /// Application Insights component. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ApplicationInsightsComponentBillingFeatures>> UpdateWithHttpMessagesAsync(string resourceGroupName, string resourceName, ApplicationInsightsComponentBillingFeatures billingFeaturesProperties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceName"); } if (billingFeaturesProperties == null) { throw new ValidationException(ValidationRules.CannotBeNull, "billingFeaturesProperties"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("billingFeaturesProperties", billingFeaturesProperties); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/currentbillingfeatures").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(resourceName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(billingFeaturesProperties != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(billingFeaturesProperties, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ApplicationInsightsComponentBillingFeatures>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationInsightsComponentBillingFeatures>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenVX { public partial class VXU { public static Status ColorConvert(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuColorConvert != null, "pvxuColorConvert not implemented"); retValue = Delegates.pvxuColorConvert(context, input, output); LogCommand("vxuColorConvert", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status ChannelExtract(Context context, Image input, int channel, Image output) { Status retValue; Debug.Assert(Delegates.pvxuChannelExtract != null, "pvxuChannelExtract not implemented"); retValue = Delegates.pvxuChannelExtract(context, input, channel, output); LogCommand("vxuChannelExtract", retValue, context, input, channel, output ); DebugCheckErrors(retValue); return (retValue); } public static Status ChannelCombine(Context context, Image plane0, Image plane1, Image plane2, Image plane3, Image output) { Status retValue; Debug.Assert(Delegates.pvxuChannelCombine != null, "pvxuChannelCombine not implemented"); retValue = Delegates.pvxuChannelCombine(context, plane0, plane1, plane2, plane3, output); LogCommand("vxuChannelCombine", retValue, context, plane0, plane1, plane2, plane3, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Sobel3x3(Context context, Image input, Image output_x, Image output_y) { Status retValue; Debug.Assert(Delegates.pvxuSobel3x3 != null, "pvxuSobel3x3 not implemented"); retValue = Delegates.pvxuSobel3x3(context, input, output_x, output_y); LogCommand("vxuSobel3x3", retValue, context, input, output_x, output_y ); DebugCheckErrors(retValue); return (retValue); } public static Status Magnitude(Context context, Image grad_x, Image grad_y, Image mag) { Status retValue; Debug.Assert(Delegates.pvxuMagnitude != null, "pvxuMagnitude not implemented"); retValue = Delegates.pvxuMagnitude(context, grad_x, grad_y, mag); LogCommand("vxuMagnitude", retValue, context, grad_x, grad_y, mag ); DebugCheckErrors(retValue); return (retValue); } public static Status Phase(Context context, Image grad_x, Image grad_y, Image orientation) { Status retValue; Debug.Assert(Delegates.pvxuPhase != null, "pvxuPhase not implemented"); retValue = Delegates.pvxuPhase(context, grad_x, grad_y, orientation); LogCommand("vxuPhase", retValue, context, grad_x, grad_y, orientation ); DebugCheckErrors(retValue); return (retValue); } public static Status ScaleImage(Context context, Image src, Image dst, int type) { Status retValue; Debug.Assert(Delegates.pvxuScaleImage != null, "pvxuScaleImage not implemented"); retValue = Delegates.pvxuScaleImage(context, src, dst, type); LogCommand("vxuScaleImage", retValue, context, src, dst, type ); DebugCheckErrors(retValue); return (retValue); } public static Status TableLookup(Context context, Image input, Lut lut, Image output) { Status retValue; Debug.Assert(Delegates.pvxuTableLookup != null, "pvxuTableLookup not implemented"); retValue = Delegates.pvxuTableLookup(context, input, lut, output); LogCommand("vxuTableLookup", retValue, context, input, lut, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Histogram(Context context, Image input, Distribution distribution) { Status retValue; Debug.Assert(Delegates.pvxuHistogram != null, "pvxuHistogram not implemented"); retValue = Delegates.pvxuHistogram(context, input, distribution); LogCommand("vxuHistogram", retValue, context, input, distribution ); DebugCheckErrors(retValue); return (retValue); } public static Status EqualizeHist(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuEqualizeHist != null, "pvxuEqualizeHist not implemented"); retValue = Delegates.pvxuEqualizeHist(context, input, output); LogCommand("vxuEqualizeHist", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status AbsDiff(Context context, Image in1, Image in2, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuAbsDiff != null, "pvxuAbsDiff not implemented"); retValue = Delegates.pvxuAbsDiff(context, in1, in2, @out); LogCommand("vxuAbsDiff", retValue, context, in1, in2, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status MeanStdDev(Context context, Image input, float[] mean, float[] stddev) { Status retValue; unsafe { fixed (float* p_mean = mean) fixed (float* p_stddev = stddev) { Debug.Assert(Delegates.pvxuMeanStdDev != null, "pvxuMeanStdDev not implemented"); retValue = Delegates.pvxuMeanStdDev(context, input, p_mean, p_stddev); LogCommand("vxuMeanStdDev", retValue, context, input, mean, stddev ); } } DebugCheckErrors(retValue); return (retValue); } public static Status Threshold(Context context, Image input, Threshold thresh, Image output) { Status retValue; Debug.Assert(Delegates.pvxuThreshold != null, "pvxuThreshold not implemented"); retValue = Delegates.pvxuThreshold(context, input, thresh, output); LogCommand("vxuThreshold", retValue, context, input, thresh, output ); DebugCheckErrors(retValue); return (retValue); } public static Status NonMaxSuppression(Context context, Image input, Image mask, int win_size, Image output) { Status retValue; Debug.Assert(Delegates.pvxuNonMaxSuppression != null, "pvxuNonMaxSuppression not implemented"); retValue = Delegates.pvxuNonMaxSuppression(context, input, mask, win_size, output); LogCommand("vxuNonMaxSuppression", retValue, context, input, mask, win_size, output ); DebugCheckErrors(retValue); return (retValue); } public static Status IntegralImage(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuIntegralImage != null, "pvxuIntegralImage not implemented"); retValue = Delegates.pvxuIntegralImage(context, input, output); LogCommand("vxuIntegralImage", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Erode3x3(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuErode3x3 != null, "pvxuErode3x3 not implemented"); retValue = Delegates.pvxuErode3x3(context, input, output); LogCommand("vxuErode3x3", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Dilate3x3(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuDilate3x3 != null, "pvxuDilate3x3 not implemented"); retValue = Delegates.pvxuDilate3x3(context, input, output); LogCommand("vxuDilate3x3", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Median3x3(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuMedian3x3 != null, "pvxuMedian3x3 not implemented"); retValue = Delegates.pvxuMedian3x3(context, input, output); LogCommand("vxuMedian3x3", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Box3x3(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuBox3x3 != null, "pvxuBox3x3 not implemented"); retValue = Delegates.pvxuBox3x3(context, input, output); LogCommand("vxuBox3x3", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Gaussian3x3(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuGaussian3x3 != null, "pvxuGaussian3x3 not implemented"); retValue = Delegates.pvxuGaussian3x3(context, input, output); LogCommand("vxuGaussian3x3", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status NonLinearFilter(Context context, int function, Image input, Matrix mask, Image output) { Status retValue; Debug.Assert(Delegates.pvxuNonLinearFilter != null, "pvxuNonLinearFilter not implemented"); retValue = Delegates.pvxuNonLinearFilter(context, function, input, mask, output); LogCommand("vxuNonLinearFilter", retValue, context, function, input, mask, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Convolve(Context context, Image input, Convolution conv, Image output) { Status retValue; Debug.Assert(Delegates.pvxuConvolve != null, "pvxuConvolve not implemented"); retValue = Delegates.pvxuConvolve(context, input, conv, output); LogCommand("vxuConvolve", retValue, context, input, conv, output ); DebugCheckErrors(retValue); return (retValue); } public static Status GaussianPyramid(Context context, Image input, Pyramid gaussian) { Status retValue; Debug.Assert(Delegates.pvxuGaussianPyramid != null, "pvxuGaussianPyramid not implemented"); retValue = Delegates.pvxuGaussianPyramid(context, input, gaussian); LogCommand("vxuGaussianPyramid", retValue, context, input, gaussian ); DebugCheckErrors(retValue); return (retValue); } public static Status LaplacianPyramid(Context context, Image input, Pyramid laplacian, Image output) { Status retValue; Debug.Assert(Delegates.pvxuLaplacianPyramid != null, "pvxuLaplacianPyramid not implemented"); retValue = Delegates.pvxuLaplacianPyramid(context, input, laplacian, output); LogCommand("vxuLaplacianPyramid", retValue, context, input, laplacian, output ); DebugCheckErrors(retValue); return (retValue); } public static Status LaplacianReconstruct(Context context, Pyramid laplacian, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuLaplacianReconstruct != null, "pvxuLaplacianReconstruct not implemented"); retValue = Delegates.pvxuLaplacianReconstruct(context, laplacian, input, output); LogCommand("vxuLaplacianReconstruct", retValue, context, laplacian, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status AccumulateImage(Context context, Image input, Image accum) { Status retValue; Debug.Assert(Delegates.pvxuAccumulateImage != null, "pvxuAccumulateImage not implemented"); retValue = Delegates.pvxuAccumulateImage(context, input, accum); LogCommand("vxuAccumulateImage", retValue, context, input, accum ); DebugCheckErrors(retValue); return (retValue); } public static Status AccumulateWeightedImage(Context context, Image input, Scalar alpha, Image accum) { Status retValue; Debug.Assert(Delegates.pvxuAccumulateWeightedImage != null, "pvxuAccumulateWeightedImage not implemented"); retValue = Delegates.pvxuAccumulateWeightedImage(context, input, alpha, accum); LogCommand("vxuAccumulateWeightedImage", retValue, context, input, alpha, accum ); DebugCheckErrors(retValue); return (retValue); } public static Status AccumulateSquareImage(Context context, Image input, Scalar shift, Image accum) { Status retValue; Debug.Assert(Delegates.pvxuAccumulateSquareImage != null, "pvxuAccumulateSquareImage not implemented"); retValue = Delegates.pvxuAccumulateSquareImage(context, input, shift, accum); LogCommand("vxuAccumulateSquareImage", retValue, context, input, shift, accum ); DebugCheckErrors(retValue); return (retValue); } public static Status MinMaxLoc(Context context, Image input, Scalar minVal, Scalar maxVal, Array minLoc, Array maxLoc, Scalar minCount, Scalar maxCount) { Status retValue; Debug.Assert(Delegates.pvxuMinMaxLoc != null, "pvxuMinMaxLoc not implemented"); retValue = Delegates.pvxuMinMaxLoc(context, input, minVal, maxVal, minLoc, maxLoc, minCount, maxCount); LogCommand("vxuMinMaxLoc", retValue, context, input, minVal, maxVal, minLoc, maxLoc, minCount, maxCount ); DebugCheckErrors(retValue); return (retValue); } public static Status Min(Context context, Image in1, Image in2, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuMin != null, "pvxuMin not implemented"); retValue = Delegates.pvxuMin(context, in1, in2, @out); LogCommand("vxuMin", retValue, context, in1, in2, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status Max(Context context, Image in1, Image in2, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuMax != null, "pvxuMax not implemented"); retValue = Delegates.pvxuMax(context, in1, in2, @out); LogCommand("vxuMax", retValue, context, in1, in2, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status ConvertDepth(Context context, Image input, Image output, int policy, int shift) { Status retValue; Debug.Assert(Delegates.pvxuConvertDepth != null, "pvxuConvertDepth not implemented"); retValue = Delegates.pvxuConvertDepth(context, input, output, policy, shift); LogCommand("vxuConvertDepth", retValue, context, input, output, policy, shift ); DebugCheckErrors(retValue); return (retValue); } public static Status CannyEdgeDetector(Context context, Image input, Threshold hyst, int gradient_size, int norm_type, Image output) { Status retValue; Debug.Assert(Delegates.pvxuCannyEdgeDetector != null, "pvxuCannyEdgeDetector not implemented"); retValue = Delegates.pvxuCannyEdgeDetector(context, input, hyst, gradient_size, norm_type, output); LogCommand("vxuCannyEdgeDetector", retValue, context, input, hyst, gradient_size, norm_type, output ); DebugCheckErrors(retValue); return (retValue); } public static Status HalfScaleGaussian(Context context, Image input, Image output, int kernel_size) { Status retValue; Debug.Assert(Delegates.pvxuHalfScaleGaussian != null, "pvxuHalfScaleGaussian not implemented"); retValue = Delegates.pvxuHalfScaleGaussian(context, input, output, kernel_size); LogCommand("vxuHalfScaleGaussian", retValue, context, input, output, kernel_size ); DebugCheckErrors(retValue); return (retValue); } public static Status And(Context context, Image in1, Image in2, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuAnd != null, "pvxuAnd not implemented"); retValue = Delegates.pvxuAnd(context, in1, in2, @out); LogCommand("vxuAnd", retValue, context, in1, in2, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status Or(Context context, Image in1, Image in2, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuOr != null, "pvxuOr not implemented"); retValue = Delegates.pvxuOr(context, in1, in2, @out); LogCommand("vxuOr", retValue, context, in1, in2, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status Xor(Context context, Image in1, Image in2, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuXor != null, "pvxuXor not implemented"); retValue = Delegates.pvxuXor(context, in1, in2, @out); LogCommand("vxuXor", retValue, context, in1, in2, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status Not(Context context, Image input, Image output) { Status retValue; Debug.Assert(Delegates.pvxuNot != null, "pvxuNot not implemented"); retValue = Delegates.pvxuNot(context, input, output); LogCommand("vxuNot", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Multiply(Context context, Image in1, Image in2, float scale, int overflow_policy, int rounding_policy, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuMultiply != null, "pvxuMultiply not implemented"); retValue = Delegates.pvxuMultiply(context, in1, in2, scale, overflow_policy, rounding_policy, @out); LogCommand("vxuMultiply", retValue, context, in1, in2, scale, overflow_policy, rounding_policy, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status Add(Context context, Image in1, Image in2, int policy, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuAdd != null, "pvxuAdd not implemented"); retValue = Delegates.pvxuAdd(context, in1, in2, policy, @out); LogCommand("vxuAdd", retValue, context, in1, in2, policy, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status Subtract(Context context, Image in1, Image in2, int policy, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuSubtract != null, "pvxuSubtract not implemented"); retValue = Delegates.pvxuSubtract(context, in1, in2, policy, @out); LogCommand("vxuSubtract", retValue, context, in1, in2, policy, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status WarpAffine(Context context, Image input, Matrix matrix, int type, Image output) { Status retValue; Debug.Assert(Delegates.pvxuWarpAffine != null, "pvxuWarpAffine not implemented"); retValue = Delegates.pvxuWarpAffine(context, input, matrix, type, output); LogCommand("vxuWarpAffine", retValue, context, input, matrix, type, output ); DebugCheckErrors(retValue); return (retValue); } public static Status WarpPerspective(Context context, Image input, Matrix matrix, int type, Image output) { Status retValue; Debug.Assert(Delegates.pvxuWarpPerspective != null, "pvxuWarpPerspective not implemented"); retValue = Delegates.pvxuWarpPerspective(context, input, matrix, type, output); LogCommand("vxuWarpPerspective", retValue, context, input, matrix, type, output ); DebugCheckErrors(retValue); return (retValue); } public static Status HarrisCorners(Context context, Image input, Scalar strength_thresh, Scalar min_distance, Scalar sensitivity, int gradient_size, int block_size, Array corners, Scalar num_corners) { Status retValue; Debug.Assert(Delegates.pvxuHarrisCorners != null, "pvxuHarrisCorners not implemented"); retValue = Delegates.pvxuHarrisCorners(context, input, strength_thresh, min_distance, sensitivity, gradient_size, block_size, corners, num_corners); LogCommand("vxuHarrisCorners", retValue, context, input, strength_thresh, min_distance, sensitivity, gradient_size, block_size, corners, num_corners ); DebugCheckErrors(retValue); return (retValue); } public static Status FastCorners(Context context, Image input, Scalar strength_thresh, bool nonmax_suppression, Array corners, Scalar num_corners) { Status retValue; Debug.Assert(Delegates.pvxuFastCorners != null, "pvxuFastCorners not implemented"); retValue = Delegates.pvxuFastCorners(context, input, strength_thresh, nonmax_suppression, corners, num_corners); LogCommand("vxuFastCorners", retValue, context, input, strength_thresh, nonmax_suppression, corners, num_corners ); DebugCheckErrors(retValue); return (retValue); } public static Status OpticalFlowPyrLK(Context context, Pyramid old_images, Pyramid new_images, Array old_points, Array new_points_estimates, Array new_points, int termination, Scalar epsilon, Scalar num_iterations, Scalar use_initial_estimate, UIntPtr window_dimension) { Status retValue; Debug.Assert(Delegates.pvxuOpticalFlowPyrLK != null, "pvxuOpticalFlowPyrLK not implemented"); retValue = Delegates.pvxuOpticalFlowPyrLK(context, old_images, new_images, old_points, new_points_estimates, new_points, termination, epsilon, num_iterations, use_initial_estimate, window_dimension); LogCommand("vxuOpticalFlowPyrLK", retValue, context, old_images, new_images, old_points, new_points_estimates, new_points, termination, epsilon, num_iterations, use_initial_estimate, window_dimension ); DebugCheckErrors(retValue); return (retValue); } public static Status MatchTemplateNode(Context context, Image src, Image templateImage, int matchingMethod, Image output) { Status retValue; Debug.Assert(Delegates.pvxuMatchTemplateNode != null, "pvxuMatchTemplateNode not implemented"); retValue = Delegates.pvxuMatchTemplateNode(context, src, templateImage, matchingMethod, output); LogCommand("vxuMatchTemplateNode", retValue, context, src, templateImage, matchingMethod, output ); DebugCheckErrors(retValue); return (retValue); } public static Status LBPNode(Context context, Image @in, int format, sbyte kernel_size, Image @out) { Status retValue; Debug.Assert(Delegates.pvxuLBPNode != null, "pvxuLBPNode not implemented"); retValue = Delegates.pvxuLBPNode(context, @in, format, kernel_size, @out); LogCommand("vxuLBPNode", retValue, context, @in, format, kernel_size, @out ); DebugCheckErrors(retValue); return (retValue); } public static Status HOGFeatures(Context context, Image input, Tensor magnitudes, Tensor bins, Hog[] @params, UIntPtr hog_param_size, Tensor features) { Status retValue; unsafe { fixed (Hog* p_params = @params) { Debug.Assert(Delegates.pvxuHOGFeatures != null, "pvxuHOGFeatures not implemented"); retValue = Delegates.pvxuHOGFeatures(context, input, magnitudes, bins, p_params, hog_param_size, features); LogCommand("vxuHOGFeatures", retValue, context, input, magnitudes, bins, @params, hog_param_size, features ); } } DebugCheckErrors(retValue); return (retValue); } public static Status HOGCells(Context context, Image input, int cell_size, int num_bins, Tensor magnitudes, Tensor bins) { Status retValue; Debug.Assert(Delegates.pvxuHOGCells != null, "pvxuHOGCells not implemented"); retValue = Delegates.pvxuHOGCells(context, input, cell_size, num_bins, magnitudes, bins); LogCommand("vxuHOGCells", retValue, context, input, cell_size, num_bins, magnitudes, bins ); DebugCheckErrors(retValue); return (retValue); } public static Status HoughLinesPNode(Context context, Image input, HoughLinesParams[] @params, Array lines_array, Scalar num_lines) { Status retValue; unsafe { fixed (HoughLinesParams* p_params = @params) { Debug.Assert(Delegates.pvxuHoughLinesPNode != null, "pvxuHoughLinesPNode not implemented"); retValue = Delegates.pvxuHoughLinesPNode(context, input, p_params, lines_array, num_lines); LogCommand("vxuHoughLinesPNode", retValue, context, input, @params, lines_array, num_lines ); } } DebugCheckErrors(retValue); return (retValue); } public static Status Remap(Context context, Image input, Remap table, int policy, Image output) { Status retValue; Debug.Assert(Delegates.pvxuRemap != null, "pvxuRemap not implemented"); retValue = Delegates.pvxuRemap(context, input, table, policy, output); LogCommand("vxuRemap", retValue, context, input, table, policy, output ); DebugCheckErrors(retValue); return (retValue); } public static Status BilateralFilter(Context context, Tensor src, int diameter, float sigmaSpace, float sigmaValues, Tensor dst) { Status retValue; Debug.Assert(Delegates.pvxuBilateralFilter != null, "pvxuBilateralFilter not implemented"); retValue = Delegates.pvxuBilateralFilter(context, src, diameter, sigmaSpace, sigmaValues, dst); LogCommand("vxuBilateralFilter", retValue, context, src, diameter, sigmaSpace, sigmaValues, dst ); DebugCheckErrors(retValue); return (retValue); } public static Status TensorMultiply(Context context, Tensor input1, Tensor input2, Scalar scale, int overflow_policy, int rounding_policy, Tensor output) { Status retValue; Debug.Assert(Delegates.pvxuTensorMultiply != null, "pvxuTensorMultiply not implemented"); retValue = Delegates.pvxuTensorMultiply(context, input1, input2, scale, overflow_policy, rounding_policy, output); LogCommand("vxuTensorMultiply", retValue, context, input1, input2, scale, overflow_policy, rounding_policy, output ); DebugCheckErrors(retValue); return (retValue); } public static Status TensorAdd(Context context, Tensor input1, Tensor input2, int policy, Tensor output) { Status retValue; Debug.Assert(Delegates.pvxuTensorAdd != null, "pvxuTensorAdd not implemented"); retValue = Delegates.pvxuTensorAdd(context, input1, input2, policy, output); LogCommand("vxuTensorAdd", retValue, context, input1, input2, policy, output ); DebugCheckErrors(retValue); return (retValue); } public static Status TensorSubtract(Context context, Tensor input1, Tensor input2, int policy, Tensor output) { Status retValue; Debug.Assert(Delegates.pvxuTensorSubtract != null, "pvxuTensorSubtract not implemented"); retValue = Delegates.pvxuTensorSubtract(context, input1, input2, policy, output); LogCommand("vxuTensorSubtract", retValue, context, input1, input2, policy, output ); DebugCheckErrors(retValue); return (retValue); } public static Status TensorTableLookup(Context context, Tensor input1, Lut lut, Tensor output) { Status retValue; Debug.Assert(Delegates.pvxuTensorTableLookup != null, "pvxuTensorTableLookup not implemented"); retValue = Delegates.pvxuTensorTableLookup(context, input1, lut, output); LogCommand("vxuTensorTableLookup", retValue, context, input1, lut, output ); DebugCheckErrors(retValue); return (retValue); } public static Status Tensor(Context context, Tensor input, Tensor output, UIntPtr dimension1, UIntPtr dimension2) { Status retValue; Debug.Assert(Delegates.pvxuTensorTranspose != null, "pvxuTensorTranspose not implemented"); retValue = Delegates.pvxuTensorTranspose(context, input, output, dimension1, dimension2); LogCommand("vxuTensorTranspose", retValue, context, input, output, dimension1, dimension2 ); DebugCheckErrors(retValue); return (retValue); } public static Status TensorConvertDepth(Context context, Tensor input, int policy, Scalar norm, Scalar offset, Tensor output) { Status retValue; Debug.Assert(Delegates.pvxuTensorConvertDepth != null, "pvxuTensorConvertDepth not implemented"); retValue = Delegates.pvxuTensorConvertDepth(context, input, policy, norm, offset, output); LogCommand("vxuTensorConvertDepth", retValue, context, input, policy, norm, offset, output ); DebugCheckErrors(retValue); return (retValue); } public static Status MatrixMultiply(Context context, Tensor input1, Tensor input2, Tensor input3, MatrixMulParams[] matrix_multiply_params, Tensor output) { Status retValue; unsafe { fixed (MatrixMulParams* p_matrix_multiply_params = matrix_multiply_params) { Debug.Assert(Delegates.pvxuMatrixMultiply != null, "pvxuMatrixMultiply not implemented"); retValue = Delegates.pvxuMatrixMultiply(context, input1, input2, input3, p_matrix_multiply_params, output); LogCommand("vxuMatrixMultiply", retValue, context, input1, input2, input3, matrix_multiply_params, output ); } } DebugCheckErrors(retValue); return (retValue); } public static Status Copy(Context context, Reference input, Reference output) { Status retValue; Debug.Assert(Delegates.pvxuCopy != null, "pvxuCopy not implemented"); retValue = Delegates.pvxuCopy(context, input, output); LogCommand("vxuCopy", retValue, context, input, output ); DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [SuppressUnmanagedCodeSecurity] internal delegate Status vxuColorConvert(Context context, Image input, Image output); internal static vxuColorConvert pvxuColorConvert; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuChannelExtract(Context context, Image input, int channel, Image output); internal static vxuChannelExtract pvxuChannelExtract; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuChannelCombine(Context context, Image plane0, Image plane1, Image plane2, Image plane3, Image output); internal static vxuChannelCombine pvxuChannelCombine; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuSobel3x3(Context context, Image input, Image output_x, Image output_y); internal static vxuSobel3x3 pvxuSobel3x3; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMagnitude(Context context, Image grad_x, Image grad_y, Image mag); internal static vxuMagnitude pvxuMagnitude; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuPhase(Context context, Image grad_x, Image grad_y, Image orientation); internal static vxuPhase pvxuPhase; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuScaleImage(Context context, Image src, Image dst, int type); internal static vxuScaleImage pvxuScaleImage; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTableLookup(Context context, Image input, Lut lut, Image output); internal static vxuTableLookup pvxuTableLookup; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuHistogram(Context context, Image input, Distribution distribution); internal static vxuHistogram pvxuHistogram; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuEqualizeHist(Context context, Image input, Image output); internal static vxuEqualizeHist pvxuEqualizeHist; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuAbsDiff(Context context, Image in1, Image in2, Image @out); internal static vxuAbsDiff pvxuAbsDiff; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMeanStdDev(Context context, Image input, float* mean, float* stddev); internal static vxuMeanStdDev pvxuMeanStdDev; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuThreshold(Context context, Image input, Threshold thresh, Image output); internal static vxuThreshold pvxuThreshold; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuNonMaxSuppression(Context context, Image input, Image mask, int win_size, Image output); internal static vxuNonMaxSuppression pvxuNonMaxSuppression; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuIntegralImage(Context context, Image input, Image output); internal static vxuIntegralImage pvxuIntegralImage; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuErode3x3(Context context, Image input, Image output); internal static vxuErode3x3 pvxuErode3x3; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuDilate3x3(Context context, Image input, Image output); internal static vxuDilate3x3 pvxuDilate3x3; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMedian3x3(Context context, Image input, Image output); internal static vxuMedian3x3 pvxuMedian3x3; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuBox3x3(Context context, Image input, Image output); internal static vxuBox3x3 pvxuBox3x3; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuGaussian3x3(Context context, Image input, Image output); internal static vxuGaussian3x3 pvxuGaussian3x3; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuNonLinearFilter(Context context, int function, Image input, Matrix mask, Image output); internal static vxuNonLinearFilter pvxuNonLinearFilter; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuConvolve(Context context, Image input, Convolution conv, Image output); internal static vxuConvolve pvxuConvolve; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuGaussianPyramid(Context context, Image input, Pyramid gaussian); internal static vxuGaussianPyramid pvxuGaussianPyramid; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuLaplacianPyramid(Context context, Image input, Pyramid laplacian, Image output); internal static vxuLaplacianPyramid pvxuLaplacianPyramid; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuLaplacianReconstruct(Context context, Pyramid laplacian, Image input, Image output); internal static vxuLaplacianReconstruct pvxuLaplacianReconstruct; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuAccumulateImage(Context context, Image input, Image accum); internal static vxuAccumulateImage pvxuAccumulateImage; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuAccumulateWeightedImage(Context context, Image input, Scalar alpha, Image accum); internal static vxuAccumulateWeightedImage pvxuAccumulateWeightedImage; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuAccumulateSquareImage(Context context, Image input, Scalar shift, Image accum); internal static vxuAccumulateSquareImage pvxuAccumulateSquareImage; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMinMaxLoc(Context context, Image input, Scalar minVal, Scalar maxVal, Array minLoc, Array maxLoc, Scalar minCount, Scalar maxCount); internal static vxuMinMaxLoc pvxuMinMaxLoc; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMin(Context context, Image in1, Image in2, Image @out); internal static vxuMin pvxuMin; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMax(Context context, Image in1, Image in2, Image @out); internal static vxuMax pvxuMax; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuConvertDepth(Context context, Image input, Image output, int policy, int shift); internal static vxuConvertDepth pvxuConvertDepth; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuCannyEdgeDetector(Context context, Image input, Threshold hyst, int gradient_size, int norm_type, Image output); internal static vxuCannyEdgeDetector pvxuCannyEdgeDetector; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuHalfScaleGaussian(Context context, Image input, Image output, int kernel_size); internal static vxuHalfScaleGaussian pvxuHalfScaleGaussian; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuAnd(Context context, Image in1, Image in2, Image @out); internal static vxuAnd pvxuAnd; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuOr(Context context, Image in1, Image in2, Image @out); internal static vxuOr pvxuOr; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuXor(Context context, Image in1, Image in2, Image @out); internal static vxuXor pvxuXor; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuNot(Context context, Image input, Image output); internal static vxuNot pvxuNot; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMultiply(Context context, Image in1, Image in2, float scale, int overflow_policy, int rounding_policy, Image @out); internal static vxuMultiply pvxuMultiply; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuAdd(Context context, Image in1, Image in2, int policy, Image @out); internal static vxuAdd pvxuAdd; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuSubtract(Context context, Image in1, Image in2, int policy, Image @out); internal static vxuSubtract pvxuSubtract; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuWarpAffine(Context context, Image input, Matrix matrix, int type, Image output); internal static vxuWarpAffine pvxuWarpAffine; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuWarpPerspective(Context context, Image input, Matrix matrix, int type, Image output); internal static vxuWarpPerspective pvxuWarpPerspective; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuHarrisCorners(Context context, Image input, Scalar strength_thresh, Scalar min_distance, Scalar sensitivity, int gradient_size, int block_size, Array corners, Scalar num_corners); internal static vxuHarrisCorners pvxuHarrisCorners; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuFastCorners(Context context, Image input, Scalar strength_thresh, bool nonmax_suppression, Array corners, Scalar num_corners); internal static vxuFastCorners pvxuFastCorners; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuOpticalFlowPyrLK(Context context, Pyramid old_images, Pyramid new_images, Array old_points, Array new_points_estimates, Array new_points, int termination, Scalar epsilon, Scalar num_iterations, Scalar use_initial_estimate, UIntPtr window_dimension); internal static vxuOpticalFlowPyrLK pvxuOpticalFlowPyrLK; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMatchTemplateNode(Context context, Image src, Image templateImage, int matchingMethod, Image output); internal static vxuMatchTemplateNode pvxuMatchTemplateNode; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuLBPNode(Context context, Image @in, int format, sbyte kernel_size, Image @out); internal static vxuLBPNode pvxuLBPNode; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuHOGFeatures(Context context, Image input, Tensor magnitudes, Tensor bins, Hog* @params, UIntPtr hog_param_size, Tensor features); internal static vxuHOGFeatures pvxuHOGFeatures; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuHOGCells(Context context, Image input, int cell_size, int num_bins, Tensor magnitudes, Tensor bins); internal static vxuHOGCells pvxuHOGCells; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuHoughLinesPNode(Context context, Image input, HoughLinesParams* @params, Array lines_array, Scalar num_lines); internal static vxuHoughLinesPNode pvxuHoughLinesPNode; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuRemap(Context context, Image input, Remap table, int policy, Image output); internal static vxuRemap pvxuRemap; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuBilateralFilter(Context context, Tensor src, int diameter, float sigmaSpace, float sigmaValues, Tensor dst); internal static vxuBilateralFilter pvxuBilateralFilter; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTensorMultiply(Context context, Tensor input1, Tensor input2, Scalar scale, int overflow_policy, int rounding_policy, Tensor output); internal static vxuTensorMultiply pvxuTensorMultiply; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTensorAdd(Context context, Tensor input1, Tensor input2, int policy, Tensor output); internal static vxuTensorAdd pvxuTensorAdd; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTensorSubtract(Context context, Tensor input1, Tensor input2, int policy, Tensor output); internal static vxuTensorSubtract pvxuTensorSubtract; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTensorTableLookup(Context context, Tensor input1, Lut lut, Tensor output); internal static vxuTensorTableLookup pvxuTensorTableLookup; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTensorTranspose(Context context, Tensor input, Tensor output, UIntPtr dimension1, UIntPtr dimension2); internal static vxuTensorTranspose pvxuTensorTranspose; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuTensorConvertDepth(Context context, Tensor input, int policy, Scalar norm, Scalar offset, Tensor output); internal static vxuTensorConvertDepth pvxuTensorConvertDepth; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuMatrixMultiply(Context context, Tensor input1, Tensor input2, Tensor input3, MatrixMulParams* matrix_multiply_params, Tensor output); internal static vxuMatrixMultiply pvxuMatrixMultiply; [SuppressUnmanagedCodeSecurity] internal delegate Status vxuCopy(Context context, Reference input, Reference output); internal static vxuCopy pvxuCopy; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> public partial class FileStream : Stream { /// <summary>File mode.</summary> private FileMode _mode; /// <summary>Advanced options requested when opening the file.</summary> private FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private long _appendStart = -1; /// <summary> /// Extra state used by the file stream when _useAsyncIO is true. This includes /// the semaphore used to serialize all operation, the buffer/offset/count provided by the /// caller for ReadAsync/WriteAsync operations, and the last successful task returned /// synchronously from ReadAsync which can be reused if the count matches the next request. /// Only initialized when <see cref="_useAsyncIO"/> is true. /// </summary> private AsyncState _asyncState; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _mode = mode; _options = options; if (_useAsyncIO) _asyncState = new AsyncState(); // Translate the arguments into arguments for an open call. Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, share, options); // If the file gets created a new, we'll select the permissions for it. Most Unix utilities by default use 666 (read and // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the // actual permissions will typically be less than what we select here. const Interop.Sys.Permissions OpenPermissions = Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); } /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="mode">How the file should be opened.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> private void Init(FileMode mode, FileShare share) { _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH; if (Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB) < 0) { // The only error we care about is EWOULDBLOCK, which indicates that the file is currently locked by someone // else and we would block trying to access it. Other errors, such as ENOTSUP (locking isn't supported) or // EACCES (the file system doesn't allow us to lock), will only hamper FileStream's usage without providing value, // given again that this is only advisory / best-effort. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EWOULDBLOCK) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } // These provide hints around how the file will be accessed. Specifying both RandomAccess // and Sequential together doesn't make sense as they are two competing options on the same spectrum, // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided). Interop.Sys.FileAdvice fadv = (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM : (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL : 0; if (fadv != 0) { CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), ignoreNotSupported: true); // just a hint. } if (_mode == FileMode.Append) { // Jump to the end of the file if opened as Append. _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } else if (mode == FileMode.Create || mode == FileMode.Truncate) { // Truncate the file now if the file mode requires it. This ensures that the file only will be truncated // if opened successfully. CheckFileCall(Interop.Sys.FTruncate(_fileHandle, 0)); } } /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { if (useAsyncIO) _asyncState = new AsyncState(); if (CanSeekCore(handle)) // use non-virtual CanSeekCore rather than CanSeek to avoid making virtual call during ctor SeekCore(handle, 0, SeekOrigin.Current); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="share">The FileShare provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileShare share, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. case FileMode.Truncate: // We truncate the file after getting the lock break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: case FileMode.Create: // We truncate the file after getting the lock flags |= Interop.Sys.OpenFlags.O_CREAT; break; case FileMode.CreateNew: flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL); break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.Sys.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.Sys.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.Sys.OpenFlags.O_WRONLY; break; } // Handle Inheritable, other FileShare flags are handled by Init if ((share & FileShare.Inheritable) == 0) { flags |= Interop.Sys.OpenFlags.O_CLOEXEC; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. // - Asynchronous: Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true // - DeleteOnClose: Doesn't have a Unix equivalent, but we approximate it in Dispose // - Encrypted: No equivalent on Unix and is ignored // - RandomAccess: Implemented after open if posix_fadvise is available // - SequentialScan: Implemented after open if posix_fadvise is available // - WriteThrough: Handled here if ((options & FileOptions.WriteThrough) != 0) { flags |= Interop.Sys.OpenFlags.O_SYNC; } return flags; } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek => CanSeekCore(_fileHandle); /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <remarks> /// Separated out of CanSeek to enable making non-virtual call to this logic. /// We also pass in the file handle to allow the constructor to use this before it stashes the handle. /// </remarks> private bool CanSeekCore(SafeFileHandle fileHandle) { if (fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = Interop.Sys.LSeek(fileHandle, 0, Interop.Sys.SeekWhence.SEEK_CUR) >= 0; } return _canSeek.Value; } private long GetLengthInternal() { // Get the length of the file as reported by the OS Interop.Sys.FileStatus status; CheckFileCall(Interop.Sys.FStat(_fileHandle, out status)); long length = status.Size; // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { try { if (_fileHandle != null && !_fileHandle.IsClosed) { // Flush any remaining data in the file try { FlushWriteBuffer(); } catch (Exception e) when (IsIoRelatedException(e) && !disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } // If DeleteOnClose was requested when constructed, delete the file now. // (Unix doesn't directly support DeleteOnClose, so we mimic it here.) if (_path != null && (_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed, but the // name will be removed immediately. Interop.Sys.Unlink(_path); // ignore errors; it's valid that the path may no longer exist } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { if (Interop.Sys.FSync(_fileHandle) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EROFS: case Interop.Error.EINVAL: case Interop.Error.ENOTSUP: // Ignore failures due to the FileStream being bound to a special file that // doesn't support synchronization. In such cases there's nothing to flush. break; default: throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } } private void FlushWriteBufferForWriteByte() { _asyncState?.Wait(); try { FlushWriteBuffer(); } finally { _asyncState?.Release(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { AssertBufferInvariants(); if (_writePos > 0) { WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> private void SetLengthInternal(long value) { FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(_fileHandle, value, SeekOrigin.Begin); } CheckFileCall(Interop.Sys.FTruncate(_fileHandle, value)); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(_fileHandle, origPos, SeekOrigin.Begin); } else { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> private int ReadSpan(Span<byte> destination) { PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; bool readFromOS = false; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!CanSeek || (destination.Length >= _bufferLength)) { // Read directly into the user's buffer _readPos = _readLength = 0; return ReadNative(destination); } else { // Read into our buffer. _readLength = numBytesAvailable = ReadNative(GetBuffer()); _readPos = 0; if (numBytesAvailable == 0) { return 0; } // Note that we did an OS read as part of this Read, so that later // we don't try to do one again if what's in the buffer doesn't // meet the user's request. readFromOS = true; } } // Now that we know there's data in the buffer, read from it into the user's buffer. Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here"); int bytesRead = Math.Min(numBytesAvailable, destination.Length); new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination); _readPos += bytesRead; // We may not have had enough data in the buffer to completely satisfy the user's request. // While Read doesn't require that we return as much data as the user requested (any amount // up to the requested count is fine), FileStream on Windows tries to do so by doing a // subsequent read from the file if we tried to satisfy the request with what was in the // buffer but the buffer contained less than the requested count. To be consistent with that // behavior, we do the same thing here on Unix. Note that we may still get less the requested // amount, as the OS may give us back fewer than we request, either due to reaching the end of // file, or due to its own whims. if (!readFromOS && bytesRead < destination.Length) { Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length"); _readPos = _readLength = 0; // no data left in the read buffer bytesRead += ReadNative(destination.Slice(bytesRead)); } return bytesRead; } /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary> /// <param name="buffer">The buffer into which data from the file is read.</param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadNative(Span<byte> buffer) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer)) { bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length)); Debug.Assert(bytesRead <= buffer.Length); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="destination">The buffer to write the data into.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <param name="synchronousResult">If the operation completes synchronously, the number of bytes read.</param> /// <returns>A task that represents the asynchronous read operation.</returns> private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult) { Debug.Assert(_useAsyncIO); if (!CanRead) // match Windows behavior; this gets thrown synchronously { throw Error.GetReadNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough data in our buffer // to satisfy the full request of the caller, hand back the buffered data. // While it would be a legal implementation of the Read contract, we don't // hand back here less than the amount requested so as to match the behavior // in ReadCore that will make a native call to try to fulfill the remainder // of the request. if (waitTask.Status == TaskStatus.RanToCompletion) { int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable >= destination.Length) { try { PrepareForReading(); new Span<byte>(GetBuffer(), _readPos, destination.Length).CopyTo(destination.Span); _readPos += destination.Length; synchronousResult = destination.Length; return null; } catch (Exception exc) { synchronousResult = 0; return Task.FromException<int>(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. synchronousResult = 0; _asyncState.Memory = destination; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position /length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { Memory<byte> memory = thisRef._asyncState.Memory; thisRef._asyncState.Memory = default(Memory<byte>); return thisRef.ReadSpan(memory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() { _asyncState?.Wait(); try { return ReadNative(_buffer); } finally { _asyncState?.Release(); } } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private void WriteSpan(ReadOnlySpan<byte> source) { PrepareForWriting(); // If no data is being written, nothing more to do. if (source.Length == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += source.Length; return; } else if (spaceRemaining > 0) { source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos)); _writePos += spaceRemaining; source = source.Slice(spaceRemaining); } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (source.Length >= _bufferLength) { WriteNative(source); } else { source.CopyTo(new Span<byte>(GetBuffer())); _writePos = source.Length; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="source">The buffer containing data to write to the stream.</param> private unsafe void WriteNative(ReadOnlySpan<byte> source) { VerifyOSHandlePosition(); fixed (byte* bufPtr = &MemoryMarshal.GetReference(source)) { int offset = 0; int count = source.Length; while (count > 0) { int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count)); _filePosition += bytesWritten; offset += bytesWritten; count -= bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="source">The buffer to write data from.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> private Task WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanWrite) // match Windows behavior; this gets thrown synchronously { throw Error.GetWriteNotSupported(); } // Serialize operations using the semaphore. Task waitTask = _asyncState.WaitAsync(); // If we got ownership immediately, and if there's enough space in our buffer // to buffer the entire write request, then do so and we're done. if (waitTask.Status == TaskStatus.RanToCompletion) { int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining >= source.Length) { try { PrepareForWriting(); source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length)); _writePos += source.Length; return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } finally { _asyncState.Release(); } } } // Otherwise, issue the whole request asynchronously. _asyncState.ReadOnlyMemory = source; return waitTask.ContinueWith((t, s) => { // The options available on Unix for writing asynchronously to an arbitrary file // handle typically amount to just using another thread to do the synchronous write, // which is exactly what this implementation does. This does mean there are subtle // differences in certain FileStream behaviors between Windows and Unix when multiple // asynchronous operations are issued against the stream to execute concurrently; on // Unix the operations will be serialized due to the usage of a semaphore, but the // position/length information won't be updated until after the write has completed, // whereas on Windows it may happen before the write has completed. Debug.Assert(t.Status == TaskStatus.RanToCompletion); var thisRef = (FileStream)s; try { ReadOnlyMemory<byte> readOnlyMemory = thisRef._asyncState.ReadOnlyMemory; thisRef._asyncState.ReadOnlyMemory = default(ReadOnlyMemory<byte>); thisRef.WriteSpan(readOnlyMemory.Span); } finally { thisRef._asyncState.Release(); } }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } if (!CanSeek) { throw Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin) { Debug.Assert(!fileHandle.IsClosed && (GetType() != typeof(FileStream) || CanSeekCore(fileHandle))); // verify that we can seek, but only if CanSeek won't be a virtual call (which could happen in the ctor) Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = CheckFileCall(Interop.Sys.LSeek(fileHandle, offset, (Interop.Sys.SeekWhence)(int)origin)); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } private long CheckFileCall(long result, bool ignoreNotSupported = false) { if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (!(ignoreNotSupported && errorInfo.Error == Interop.Error.ENOTSUP)) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } private int CheckFileCall(int result, bool ignoreNotSupported = false) { CheckFileCall((long)result, ignoreNotSupported); return result; } /// <summary>State used when the stream is in async mode.</summary> private sealed class AsyncState : SemaphoreSlim { internal ReadOnlyMemory<byte> ReadOnlyMemory; internal Memory<byte> Memory; /// <summary>Initialize the AsyncState.</summary> internal AsyncState() : base(initialCount: 1, maxCount: 1) { } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace System.Drawing.Graphics { internal class DLLImports { const int gdMaxColors = 256; enum gdInterpolationMethod { GD_DEFAULT = 0, GD_BELL, GD_BESSEL, GD_BILINEAR_FIXED, GD_BICUBIC, GD_BICUBIC_FIXED, GD_BLACKMAN, GD_BOX, GD_BSPLINE, GD_CATMULLROM, GD_GAUSSIAN, GD_GENERALIZED_CUBIC, GD_HERMITE, GD_HAMMING, GD_HANNING, GD_MITCHELL, GD_NEAREST_NEIGHBOUR, GD_POWER, GD_QUADRATIC, GD_SINC, GD_TRIANGLE, GD_WEIGHTED4, GD_METHOD_COUNT = 21 }; public delegate double interpolation_method(double param0); [StructLayout(LayoutKind.Sequential)] //[CLSCompliant(false)] unsafe internal struct gdImageStruct { public byte** pixels; //public IntPtr pixels; public int sx; public int sy; public int colorsTotal; public fixed int red[gdMaxColors]; public fixed int green[gdMaxColors]; public fixed int blue[gdMaxColors]; public fixed int open[gdMaxColors]; public int transparent; public IntPtr polyInts; public int polyAllocated; IntPtr brush; IntPtr tile; public fixed int brushColorMap[gdMaxColors]; public fixed int tileColorMap[gdMaxColors]; public int styleLength; public int stylePos; public IntPtr style; public int interlace; public int thick; public fixed int alpha[gdMaxColors]; public int trueColor; public int** tpixels; public int alphaBlendingFlag; public int saveAlphaFlag; public int AA; public int AA_color; public int AA_dont_blend; public int cx1; public int cy1; public int cx2; public int cy2; public uint res_x; public uint res_y; public int paletteQuantizationMethod; public int paletteQuantizationSpeed; public int paletteQuantizationMinQuality; public int paletteQuantizationMaxQuality; //gdInterpolationMethod interpolation_id; //interpolation_method interpolation; } [DllImport(Interop.LibGDBinary, CharSet = CharSet.Ansi)] internal static extern bool gdSupportsFileType(string filename, bool writing); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern IntPtr gdImageCreate(int sx, int sy); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern IntPtr gdImageCreateTrueColor(int sx, int sy); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode, EntryPoint = Interop.LibGDColorAllocateEntryPoint)] internal static extern int gdImageColorAllocate(int r, int b, int g); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Ansi)] internal static extern IntPtr gdImageCreateFromFile(string filename); //had to use mangled name here [DllImport(Interop.LibGDBinary, CharSet = CharSet.Ansi, EntryPoint = Interop.LibGDImageFileEntryPoint)] internal static extern bool gdImageFile(IntPtr image, string filename); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageCopyResized(IntPtr destination, IntPtr source, int destinationX, int destinationY, int sourceX, int sourceY, int destinationWidth, int destinationHeight, int sourceWidth, int sourceHeight); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageCopyMerge(IntPtr destination, IntPtr source, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageColorTransparent(IntPtr im, int color); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageSaveAlpha(IntPtr im, int flag); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageAlphaBlending(IntPtr im, int flag); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern int gdImageGetPixel(IntPtr im, int x, int y); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern int gdImageGetTrueColorPixel(IntPtr im, int x, int y); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern void gdImageSetPixel(IntPtr im, int x, int y, int color); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] internal static extern int gdImagePaletteToTrueColor(IntPtr src); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImageCreateFromPngCtxEntryPoint)] public static extern IntPtr gdImageCreateFromPngCtx(ref gdIOCtx @in); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImagePngCtxEntryPoint)] public static extern void gdImagePngCtx(ref gdImageStruct im, ref gdIOCtx @out); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImageCreateFromJpegCtxEntryPoint)] public static extern IntPtr gdImageCreateFromJpegCtx(ref gdIOCtx @in); [DllImport(Interop.LibGDBinary, EntryPoint = Interop.LibGDImageJpegCtxEntryPoint)] public static extern void gdImageJpegCtx(ref gdImageStruct im, ref gdIOCtx @out); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] public static extern void gdImageDestroy(IntPtr im); [DllImport(Interop.LibGDBinary, CharSet = CharSet.Unicode)] public static extern int gdAlphaBlend(int src, int dst); /// Return Type: int ///param0: gdIOCtx* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_getC(IntPtr ctx); /// Return Type: int ///param0: gdIOCtx* ///param1: void* ///param2: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_getBuf(IntPtr ctx, System.IntPtr buf, int wanted); /// Return Type: void ///param0: gdIOCtx* ///param1: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void gdIOCtx_putC(IntPtr ctx, int ch); /// Return Type: int ///param0: gdIOCtx* ///param1: void* ///param2: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_putBuf(IntPtr ctx, System.IntPtr buf, int wanted); /// Return Type: int ///param0: gdIOCtx* ///param1: int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_seek(IntPtr ctx, int pos); /// Return Type: int ///param0: gdIOCtx* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int gdIOCtx_tell(IntPtr ctx); /// Return Type: void ///param0: gdIOCtx* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void gdIOCtx_gd_free(IntPtr param0); [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct gdIOCtx { /// gdIOCtx_getC public gdIOCtx_getC getC; /// gdIOCtx_getBuf public gdIOCtx_getBuf getBuf; /// gdIOCtx_putC public gdIOCtx_putC putC; /// gdIOCtx_putBuf public gdIOCtx_putBuf putBuf; /// gdIOCtx_seek public gdIOCtx_seek seek; /// gdIOCtx_tell public gdIOCtx_tell tell; /// gdIOCtx_gd_free public gdIOCtx_gd_free gd_free; /// void* public System.IntPtr data; } } }
// 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.Contracts; namespace System.Globalization { /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/02/18 2051/02/10 ** TaiwanLunisolar 1912/01/01 2050/13/29 */ [Serializable] public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. internal static EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1912; internal const int MAX_LUNISOLAR_YEAR = 2050; internal const int MIN_GREGORIAN_YEAR = 1912; internal const int MIN_GREGORIAN_MONTH = 2; internal const int MIN_GREGORIAN_DAY = 18; internal const int MAX_GREGORIAN_YEAR = 2051; internal const int MAX_GREGORIAN_MONTH = 2; internal const int MAX_GREGORIAN_DAY = 10; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1911 from ChineseLunisolarCalendar return 384; } } private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1912 */ { 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 */}; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (taiwanLunisolarEraInfo); } } internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MIN_LUNISOLAR_YEAR) || (lunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.TAIWAN); } } internal override CalendarId ID { get { return (CalendarId.TAIWANLUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
#pragma warning disable 162,108,618 using Casanova.Prelude; using System.Linq; using System; using System.Collections.Generic; using Track; using UnityEngine; namespace DyslexiaDetector {public class World : MonoBehaviour{ public static int frame; void Update () { Update(Time.deltaTime, this); frame++; } public bool JustEntered = true; public void Start() { UnityAudio = UnityAudio.Find(); StopGame = false; RunningTutorial = true; PauseMenu = (new Nothing<PauseMenu>()); PauseButton = new PauseButton(); Fox = new Animal("Fox","fox_walking",4,"fox_singing",15,new UnityEngine.Vector3(-0.4f,-7.9f,-0.7f),new UnityEngine.Vector3(-0.4f,-7.9f,-0.7f),new UnityEngine.Vector3(-0.4f,-7.9f,-0.7f)); Foreground = UnityBackground.Find("GroundMid",0f); CurrentTrack = (new Nothing<Track.Item>()); CurrentCheckpoint = (new Nothing<UnityEngine.Transform>()); Button = new Button(); Bird = new Animal("Bird","bird_flying",4,"bird_singing",12,new UnityEngine.Vector3(3f,-7.9f,2f),new UnityEngine.Vector3(-3f,-7.9f,2f),new UnityEngine.Vector3(3f,-7.9f,2f)); Background = UnityBackground.Find("GroundBack",0f); AnimationEnd = false; } public System.Boolean AnimationEnd; public UnityBackground Background; public Animal Bird; public Button Button; public System.Single ClipLength{ get { return UnityAudio.ClipLength; } set{UnityAudio.ClipLength = value; } } public Option<UnityEngine.Transform> CurrentCheckpoint; public Option<Track.Item> CurrentTrack; public UnityBackground Foreground; public Animal Fox; public PauseButton __PauseButton; public PauseButton PauseButton{ get { return __PauseButton; } set{ __PauseButton = value; if(!value.JustEntered) __PauseButton = value; else{ value.JustEntered = false; } } } public Option<PauseMenu> PauseMenu; public System.Boolean RunningTutorial; public System.Boolean StopGame; public UnityAudio UnityAudio; public UnityEngine.Animation animation{ get { return UnityAudio.animation; } } public UnityEngine.AudioSource audio{ get { return UnityAudio.audio; } } public UnityEngine.Camera camera{ get { return UnityAudio.camera; } } public UnityEngine.Collider collider{ get { return UnityAudio.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityAudio.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityAudio.constantForce; } } public System.Boolean enabled{ get { return UnityAudio.enabled; } set{UnityAudio.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityAudio.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityAudio.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityAudio.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityAudio.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityAudio.hideFlags; } set{UnityAudio.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityAudio.hingeJoint; } } public UnityEngine.Light light{ get { return UnityAudio.light; } } public System.String name{ get { return UnityAudio.name; } set{UnityAudio.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityAudio.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityAudio.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityAudio.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityAudio.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityAudio.rigidbody2D; } } public System.String tag{ get { return UnityAudio.tag; } set{UnityAudio.tag = value; } } public UnityEngine.Transform transform{ get { return UnityAudio.transform; } } public System.Boolean useGUILayout{ get { return UnityAudio.useGUILayout; } set{UnityAudio.useGUILayout = value; } } public System.DateTime ___t000; public System.DateTime ___t100; public System.TimeSpan ___dt00; public Track.Item ___item10; public System.Int32 counter121; public System.Single count_down2; public System.String ___texture10; public System.Int32 ___i10; public System.Int32 counter191; public System.Single count_down1; public Track.Item ___item110; public System.Int32 counter51; public System.Collections.Generic.List<System.Collections.Generic.List<Track.Item>> ___elems10; public System.Single count_down4; public System.Single count_down3; public Track.Item ___item21; public UnityEngine.Transform ___item32; public System.Int32 counter13; System.DateTime init_time = System.DateTime.Now; public void Update(float dt, World world) { var t = System.DateTime.Now; Bird.Update(dt, world); Button.Update(dt, world); if(CurrentCheckpoint.IsSome){ } if(CurrentTrack.IsSome){ } Fox.Update(dt, world); PauseButton.Update(dt, world); if(PauseMenu.IsSome){ PauseMenu.Value.Update(dt, world); } this.Rule0(dt, world); this.Rule1(dt, world); this.Rule2(dt, world); this.Rule3(dt, world); this.Rule4(dt, world); this.Rule5(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: if(!(!(RunningTutorial))) { s0 = -1; return; }else { goto case 7; } case 7: if(!(((CurrentTrack.IsSome) && (Fox.Sing)))) { s0 = 7; return; }else { goto case 6; } case 6: if(!(Bird.Sing)) { s0 = 6; return; }else { goto case 5; } case 5: if(!(!(Bird.Sing))) { s0 = 5; return; }else { goto case 4; } case 4: ___t000 = DateTime.Now; goto case 3; case 3: if(!(((((Button.Yes) || (Button.No))) && (!(Bird.Sing))))) { s0 = 3; return; }else { goto case 2; } case 2: ___t100 = DateTime.Now; ___dt00 = ___t100.Subtract(___t000); CurrentTrack.Value.Answer = Button.Yes; CurrentTrack.Value.ResponceTime = ___dt00.TotalSeconds; s0 = -1; return; default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: counter121 = -1; if((((TrackManager.CurrentTutorial).Count) == (0))) { goto case 4; }else { ___item10 = (TrackManager.CurrentTutorial)[0]; goto case 12; } case 12: counter121 = ((counter121) + (1)); if((((((TrackManager.CurrentTutorial).Count) == (counter121))) || (((counter121) > ((TrackManager.CurrentTutorial).Count))))) { goto case 4; }else { ___item10 = (TrackManager.CurrentTutorial)[counter121]; goto case 13; } case 13: CurrentTrack = (new Just<Track.Item>(___item10)); AnimationEnd = true; Button.Yes = Button.Yes; Button.Index = Button.Index; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = true; StopGame = StopGame; s1 = 29; return; case 29: if(!(Bird.Sing)) { s1 = 29; return; }else { goto case 28; } case 28: if(!(!(Bird.Sing))) { s1 = 28; return; }else { goto case 26; } case 26: count_down2 = 2f; goto case 27; case 27: if(((count_down2) > (0f))) { count_down2 = ((count_down2) - (dt)); s1 = 27; return; }else { goto case 25; } case 25: if(___item10.IsSame) { ___texture10 = "yes_frames"; }else { ___texture10 = "no_frames"; } CurrentTrack = CurrentTrack; AnimationEnd = AnimationEnd; Button.Yes = Button.Yes; Button.Index = 0; Button.AnimationNumber = 5; Button.Texture = ___texture10; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 18; return; case 18: counter191 = -1; if((((Enumerable.Range(0,((1) + (((((Button.AnimationNumber) - (1))) - (0))))).ToList<System.Int32>()).Count) == (0))) { goto case 17; }else { ___i10 = (Enumerable.Range(0,((1) + (((((Button.AnimationNumber) - (1))) - (0))))).ToList<System.Int32>())[0]; goto case 19; } case 19: counter191 = ((counter191) + (1)); if((((((Enumerable.Range(0,((1) + (((((Button.AnimationNumber) - (1))) - (0))))).ToList<System.Int32>()).Count) == (counter191))) || (((counter191) > ((Enumerable.Range(0,((1) + (((((Button.AnimationNumber) - (1))) - (0))))).ToList<System.Int32>()).Count))))) { goto case 17; }else { ___i10 = (Enumerable.Range(0,((1) + (((((Button.AnimationNumber) - (1))) - (0))))).ToList<System.Int32>())[counter191]; goto case 20; } case 20: CurrentTrack = CurrentTrack; AnimationEnd = AnimationEnd; Button.Yes = Button.Yes; Button.Index = ___i10; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 21; return; case 21: count_down1 = 0.15f; goto case 22; case 22: if(((count_down1) > (0f))) { count_down1 = ((count_down1) - (dt)); s1 = 22; return; }else { s1 = 19; return; } case 17: CurrentTrack = (new Nothing<Track.Item>()); AnimationEnd = true; Button.Yes = true; Button.Index = 0; Button.AnimationNumber = 1; Button.Texture = "both_up"; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 16; return; case 16: CurrentTrack = CurrentTrack; AnimationEnd = AnimationEnd; Button.Yes = false; Button.Index = Button.Index; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 15; return; case 15: if(!(!(AnimationEnd))) { s1 = 15; return; }else { goto case 14; } case 14: CurrentTrack = CurrentTrack; AnimationEnd = true; Button.Yes = Button.Yes; Button.Index = Button.Index; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 12; return; case 4: counter51 = -1; if((((TrackManager.CurrentExperiment).Count) == (0))) { goto case 3; }else { ___item110 = (TrackManager.CurrentExperiment)[0]; goto case 5; } case 5: counter51 = ((counter51) + (1)); if((((((TrackManager.CurrentExperiment).Count) == (counter51))) || (((counter51) > ((TrackManager.CurrentExperiment).Count))))) { goto case 3; }else { ___item110 = (TrackManager.CurrentExperiment)[counter51]; goto case 6; } case 6: CurrentTrack = (new Just<Track.Item>(___item110)); AnimationEnd = true; Button.Yes = Button.Yes; Button.Index = Button.Index; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 9; return; case 9: CurrentTrack = CurrentTrack; AnimationEnd = true; Button.Yes = Button.Yes; Button.Index = Button.Index; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = false; StopGame = StopGame; s1 = 8; return; case 8: if(!(!(AnimationEnd))) { s1 = 8; return; }else { goto case 7; } case 7: CurrentTrack = CurrentTrack; AnimationEnd = true; Button.Yes = Button.Yes; Button.Index = Button.Index; Button.AnimationNumber = Button.AnimationNumber; Button.Texture = Button.Texture; RunningTutorial = RunningTutorial; StopGame = StopGame; s1 = 5; return; case 3: ___elems10 = TrackManager.ItemsToPlay; Track.TrackManager.SaveAll(); Track.TrackManager.MoveNextExperiment(); UnityEngine.Application.LoadLevel("End"); s1 = -1; return; default: return;}} int s2=-1; public void Rule2(float dt, World world){ switch (s2) { case -1: if(!(AnimationEnd)) { s2 = -1; return; }else { goto case 21; } case 21: AnimationEnd = AnimationEnd; Fox.Walk = true; Fox.Sing = false; Bird.Sing = false; Foreground.RotatingVelocity = -7f; Background.RotatingVelocity = -2f; s2 = 20; return; case 20: if(!(((CurrentCheckpoint.IsSome) && (((1.5f) > (UnityEngine.Vector3.Distance(Fox.Position,CurrentCheckpoint.Value.position))))))) { s2 = 20; return; }else { goto case 19; } case 19: AnimationEnd = AnimationEnd; Fox.Walk = false; Fox.Sing = false; Bird.Sing = false; Foreground.RotatingVelocity = 0f; Background.RotatingVelocity = 0f; s2 = 18; return; case 18: if(!(!(Bird.Walk))) { s2 = 18; return; }else { goto case 17; } case 17: AnimationEnd = AnimationEnd; Fox.Walk = false; Fox.Sing = true; Bird.Sing = false; Foreground.RotatingVelocity = 0f; Background.RotatingVelocity = 0f; s2 = 16; return; case 16: UnityAudio.Play(CurrentTrack.Value.ItemName); count_down4 = ((ClipLength) / (2f)); goto case 15; case 15: if(((count_down4) > (0f))) { count_down4 = ((count_down4) - (dt)); s2 = 15; return; }else { goto case 13; } case 13: AnimationEnd = AnimationEnd; Fox.Walk = false; Fox.Sing = false; Bird.Sing = true; Foreground.RotatingVelocity = Foreground.RotatingVelocity; Background.RotatingVelocity = Background.RotatingVelocity; s2 = 11; return; case 11: count_down3 = ((ClipLength) / (2f)); goto case 12; case 12: if(((count_down3) > (0f))) { count_down3 = ((count_down3) - (dt)); s2 = 12; return; }else { goto case 10; } case 10: AnimationEnd = AnimationEnd; Fox.Walk = false; Fox.Sing = false; Bird.Sing = false; Foreground.RotatingVelocity = Foreground.RotatingVelocity; Background.RotatingVelocity = Background.RotatingVelocity; s2 = 9; return; case 9: ___item21 = CurrentTrack.Value; goto case 8; case 8: if(!(((Button.Yes) || (Button.No)))) { s2 = 8; return; }else { goto case 5; } case 5: if(((___item21.Answer) || (RunningTutorial))) { goto case 3; }else { goto case 4; } case 3: UnityAudio.Play("cheer"); s2 = 2; return; case 4: UnityAudio.Play("boo"); s2 = 2; return; case 2: if(!(Bird.Walk)) { s2 = 2; return; }else { goto case 1; } case 1: if(!(!(Bird.Walk))) { s2 = 1; return; }else { goto case 0; } case 0: AnimationEnd = false; Fox.Walk = Fox.Walk; Fox.Sing = Fox.Sing; Bird.Sing = Bird.Sing; Foreground.RotatingVelocity = Foreground.RotatingVelocity; Background.RotatingVelocity = Background.RotatingVelocity; s2 = -1; return; default: return;}} int s3=-1; public void Rule3(float dt, World world){ switch (s3) { case -1: counter13 = -1; if((((Foreground.CheckPoints).Count) == (0))) { s3 = -1; return; }else { ___item32 = (Foreground.CheckPoints)[0]; goto case 1; } case 1: counter13 = ((counter13) + (1)); if((((((Foreground.CheckPoints).Count) == (counter13))) || (((counter13) > ((Foreground.CheckPoints).Count))))) { s3 = -1; return; }else { ___item32 = (Foreground.CheckPoints)[counter13]; goto case 2; } case 2: if(!(!(StopGame))) { s3 = 2; return; }else { goto case 14; } case 14: CurrentCheckpoint = (new Just<UnityEngine.Transform>(___item32)); Bird.Walk = true; Bird.Position = Bird.Position; Bird.Destination = Bird.Destination; s3 = 13; return; case 13: if(!(Fox.Walk)) { s3 = 13; return; }else { goto case 12; } case 12: if(!(!(Fox.Walk))) { s3 = 12; return; }else { goto case 11; } case 11: CurrentCheckpoint = CurrentCheckpoint; Bird.Walk = Bird.Walk; Bird.Position = Bird.Enter; Bird.Destination = ___item32.position; s3 = 10; return; case 10: if(!(((0.1f) > (UnityEngine.Vector3.Distance(Bird.Position,___item32.position))))) { s3 = 10; return; }else { goto case 9; } case 9: CurrentCheckpoint = CurrentCheckpoint; Bird.Walk = false; Bird.Position = Bird.Destination; Bird.Destination = Bird.Destination; s3 = 8; return; case 8: if(!(Bird.Sing)) { s3 = 8; return; }else { goto case 7; } case 7: if(!(!(Bird.Sing))) { s3 = 7; return; }else { goto case 6; } case 6: if(!(((Button.Yes) || (Button.No)))) { s3 = 6; return; }else { goto case 5; } case 5: CurrentCheckpoint = CurrentCheckpoint; Bird.Walk = true; Bird.Position = Bird.Position; Bird.Destination = Bird.Exit; s3 = 4; return; case 4: if(!(((0.1f) > (UnityEngine.Vector3.Distance(Bird.Position,Bird.Exit))))) { s3 = 4; return; }else { goto case 3; } case 3: CurrentCheckpoint = (new Nothing<UnityEngine.Transform>()); Bird.Walk = false; Bird.Position = Bird.Exit; Bird.Destination = Bird.Destination; s3 = 1; return; default: return;}} int s4=-1; public void Rule4(float dt, World world){ switch (s4) { case -1: if(!(((PauseMenu.IsSome) && (PauseMenu.Value.Resume)))) { s4 = -1; return; }else { goto case 1; } case 1: UnityAudio.Resume(); PauseMenu.Value.Destroyed = true; PauseMenu = (new Nothing<PauseMenu>()); Time.timeScale = 1f; s4 = -1; return; default: return;}} int s5=-1; public void Rule5(float dt, World world){ switch (s5) { case -1: if(!(PauseButton.Pressed)) { s5 = -1; return; }else { goto case 2; } case 2: PauseMenu = (new Just<PauseMenu>(new PauseMenu())); Time.timeScale = 0f; s5 = 1; return; case 1: UnityAudio.Pause(); goto case 0; case 0: if(!(!(PauseButton.Pressed))) { s5 = 0; return; }else { s5 = -1; return; } default: return;}} } public class Button{ public int frame; public bool JustEntered = true; public int ID; public Button() {JustEntered = false; frame = World.frame; Yes = false; UnityYesNo = UnityYesNo.Find(1); No = false; } public System.Int32 AnimationNumber{ get { return UnityYesNo.AnimationNumber; } set{UnityYesNo.AnimationNumber = value; } } public System.Int32 Index{ get { return UnityYesNo.Index; } set{UnityYesNo.Index = value; } } public System.Boolean IsNoPressed{ get { return UnityYesNo.IsNoPressed; } } public System.Boolean IsYesPressed{ get { return UnityYesNo.IsYesPressed; } } public System.Boolean No; public System.String Texture{ get { return UnityYesNo.Texture; } set{UnityYesNo.Texture = value; } } public UnityYesNo UnityYesNo; public System.Boolean Yes; public UnityEngine.Animation animation{ get { return UnityYesNo.animation; } } public UnityEngine.AudioSource audio{ get { return UnityYesNo.audio; } } public UnityEngine.Camera camera{ get { return UnityYesNo.camera; } } public System.Int32 colCount{ get { return UnityYesNo.colCount; } set{UnityYesNo.colCount = value; } } public UnityEngine.Collider collider{ get { return UnityYesNo.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityYesNo.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityYesNo.constantForce; } } public System.Boolean enabled{ get { return UnityYesNo.enabled; } set{UnityYesNo.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityYesNo.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityYesNo.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityYesNo.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityYesNo.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityYesNo.hideFlags; } set{UnityYesNo.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityYesNo.hingeJoint; } } public UnityEngine.Light light{ get { return UnityYesNo.light; } } public System.String name{ get { return UnityYesNo.name; } set{UnityYesNo.name = value; } } public UnityEngine.Transform noButton{ get { return UnityYesNo.noButton; } set{UnityYesNo.noButton = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityYesNo.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityYesNo.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityYesNo.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityYesNo.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityYesNo.rigidbody2D; } } public System.String tag{ get { return UnityYesNo.tag; } set{UnityYesNo.tag = value; } } public UnityEngine.Transform transform{ get { return UnityYesNo.transform; } } public System.Boolean useGUILayout{ get { return UnityYesNo.useGUILayout; } set{UnityYesNo.useGUILayout = value; } } public UnityEngine.Transform yesButton{ get { return UnityYesNo.yesButton; } set{UnityYesNo.yesButton = value; } } public System.Single count_down5; public System.Single count_down6; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); this.Rule1(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: Texture = "both_up"; Yes = false; s0 = 3; return; case 3: if(!(((((!(world.RunningTutorial)) && (UnityEngine.Input.GetMouseButtonDown(0)))) && (IsYesPressed)))) { s0 = 3; return; }else { goto case 2; } case 2: Texture = "Yes_down"; Yes = true; s0 = 0; return; case 0: count_down5 = 0.1f; goto case 1; case 1: if(((count_down5) > (0f))) { count_down5 = ((count_down5) - (dt)); s0 = 1; return; }else { s0 = -1; return; } default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: Texture = "both_up"; No = false; s1 = 3; return; case 3: if(!(((((!(world.RunningTutorial)) && (UnityEngine.Input.GetMouseButtonDown(0)))) && (IsNoPressed)))) { s1 = 3; return; }else { goto case 2; } case 2: Texture = "No_down"; No = true; s1 = 0; return; case 0: count_down6 = 0.1f; goto case 1; case 1: if(((count_down6) > (0f))) { count_down6 = ((count_down6) - (dt)); s1 = 1; return; }else { s1 = -1; return; } default: return;}} } public class PauseButton{ public int frame; public bool JustEntered = true; public int ID; public PauseButton() {JustEntered = false; frame = World.frame; UnityPause = UnityPause.Find(); Pressed = false; } public System.Boolean IsPausePressed{ get { return UnityPause.IsPausePressed; } } public System.Boolean Pressed; public System.String Texture{ get { return UnityPause.Texture; } set{UnityPause.Texture = value; } } public UnityPause UnityPause; public UnityEngine.Animation animation{ get { return UnityPause.animation; } } public UnityEngine.AudioSource audio{ get { return UnityPause.audio; } } public UnityEngine.Camera camera{ get { return UnityPause.camera; } } public UnityEngine.Collider collider{ get { return UnityPause.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityPause.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityPause.constantForce; } } public System.Boolean enabled{ get { return UnityPause.enabled; } set{UnityPause.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityPause.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityPause.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityPause.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityPause.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityPause.hideFlags; } set{UnityPause.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityPause.hingeJoint; } } public UnityEngine.Light light{ get { return UnityPause.light; } } public System.String name{ get { return UnityPause.name; } set{UnityPause.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityPause.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityPause.particleSystem; } } public UnityEngine.Transform pauseButton{ get { return UnityPause.pauseButton; } set{UnityPause.pauseButton = value; } } public UnityEngine.Renderer renderer{ get { return UnityPause.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityPause.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityPause.rigidbody2D; } } public System.String tag{ get { return UnityPause.tag; } set{UnityPause.tag = value; } } public UnityEngine.Transform transform{ get { return UnityPause.transform; } } public System.Boolean useGUILayout{ get { return UnityPause.useGUILayout; } set{UnityPause.useGUILayout = value; } } public System.Single count_down7; public void Update(float dt, World world) { frame = World.frame; this.Rule0(dt, world); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: Texture = "PauseButton"; Pressed = false; s0 = 3; return; case 3: if(!(((UnityEngine.Input.GetMouseButtonDown(0)) && (IsPausePressed)))) { s0 = 3; return; }else { goto case 2; } case 2: Texture = "PauseButton_down"; Pressed = true; s0 = 0; return; case 0: count_down7 = 0.1f; goto case 1; case 1: if(((count_down7) > (0f))) { count_down7 = ((count_down7) - (dt)); s0 = 1; return; }else { s0 = -1; return; } default: return;}} } public class PauseMenu{ public int frame; public bool JustEntered = true; public int ID; public PauseMenu() {JustEntered = false; frame = World.frame; UnityPauseMenu = UnityPauseMenu.Instantiate(); } public System.Boolean Destroyed{ get { return UnityPauseMenu.Destroyed; } set{UnityPauseMenu.Destroyed = value; } } public System.Boolean Resume{ get { return UnityPauseMenu.Resume; } set{UnityPauseMenu.Resume = value; } } public UnityPauseMenu UnityPauseMenu; public UnityEngine.Animation animation{ get { return UnityPauseMenu.animation; } } public UnityEngine.AudioSource audio{ get { return UnityPauseMenu.audio; } } public UnityEngine.Camera camera{ get { return UnityPauseMenu.camera; } } public UnityEngine.Collider collider{ get { return UnityPauseMenu.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityPauseMenu.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityPauseMenu.constantForce; } } public System.Boolean enabled{ get { return UnityPauseMenu.enabled; } set{UnityPauseMenu.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityPauseMenu.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityPauseMenu.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityPauseMenu.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityPauseMenu.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityPauseMenu.hideFlags; } set{UnityPauseMenu.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityPauseMenu.hingeJoint; } } public UnityEngine.Light light{ get { return UnityPauseMenu.light; } } public System.String name{ get { return UnityPauseMenu.name; } set{UnityPauseMenu.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityPauseMenu.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityPauseMenu.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityPauseMenu.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityPauseMenu.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityPauseMenu.rigidbody2D; } } public System.String tag{ get { return UnityPauseMenu.tag; } set{UnityPauseMenu.tag = value; } } public UnityEngine.Transform transform{ get { return UnityPauseMenu.transform; } } public System.Boolean useGUILayout{ get { return UnityPauseMenu.useGUILayout; } set{UnityPauseMenu.useGUILayout = value; } } public void Update(float dt, World world) { frame = World.frame; } } public class Animal{ public int frame; public bool JustEntered = true; private System.String animal; private System.String walkTexture; private System.Int32 walkTextureFrames; private System.String singTexture; private System.Int32 singTextureFrames; private UnityEngine.Vector3 enter; private UnityEngine.Vector3 exit; private UnityEngine.Vector3 destination; public int ID; public Animal(System.String animal, System.String walkTexture, System.Int32 walkTextureFrames, System.String singTexture, System.Int32 singTextureFrames, UnityEngine.Vector3 enter, UnityEngine.Vector3 exit, UnityEngine.Vector3 destination) {JustEntered = false; frame = World.frame; WalkTextureFrames = walkTextureFrames; WalkTexture = walkTexture; Walk = false; UnityAnimal = UnityAnimal.Find(animal,walkTextureFrames,enter); SingTextureFrames = singTextureFrames; SingTexture = singTexture; Sing = false; Exit = exit; Enter = enter; Destination = destination; } public System.String AnimalTexture{ get { return UnityAnimal.AnimalTexture; } set{UnityAnimal.AnimalTexture = value; } } public System.Int32 AnimationIndex{ get { return UnityAnimal.AnimationIndex; } set{UnityAnimal.AnimationIndex = value; } } public System.Int32 AnimationNumber{ get { return UnityAnimal.AnimationNumber; } set{UnityAnimal.AnimationNumber = value; } } public UnityEngine.Vector3 Destination; public UnityEngine.Vector3 Enter; public UnityEngine.Vector3 Exit; public UnityEngine.Vector3 Position{ get { return UnityAnimal.Position; } set{UnityAnimal.Position = value; } } public System.Boolean Sing; public System.String SingTexture; public System.Int32 SingTextureFrames; public UnityAnimal UnityAnimal; public UnityEngine.Vector3 Velocity{ get { return UnityAnimal.Velocity; } set{UnityAnimal.Velocity = value; } } public System.Boolean Walk; public System.String WalkTexture; public System.Int32 WalkTextureFrames; public UnityEngine.Animation animation{ get { return UnityAnimal.animation; } } public UnityEngine.AudioSource audio{ get { return UnityAnimal.audio; } } public UnityEngine.Camera camera{ get { return UnityAnimal.camera; } } public System.Int32 colCount{ get { return UnityAnimal.colCount; } set{UnityAnimal.colCount = value; } } public UnityEngine.Collider collider{ get { return UnityAnimal.collider; } } public UnityEngine.Collider2D collider2D{ get { return UnityAnimal.collider2D; } } public UnityEngine.ConstantForce constantForce{ get { return UnityAnimal.constantForce; } } public System.Boolean enabled{ get { return UnityAnimal.enabled; } set{UnityAnimal.enabled = value; } } public UnityEngine.GameObject gameObject{ get { return UnityAnimal.gameObject; } } public UnityEngine.GUIElement guiElement{ get { return UnityAnimal.guiElement; } } public UnityEngine.GUIText guiText{ get { return UnityAnimal.guiText; } } public UnityEngine.GUITexture guiTexture{ get { return UnityAnimal.guiTexture; } } public UnityEngine.HideFlags hideFlags{ get { return UnityAnimal.hideFlags; } set{UnityAnimal.hideFlags = value; } } public UnityEngine.HingeJoint hingeJoint{ get { return UnityAnimal.hingeJoint; } } public UnityEngine.Light light{ get { return UnityAnimal.light; } } public System.String name{ get { return UnityAnimal.name; } set{UnityAnimal.name = value; } } public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityAnimal.particleEmitter; } } public UnityEngine.ParticleSystem particleSystem{ get { return UnityAnimal.particleSystem; } } public UnityEngine.Renderer renderer{ get { return UnityAnimal.renderer; } } public UnityEngine.Rigidbody rigidbody{ get { return UnityAnimal.rigidbody; } } public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityAnimal.rigidbody2D; } } public System.String tag{ get { return UnityAnimal.tag; } set{UnityAnimal.tag = value; } } public UnityEngine.Transform transform{ get { return UnityAnimal.transform; } } public System.Boolean useGUILayout{ get { return UnityAnimal.useGUILayout; } set{UnityAnimal.useGUILayout = value; } } public System.Int32 ___i01; public System.Int32 counter130; public System.Single count_down9; public System.Int32 ___i02; public System.Int32 counter30; public System.Single count_down8; public System.Single count_down10; public void Update(float dt, World world) { frame = World.frame; this.Rule2(dt, world); this.Rule0(dt, world); this.Rule1(dt, world); } public void Rule2(float dt, World world) { Position = (Position) + ((Velocity) * (dt)); } int s0=-1; public void Rule0(float dt, World world){ switch (s0) { case -1: AnimationIndex = 0; AnimationNumber = WalkTextureFrames; AnimalTexture = WalkTexture; s0 = 18; return; case 18: if(!(Walk)) { s0 = 18; return; }else { goto case 10; } case 10: if(!(Walk)) { goto case 9; }else { goto case 11; } case 11: counter130 = -1; if((((Enumerable.Range(0,((1) + (((((WalkTextureFrames) - (1))) - (0))))).ToList<System.Int32>()).Count) == (0))) { s0 = 10; return; }else { ___i01 = (Enumerable.Range(0,((1) + (((((WalkTextureFrames) - (1))) - (0))))).ToList<System.Int32>())[0]; goto case 13; } case 13: counter130 = ((counter130) + (1)); if((((((Enumerable.Range(0,((1) + (((((WalkTextureFrames) - (1))) - (0))))).ToList<System.Int32>()).Count) == (counter130))) || (((counter130) > ((Enumerable.Range(0,((1) + (((((WalkTextureFrames) - (1))) - (0))))).ToList<System.Int32>()).Count))))) { s0 = 10; return; }else { ___i01 = (Enumerable.Range(0,((1) + (((((WalkTextureFrames) - (1))) - (0))))).ToList<System.Int32>())[counter130]; goto case 14; } case 14: AnimationIndex = ___i01; AnimationNumber = AnimationNumber; AnimalTexture = AnimalTexture; s0 = 15; return; case 15: count_down9 = 0.15f; goto case 16; case 16: if(((count_down9) > (0f))) { count_down9 = ((count_down9) - (dt)); s0 = 16; return; }else { s0 = 13; return; } case 9: AnimationIndex = 0; AnimationNumber = SingTextureFrames; AnimalTexture = SingTexture; s0 = 8; return; case 8: if(!(Sing)) { s0 = 8; return; }else { goto case 0; } case 0: if(!(Sing)) { s0 = -1; return; }else { goto case 1; } case 1: counter30 = -1; if((((Enumerable.Range(0,((1) + (((((SingTextureFrames) - (1))) - (0))))).ToList<System.Int32>()).Count) == (0))) { s0 = 0; return; }else { ___i02 = (Enumerable.Range(0,((1) + (((((SingTextureFrames) - (1))) - (0))))).ToList<System.Int32>())[0]; goto case 3; } case 3: counter30 = ((counter30) + (1)); if((((((Enumerable.Range(0,((1) + (((((SingTextureFrames) - (1))) - (0))))).ToList<System.Int32>()).Count) == (counter30))) || (((counter30) > ((Enumerable.Range(0,((1) + (((((SingTextureFrames) - (1))) - (0))))).ToList<System.Int32>()).Count))))) { s0 = 0; return; }else { ___i02 = (Enumerable.Range(0,((1) + (((((SingTextureFrames) - (1))) - (0))))).ToList<System.Int32>())[counter30]; goto case 4; } case 4: AnimationIndex = ___i02; AnimationNumber = AnimationNumber; AnimalTexture = AnimalTexture; s0 = 5; return; case 5: count_down8 = 0.08f; goto case 6; case 6: if(((count_down8) > (0f))) { count_down8 = ((count_down8) - (dt)); s0 = 6; return; }else { s0 = 3; return; } default: return;}} int s1=-1; public void Rule1(float dt, World world){ switch (s1) { case -1: count_down10 = 0f; goto case 6; case 6: if(((count_down10) > (0f))) { count_down10 = ((count_down10) - (dt)); s1 = 6; return; }else { goto case 2; } case 2: if(((UnityEngine.Vector3.Distance(Position,Destination)) > (0.1f))) { goto case 0; }else { goto case 1; } case 0: Velocity = ((Destination) - (Position)); s1 = -1; return; case 1: Velocity = Vector3.zero; s1 = -1; return; default: return;}} } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using Data; using Data.Scans; using NationalInstruments.DAQmx; using DAQ.Environment; using DAQ.HAL; using DAQ.Remoting; using System.Windows.Forms; namespace DecelerationLaserLock { /// <summary> /// A class for controlling the laser frequency. Contains a method for locking the laser to a stabilized /// reference cavity. /// </summary> public class LaserController : MarshalByRefObject { private const double UPPER_VOLTAGE_LIMIT = 10.0; //volts private const double LOWER_VOLTAGE_LIMIT = -10.0; //volts private const double UPPER_SETPOINT_LIMIT = 100.0; //volts private const double LOWER_SETPOINT_LIMIT = -100.0; //volts private const int SAMPLES_PER_READ = 10; private const int READS_PER_FEEDBACK = 4; private const int SLEEPING_TIME = 500; //milliseconds private const int LATENCY = 10000; //milliseconds private const int CAVITY_FWHM = 150; //MHz private const double CAVITY_PEAK_HEIGHT = 4.0; //volts private const int LASER_SCAN_CALIBRATION = 200; //MHz/volt private const int HARDWARE_CONTROL_TALK_PERIOD = 2000; //milliseconds private double proportionalGain; private double integralGain; // private double derivativeGain; private double setPoint; private double deviation; private double integratedDeviation; private ScanMaster.Controller scanMaster; private DAQ.Analyze.GaussianFitter fitter; private DecelerationHardwareControl.Controller hardwareControl; private MainForm ui; private Task outputTask; private AnalogOutputChannel laserChannel; private AnalogSingleChannelWriter laserWriter; private Task inputTask; private AnalogInputChannel cavityChannel; private AnalogSingleChannelReader cavityReader; //private AnalogMultiChannelReader cavityReader; private Task inputrefTask; private AnalogInputChannel cavityrefChannel; private AnalogSingleChannelReader cavityrefReader; public enum ControllerState { free, busy, stopping }; private ControllerState status = ControllerState.free; private System.Threading.Timer hardwareControlTimer; private TimerCallback timerDelegate; private double[] latestData; private double[] latestrefData; // without this method, any remote connections to this object will time out after // five minutes of inactivity. // It just overrides the lifetime lease system completely. public override Object InitializeLifetimeService() { return null; } #region Setup public void Start() { proportionalGain = 0; integralGain = 0; // derivativeGain = 0; ui = new MainForm(); ui.controller = this; // get access to ScanMaster and the DecelerationHardwareController RemotingHelper.ConnectScanMaster(); RemotingHelper.ConnectDecelerationHardwareControl(); scanMaster = new ScanMaster.Controller(); hardwareControl = new DecelerationHardwareControl.Controller(); fitter = new DAQ.Analyze.GaussianFitter(); if (!Environs.Debug) { outputTask = new Task("LaserControllerOutput"); laserChannel = (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels["laser"]; laserChannel.AddToTask(outputTask, -10, 10); outputTask.Control(TaskAction.Verify); laserWriter = new AnalogSingleChannelWriter(outputTask.Stream); inputTask = new Task("LaserControllerInput"); cavityChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["lockcavity"]; cavityChannel.AddToTask(inputTask, -10, 10); cavityReader = new AnalogSingleChannelReader(inputTask.Stream); inputrefTask = new Task("ReferenceLaserControllerInput"); cavityrefChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["refcavity"]; cavityrefChannel.AddToTask(inputrefTask, -10, 10); cavityrefReader = new AnalogSingleChannelReader(inputrefTask.Stream); } timerDelegate = new TimerCallback(TalkToHardwareControl); hardwareControlTimer = new System.Threading.Timer(timerDelegate, null, 5000, HARDWARE_CONTROL_TALK_PERIOD); Application.Run(ui); } #endregion #region Public properties public ControllerState Status { get { return status; } set { status = value; } } public double SetPoint { get { return setPoint; } set { setPoint = value; } } // the getter asks the hardware controller for the laser frequency control voltage // the setter sets the value and tells the hardware controller and the front-panel control about it public double LaserVoltage { get { return hardwareControl.LaserFrequencyControlVoltage; } set { if (value >= LOWER_VOLTAGE_LIMIT && value <= UPPER_VOLTAGE_LIMIT) { if (!Environs.Debug) { laserWriter.WriteSingleSample(true, value); outputTask.Control(TaskAction.Unreserve); } else { // Debug mode, do nothing } hardwareControl.LaserFrequencyControlVoltage = value; ui.SetControlVoltageNumericEditorValue(value); } else { // Out of range, do nothing } } } #endregion #region Public methods /// <summary> /// Parks the laser on a resonance. Uses ScanMaster to scan the laser and fit to the spectrum in order /// to locate the resonance. Then adjusts the laser frequency to park the laser on the resonance. /// Note that this method parks but doesn't lock the laser /// </summary> public void Park() { double[] fitresult; ui.AddToTextBox("Attempting to park..." + Environment.NewLine); status = ControllerState.busy; try { scanMaster.AcquireAndWait(ui.ScansPerPark); Scan scan = scanMaster.DataStore.AverageScan; if (scan.Points.Count != 0) { fitresult = FitSpectrum(scan); double centreVoltage = fitresult[2]; double scanStart = (double)scanMaster.GetOutputSetting("start"); double scanEnd = (double)scanMaster.GetOutputSetting("end"); if (centreVoltage > scanStart && centreVoltage < scanEnd) { if (!Environs.Debug) { RampToVoltage(centreVoltage); ui.AddToTextBox("Parked at " + centreVoltage + " volts." + Environment.NewLine); ui.SetControlVoltageNumericEditorValue(centreVoltage); } else ui.AddToTextBox("Ramping to " + centreVoltage + " volts. \n"); } else ui.AddToTextBox("Failed - Unable to locate the resonance." + Environment.NewLine); } else ui.AddToTextBox("Failed - Nothing to fit." + Environment.NewLine); } catch (System.Net.Sockets.SocketException) { ui.AddToTextBox("The connection to ScanMaster was refused. Make sure that ScanMaster is running." + Environment.NewLine); } status = ControllerState.free; } /// <summary> /// Locks the laser to a reference cavity. This method runs continuously until the laser is unlocked. /// When this method is called, the reference cavity is read in order to establish the lock point. /// The reference cavity is then read continuously and adjustments fed-back to the laser. /// </summary> public void Lock() { double singleValue; double singlerefValue; double averageValue = 0; int reads = 0; bool firstTime = true; DateTime oldCavityStamp = new DateTime(); DateTime newCavityStamp = new DateTime(); newCavityStamp = DateTime.Now; status = ControllerState.busy; ui.ControlVoltageEditorEnabledState(false); hardwareControl.LaserLocked = true; hardwareControl.SetAnalogOutputBlockedStatus("laser", true); while (status == ControllerState.busy) { if (!Environs.Debug) { oldCavityStamp = newCavityStamp; // read the cavity if (hardwareControl.AnalogInputsAvailable)//scanmaster not running { singleValue = 0; inputTask.Start(); latestData = cavityReader.ReadMultiSample(SAMPLES_PER_READ); inputTask.Stop(); singlerefValue = 0; inputrefTask.Start(); latestrefData = cavityrefReader.ReadMultiSample(SAMPLES_PER_READ); inputrefTask.Stop(); foreach (double d in latestData) singleValue += d; foreach (double e in latestrefData) singlerefValue += e; singleValue = singleValue / SAMPLES_PER_READ; singlerefValue = singlerefValue / SAMPLES_PER_READ; if (singleValue > 4.7) { hardwareControl.diodeSaturationError(); } else { hardwareControl.diodeSaturation(); } singleValue = singleValue / singlerefValue; newCavityStamp = DateTime.Now; hardwareControl.UpdateLockCavityData(singleValue); //hardwareControl.UpdateLockCavityData(singleValue / singlerefValue); } else { singleValue = hardwareControl.LastCavityData; newCavityStamp = hardwareControl.LastCavityTimeStamp; } // provided the last cavity read is recent, do something with it if (hardwareControl.TimeSinceLastCavityRead < LATENCY && newCavityStamp.CompareTo(oldCavityStamp) != 0) { // if this is the first read since throwing the lock, the result defines the set-point if (firstTime) { integratedDeviation = 0; // make sure we don't have a value that's out of range if (singleValue > UPPER_SETPOINT_LIMIT) singleValue = UPPER_SETPOINT_LIMIT; if (singleValue < LOWER_SETPOINT_LIMIT) singleValue = LOWER_SETPOINT_LIMIT; setPoint = singleValue; ui.SetSetPointNumericEditorValue(setPoint); firstTime = false; } // otherwise, use the last read to update the running average else { averageValue += singleValue; reads++; deviation = averageValue / reads - setPoint; integratedDeviation = integratedDeviation + deviation * hardwareControl.TimeSinceLastCavityRead; } // is it time to feed-back to the laser if (reads != 0 && (reads >= READS_PER_FEEDBACK || ui.SpeedSwitchState)) { averageValue = averageValue / reads; deviation = averageValue - setPoint; LaserVoltage = LaserVoltage + SignOfFeedback * proportionalGain * deviation + integralGain * integratedDeviation; //other terms to go here // update the deviation plot ui.DeviationPlotXYAppend(deviation); // reset the variables averageValue = 0; reads = 0; } } } else { // Debug mode ui.DeviationPlotXYAppend(hardwareControl.LaserFrequencyControlVoltage - setPoint); } Thread.Sleep(SLEEPING_TIME); } // we're out of the while loop - revert to the unlocked state status = ControllerState.free; hardwareControl.LaserLocked = false; ui.ControlVoltageEditorEnabledState(true); hardwareControl.SetAnalogOutputBlockedStatus("laser", false); } public void SetProportionalGain(double frontPanelValue) { // the pre-factor of 0.2 is chosen so that a front-panel setting of 5 (mid-range) is close to the threshold for oscillation // empirical evidence says a value of 0.4 makes 5 the oscillation threshold proportionalGain = 0.4 * CAVITY_FWHM / (CAVITY_PEAK_HEIGHT * LASER_SCAN_CALIBRATION) * frontPanelValue; } public void SetIntegralGain(double frontPanelValue) { // integralGain = proportionalGain / T where T is the integral time. hardwareControl.TimeSinceLastCavityRead is used // below which is probably too short, so prefactor should be << 1 ? integralGain = 0.2 * CAVITY_FWHM / (CAVITY_PEAK_HEIGHT * LASER_SCAN_CALIBRATION * hardwareControl.TimeSinceLastCavityRead) * frontPanelValue; } #endregion #region Private methods private void RampToVoltage(double v) { int steps = 20; int delayAtEachStep = 50; double laserVoltage = hardwareControl.LaserFrequencyControlVoltage; double stepsize = (v - laserVoltage) / steps; for (int i = 1; i <= steps; i++) { laserVoltage += stepsize; laserWriter.WriteSingleSample(true, laserVoltage); hardwareControl.LaserFrequencyControlVoltage = laserVoltage; Thread.Sleep(delayAtEachStep); } outputTask.Control(TaskAction.Unreserve); } private double[] FitSpectrum(Scan s) { double[] xDat = s.ScanParameterArray; double scanStart = xDat[0]; double scanEnd = xDat[xDat.Length - 1]; TOF avTof = (TOF)s.GetGatedAverageOnShot(scanStart, scanEnd).TOFs[0]; double gateStart = avTof.GateStartTime; double gateEnd = avTof.GateStartTime + avTof.Length * avTof.ClockPeriod; double[] yDat = s.GetTOFOnIntegralArray(0, gateStart, gateEnd); fitter.Fit(xDat, yDat, fitter.SuggestParameters(xDat, yDat, scanStart, scanEnd)); string report = fitter.ParameterReport; string[] tokens = report.Split(' '); double[] fitresult = new double[4]; for (int i = 0; i < fitresult.Length; i++) fitresult[i] = Convert.ToDouble(tokens[2 * i + 1]); return fitresult; } // returns -1 for locking to positve slope, +1 for locking to negative slope private int SignOfFeedback { get { if (ui.SlopeSwitchState) return -1; else return +1; } } private void TalkToHardwareControl(Object stateInfo) { //ui.SetControlVoltageNumericEditorValue = hardwareControl.LaserFrequencyControlVoltage; ui.SetLockCheckBox(hardwareControl.LaserLocked); } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Reflection; using System.Windows.Forms; using System.IO; using WeifenLuo.WinFormsUI.Docking; using DockSample.Customization; namespace DockSample { public partial class MainForm2 : Form { private bool m_bSaveLayout = true; private DeserializeDockContent m_deserializeDockContent; private DummySolutionExplorer m_solutionExplorer = new DummySolutionExplorer(); private DummyPropertyWindow m_propertyWindow = new DummyPropertyWindow(); private DummyToolbox m_toolbox = new DummyToolbox(); private DummyOutputWindow m_outputWindow = new DummyOutputWindow(); private DummyTaskList m_taskList = new DummyTaskList(); public MainForm2() { InitializeComponent(); showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes); RightToLeftLayout = showRightToLeft.Checked; m_solutionExplorer = new DummySolutionExplorer(); m_solutionExplorer.RightToLeftLayout = RightToLeftLayout; m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString); } private void menuItemExit_Click(object sender, System.EventArgs e) { Close(); } private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e) { m_solutionExplorer.Show(dockPanel); } private void menuItemPropertyWindow_Click(object sender, System.EventArgs e) { m_propertyWindow.Show(dockPanel); } private void menuItemToolbox_Click(object sender, System.EventArgs e) { m_toolbox.Show(dockPanel); } private void menuItemOutputWindow_Click(object sender, System.EventArgs e) { m_outputWindow.Show(dockPanel); } private void menuItemTaskList_Click(object sender, System.EventArgs e) { m_taskList.Show(dockPanel); } private void menuItemAbout_Click(object sender, System.EventArgs e) { AboutDialog aboutDialog = new AboutDialog(); aboutDialog.ShowDialog(this); } private IDockContent FindDocument(string text) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { foreach (Form form in MdiChildren) if (form.Text == text) return form as IDockContent; return null; } else { foreach (IDockContent content in dockPanel.Documents) if (content.DockHandler.TabText == text) return content; return null; } } private void menuItemNew_Click(object sender, System.EventArgs e) { DummyDoc dummyDoc = CreateNewDocument(); if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { dummyDoc.MdiParent = this; dummyDoc.Show(); } else dummyDoc.Show(dockPanel); } private DummyDoc CreateNewDocument() { DummyDoc dummyDoc = new DummyDoc(); int count = 1; //string text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString(); string text = "Document" + count.ToString(); while (FindDocument(text) != null) { count ++; //text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString(); text = "Document" + count.ToString(); } dummyDoc.Text = text; return dummyDoc; } private DummyDoc CreateNewDocument(string text) { DummyDoc dummyDoc = new DummyDoc(); dummyDoc.Text = text; return dummyDoc; } private void menuItemOpen_Click(object sender, System.EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.InitialDirectory = Application.ExecutablePath; openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*" ; openFile.FilterIndex = 1; openFile.RestoreDirectory = true ; if(openFile.ShowDialog() == DialogResult.OK) { string fullName = openFile.FileName; string fileName = Path.GetFileName(fullName); if (FindDocument(fileName) != null) { MessageBox.Show("The document: " + fileName + " has already opened!"); return; } DummyDoc dummyDoc = new DummyDoc(); dummyDoc.Text = fileName; dummyDoc.Show(dockPanel); try { dummyDoc.FileName = fullName; } catch (Exception exception) { dummyDoc.Close(); MessageBox.Show(exception.Message); } } } private void menuItemFile_Popup(object sender, System.EventArgs e) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { menuItemClose.Enabled = menuItemCloseAll.Enabled = (ActiveMdiChild != null); } else { menuItemClose.Enabled = (dockPanel.ActiveDocument != null); menuItemCloseAll.Enabled = (dockPanel.DocumentsCount > 0); } } private void menuItemClose_Click(object sender, System.EventArgs e) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) ActiveMdiChild.Close(); else if (dockPanel.ActiveDocument != null) dockPanel.ActiveDocument.DockHandler.Close(); } private void menuItemCloseAll_Click(object sender, System.EventArgs e) { CloseAllDocuments(); } private void CloseAllDocuments() { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { foreach (Form form in MdiChildren) form.Close(); } else { IDockContent[] documents = dockPanel.DocumentsToArray(); foreach (IDockContent content in documents) content.DockHandler.Close(); } } private IDockContent GetContentFromPersistString(string persistString) { if (persistString == typeof(DummySolutionExplorer).ToString()) return m_solutionExplorer; else if (persistString == typeof(DummyPropertyWindow).ToString()) return m_propertyWindow; else if (persistString == typeof(DummyToolbox).ToString()) return m_toolbox; else if (persistString == typeof(DummyOutputWindow).ToString()) return m_outputWindow; else if (persistString == typeof(DummyTaskList).ToString()) return m_taskList; else { string[] parsedStrings = persistString.Split(new char[] { ',' }); if (parsedStrings.Length != 3) return null; if (parsedStrings[0] != typeof(DummyDoc).ToString()) return null; DummyDoc dummyDoc = new DummyDoc(); if (parsedStrings[1] != string.Empty) dummyDoc.FileName = parsedStrings[1]; if (parsedStrings[2] != string.Empty) dummyDoc.Text = parsedStrings[2]; return dummyDoc; } } private void MainForm_Load(object sender, System.EventArgs e) { string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config"); if (File.Exists(configFile)) dockPanel.LoadFromXml(configFile, m_deserializeDockContent); } private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config"); if (m_bSaveLayout) dockPanel.SaveAsXml(configFile); else if (File.Exists(configFile)) File.Delete(configFile); } private void menuItemToolBar_Click(object sender, System.EventArgs e) { toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked; } private void menuItemStatusBar_Click(object sender, System.EventArgs e) { statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked; } private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e) { if (e.ClickedItem == toolBarButtonNew) menuItemNew_Click(null, null); else if (e.ClickedItem == toolBarButtonOpen) menuItemOpen_Click(null, null); else if (e.ClickedItem == toolBarButtonSolutionExplorer) menuItemSolutionExplorer_Click(null, null); else if (e.ClickedItem == toolBarButtonPropertyWindow) menuItemPropertyWindow_Click(null, null); else if (e.ClickedItem == toolBarButtonToolbox) menuItemToolbox_Click(null, null); else if (e.ClickedItem == toolBarButtonOutputWindow) menuItemOutputWindow_Click(null, null); else if (e.ClickedItem == toolBarButtonTaskList) menuItemTaskList_Click(null, null); else if (e.ClickedItem == toolBarButtonLayoutByCode) menuItemLayoutByCode_Click(null, null); else if (e.ClickedItem == toolBarButtonLayoutByXml) menuItemLayoutByXml_Click(null, null); } private void menuItemNewWindow_Click(object sender, System.EventArgs e) { MainForm newWindow = new MainForm(); newWindow.Text = newWindow.Text + " - New"; newWindow.Show(); } private void menuItemTools_Popup(object sender, System.EventArgs e) { menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking; } private void menuItemLockLayout_Click(object sender, System.EventArgs e) { dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking; } private void menuItemLayoutByCode_Click(object sender, System.EventArgs e) { dockPanel.SuspendLayout(true); m_solutionExplorer.Show(dockPanel, DockState.DockRight); m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer); m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383)); m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35); m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4); CloseAllDocuments(); DummyDoc doc1 = CreateNewDocument("Document1"); DummyDoc doc2 = CreateNewDocument("Document2"); DummyDoc doc3 = CreateNewDocument("Document3"); DummyDoc doc4 = CreateNewDocument("Document4"); doc1.Show(dockPanel, DockState.Document); doc2.Show(doc1.Pane, null); doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5); doc4.Show(doc3.Pane, DockAlignment.Right, 0.5); dockPanel.ResumeLayout(true, true); } private void menuItemLayoutByXml_Click(object sender, System.EventArgs e) { dockPanel.SuspendLayout(true); // In order to load layout from XML, we need to close all the DockContents CloseAllContents(); Assembly assembly = Assembly.GetAssembly(typeof(MainForm)); Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml"); dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent); xmlStream.Close(); dockPanel.ResumeLayout(true, true); } private void CloseAllContents() { // we don't want to create another instance of tool window, set DockPanel to null m_solutionExplorer.DockPanel = null; m_propertyWindow.DockPanel = null; m_toolbox.DockPanel = null; m_outputWindow.DockPanel = null; m_taskList.DockPanel = null; // Close all other document windows CloseAllDocuments(); } private void SetSchema(object sender, System.EventArgs e) { CloseAllContents(); if (sender == menuItemSchemaVS2005) Extender.SetSchema(dockPanel, Extender.Schema.VS2005); else if (sender == menuItemSchemaVS2003) Extender.SetSchema(dockPanel, Extender.Schema.VS2003); menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005); menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003); } private void SetDocumentStyle(object sender, System.EventArgs e) { DocumentStyle oldStyle = dockPanel.DocumentStyle; DocumentStyle newStyle; if (sender == menuItemDockingMdi) newStyle = DocumentStyle.DockingMdi; else if (sender == menuItemDockingWindow) newStyle = DocumentStyle.DockingWindow; else if (sender == menuItemDockingSdi) newStyle = DocumentStyle.DockingSdi; else newStyle = DocumentStyle.SystemMdi; if (oldStyle == newStyle) return; if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi) CloseAllDocuments(); dockPanel.DocumentStyle = newStyle; menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi); menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow); menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi); menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi); menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi); menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi); toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi); toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi); } private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form activeMdi = ActiveMdiChild; foreach (Form form in MdiChildren) { if (form != activeMdi) form.Close(); } } else { foreach (IDockContent document in dockPanel.DocumentsToArray()) { if (!document.DockHandler.IsActivated) document.DockHandler.Close(); } } } private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e) { dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked= !menuItemShowDocumentIcon.Checked; } private void showRightToLeft_Click(object sender, EventArgs e) { CloseAllContents(); if (showRightToLeft.Checked) { this.RightToLeft = RightToLeft.No; this.RightToLeftLayout = false; } else { this.RightToLeft = RightToLeft.Yes; this.RightToLeftLayout = true; } m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout; showRightToLeft.Checked = !showRightToLeft.Checked; } private void exitWithoutSavingLayout_Click(object sender, EventArgs e) { m_bSaveLayout = false; Close(); m_bSaveLayout = true; } } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEngine.EventSystems; using DaydreamElements.Common; namespace DaydreamElements.ClickMenu { /// This script is attached to the game object responsible for spawning /// the click menu. public class ClickMenuRoot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { /// The position and orientation of the menu. private Vector3 menuCenter; private Quaternion menuOrientation; private ClickMenuIcon dummyParent; private bool selected; public delegate void MenuOpenedEvent(); public event MenuOpenedEvent OnMenuOpened; public delegate void MenuClosedEvent(); public event MenuClosedEvent OnMenuClosed; public delegate void ItemSelectedEvent(ClickMenuItem id); public event ItemSelectedEvent OnItemSelected; public delegate void ItemHoveredEvent(ClickMenuItem id); public event ItemHoveredEvent OnItemHovered; [Tooltip("The tree of menu items")] public ClickMenuTree menuTree; public delegate AssetTree.Node OnMenuShowEvent(); public event OnMenuShowEvent OnMenuShow; [Tooltip("(Optional) The center icon")] public Sprite backIcon; [Tooltip("(Optional) Moves reticle closer on hover")] public GvrLaserPointer laserPointer; [Tooltip("(Optional) Background material for the menu")] public Material pieMaterial; [Tooltip("Scale applied to all the icons")] public float iconScale = .1f; [Tooltip("Color for tooltip text")] public Color tooltipTextColor = new Color(0x56, 0x56, 0x56); public enum GvrMenuActivationButton { ClickButtonDown, ClickButtonUp, AppButtonDown, AppButtonUp } [Tooltip("Input event to trigger the menu")] public GvrMenuActivationButton menuActivationButton = GvrMenuActivationButton.ClickButtonDown; [Tooltip("Prefab used for each item in the menu")] public ClickMenuIcon menuIconPrefab; [Tooltip("Maximum number of meters the reticle can move per second.")] [Range(0.1f, 50.0f)] public float reticleDelta = 10.0f; [Tooltip("Distance away from the controller of the menu in meters.")] [Range(0.6f, 5.0f)] public float menuDistance = 0.75f; [Tooltip("Angle away from the menu center to cause a closure.")] [Range(20.0f, 40.0f)] public float closeAngle = 25.0f; [Tooltip("Angle of gaze vs pointer needed to open a menu.")] [Range(30.0f, 50.0f)] public float openFovAngle = 35.0f; /// Scale factor to apply to the menuDistance used to /// determine the max distance of the pointer. Without this scale factor, /// the max distance will fall short of the menu by an increasing amount as the /// pointer moves away from the center of the menu. private const float POINTER_DISTANCE_SCALE = 1.0f; void Awake() { selected = false; } public bool IsMenuOpen() { return dummyParent != null; } /// Determine if the activation button is held down. private bool IsButtonClicked() { switch (menuActivationButton) { case GvrMenuActivationButton.ClickButtonDown: return GvrControllerInput.ClickButtonDown; case GvrMenuActivationButton.ClickButtonUp: return GvrControllerInput.ClickButtonUp; case GvrMenuActivationButton.AppButtonDown: return GvrControllerInput.AppButtonDown; case GvrMenuActivationButton.AppButtonUp: return GvrControllerInput.AppButtonUp; default: return false; } } private void SetMenuLocation() { Vector3 laserEndPt; if (true) { // NOTE:(pv) This original code isn't actually centering on the point clicked! laserEndPt = laserPointer.GetPointAlongPointer(menuDistance); } else { RaycastResult raycastResult = laserPointer.CurrentRaycastResult; if (raycastResult.gameObject != null) { laserEndPt = raycastResult.worldPosition; } else { laserEndPt = laserPointer.GetPointAlongPointer(laserPointer.defaultReticleDistance); } } // Center and orient the menu menuCenter = laserEndPt; Vector3 headRight = Camera.main.transform.right; headRight.y = 0.0f; headRight.Normalize(); Vector3 cameraCenter = Camera.main.transform.position; Vector3 rayFromCamera = (laserEndPt - cameraCenter).normalized; Vector3 up = Vector3.Cross(rayFromCamera, headRight); menuOrientation = Quaternion.LookRotation(rayFromCamera, up); Debug.DrawRay(laserEndPt, menuOrientation.eulerAngles, Color.magenta, 10); } private bool IsMenuInFOV() { Vector3 cameraCenter = Camera.main.transform.position; Vector3 menuDirection = menuCenter - cameraCenter; Vector3 gazeDirection = Camera.main.transform.forward; return Vector3.Angle(menuDirection, gazeDirection) < openFovAngle; } private bool IsPointingAway() { if (!laserPointer.IsAvailable) { return true; } // Get the position and orientation form the arm model Vector3 laserEnd = laserPointer.MaxPointerEndPoint; Vector3 cameraCenter = Camera.main.transform.position; Vector3 menuCenterRelativeToCamera = menuCenter - cameraCenter; Vector3 laserEndRelativeToCamera = laserEnd - cameraCenter; float angle = Vector3.Angle(laserEndRelativeToCamera.normalized, menuCenterRelativeToCamera.normalized); return angle > closeAngle; } public void CloseAll() { selected = false; if (dummyParent) { dummyParent.CloseAll(); Destroy(dummyParent.gameObject); dummyParent = null; if (OnMenuClosed != null) { OnMenuClosed.Invoke(); } } } void Update() { // Update the menu state if it needs to suddenly open or close if (!dummyParent && IsButtonClicked()) { SetMenuLocation(); if (IsMenuInFOV()) { dummyParent = (ClickMenuIcon)Instantiate(menuIconPrefab, transform); dummyParent.menuRoot = this; AssetTree.Node node = null; if (OnMenuShow != null) { node = OnMenuShow(); } if (node == null) { node = menuTree.tree.Root; } ClickMenuIcon.ShowMenu(this, node, dummyParent, menuCenter, menuOrientation, iconScale); dummyParent.SetDummy(); if (OnMenuOpened != null) { OnMenuOpened.Invoke(); } } } else if ((GvrControllerInput.ClickButtonDown && !selected) || IsPointingAway()) { CloseAll(); } else if (dummyParent && GvrControllerInput.AppButtonUp) { MakeSelection(null); dummyParent.DeepestMenu().ShowParentMenu(); } } public void OnPointerEnter(PointerEventData eventData) { selected = true; } public void OnPointerExit(PointerEventData eventData) { selected = false; } public void MakeSelection(ClickMenuItem item) { if (OnItemSelected != null) { OnItemSelected.Invoke(item); } } public void MakeHover(ClickMenuItem item) { if (OnItemHovered != null) { OnItemHovered.Invoke(item); } } } }
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ namespace ArangoDB.Velocypack.Internal.Util { /// <author>Mark - mark at arangodb.com</author> public class ValueLengthUtil { private const int DOUBLE_BYTES = 8; private const int LONG_BYTES = 8; private const int CHARACTER_BYTES = 2; private static readonly System.Collections.Generic.IDictionary<byte, int> MAP; static ValueLengthUtil() { MAP = new System.Collections.Generic.Dictionary<byte, int>(); MAP[unchecked((byte)unchecked((int)0x00))] = 1; MAP[unchecked((byte)unchecked((int)0x01))] = 1; MAP[unchecked((byte)unchecked((int)0x02))] = 0; MAP[unchecked((byte)unchecked((int)0x03))] = 0; MAP[unchecked((byte)unchecked((int)0x04))] = 0; MAP[unchecked((byte)unchecked((int)0x05))] = 0; MAP[unchecked((byte)unchecked((int)0x06))] = 0; MAP[unchecked((byte)unchecked((int)0x07))] = 0; MAP[unchecked((byte)unchecked((int)0x08))] = 0; MAP[unchecked((byte)unchecked((int)0x09))] = 0; MAP[unchecked((byte)unchecked((int)0x0a))] = 1; MAP[unchecked((byte)unchecked((int)0x0b))] = 0; MAP[unchecked((byte)unchecked((int)0x0c))] = 0; MAP[unchecked((byte)unchecked((int)0x0d))] = 0; MAP[unchecked((byte)unchecked((int)0x0e))] = 0; MAP[unchecked((byte)unchecked((int)0x0f))] = 0; MAP[unchecked((byte)unchecked((int)0x10))] = 0; MAP[unchecked((byte)unchecked((int)0x11))] = 0; MAP[unchecked((byte)unchecked((int)0x12))] = 0; MAP[unchecked((byte)unchecked((int)0x13))] = 0; MAP[unchecked((byte)unchecked((int)0x14))] = 0; MAP[unchecked((byte)unchecked((int)0x15))] = 0; MAP[unchecked((byte)unchecked((int)0x16))] = 0; MAP[unchecked((byte)unchecked((int)0x17))] = 1; MAP[unchecked((byte)unchecked((int)0x18))] = 1; MAP[unchecked((byte)unchecked((int)0x19))] = 1; MAP[unchecked((byte)unchecked((int)0x1a))] = 1; MAP[unchecked((byte)unchecked((int)0x1b))] = 1 + DOUBLE_BYTES; MAP[unchecked((byte)unchecked((int)0x1c))] = 1 + LONG_BYTES; MAP[unchecked((byte)unchecked((int)0x1d))] = 1 + CHARACTER_BYTES; MAP[unchecked((byte)unchecked((int)0x1e))] = 1; MAP[unchecked((byte)unchecked((int)0x1f))] = 1; MAP[unchecked((byte)unchecked((int)0x20))] = 2; MAP[unchecked((byte)unchecked((int)0x21))] = 3; MAP[unchecked((byte)unchecked((int)0x22))] = 4; MAP[unchecked((byte)unchecked((int)0x23))] = 5; MAP[unchecked((byte)unchecked((int)0x24))] = 6; MAP[unchecked((byte)unchecked((int)0x25))] = 7; MAP[unchecked((byte)unchecked((int)0x26))] = 8; MAP[unchecked((byte)unchecked((int)0x27))] = 9; MAP[unchecked((byte)unchecked((int)0x28))] = 2; MAP[unchecked((byte)unchecked((int)0x29))] = 3; MAP[unchecked((byte)unchecked((int)0x2a))] = 4; MAP[unchecked((byte)unchecked((int)0x2b))] = 5; MAP[unchecked((byte)unchecked((int)0x2c))] = 6; MAP[unchecked((byte)unchecked((int)0x2d))] = 7; MAP[unchecked((byte)unchecked((int)0x2e))] = 8; MAP[unchecked((byte)unchecked((int)0x2f))] = 9; MAP[unchecked((byte)unchecked((int)0x30))] = 1; MAP[unchecked((byte)unchecked((int)0x31))] = 1; MAP[unchecked((byte)unchecked((int)0x32))] = 1; MAP[unchecked((byte)unchecked((int)0x33))] = 1; MAP[unchecked((byte)unchecked((int)0x34))] = 1; MAP[unchecked((byte)unchecked((int)0x35))] = 1; MAP[unchecked((byte)unchecked((int)0x36))] = 1; MAP[unchecked((byte)unchecked((int)0x37))] = 1; MAP[unchecked((byte)unchecked((int)0x38))] = 1; MAP[unchecked((byte)unchecked((int)0x39))] = 1; MAP[unchecked((byte)unchecked((int)0x3a))] = 1; MAP[unchecked((byte)unchecked((int)0x3b))] = 1; MAP[unchecked((byte)unchecked((int)0x3c))] = 1; MAP[unchecked((byte)unchecked((int)0x3d))] = 1; MAP[unchecked((byte)unchecked((int)0x3e))] = 1; MAP[unchecked((byte)unchecked((int)0x3f))] = 1; MAP[unchecked((byte)unchecked((int)0x40))] = 1; MAP[unchecked((byte)unchecked((int)0x41))] = 2; MAP[unchecked((byte)unchecked((int)0x42))] = 3; MAP[unchecked((byte)unchecked((int)0x43))] = 4; MAP[unchecked((byte)unchecked((int)0x44))] = 5; MAP[unchecked((byte)unchecked((int)0x45))] = 6; MAP[unchecked((byte)unchecked((int)0x46))] = 7; MAP[unchecked((byte)unchecked((int)0x47))] = 8; MAP[unchecked((byte)unchecked((int)0x48))] = 9; MAP[unchecked((byte)unchecked((int)0x49))] = 10; MAP[unchecked((byte)unchecked((int)0x4a))] = 11; MAP[unchecked((byte)unchecked((int)0x4b))] = 12; MAP[unchecked((byte)unchecked((int)0x4c))] = 13; MAP[unchecked((byte)unchecked((int)0x4d))] = 14; MAP[unchecked((byte)unchecked((int)0x4e))] = 15; MAP[unchecked((byte)unchecked((int)0x4f))] = 16; MAP[unchecked((byte)unchecked((int)0x50))] = 17; MAP[unchecked((byte)unchecked((int)0x51))] = 18; MAP[unchecked((byte)unchecked((int)0x52))] = 19; MAP[unchecked((byte)unchecked((int)0x53))] = 20; MAP[unchecked((byte)unchecked((int)0x54))] = 21; MAP[unchecked((byte)unchecked((int)0x55))] = 22; MAP[unchecked((byte)unchecked((int)0x56))] = 23; MAP[unchecked((byte)unchecked((int)0x57))] = 24; MAP[unchecked((byte)unchecked((int)0x58))] = 25; MAP[unchecked((byte)unchecked((int)0x59))] = 26; MAP[unchecked((byte)unchecked((int)0x5a))] = 27; MAP[unchecked((byte)unchecked((int)0x5b))] = 28; MAP[unchecked((byte)unchecked((int)0x5c))] = 29; MAP[unchecked((byte)unchecked((int)0x5d))] = 30; MAP[unchecked((byte)unchecked((int)0x5e))] = 31; MAP[unchecked((byte)unchecked((int)0x5f))] = 32; MAP[unchecked((byte)unchecked((int)0x60))] = 33; MAP[unchecked((byte)unchecked((int)0x61))] = 34; MAP[unchecked((byte)unchecked((int)0x62))] = 35; MAP[unchecked((byte)unchecked((int)0x63))] = 36; MAP[unchecked((byte)unchecked((int)0x64))] = 37; MAP[unchecked((byte)unchecked((int)0x65))] = 38; MAP[unchecked((byte)unchecked((int)0x66))] = 39; MAP[unchecked((byte)unchecked((int)0x67))] = 40; MAP[unchecked((byte)unchecked((int)0x68))] = 41; MAP[unchecked((byte)unchecked((int)0x69))] = 42; MAP[unchecked((byte)unchecked((int)0x6a))] = 43; MAP[unchecked((byte)unchecked((int)0x6b))] = 44; MAP[unchecked((byte)unchecked((int)0x6c))] = 45; MAP[unchecked((byte)unchecked((int)0x6d))] = 46; MAP[unchecked((byte)unchecked((int)0x6e))] = 47; MAP[unchecked((byte)unchecked((int)0x6f))] = 48; MAP[unchecked((byte)unchecked((int)0x70))] = 49; MAP[unchecked((byte)unchecked((int)0x71))] = 50; MAP[unchecked((byte)unchecked((int)0x72))] = 51; MAP[unchecked((byte)unchecked((int)0x73))] = 52; MAP[unchecked((byte)unchecked((int)0x74))] = 53; MAP[unchecked((byte)unchecked((int)0x75))] = 54; MAP[unchecked((byte)unchecked((int)0x76))] = 55; MAP[unchecked((byte)unchecked((int)0x77))] = 56; MAP[unchecked((byte)unchecked((int)0x78))] = 57; MAP[unchecked((byte)unchecked((int)0x79))] = 58; MAP[unchecked((byte)unchecked((int)0x7a))] = 59; MAP[unchecked((byte)unchecked((int)0x7b))] = 60; MAP[unchecked((byte)unchecked((int)0x7c))] = 61; MAP[unchecked((byte)unchecked((int)0x7d))] = 62; MAP[unchecked((byte)unchecked((int)0x7e))] = 63; MAP[unchecked((byte)unchecked((int)0x7f))] = 64; MAP[unchecked((byte)unchecked((int)0x80))] = 65; MAP[unchecked((byte)unchecked((int)0x81))] = 66; MAP[unchecked((byte)unchecked((int)0x82))] = 67; MAP[unchecked((byte)unchecked((int)0x83))] = 68; MAP[unchecked((byte)unchecked((int)0x84))] = 69; MAP[unchecked((byte)unchecked((int)0x85))] = 70; MAP[unchecked((byte)unchecked((int)0x86))] = 71; MAP[unchecked((byte)unchecked((int)0x87))] = 72; MAP[unchecked((byte)unchecked((int)0x88))] = 73; MAP[unchecked((byte)unchecked((int)0x89))] = 74; MAP[unchecked((byte)unchecked((int)0x8a))] = 75; MAP[unchecked((byte)unchecked((int)0x8b))] = 76; MAP[unchecked((byte)unchecked((int)0x8c))] = 77; MAP[unchecked((byte)unchecked((int)0x8d))] = 78; MAP[unchecked((byte)unchecked((int)0x8e))] = 79; MAP[unchecked((byte)unchecked((int)0x8f))] = 80; MAP[unchecked((byte)unchecked((int)0x90))] = 81; MAP[unchecked((byte)unchecked((int)0x91))] = 82; MAP[unchecked((byte)unchecked((int)0x92))] = 83; MAP[unchecked((byte)unchecked((int)0x93))] = 84; MAP[unchecked((byte)unchecked((int)0x94))] = 85; MAP[unchecked((byte)unchecked((int)0x95))] = 86; MAP[unchecked((byte)unchecked((int)0x96))] = 87; MAP[unchecked((byte)unchecked((int)0x97))] = 88; MAP[unchecked((byte)unchecked((int)0x98))] = 89; MAP[unchecked((byte)unchecked((int)0x99))] = 90; MAP[unchecked((byte)unchecked((int)0x9a))] = 91; MAP[unchecked((byte)unchecked((int)0x9b))] = 92; MAP[unchecked((byte)unchecked((int)0x9c))] = 93; MAP[unchecked((byte)unchecked((int)0x9d))] = 94; MAP[unchecked((byte)unchecked((int)0x9e))] = 95; MAP[unchecked((byte)unchecked((int)0x9f))] = 96; MAP[unchecked((byte)unchecked((int)0xa0))] = 97; MAP[unchecked((byte)unchecked((int)0xa1))] = 98; MAP[unchecked((byte)unchecked((int)0xa2))] = 99; MAP[unchecked((byte)unchecked((int)0xa3))] = 100; MAP[unchecked((byte)unchecked((int)0xa4))] = 101; MAP[unchecked((byte)unchecked((int)0xa5))] = 102; MAP[unchecked((byte)unchecked((int)0xa6))] = 103; MAP[unchecked((byte)unchecked((int)0xa7))] = 104; MAP[unchecked((byte)unchecked((int)0xa8))] = 105; MAP[unchecked((byte)unchecked((int)0xa9))] = 106; MAP[unchecked((byte)unchecked((int)0xaa))] = 107; MAP[unchecked((byte)unchecked((int)0xab))] = 108; MAP[unchecked((byte)unchecked((int)0xac))] = 109; MAP[unchecked((byte)unchecked((int)0xad))] = 110; MAP[unchecked((byte)unchecked((int)0xae))] = 111; MAP[unchecked((byte)unchecked((int)0xaf))] = 112; MAP[unchecked((byte)unchecked((int)0xb0))] = 113; MAP[unchecked((byte)unchecked((int)0xb1))] = 114; MAP[unchecked((byte)unchecked((int)0xb2))] = 115; MAP[unchecked((byte)unchecked((int)0xb3))] = 116; MAP[unchecked((byte)unchecked((int)0xb4))] = 117; MAP[unchecked((byte)unchecked((int)0xb5))] = 118; MAP[unchecked((byte)unchecked((int)0xb6))] = 119; MAP[unchecked((byte)unchecked((int)0xb7))] = 120; MAP[unchecked((byte)unchecked((int)0xb8))] = 121; MAP[unchecked((byte)unchecked((int)0xb9))] = 122; MAP[unchecked((byte)unchecked((int)0xba))] = 123; MAP[unchecked((byte)unchecked((int)0xbb))] = 124; MAP[unchecked((byte)unchecked((int)0xbc))] = 125; MAP[unchecked((byte)unchecked((int)0xbd))] = 126; MAP[unchecked((byte)unchecked((int)0xbe))] = 127; MAP[unchecked((byte)unchecked((int)0xbf))] = 0; MAP[unchecked((byte)unchecked((int)0xc0))] = 0; MAP[unchecked((byte)unchecked((int)0xc1))] = 0; MAP[unchecked((byte)unchecked((int)0xc2))] = 0; MAP[unchecked((byte)unchecked((int)0xc3))] = 0; MAP[unchecked((byte)unchecked((int)0xc4))] = 0; MAP[unchecked((byte)unchecked((int)0xc5))] = 0; MAP[unchecked((byte)unchecked((int)0xc6))] = 0; MAP[unchecked((byte)unchecked((int)0xc7))] = 0; MAP[unchecked((byte)unchecked((int)0xc8))] = 0; MAP[unchecked((byte)unchecked((int)0xc9))] = 0; MAP[unchecked((byte)unchecked((int)0xca))] = 0; MAP[unchecked((byte)unchecked((int)0xcb))] = 0; MAP[unchecked((byte)unchecked((int)0xcc))] = 0; MAP[unchecked((byte)unchecked((int)0xcd))] = 0; MAP[unchecked((byte)unchecked((int)0xce))] = 0; MAP[unchecked((byte)unchecked((int)0xcf))] = 0; MAP[unchecked((byte)unchecked((int)0xd0))] = 0; MAP[unchecked((byte)unchecked((int)0xd1))] = 0; MAP[unchecked((byte)unchecked((int)0xd2))] = 0; MAP[unchecked((byte)unchecked((int)0xd3))] = 0; MAP[unchecked((byte)unchecked((int)0xd4))] = 0; MAP[unchecked((byte)unchecked((int)0xd5))] = 0; MAP[unchecked((byte)unchecked((int)0xd6))] = 0; MAP[unchecked((byte)unchecked((int)0xd7))] = 0; MAP[unchecked((byte)unchecked((int)0xd8))] = 0; MAP[unchecked((byte)unchecked((int)0xd9))] = 0; MAP[unchecked((byte)unchecked((int)0xda))] = 0; MAP[unchecked((byte)unchecked((int)0xdb))] = 0; MAP[unchecked((byte)unchecked((int)0xdc))] = 0; MAP[unchecked((byte)unchecked((int)0xdd))] = 0; MAP[unchecked((byte)unchecked((int)0xde))] = 0; MAP[unchecked((byte)unchecked((int)0xdf))] = 0; MAP[unchecked((byte)unchecked((int)0xe0))] = 0; MAP[unchecked((byte)unchecked((int)0xe1))] = 0; MAP[unchecked((byte)unchecked((int)0xe2))] = 0; MAP[unchecked((byte)unchecked((int)0xe3))] = 0; MAP[unchecked((byte)unchecked((int)0xe4))] = 0; MAP[unchecked((byte)unchecked((int)0xe5))] = 0; MAP[unchecked((byte)unchecked((int)0xe6))] = 0; MAP[unchecked((byte)unchecked((int)0xe7))] = 0; MAP[unchecked((byte)unchecked((int)0xe8))] = 0; MAP[unchecked((byte)unchecked((int)0xe9))] = 0; MAP[unchecked((byte)unchecked((int)0xea))] = 0; MAP[unchecked((byte)unchecked((int)0xeb))] = 0; MAP[unchecked((byte)unchecked((int)0xec))] = 0; MAP[unchecked((byte)unchecked((int)0xed))] = 0; MAP[unchecked((byte)unchecked((int)0xee))] = 0; MAP[unchecked((byte)unchecked((int)0xef))] = 0; MAP[unchecked((byte)unchecked((int)0xf0))] = 2; MAP[unchecked((byte)unchecked((int)0xf1))] = 3; MAP[unchecked((byte)unchecked((int)0xf2))] = 5; MAP[unchecked((byte)unchecked((int)0xf3))] = 9; MAP[unchecked((byte)unchecked((int)0xf4))] = 0; MAP[unchecked((byte)unchecked((int)0xf5))] = 0; MAP[unchecked((byte)unchecked((int)0xf6))] = 0; MAP[unchecked((byte)unchecked((int)0xf7))] = 0; MAP[unchecked((byte)unchecked((int)0xf8))] = 0; MAP[unchecked((byte)unchecked((int)0xf9))] = 0; MAP[unchecked((byte)unchecked((int)0xfa))] = 0; MAP[unchecked((byte)unchecked((int)0xfb))] = 0; MAP[unchecked((byte)unchecked((int)0xfc))] = 0; MAP[unchecked((byte)unchecked((int)0xfd))] = 0; MAP[unchecked((byte)unchecked((int)0xfe))] = 0; MAP[unchecked((byte)unchecked((int)0xff))] = 0; } private ValueLengthUtil() : base() { } public static int get(byte key) { return MAP[key]; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Caching { using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Linq; using System.Runtime.Caching; using System.Web.Caching; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Caching; using Adxstudio.Xrm.Configuration; using Adxstudio.Xrm.Threading; /// <summary> /// A custom <see cref="OutputCacheProvider"/> for writing to a configured <see cref="ObjectCache"/>. /// </summary> /// <remarks> /// The following configuration points the <see cref="OutputCacheProvider"/> to a secondary local <see cref="MemoryCache"/>. If the /// 'cacheItemDependenciesEnabled' flag is 'true', then any cache insertions collected during the course of a request is added to the output cache item /// as cache dependencies. /// <code> /// <![CDATA[ /// <configuration> /// /// <configSections> /// <section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/> /// </configSections> /// /// <system.web> /// <caching> /// <outputCache defaultProvider="Xrm"> /// <providers> /// <add /// name="Xrm" /// type="Adxstudio.Xrm.Caching.ObjectCacheOutputCacheProvider, Adxstudio.Xrm" /// objectCacheName="LocalMemory" /// cacheItemDependenciesEnabled="true" [true|false] /// /> /// </providers> /// </outputCache> /// </caching> /// </system.web> /// /// <microsoft.xrm.client> /// <objectCache default="Xrm"> /// <add name="Xrm" type="Adxstudio.Xrm.Caching.OutputObjectCache, Adxstudio.Xrm" innerObjectCacheName="LocalMemory"/> /// <add name="LocalMemory"/> <!-- uses MemoryCache by default --> /// </objectCache> /// </microsoft.xrm.client> /// /// </configuration> /// ]]> /// </code> /// /// Enable output caching on the ASP.Net page. /// <code> /// <![CDATA[ /// <%@ Page ... %> /// <%@ OutputCache VaryByParam="*" Duration="60" %> /// ]]> /// </code> /// </remarks> /// <seealso cref="OutputObjectCache"/> /// <seealso cref="CrmConfigurationManager"/> public class ObjectCacheOutputCacheProvider : OutputCacheProvider { private static readonly string _outputCacheDependency = "xrm:dependency:output:*"; private static readonly string _outputCacheSecondaryDependencyPrefix = "xrm:secondary-dependency:output"; /// <summary> /// The name of the configured <see cref="ObjectCacheElement"/> to be used for caching. /// </summary> public string ObjectCacheName { get; set; } /// <summary> /// The name of a specific cache region. /// </summary> public string CacheRegionName { get; set; } /// <summary> /// A format string for decorating the cache item keys. /// </summary> public string CacheKeyFormat { get; set; } /// <summary> /// The flag to apply cache dependencies to the output cache item. Enabled by default. /// </summary> public bool CacheItemDependenciesEnabled { get; set; } /// <summary> /// The flag to also add CacheItemDetails when adding OutputCache items to cache. This allows dependencies of OutputCache items to be /// shown in the cache feed. Disabled by default. /// </summary> public bool IncludeCacheItemDetails { get; set; } public override void Initialize(string name, NameValueCollection config) { ObjectCacheName = config["objectCacheName"]; CacheRegionName = config["cacheRegionName"]; CacheKeyFormat = config["cacheKeyFormat"] ?? @"{0}:{{0}}".FormatWith(this); bool cacheItemDependenciesEnabled; if (!bool.TryParse(config["cacheItemDependenciesEnabled"], out cacheItemDependenciesEnabled)) { cacheItemDependenciesEnabled = true; // true by default } CacheItemDependenciesEnabled = cacheItemDependenciesEnabled; bool includeCacheItemDetails; IncludeCacheItemDetails = bool.TryParse(config["includeCacheItemDetails"], out includeCacheItemDetails) && includeCacheItemDetails; // false by default base.Initialize(name, config); config.Remove("objectCacheName"); config.Remove("cacheRegionName"); config.Remove("cacheKeyFormat"); config.Remove("cacheItemDependenciesEnabled"); config.Remove("includeCacheItemDetails"); if (config.Count > 0) { string unrecognizedAttribute = config.GetKey(0); if (!string.IsNullOrEmpty(unrecognizedAttribute)) { throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(this, unrecognizedAttribute)); } } } public override object Add(string key, object entry, DateTime utcExpiry) { var cache = GetCache(); var cacheKey = GetCacheKey(key); var container = new CacheItemContainer(entry); if (CacheItemDependenciesEnabled) { var policy = GetPolicy(cache, utcExpiry, CacheRegionName); container.Detail = this.IncludeCacheItemDetails ? cache.CreateCacheItemDetailObject(cacheKey, policy, CacheRegionName) : null; var addedItem = cache.AddOrGetExisting(cacheKey, container, policy, CacheRegionName); return (addedItem as CacheItemContainer)?.Value; } return (cache.AddOrGetExisting(cacheKey, container, ToDateTimeOffset(utcExpiry), CacheRegionName) as CacheItemContainer)?.Value; } public override object Get(string key) { var cache = GetCache(); var cacheKey = GetCacheKey(key); return (cache.Get(cacheKey, CacheRegionName) as CacheItemContainer)?.Value; } public override void Remove(string key) { var cache = GetCache(); var cacheKey = GetCacheKey(key); cache.Remove(cacheKey, CacheRegionName); } public override void Set(string key, object entry, DateTime utcExpiry) { var cache = GetCache(); var cacheKey = GetCacheKey(key); var container = new CacheItemContainer(entry); if (CacheItemDependenciesEnabled) { var policy = GetPolicy(cache, utcExpiry, CacheRegionName); container.Detail = this.IncludeCacheItemDetails ? cache.CreateCacheItemDetailObject(cacheKey, policy, CacheRegionName) : null; cache.Set(cacheKey, container, policy, CacheRegionName); return; } cache.Set(cacheKey, container, ToDateTimeOffset(utcExpiry), CacheRegionName); } public static string GetSecondaryDependencyKey(string key) { return string.Format("{0}:{1}", _outputCacheSecondaryDependencyPrefix, key.ToLower()); } private CacheItemPolicy GetPolicy(ObjectCache cache, DateTime utcExpiry, string regionName) { // Add an output cache specific dependency item and key cache.AddOrGetExisting(_outputCacheDependency, _outputCacheDependency, ObjectCache.InfiniteAbsoluteExpiration, CacheRegionName); // Get the keys from HttpContext var name = AdxstudioCrmConfigurationManager.GetCrmSection().OutputObjectCacheName; var keys = HttpSingleton<OutputCacheKeyCollection>.GetInstance(name, () => new OutputCacheKeyCollection()); // Create Monitor and Policy objects var monitorKeys = keys.Select(d => d.ToLower()).ToArray(); var monitor = GetChangeMonitor(cache, monitorKeys, regionName); var policy = monitor.GetCacheItemPolicy(cache.Name); policy.AbsoluteExpiration = ToDateTimeOffset(utcExpiry); policy.RemovedCallback += CacheEventSource.Log.OnRemovedCallback; return policy; } private static CacheEntryChangeMonitor GetChangeMonitor(ObjectCache cache, string[] monitorKeys, string regionName) { if (!monitorKeys.Any()) return null; // Only take the dependencies that currently exist in the cache, some may have been invalidated in the interim. // Also filter out output cache secondary dependencies. var filteredKeys = monitorKeys.Where(key => cache.Contains(key, regionName) && !key.StartsWith(_outputCacheSecondaryDependencyPrefix)).Distinct(); if (!filteredKeys.Any()) { return null; } // For each output cache dependency, create a secondary dependency, this allows callers to invalidate just the output cache without also invalidating // other cache items which could be in dirty state. var includingSecondaryKeys = new List<string>(); foreach (var filteredKey in filteredKeys) { // Each secondary dependency should be dependent on the primary dependency. var policy = new CacheItemPolicy(); policy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(new[] { filteredKey }, regionName)); var secondaryDependencyKey = GetSecondaryDependencyKey(filteredKey); cache.AddOrGetExisting(secondaryDependencyKey, string.Empty, policy, regionName); includingSecondaryKeys.Add(secondaryDependencyKey); } includingSecondaryKeys.AddRange(filteredKeys); return cache.CreateCacheEntryChangeMonitor(includingSecondaryKeys, regionName); } private ObjectCache GetCache() { return ObjectCacheManager.GetInstance(ObjectCacheName); } private static DateTimeOffset ToDateTimeOffset(DateTime dt) { if (dt == DateTime.MinValue) return DateTimeOffset.MinValue; if (dt == DateTime.MaxValue) return DateTimeOffset.MaxValue; return dt; } private string GetCacheKey(string key) { return CacheKeyFormat.FormatWith(key).ToLower(); } } }
using System; using System.IO; using System.Linq; using System.Collections.Generic; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Tools; using Microsoft.Extensions.EnvironmentAbstractions; using NuGet.ProjectModel; using NuGet.Versioning; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.ToolPackage { // This is named "ToolPackageInstance" because "ToolPackage" would conflict with the namespace internal class ToolPackageInstance : IToolPackage { private const string PackagedShimsDirectoryConvention = "shims"; public IEnumerable<string> Warnings => _toolConfiguration.Value.Warnings; public PackageId Id { get; private set; } public NuGetVersion Version { get; private set; } public DirectoryPath PackageDirectory { get; private set; } public IReadOnlyList<CommandSettings> Commands { get { return _commands.Value; } } public IReadOnlyList<FilePath> PackagedShims { get { return _packagedShims.Value; } } private const string AssetsFileName = "project.assets.json"; private const string ToolSettingsFileName = "DotnetToolSettings.xml"; private IToolPackageStore _store; private Lazy<IReadOnlyList<CommandSettings>> _commands; private Lazy<ToolConfiguration> _toolConfiguration; private Lazy<IReadOnlyList<FilePath>> _packagedShims; public ToolPackageInstance( IToolPackageStore store, PackageId id, NuGetVersion version, DirectoryPath packageDirectory) { _store = store ?? throw new ArgumentNullException(nameof(store)); _commands = new Lazy<IReadOnlyList<CommandSettings>>(GetCommands); _packagedShims = new Lazy<IReadOnlyList<FilePath>>(GetPackagedShims); Id = id; Version = version ?? throw new ArgumentNullException(nameof(version)); PackageDirectory = packageDirectory; _toolConfiguration = new Lazy<ToolConfiguration>(GetToolConfiguration); } public void Uninstall() { var rootDirectory = PackageDirectory.GetParentPath(); string tempPackageDirectory = null; TransactionalAction.Run( action: () => { try { if (Directory.Exists(PackageDirectory.Value)) { // Use the staging directory for uninstall // This prevents cross-device moves when temp is mounted to a different device var tempPath = _store.GetRandomStagingDirectory().Value; Directory.Move(PackageDirectory.Value, tempPath); tempPackageDirectory = tempPath; } if (Directory.Exists(rootDirectory.Value) && !Directory.EnumerateFileSystemEntries(rootDirectory.Value).Any()) { Directory.Delete(rootDirectory.Value, false); } } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToUninstallToolPackage, Id, ex.Message), ex); } }, commit: () => { if (tempPackageDirectory != null) { Directory.Delete(tempPackageDirectory, true); } }, rollback: () => { if (tempPackageDirectory != null) { Directory.CreateDirectory(rootDirectory.Value); Directory.Move(tempPackageDirectory, PackageDirectory.Value); } }); } private IReadOnlyList<CommandSettings> GetCommands() { try { var commands = new List<CommandSettings>(); LockFile lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); LockFileTargetLibrary library = FindLibraryInLockFile(lockFile); ToolConfiguration configuration = _toolConfiguration.Value; LockFileItem entryPointFromLockFile = FindItemInTargetLibrary(library, configuration.ToolAssemblyEntryPoint); if (entryPointFromLockFile == null) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.MissingToolEntryPointFile, configuration.ToolAssemblyEntryPoint, configuration.CommandName)); } // Currently only "dotnet" commands are supported commands.Add(new CommandSettings( configuration.CommandName, "dotnet", LockFileRelativePathToFullFilePath(entryPointFromLockFile.Path, library))); return commands; } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, ex.Message), ex); } } private FilePath LockFileRelativePathToFullFilePath(string lockFileRelativePath, LockFileTargetLibrary library) { return PackageDirectory .WithSubDirectories( Id.ToString(), library.Version.ToNormalizedString()) .WithFile(lockFileRelativePath); } private ToolConfiguration GetToolConfiguration() { try { var lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); var library = FindLibraryInLockFile(lockFile); return DeserializeToolConfiguration(ToolSettingsFileName, library); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { throw new ToolConfigurationException( string.Format( CommonLocalizableStrings.FailedToRetrieveToolConfiguration, ex.Message), ex); } } private IReadOnlyList<FilePath> GetPackagedShims() { LockFileTargetLibrary library; try { LockFile lockFile = new LockFileFormat().Read(PackageDirectory.WithFile(AssetsFileName).Value); library = FindLibraryInLockFile(lockFile); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { throw new ToolPackageException( string.Format( CommonLocalizableStrings.FailedToReadNuGetLockFile, Id, ex.Message), ex); } IEnumerable<LockFileItem> filesUnderShimsDirectory = library ?.ToolsAssemblies ?.Where(t => LockFileMatcher.MatchesDirectoryPath(t, PackagedShimsDirectoryConvention)); if (filesUnderShimsDirectory == null) { return Array.Empty<FilePath>(); } IEnumerable<string> allAvailableShimRuntimeIdentifiers = filesUnderShimsDirectory .Select(f => f.Path.Split('\\', '/')?[4]) // ex: "tools/netcoreapp2.1/any/shims/osx-x64/demo" osx-x64 is at [4] .Where(f => !string.IsNullOrEmpty(f)); if (new FrameworkDependencyFile().TryGetMostFitRuntimeIdentifier( DotnetFiles.VersionFileObject.BuildRid, allAvailableShimRuntimeIdentifiers.ToArray(), out var mostFitRuntimeIdentifier)) { return library ?.ToolsAssemblies ?.Where(l => LockFileMatcher.MatchesDirectoryPath(l, $"{PackagedShimsDirectoryConvention}/{mostFitRuntimeIdentifier}")) .Select(l => LockFileRelativePathToFullFilePath(l.Path, library)).ToArray() ?? Array.Empty<FilePath>(); } else { return Array.Empty<FilePath>(); } } private ToolConfiguration DeserializeToolConfiguration(string ToolSettingsFileName, LockFileTargetLibrary library) { var dotnetToolSettings = FindItemInTargetLibrary(library, ToolSettingsFileName); if (dotnetToolSettings == null) { throw new ToolConfigurationException( CommonLocalizableStrings.MissingToolSettingsFile); } var toolConfigurationPath = PackageDirectory .WithSubDirectories( Id.ToString(), library.Version.ToNormalizedString()) .WithFile(dotnetToolSettings.Path); var configuration = ToolConfigurationDeserializer.Deserialize(toolConfigurationPath.Value); return configuration; } private LockFileTargetLibrary FindLibraryInLockFile(LockFile lockFile) { return lockFile ?.Targets?.SingleOrDefault(t => t.RuntimeIdentifier != null) ?.Libraries?.SingleOrDefault(l => string.Compare(l.Name, Id.ToString(), StringComparison.CurrentCultureIgnoreCase) == 0); } private static LockFileItem FindItemInTargetLibrary(LockFileTargetLibrary library, string targetRelativeFilePath) { return library ?.ToolsAssemblies ?.SingleOrDefault(t => LockFileMatcher.MatchesFile(t, targetRelativeFilePath)); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace BusinessApps.O365ProjectsApp.WebApp { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// TextCustomField /// </summary> [DataContract] public partial class TextCustomField : IEquatable<TextCustomField>, IValidatableObject { public TextCustomField() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="TextCustomField" /> class. /// </summary> /// <param name="ConfigurationType">If merge field&#39;s are being used, specifies the type of the merge field. The only supported value is **salesforce**..</param> /// <param name="ErrorDetails">ErrorDetails.</param> /// <param name="FieldId">An ID used to specify a custom field..</param> /// <param name="Name">The name of the custom field..</param> /// <param name="Required">When set to **true**, the signer is required to fill out this tab.</param> /// <param name="Show">A boolean indicating if the value should be displayed..</param> /// <param name="Value">The value of the custom field..</param> public TextCustomField(string ConfigurationType = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string FieldId = default(string), string Name = default(string), string Required = default(string), string Show = default(string), string Value = default(string)) { this.ConfigurationType = ConfigurationType; this.ErrorDetails = ErrorDetails; this.FieldId = FieldId; this.Name = Name; this.Required = Required; this.Show = Show; this.Value = Value; } /// <summary> /// If merge field&#39;s are being used, specifies the type of the merge field. The only supported value is **salesforce**. /// </summary> /// <value>If merge field&#39;s are being used, specifies the type of the merge field. The only supported value is **salesforce**.</value> [DataMember(Name="configurationType", EmitDefaultValue=false)] public string ConfigurationType { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// An ID used to specify a custom field. /// </summary> /// <value>An ID used to specify a custom field.</value> [DataMember(Name="fieldId", EmitDefaultValue=false)] public string FieldId { get; set; } /// <summary> /// The name of the custom field. /// </summary> /// <value>The name of the custom field.</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// When set to **true**, the signer is required to fill out this tab /// </summary> /// <value>When set to **true**, the signer is required to fill out this tab</value> [DataMember(Name="required", EmitDefaultValue=false)] public string Required { get; set; } /// <summary> /// A boolean indicating if the value should be displayed. /// </summary> /// <value>A boolean indicating if the value should be displayed.</value> [DataMember(Name="show", EmitDefaultValue=false)] public string Show { get; set; } /// <summary> /// The value of the custom field. /// </summary> /// <value>The value of the custom field.</value> [DataMember(Name="value", EmitDefaultValue=false)] public string Value { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TextCustomField {\n"); sb.Append(" ConfigurationType: ").Append(ConfigurationType).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append(" FieldId: ").Append(FieldId).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Required: ").Append(Required).Append("\n"); sb.Append(" Show: ").Append(Show).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as TextCustomField); } /// <summary> /// Returns true if TextCustomField instances are equal /// </summary> /// <param name="other">Instance of TextCustomField to be compared</param> /// <returns>Boolean</returns> public bool Equals(TextCustomField other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ConfigurationType == other.ConfigurationType || this.ConfigurationType != null && this.ConfigurationType.Equals(other.ConfigurationType) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ) && ( this.FieldId == other.FieldId || this.FieldId != null && this.FieldId.Equals(other.FieldId) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Required == other.Required || this.Required != null && this.Required.Equals(other.Required) ) && ( this.Show == other.Show || this.Show != null && this.Show.Equals(other.Show) ) && ( this.Value == other.Value || this.Value != null && this.Value.Equals(other.Value) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ConfigurationType != null) hash = hash * 59 + this.ConfigurationType.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 59 + this.ErrorDetails.GetHashCode(); if (this.FieldId != null) hash = hash * 59 + this.FieldId.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Required != null) hash = hash * 59 + this.Required.GetHashCode(); if (this.Show != null) hash = hash * 59 + this.Show.GetHashCode(); if (this.Value != null) hash = hash * 59 + this.Value.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// 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.Reflection; using Gallio.Common.Collections; /* * This compilation unit contains MemberInfo overrides that must be duplicated for each * of the unresolved reflection types because C# does not support multiple inheritance. */ #if DOTNET40 namespace Gallio.Common.Reflection.Impl.DotNet40 #else namespace Gallio.Common.Reflection.Impl.DotNet20 #endif { internal static class UnresolvedMemberInfo { public static Type GetDeclaringType(IMemberInfo member) { return ResolveType(member.DeclaringType); } public static MethodInfo ResolveMethod(IMethodInfo method, bool nonPublic) { return method != null && (nonPublic || method.IsPublic) ? method.Resolve(false) : null; } public static Type ResolveType(ITypeInfo type) { return type != null ? type.Resolve(false) : null; } } internal partial class UnresolvedType { public override Type DeclaringType { get { return UnresolvedMemberInfo.GetDeclaringType(adapter); } } public override int MetadataToken { get { throw new NotSupportedException("Cannot get metadata token of unresolved type."); } } public override Module Module { get { throw new NotSupportedException("Cannot get module of unresolved type."); } } public override string Name { get { return adapter.Name; } } public override Type ReflectedType { get { return DeclaringType; } } public override bool Equals(object o) { UnresolvedType other = o as UnresolvedType; return other != null && adapter.Equals(other.adapter); } public override int GetHashCode() { return adapter.GetHashCode(); } public override string ToString() { return adapter.ToString(); } } internal partial class UnresolvedFieldInfo { public override Type DeclaringType { get { return UnresolvedMemberInfo.GetDeclaringType(adapter); } } public override int MetadataToken { get { throw new NotSupportedException("Cannot get metadata token of unresolved field."); } } public override Module Module { get { throw new NotSupportedException("Cannot get module of unresolved field."); } } public override string Name { get { return adapter.Name; } } public override Type ReflectedType { get { return DeclaringType; } } public override bool Equals(object o) { UnresolvedFieldInfo other = o as UnresolvedFieldInfo; return other != null && adapter.Equals(other.adapter); } public override int GetHashCode() { return adapter.GetHashCode(); } public override string ToString() { return adapter.ToString(); } } internal partial class UnresolvedPropertyInfo { public override Type DeclaringType { get { return UnresolvedMemberInfo.GetDeclaringType(adapter); } } public override int MetadataToken { get { throw new NotSupportedException("Cannot get metadata token of unresolved property."); } } public override Module Module { get { throw new NotSupportedException("Cannot get module of unresolved property."); } } public override string Name { get { return adapter.Name; } } public override Type ReflectedType { get { return DeclaringType; } } public override bool Equals(object o) { UnresolvedPropertyInfo other = o as UnresolvedPropertyInfo; return other != null && adapter.Equals(other.adapter); } public override int GetHashCode() { return adapter.GetHashCode(); } public override string ToString() { return adapter.ToString(); } } internal partial class UnresolvedEventInfo { public override Type DeclaringType { get { return UnresolvedMemberInfo.GetDeclaringType(adapter); } } public override int MetadataToken { get { throw new NotSupportedException("Cannot get metadata token of unresolved event."); } } public override Module Module { get { throw new NotSupportedException("Cannot get module of unresolved event."); } } public override string Name { get { return adapter.Name; } } public override Type ReflectedType { get { return DeclaringType; } } public override bool Equals(object o) { UnresolvedEventInfo other = o as UnresolvedEventInfo; return other != null && adapter.Equals(other.adapter); } public override int GetHashCode() { return adapter.GetHashCode(); } public override string ToString() { return adapter.ToString(); } } internal partial class UnresolvedMethodInfo { public override Type DeclaringType { get { return UnresolvedMemberInfo.GetDeclaringType(adapter); } } public override int MetadataToken { get { throw new NotSupportedException("Cannot get metadata token of unresolved method."); } } public override Module Module { get { throw new NotSupportedException("Cannot get module of unresolved method."); } } public override string Name { get { return adapter.Name; } } public override Type ReflectedType { get { return DeclaringType; } } public override bool Equals(object o) { UnresolvedMethodInfo other = o as UnresolvedMethodInfo; return other != null && adapter.Equals(other.adapter); } public override int GetHashCode() { return adapter.GetHashCode(); } public override string ToString() { return adapter.ToString(); } } internal partial class UnresolvedConstructorInfo { public override Type DeclaringType { get { return UnresolvedMemberInfo.GetDeclaringType(adapter); } } public override int MetadataToken { get { throw new NotSupportedException("Cannot get metadata token of unresolved constructor."); } } public override Module Module { get { throw new NotSupportedException("Cannot get module of unresolved constructor."); } } public override string Name { get { return adapter.Name; } } public override Type ReflectedType { get { return DeclaringType; } } public override bool Equals(object o) { UnresolvedConstructorInfo other = o as UnresolvedConstructorInfo; return other != null && adapter.Equals(other.adapter); } public override int GetHashCode() { return adapter.GetHashCode(); } public override string ToString() { return adapter.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Web.UI.WebControls; using System.Web.UI; using System.Drawing; namespace Andersc.CodeLib.Common { [Themeable(true)] [DefaultProperty("Text")] [ToolboxData("<{0}:CustomGridView runat='server'></{0}:CustomGridView>"), DisplayName("CustomGridView"), Description("A custom gridView control.")] public class CustomGridView : GridView { public enum PagerStyleType { /// <summary> /// Using gridview built-in pager style. /// </summary> Default, /// <summary> /// Using custom style pager style. /// </summary> CustomNumeric, /// <summary> /// TODO: Using dropdownlist pager style. /// </summary> DropDownList } private const string ViewStateName = "PagerStyleType"; private const string ViewStateNameOfTotalPageInfo = "ShowTotalPageInfo"; private const string ViewStateNameOfShowAllButton = "ShowAllButton"; private const string ViewStateNameOfHasShowAllItems = "HasShowAllItems"; private const string ViewStateNameOfShowAllItemCount = "ShowAllItemCount"; private const string ViewStateNameOfOriginalItemCount = "OriginalItemCount"; private const string buttonImageFormat = "<img src='{0}' border='0' />"; //private const string text = "page {0} of {1}, {2} per page, total {3} "; private const string totalInfoFormat = "Page {0} of {1}, {2} items per page. "; private const string showAllButtonTextFormat = "Show All"; private const string showOriginalButtonTextFormat = "Show {0} per page"; private int recordCount; private string mouseOverColor; private string pagerButtonCssClass; public int RecordCount { get { return recordCount; } set { recordCount = value; } } [Category("Paging")] public int OriginalItemCount { get { object count = ViewState[ViewStateNameOfOriginalItemCount]; //if (count == null) //{ // return this.PageSize; //} return Convert.ToInt32(count); } set { if (value <= 0) { throw new ArgumentOutOfRangeException("OriginalItemCount must be a positive number."); } ViewState[ViewStateNameOfOriginalItemCount] = value; } } [Category("Paging")] [DefaultValue(100)] public int ShowAllItemCount { get { object count = ViewState[ViewStateNameOfShowAllItemCount]; if (count == null) { return 100; } return Convert.ToInt32(count); } set { if (value <= 0) { throw new ArgumentOutOfRangeException("ShowAllItemCount must be a positive number."); } ViewState[ViewStateNameOfShowAllItemCount] = value; } } [Category("Paging")] [DefaultValue("CustomNumeric")] public PagerStyleType PagerType { get { return (ViewState[ViewStateName] != null ? (PagerStyleType)ViewState[ViewStateName] : PagerStyleType.CustomNumeric); } set { ViewState[ViewStateName] = value; } } [Category("Paging")] [DefaultValue("false")] public bool ShowTotalPageInfo { get { return (ViewState[ViewStateNameOfTotalPageInfo] != null ? (bool)ViewState[ViewStateNameOfTotalPageInfo] : false); } set { ViewState[ViewStateNameOfTotalPageInfo] = value; } } [Category("Paging")] [DefaultValue("false")] public bool ShowAllButton { get { return (ViewState[ViewStateNameOfShowAllButton] != null ? (bool)ViewState[ViewStateNameOfShowAllButton] : false); } set { ViewState[ViewStateNameOfShowAllButton] = value; } } [DefaultValue("")] public string MouseOverColor { get { return mouseOverColor; } set { mouseOverColor = value; } } [Category("Paging")] [DefaultValue("")] public string PagerButtonCssClass { get { return pagerButtonCssClass; } set { pagerButtonCssClass = value; } } [Category("Paging")] [DefaultValue("false")] public bool HasShowAllItems { get { return (ViewState[ViewStateNameOfHasShowAllItems] != null ? (bool)ViewState[ViewStateNameOfHasShowAllItems] : false); } set { ViewState[ViewStateNameOfHasShowAllItems] = value; } } #region Sorting Image private string ascImageUrl; public string AscImageUrl { get { return ascImageUrl; } set { ascImageUrl = value; } } private string descImageUrl; public string DescImageUrl { get { return descImageUrl; } set { descImageUrl = value; } } #endregion protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) { switch (PagerType) { case PagerStyleType.CustomNumeric: InitializeNumericPager(row, columnSpan, pagedDataSource); break; case PagerStyleType.DropDownList: InitializeDropDownListPager(row, columnSpan, pagedDataSource); break; default: InitializeDefaultPager(row, columnSpan, pagedDataSource); break; } if (pagedDataSource != null) { RecordCount = pagedDataSource.DataSourceCount; } } private void InitializeDefaultPager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) { // if PagerType is default, render the regular GridView Pager base.InitializePager(row, columnSpan, pagedDataSource); } private void InitializeNumericPager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) { // create a Table that will replace entirely our GridView's Pager section Table tbl = new Table(); tbl.BorderWidth = 0; tbl.Width = Unit.Percentage(100); // add one TableRow to our Table tbl.Rows.Add(new TableRow()); // add our first TableCell which will contain the total pager info(total page count, current page index, page size...) TableCell cell_1 = new TableCell(); // we just add a Label with total pager info text. if (ShowTotalPageInfo) { cell_1.Controls.Add(GetTotalPageInfo(pagedDataSource.DataSourceCount)); } // the 2nd TableCell will display the Record number you are currently in. TableCell cell_2 = new TableCell(); // cell_2.Controls.Add(PageInfo(pagedDataSource.DataSourceCount)); FillPagerButtons(cell_2); // add now the 2 cell to our created row tbl.Rows[0].Cells.Add(cell_1); tbl.Rows[0].Cells.Add(cell_2); tbl.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Left; tbl.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Right; // in Pager's Row of our GridView add a TableCell row.Controls.AddAt(0, new TableCell()); // sets it span to GridView's number of columns row.Cells[0].ColumnSpan = Columns.Count; // finally add our created Table row.Cells[0].Controls.AddAt(0, tbl); } private void InitializeDropDownListPager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource) { // our Pager with DropDownList control // create our DropDownList control DropDownList ddl = new DropDownList(); // populate it with the number of Pages of our GridView for (int i = 0; i < PageCount; i++) { ddl.Items.Add(new ListItem(Convert.ToString(i + 1), i.ToString())); } ddl.AutoPostBack = true; // assign an Event Handler when its Selected Index Changed ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged); // synchronize its selected index to GridView's current PageIndex ddl.SelectedIndex = PageIndex; // create a Table that will replace entirely our GridView's Pager section Table tbl = new Table(); tbl.BorderWidth = 0; tbl.Width = Unit.Percentage(100); // add one TableRow to our Table tbl.Rows.Add(new TableRow()); // add our first TableCell which will contain the DropDownList TableCell cell_1 = new TableCell(); // we just add a Label with 'Page ' Text cell_1.Controls.Add(PageOf()); // our DropDownList control here. cell_1.Controls.Add(ddl); // and our Total number of Pages cell_1.Controls.Add(PageTotal()); // the 2nd TableCell will display the Record number you are currently in. TableCell cell_2 = new TableCell(); cell_2.Controls.Add(PageInfo(pagedDataSource.DataSourceCount)); // add now the 2 cell to our created row tbl.Rows[0].Cells.Add(cell_1); tbl.Rows[0].Cells.Add(cell_2); tbl.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Left; tbl.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Right; // in Pager's Row of our GridView add a TableCell row.Controls.AddAt(0, new TableCell()); // sets it span to GridView's number of columns row.Cells[0].ColumnSpan = Columns.Count; // finally add our created Table row.Cells[0].Controls.AddAt(0, tbl); } #region CustomNumeric Style private Label GetTotalPageInfo(int dataSourceCount) { // it is just a label Label lbl = new Label(); lbl.Text = string.Format(totalInfoFormat, this.PageIndex + 1, this.PageCount, this.PageSize, dataSourceCount); return lbl; } private void SetPagerButtonCssClass(LinkButton link) { if (!string.IsNullOrEmpty(pagerButtonCssClass)) { link.CssClass = pagerButtonCssClass; } } private void AddShowAllButton(TableCell container) { if (ShowAllButton) { LinkButton showAll = new LinkButton(); showAll.Click += new EventHandler(showAll_Click); SetShowAllButtonText(showAll); showAll.Visible = (PageCount > 1); SetPagerButtonCssClass(showAll); container.Controls.Add(showAll); container.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); } } private void SetShowAllButtonText(LinkButton showAll) { if (!HasShowAllItems) { showAll.Text = showAllButtonTextFormat; } else { showAll.Text = string.Format(showOriginalButtonTextFormat, OriginalItemCount); } } private void showAll_Click(object sender, EventArgs e) { HasShowAllItems = !HasShowAllItems; if (HasShowAllItems) { this.PageSize = ShowAllItemCount; } else { this.PageSize = OriginalItemCount; } SetShowAllButtonText(sender as LinkButton); this.PageIndex = 0; this.DataBind(); } private void AddLastButton(TableCell container) { LinkButton last = new LinkButton(); if (!string.IsNullOrEmpty(PagerSettings.LastPageImageUrl)) { last.Text = GetButtonImageString(PagerSettings.LastPageImageUrl); } else { last.Text = PagerSettings.LastPageText; } last.CommandName = "Page"; last.CommandArgument = "Last"; SetPagerButtonCssClass(last); last.Visible = (PageIndex != PageCount - 1); container.Controls.Add(last); container.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); } private void AddNextButton(TableCell container) { LinkButton next = new LinkButton(); if (!string.IsNullOrEmpty(PagerSettings.NextPageImageUrl)) { next.Text = GetButtonImageString(PagerSettings.NextPageImageUrl); } else { next.Text = PagerSettings.NextPageText; } next.CommandName = "Page"; next.CommandArgument = "Next"; SetPagerButtonCssClass(next); next.Visible = (PageIndex != PageCount - 1); container.Controls.Add(next); container.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); } private void AddPrevButton(TableCell container) { LinkButton prev = new LinkButton(); if (!string.IsNullOrEmpty(PagerSettings.PreviousPageImageUrl)) { prev.Text = GetButtonImageString(PagerSettings.PreviousPageImageUrl); } else { prev.Text = PagerSettings.PreviousPageText; } prev.CommandName = "Page"; prev.CommandArgument = "Prev"; SetPagerButtonCssClass(prev); prev.Visible = (PageIndex != 0); container.Controls.Add(prev); container.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); } private void AddFirstButton(TableCell container) { LinkButton first = new LinkButton(); if (!string.IsNullOrEmpty(PagerSettings.FirstPageImageUrl)) { first.Text = GetButtonImageString(PagerSettings.FirstPageImageUrl); } else { first.Text = PagerSettings.FirstPageText; } first.CommandName = "Page"; first.CommandArgument = "First"; SetPagerButtonCssClass(first); first.Visible = (PageIndex != 0); container.Controls.Add(first); container.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); } private string GetButtonImageString(string originalUrl) { return string.Format(buttonImageFormat, ResolveUrl(originalUrl)); } private void FillPagerButtons(TableCell container) { AddShowAllButton(container); // add first and prev buttons AddFirstButton(container); AddPrevButton(container); // if pageButtonCount is larger than pageCount, we should assign pageCount to buttonCount. int pageButtonCount = this.PagerSettings.PageButtonCount; int skipedButtons = (this.PageIndex / pageButtonCount) * pageButtonCount; int buttonCount = Math.Min(pageButtonCount, this.PageCount - skipedButtons); // draw numeric buttons for (int i = 0; i < buttonCount; i++) { container.Controls.Add(GetPagerButton(skipedButtons + i, this.PageIndex == (skipedButtons + i))); container.Controls.Add(new LiteralControl("&nbsp;&nbsp;")); } // add next and last buttons AddNextButton(container); AddLastButton(container); } private Control GetPagerButton(int index, bool isCurrentIndex) { if (isCurrentIndex) { return GetLiteral(index); } LinkButton link = new LinkButton(); link.Text = (index + 1).ToString(); link.CommandName = "Page"; link.CommandArgument = (index + 1).ToString(); SetPagerButtonCssClass(link); return link; } private LiteralControl GetLiteral(int pageIndex) { return new LiteralControl(string.Format("<span class='{0}'>{1}</span>", pagerButtonCssClass, (pageIndex + 1).ToString())); } #endregion #region DropDownList Pager Style protected void ddl_SelectedIndexChanged(object sender, EventArgs e) { // on our DropDownList SelectedIndexChanged event call the GridView's OnPageIndexChanging method to raised the PageIndexChanging event. // pass the DropDownList SelectedIndex as its argument. if (string.IsNullOrEmpty(DataSourceID)) { OnPageIndexChanging(new GridViewPageEventArgs((sender as DropDownList).SelectedIndex)); } else { // if using DataSourceControl. PageIndex = (sender as DropDownList).SelectedIndex; } } protected Label PageOf() { // it is just a label Label lbl = new Label(); lbl.Text = "Page "; return lbl; } protected Label PageTotal() { // a label of GridView's Page Count Label lbl = new Label(); lbl.Text = string.Format(" of {0}", PageCount); return lbl; } protected Label PageInfo(int rowCount) { // create a label that will display the current Record you're in Label label = new Label(); int currentPageFirstRow = ((PageIndex * PageSize) + 1); int currentPageLastRow = 0; int lastPageRemainder = rowCount % PageSize; currentPageLastRow = (PageCount == PageIndex + 1) ? (currentPageFirstRow + lastPageRemainder - 1) : (currentPageFirstRow + PageSize - 1); label.Text = String.Format("Record {0} to {1} of {2}", currentPageFirstRow, currentPageLastRow, rowCount); return label; } #endregion /// <summary> /// Raises the <see cref="GridView.RowCreated"></see> event. /// Adds sort status icon. /// </summary> protected override void OnRowCreated(GridViewRowEventArgs e) { if (e.Row != null && e.Row.RowType == DataControlRowType.Header) { if (!string.IsNullOrEmpty(ascImageUrl) && !string.IsNullOrEmpty(descImageUrl)) { foreach (TableCell cell in e.Row.Cells) { if (cell.HasControls()) { LinkButton button = cell.Controls[0] as LinkButton; if (button != null) { if (SortExpression == button.CommandArgument) { System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image(); if (SortDirection == SortDirection.Ascending) image.ImageUrl = ascImageUrl; else image.ImageUrl = descImageUrl; cell.Controls.Add(image); } } } } } } base.OnRowCreated(e); } protected override void OnDataBound(EventArgs e) { base.OnDataBound(e); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary> /// Tests for MemoryMappedFile.CreateFromFile. /// </summary> public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateFromFile path parameter. /// </summary> [Fact] public void InvalidArguments_Path() { // null is an invalid path Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null)); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open)); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName())); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096)); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read)); } /// <summary> /// Tests invalid arguments to the CreateFromFile fileStream parameter. /// </summary> [Fact] public void InvalidArguments_FileStream() { // null is an invalid stream Assert.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); } /// <summary> /// Tests invalid arguments to the CreateFromFile mode parameter. /// </summary> [Fact] public void InvalidArguments_Mode() { // FileMode out of range Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42)); Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null)); Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096)); Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite)); // FileMode.Append never allowed Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append)); Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null)); Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096)); Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite)); // FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate)); // FileMode.Truncate can't be used with default capacity, as resulting file will be empty using (TempFile file = new TempFile(GetTestFilePath())) { Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate)); } } /// <summary> /// Tests invalid arguments to the CreateFromFile access parameter. /// </summary> [Fact] public void InvalidArguments_Access() { // Out of range access values with a path Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2))); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42))); // Write-only access is not allowed on maps (only on views) Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write)); // Test the same things, but with a FileStream instead of a path using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Out of range values with a stream Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true)); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true)); // Write-only access is not allowed Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true)); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream. The combinations should all be valid. /// </summary> [Theory] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)] public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)) { ValidateMemoryMappedFile(mmf, Capacity, mmfAccess); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)] public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { // On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile. const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) { Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception. /// </summary> [PlatformSpecific(PlatformID.AnyUnix)] [Theory] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)] public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { // On Unix we don't actually create the OS map until the view is created; this results in the permissions // error being thrown from CreateView* instead of from CreateFromFile. const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)) { Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor()); } } /// <summary> /// Tests invalid arguments to the CreateFromFile mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { using (TempFile file = new TempFile(GetTestFilePath())) { // Empty string is an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read)); using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } } } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(PlatformID.AnyUnix)] [Theory] [MemberData(nameof(CreateValidMapNames))] public void MapNamesNotSupported_Unix(string mapName) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite)); using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } } } /// <summary> /// Tests invalid arguments to the CreateFromFile capacity parameter. /// </summary> [Fact] public void InvalidArguments_Capacity() { using (TempFile file = new TempFile(GetTestFilePath())) { // Out of range values for capacity Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read)); // Positive capacity required when creating a map from an empty file Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read)); // With Read, the capacity can't be larger than the backing file's size. Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read)); // Now with a FileStream... using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // The subsequent tests are only valid we if we start with an empty FileStream, which we should have. // This also verifies the previous failed tests didn't change the length of the file. Assert.Equal(0, fs.Length); // Out of range values for capacity Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Default (0) capacity with an empty file Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Larger capacity than the underlying file, but read-only such that we can't expand the file fs.SetLength(4096); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Capacity can't be less than the file size (for such cases a view can be created with the smaller size) Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } // Capacity can't be less than the file size Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read)); } } /// <summary> /// Tests invalid arguments to the CreateFromFile inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)(-1))] [InlineData((HandleInheritability)(42))] public void InvalidArguments_Inheritability(HandleInheritability inheritability) { // Out of range values for inheritability using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true)); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.Open, FileMode.OpenOrCreate }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // Test each of the four path-based CreateFromFile overloads using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } // Finally, re-test the last overload, this time with an empty file to start using (TempFile file = new TempFile(GetTestFilePath())) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.CreateNew }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModeCreateNew( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads // that take a capacity, since the default capacity doesn't work with an empty file. using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the Create and Truncate modes, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.Create, FileMode.Truncate }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModesCreateOrTruncate( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // For FileMode.Create/Truncate, try existing files. Only the overloads that take a capacity are valid because // both of these modes will cause the input file to be made empty, and an empty file doesn't work with the default capacity. using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } // For FileMode.Create, also try letting it create a new file (Truncate needs the file to have existed) if (mode == FileMode.Create) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } } } /// <summary> /// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="modes">The modes to yield.</param> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses"> /// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it. /// </param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath( FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses) { foreach (FileMode mode in modes) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) && !IsWritable(access)) { continue; } string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mode, mapName, capacity, access }; } } } } } /// <summary> /// Test various combinations of arguments to CreateFromFile that accepts a FileStream. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream), new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable }, new bool[] { false, true })] public void ValidArgumentCombinationsWithStream( string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { // Create a file of the right size, then create the map for it. using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Start with an empty file and let the map grow it to the right size. This requires write access. if (IsWritable(access)) { using (FileStream fs = File.Create(GetTestFilePath())) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } } } /// <summary> /// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses"> /// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it. /// </param> /// <param name="inheritabilities">The inheritabilities to yield.</param> /// <param name="inheritabilities">The leaveOpen values to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (HandleInheritability inheritability in inheritabilities) { foreach (bool leaveOpen in leaveOpens) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, inheritability, leaveOpen }; } } } } } } /// <summary> /// Test that a map using the default capacity (0) grows to the size of the underlying file. /// </summary> [Fact] public void DefaultCapacityIsFileLength() { const int DesiredCapacity = 8192; const int DefaultCapacity = 0; // With path using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity)) { ValidateMemoryMappedFile(mmf, DesiredCapacity); } // With stream using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) { ValidateMemoryMappedFile(mmf, DesiredCapacity); } } /// <summary> /// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode /// that requires the file to exist. /// </summary> [Theory] [InlineData(FileMode.Truncate)] [InlineData(FileMode.Open)] public void FileDoesNotExist(FileMode mode) { Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath())); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null, 4096)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null, 4096, MemoryMappedFileAccess.ReadWrite)); } /// <summary> /// Test that appropriate exceptions are thrown creating a map with an existing file and a mode /// that requires the file to not exist. /// </summary> [Fact] public void FileAlreadyExists() { using (TempFile file = new TempFile(GetTestFilePath())) { // FileMode.CreateNew invalid when the file already exists Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew)); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName())); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096)); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a read-write file that's currently in use. /// </summary> [Fact] [PlatformSpecific(PlatformID.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile() { // Already opened with a FileStream using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use. /// </summary> [Fact] [PlatformSpecific(PlatformID.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap() { // Already opened with another read-write map using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use. /// </summary> [Fact] public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile() { // Already opened with a FileStream using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test to validate we can create multiple concurrent read-only maps from the same file path. /// </summary> [Fact] public void FileInUse_CreateFromFile_SucceedsWithReadOnly() { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read)) { Assert.Equal(acc1.Capacity, acc2.Capacity); } } /// <summary> /// Test the exceptional behavior of *Execute access levels. /// </summary> [PlatformSpecific(PlatformID.Windows)] // Unix model for executable differs from Windows [Theory] [InlineData(MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute)] public void FileNotOpenedForExecute(MemoryMappedFileAccess access) { using (TempFile file = new TempFile(GetTestFilePath(), 4096)) { // The FileStream created by the map doesn't have GENERIC_EXECUTE set Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access)); // The FileStream opened explicitly doesn't have GENERIC_EXECUTE set using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true)); } } } /// <summary> /// On Unix, modifying a file that is ReadOnly will fail under normal permissions. /// If the test is being run under the superuser, however, modification of a ReadOnly /// file is allowed. /// </summary> [Theory] [InlineData(MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.CopyOnWrite)] public void WriteToReadOnlyFile(MemoryMappedFileAccess access) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) { FileAttributes original = File.GetAttributes(file.Path); File.SetAttributes(file.Path, FileAttributes.ReadOnly); try { if (access == MemoryMappedFileAccess.Read || (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access)) ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read); else Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access)); } finally { File.SetAttributes(file.Path, original); } } } [DllImport("libc", SetLastError = true)] private static extern int geteuid(); /// <summary> /// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open /// or closing it on disposal. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void LeaveOpenRespected_Basic(bool leaveOpen) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Handle should still be open SafeFileHandle handle = fs.SafeFileHandle; Assert.False(handle.IsClosed); // Create and close the map MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose(); // The handle should now be open iff leaveOpen Assert.NotEqual(leaveOpen, handle.IsClosed); } } /// <summary> /// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open /// or closing it on disposal. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void LeaveOpenRespected_OutstandingViews(bool leaveOpen) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Handle should still be open SafeFileHandle handle = fs.SafeFileHandle; Assert.False(handle.IsClosed); // Create the map, create each of the views, then close the map using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity)) using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity)) { // Explicitly close the map. The handle should now be open iff leaveOpen. mmf.Dispose(); Assert.NotEqual(leaveOpen, handle.IsClosed); // But the views should still be usable. ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite); ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite); } } } /// <summary> /// Test to validate we can create multiple maps from the same FileStream. /// </summary> [Fact] public void MultipleMapsForTheSameFileStream() { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open)) using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor()) using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor()) { // The capacity of the two maps should be equal Assert.Equal(acc1.Capacity, acc2.Capacity); var rand = new Random(); for (int i = 1; i <= 10; i++) { // Write a value to one map, then read it from the other, // ping-ponging between the two. int pos = rand.Next((int)acc1.Capacity - 1); MemoryMappedViewAccessor reader = acc1, writer = acc2; if (i % 2 == 0) { reader = acc2; writer = acc1; } writer.Write(pos, (byte)i); writer.Flush(); Assert.Equal(i, reader.ReadByte(pos)); } } } /// <summary> /// Test to verify that the map's size increases the underlying file size if the map's capacity is larger. /// </summary> [Fact] public void FileSizeExpandsToCapacity() { const int InitialCapacity = 256; using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity)) { // Create a map with a larger capacity, and verify the file has expanded. MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose(); using (FileStream fs = File.OpenRead(file.Path)) { Assert.Equal(InitialCapacity * 2, fs.Length); } // Do the same thing again but with a FileStream. using (FileStream fs = File.Open(file.Path, FileMode.Open)) { MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose(); Assert.Equal(InitialCapacity * 4, fs.Length); } } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(~PlatformID.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately) [Fact] public void TooLargeCapacity() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew)) { try { long length = long.MaxValue; MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose(); Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested. } catch (IOException) { // Expected exception for too large a capacity } } } /// <summary> /// Test to verify map names are handled appropriately, causing a conflict when they're active but /// reusable in a sequential manner. /// </summary> [PlatformSpecific(PlatformID.Windows)] [Theory] [MemberData(nameof(CreateValidMapNames))] public void ReusingNames_Windows(string name) { const int Capacity = 4096; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)) { ValidateMemoryMappedFile(mmf, Capacity); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)) { ValidateMemoryMappedFile(mmf, Capacity); } } } }
// Copyright (c) 2013 Krkadoni.com - Released under The MIT License. // Full license text can be found at http://opensource.org/licenses/MIT using System; using System.Collections.Generic; using System.ComponentModel; namespace Krkadoni.EnigmaSettings.Interfaces { public interface ISettings : INotifyPropertyChanged, IEditableObject, ICloneable { /// <summary> /// Instance used for logging /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> ILog Log { get; set; } /// <summary> /// Full path to settings file location on disk /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> string SettingsFileName { get; set; } /// <summary> /// Directory with all the files for the settings /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> string SettingsDirectory { get; } /// <summary> /// Version of the settings file /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> Enums.SettingsVersion SettingsVersion { get; set; } /// <summary> /// List of satellites from satelites.xml file /// </summary> /// <value></value> /// <returns></returns> /// <remarks>Each satelite has coresponding xml transponders from satellites.xml file</remarks> IList<IXmlSatellite> Satellites { get; set; } /// <summary> /// All transponders (DVBS, DVBT, DVBC) from settings file /// </summary> /// <value></value> /// <returns></returns> /// <remarks>These are not transponders from satellites.xml file</remarks> IList<ITransponder> Transponders { get; set; } /// <summary> /// All services from settings file /// </summary> /// <value></value> /// <returns></returns> /// <remarks>Each service should have corresponding transponder from services file</remarks> IList<IService> Services { get; set; } /// <summary> /// All bouquets except the ones stored in 'bouquets' file from Enigma 1 /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> IList<IBouquet> Bouquets { get; set; } /// <summary> /// Returns list of satellite transponders from list with all transponders /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<ITransponderDVBS> FindSatelliteTransponders(); /// <summary> /// Returns list of transponders for selected satellite /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<ITransponderDVBS> FindTranspondersForSatellite(IXmlSatellite satellite); /// <summary> /// Returns list of transponders for selected satellite /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<IService> FindServicesForSatellite(IXmlSatellite satellite); /// <summary> /// Returns list of satellite transponders without corresponding satellite /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<ITransponderDVBS> FindTranspondersWithoutSatellite(); /// <summary> /// Returns list of services without corresponding transponder /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<IService> FindServicesWithoutTransponder(); /// <summary> /// Returns list of services for transponder /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<IService> FindServicesForTransponder(ITransponder transponder); /// <summary> /// Returns list of locked services /// </summary> /// <returns>Will return new list each time as a result of LINQ query</returns> /// <remarks></remarks> IList<IService> FindLockedServices(); /// <summary> /// Returns list of bouquets that have duplicate names /// </summary> /// <returns></returns> /// <remarks></remarks> IList<IFileBouquet> FindBouquetsWithDuplicateFilename(); /// <summary> /// Removes services without transponder from the list of services /// </summary> /// <remarks></remarks> void RemoveServicesWithoutTransponder(); /// <summary> /// Adds new xmlSatellites and xmlTransponders for all transponders in settings file /// that don't have corresponding xmlSatellite. /// </summary> /// <param name="factory"></param> /// <param name="frequencyToleration">Toleration in Hz when searching for existing transponder</param> /// <remarks>Only transponders for new xmlSatellites will be added if not found.</remarks> void AddMissingXmlSatellites(IInstanceFactory factory, int frequencyToleration = 30000); /// <summary> /// Adds new xmlTransponders for all transponders in settings file /// that don't have corresponding xmlTransponder in xmlsatellites.xml /// </summary> /// <param name="factory"></param> /// <param name="frequencyToleration">Toleration in Hz when searching for existing transponder</param> /// <remarks>Transponders are added to all satellites without matching transponder</remarks> void AddMissingXmlTransponders(IInstanceFactory factory, int frequencyToleration = 30000); /// <summary> /// Matches services without transponder with corresponding transponders /// </summary> /// <remarks></remarks> void MatchServicesWithTransponders(); /// <summary> /// Matches transponders from settings file without corresponding satellite to satellites from xml file /// </summary> /// <remarks></remarks> void MatchSatellitesWithTransponders(); /// <summary> /// Matches services from file bouquets to services from settings /// </summary> /// <remarks></remarks> void MatchFileBouquetsServices(); /// <summary> /// Matches services from bouquets inside 'bouquets' to services from settings /// </summary> /// <remarks></remarks> void MatchBouquetsBouquetsServices(); /// <summary> /// Renumbers markers in all bouquets /// </summary> /// <remarks></remarks> void RenumberMarkers(); /// <summary> /// Renumbers file names for all file bouquets that have filename starting with 'userbouquet.dbe' /// </summary> /// <remarks>Preserves path in filename if any is set</remarks> void RenumberBouquetFileNames(); /// <summary> /// Removes markers that are followed by another marker, or not followed with any items /// </summary> /// <remarks></remarks> void RemoveEmptyMarkers(); /// <summary> /// Removes markers that are followed by another marker, or not followed with any items /// </summary> /// <param name="preserveCondition">Markers that match specified condition will always be preserved</param> /// <exception cref="SettingsException"></exception> void RemoveEmptyMarkers(Func<IBouquetItemMarker, bool> preserveCondition); /// <summary> /// Removes bouquets without any items /// </summary> /// <remarks></remarks> void RemoveEmptyBouquets(); /// <summary> /// Removes all stream references from all bouquets /// </summary> /// <remarks></remarks> void RemoveStreams(); /// <summary> /// Removes service from list of services and all bouquets /// </summary> /// <remarks></remarks> void RemoveService(IService service); /// <summary> /// Removes services from list of services and all bouquets /// </summary> /// <param name="srv">List of services to be removed</param> /// <remarks></remarks> void RemoveServices(IList<IService> srv); /// <summary> /// Removes transponder from list of transponders /// and all services on that transponder from all bouquets and from list of services /// </summary> /// <param name="transponder"></param> /// <remarks></remarks> void RemoveTransponder(ITransponder transponder); /// <summary> /// Removes transponders from list of transponders /// and all services on specified transponders from all bouquets and from list of services /// </summary> /// <param name="trans"></param> /// <remarks></remarks> void RemoveTransponders(IList<ITransponder> trans); /// <summary> /// Remove satellite from list of satellites, /// removes all corresponding transponders from list of transponders /// removes services on that satellite from all bouquets and from list of services /// </summary> /// <param name="satellite"></param> /// <remarks></remarks> void RemoveSatellite(IXmlSatellite satellite); /// <summary> /// Remove satellite from list of satellites, /// removes all corresponding transponders from list of transponders /// removes services on that satellite from all bouquets and from list of services /// </summary> /// <param name="orbitalPosition">Orbital position as integer, as seen in satellites.xml file - IE. Astra 19.2 = 192</param> /// <remarks></remarks> void RemoveSatellite(int orbitalPosition); /// <summary> /// Removes IBouquetItemService, IBouquetItemFileBouquet and IBouquetItemBouquetsBouquet bouquet items without valid /// reference to service or another bouquet from all bouquets /// </summary> /// <remarks>IBouquetsBouquet, IBouquetItemMarker and IBouquetItemStream items are preserved</remarks> void RemoveInvalidBouquetItems(); /// <summary> /// Updates namespaces for all satellite transponders with calculated namespace /// </summary> /// <remarks></remarks> void UpdateSatelliteTranspondersNameSpaces(); /// <summary> /// Changes satellite position to new position for satellite and belonging transponders /// </summary> /// <param name="satellite">Instance of IXmlSatellite</param> /// <param name="newPosition">New orbital position as integer as seen in satellites.xml file, IE. Astra 19.2 = 192</param> /// <remarks></remarks> void ChangeSatellitePosition(IXmlSatellite satellite, int newPosition); /// <summary> /// Performs MemberwiseClone on current object /// </summary> /// <returns></returns> object ShallowCopy(); } }
using System; using System.Collections.Generic; using FluentAssertions; using System.Linq; using Xunit; namespace Pocket.Tests { public class FormatterTests { [Fact] public void Formatter_identifies_format_tokens() { var template = "This template contains two tokens: {this} and {that}"; var formatter = Formatter.Parse(template); formatter.Tokens.Should().BeEquivalentTo("this", "that"); } [Fact] public void Formatter_generates_key_value_pairs_associating_arguments_with_tokens() { var template = "This template contains two tokens: {this} and {that}"; var formatter = Formatter.Parse(template); var result = formatter.Format(true, 42); result.Single(v => v.Name == "this").Value.Should().Be(true); result.Single(v => v.Name == "that").Value.Should().Be(42); } [Fact] public void When_null_is_passed_to_the_args_array_of_Format_its_ok() { var formatter = Formatter.Parse("The values are {this} and {that}"); var result = formatter.Format(null); result.Should().HaveCount(2); result.Single(v => v.Name == "this").Value.Should().BeNull(); result.Single(v => v.Name == "that").Value.Should().BeNull(); result.ToString().Should().Be("The values are [null] and [null]"); } [Fact] public void Formatter_generates_key_value_pairs_associating_null_arguments_with_tokens() { var formatter = Formatter.Parse("The value is {value}"); var result = formatter.Format(new object[] { null }); result.Single(v => v.Name == "value").Value.Should().BeNull(); } [Fact] public void Formatter_templates_arguments_into_the_result() { var template = "This template contains two tokens: {this} and {that}"; var formatter = Formatter.Parse(template); var result = formatter.Format(true, 42); result.ToString() .Should() .Be("This template contains two tokens: True and 42"); } [Fact] public void Formatter_templates_null_arguments_into_the_result() { var formatter = Formatter.Parse("The value is {value}"); var result = formatter.Format(new object[] { null }); result.ToString() .Should() .Be("The value is [null]"); } [Fact] public void Formatter_can_be_reused_with_different_arguments() { var formatter = Formatter.Parse("The value is {i}"); var result1 = formatter.Format(1); var result2 = formatter.Format(2); result1.ToString().Should().Be("The value is 1"); result2.ToString().Should().Be("The value is 2"); } [Fact] public void IFormattable_args_can_have_their_format_specified_in_the_template() { var formatter = Formatter.Parse("The hour is {time:HH}"); var result = formatter.Format(DateTime.Parse("12/12/2012 11:42pm")).ToString(); result.Should() .Be("The hour is 23"); } [Fact] public void When_a_token_occurs_multiple_times_then_every_occurrence_is_replaced() { var formatter = Formatter.Parse("{one} and {two} and {one}"); var result = formatter.Format(1, 2); result.ToString() .Should() .Be("1 and 2 and 1"); } [Fact] public void When_there_are_more_tokens_than_arguments_then_some_tokens_are_not_replaced() { var formatter = Formatter.Parse("{one} and {two} and {three}"); var result = formatter.Format(1, 2); result.ToString() .Should() .Be("1 and 2 and {three}"); } [Fact] public void When_there_are_more_arguments_than_tokens_then_extra_arguments_are_appended() { var formatter = Formatter.Parse("{one} and {two}"); var result = formatter.Format(1, 2, 3, 4); result.ToString() .Should() .Be("1 and 2 +[ 3, 4 ]"); } [Fact] public void When_there_are_additional_properties_then_they_are_appended() { var formatter = Formatter.Parse(""); var result = formatter.Format( args: null, knownProperties: new List<(string, object)> { ("also", "this") }); result.ToString() .Should() .Be(" +[ (also, this) ]"); } [Fact] public void When_there_are_additional_properties_then_they_are_appended_after_additional_args() { var formatter = Formatter.Parse("{one} and {two}"); var result = formatter.Format( args: new object[] { 1, 2, 3, 4 }, knownProperties: new List<(string, object)> { ("also", "this") }); result.ToString() .Should() .Be("1 and 2 +[ 3, 4, (also, this) ]"); } [Fact] public void When_there_are_more_arguments_than_tokens_then_extra_arguments_are_available_as_key_value_pairs() { var formatter = Formatter.Parse("{one} and {two}"); var result = formatter.Format(1, 2, 3, ("some-metric", 4)); result[2].Should().Be(("arg2", 3)); result[3].Should().Be(("arg3", ("some-metric", 4))); } [Fact] public void IEnumerable_types_are_expanded() { var formatter = Formatter.Parse("The values in the array are: {values}"); var result = formatter.Format(new[] { 1, 2, 3, 4 }, new[] { 4, 5, 6 }); result.ToString() .Should() .Be("The values in the array are: [ 1, 2, 3, 4 ] +[ [ 4, 5, 6 ] ]"); } [Fact] public void Formatter_cache_stops_adding_items_after_specified_size() { Formatter.CacheLimit = 50; for (var i = 0; i < 103; i++) { Formatter.Parse($"{i}"); } Formatter.CacheCount.Should().Be(50); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void RoundToNegativeInfinityScalarDouble() { var test = new SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble testClass) { var result = Sse41.RoundToNegativeInfinityScalar(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) { var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Vector128<Double> _clsVar1; private Vector128<Double> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.RoundToNegativeInfinityScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinityScalar), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinityScalar), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.RoundToNegativeInfinityScalar), new Type[] { typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.RoundToNegativeInfinityScalar( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) { var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadVector128((Double*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var result = Sse41.RoundToNegativeInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNegativeInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var result = Sse41.RoundToNegativeInfinityScalar(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble(); var result = Sse41.RoundToNegativeInfinityScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__RoundToNegativeInfinityScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) { var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.RoundToNegativeInfinityScalar(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) { var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadVector128((Double*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.RoundToNegativeInfinityScalar(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.RoundToNegativeInfinityScalar( Sse2.LoadVector128((Double*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Floor(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.RoundToNegativeInfinityScalar)}<Double>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using NPoco; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Models.Entities; using Umbraco.Cms.Core.Persistence; using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.Factories; using Umbraco.Cms.Infrastructure.Persistence.Querying; using Umbraco.Extensions; namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement { // TODO: We should update this to support both users and members. It means we would remove referential integrity from users // and the user/member key would be a GUID (we also need to add a GUID to users) internal class ExternalLoginRepository : EntityRepositoryBase<int, IIdentityUserLogin>, IExternalLoginRepository { public ExternalLoginRepository(IScopeAccessor scopeAccessor, AppCaches cache, ILogger<ExternalLoginRepository> logger) : base(scopeAccessor, cache, logger) { } public void DeleteUserLogins(int memberId) => Database.Delete<ExternalLoginDto>("WHERE userId=@userId", new { userId = memberId }); public void Save(int userId, IEnumerable<IExternalLogin> logins) { var sql = Sql() .Select<ExternalLoginDto>() .From<ExternalLoginDto>() .Where<ExternalLoginDto>(x => x.UserId == userId) .ForUpdate(); // deduplicate the logins logins = logins.DistinctBy(x => x.ProviderKey + x.LoginProvider).ToList(); var toUpdate = new Dictionary<int, IExternalLogin>(); var toDelete = new List<int>(); var toInsert = new List<IExternalLogin>(logins); var existingLogins = Database.Fetch<ExternalLoginDto>(sql); foreach (var existing in existingLogins) { var found = logins.FirstOrDefault(x => x.LoginProvider.Equals(existing.LoginProvider, StringComparison.InvariantCultureIgnoreCase) && x.ProviderKey.Equals(existing.ProviderKey, StringComparison.InvariantCultureIgnoreCase)); if (found != null) { toUpdate.Add(existing.Id, found); // if it's an update then it's not an insert toInsert.RemoveAll(x => x.ProviderKey == found.ProviderKey && x.LoginProvider == found.LoginProvider); } else { toDelete.Add(existing.Id); } } // do the deletes, updates and inserts if (toDelete.Count > 0) { Database.DeleteMany<ExternalLoginDto>().Where(x => toDelete.Contains(x.Id)).Execute(); } foreach (var u in toUpdate) { Database.Update(ExternalLoginFactory.BuildDto(userId, u.Value, u.Key)); } Database.InsertBulk(toInsert.Select(i => ExternalLoginFactory.BuildDto(userId, i))); } protected override IIdentityUserLogin PerformGet(int id) { var sql = GetBaseQuery(false); sql.Where(GetBaseWhereClause(), new { id = id }); var dto = Database.Fetch<ExternalLoginDto>(SqlSyntax.SelectTop(sql, 1)).FirstOrDefault(); if (dto == null) return null; var entity = ExternalLoginFactory.BuildEntity(dto); // reset dirty initial properties (U4-1946) entity.ResetDirtyProperties(false); return entity; } protected override IEnumerable<IIdentityUserLogin> PerformGetAll(params int[] ids) { if (ids.Any()) { return PerformGetAllOnIds(ids); } var sql = GetBaseQuery(false).OrderByDescending<ExternalLoginDto>(x => x.CreateDate); return ConvertFromDtos(Database.Fetch<ExternalLoginDto>(sql)) .ToArray();// we don't want to re-iterate again! } private IEnumerable<IIdentityUserLogin> PerformGetAllOnIds(params int[] ids) { if (ids.Any() == false) yield break; foreach (var id in ids) { yield return Get(id); } } private IEnumerable<IIdentityUserLogin> ConvertFromDtos(IEnumerable<ExternalLoginDto> dtos) { foreach (var entity in dtos.Select(ExternalLoginFactory.BuildEntity)) { // reset dirty initial properties (U4-1946) ((BeingDirtyBase)entity).ResetDirtyProperties(false); yield return entity; } } protected override IEnumerable<IIdentityUserLogin> PerformGetByQuery(IQuery<IIdentityUserLogin> query) { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator<IIdentityUserLogin>(sqlClause, query); var sql = translator.Translate(); var dtos = Database.Fetch<ExternalLoginDto>(sql); foreach (var dto in dtos) { yield return ExternalLoginFactory.BuildEntity(dto); } } protected override Sql<ISqlContext> GetBaseQuery(bool isCount) { var sql = Sql(); if (isCount) sql.SelectCount(); else sql.SelectAll(); sql.From<ExternalLoginDto>(); return sql; } protected override string GetBaseWhereClause() => $"{Constants.DatabaseSchema.Tables.ExternalLogin}.id = @id"; protected override IEnumerable<string> GetDeleteClauses() { var list = new List<string> { "DELETE FROM umbracoExternalLogin WHERE id = @id" }; return list; } protected override void PersistNewItem(IIdentityUserLogin entity) { entity.AddingEntity(); var dto = ExternalLoginFactory.BuildDto(entity); var id = Convert.ToInt32(Database.Insert(dto)); entity.Id = id; entity.ResetDirtyProperties(); } protected override void PersistUpdatedItem(IIdentityUserLogin entity) { entity.UpdatingEntity(); var dto = ExternalLoginFactory.BuildDto(entity); Database.Update(dto); entity.ResetDirtyProperties(); } /// <summary> /// Query for user tokens /// </summary> /// <param name="query"></param> /// <returns></returns> public IEnumerable<IIdentityUserToken> Get(IQuery<IIdentityUserToken> query) { Sql<ISqlContext> sqlClause = GetBaseTokenQuery(false); var translator = new SqlTranslator<IIdentityUserToken>(sqlClause, query); Sql<ISqlContext> sql = translator.Translate(); List<ExternalLoginTokenDto> dtos = Database.Fetch<ExternalLoginTokenDto>(sql); foreach (ExternalLoginTokenDto dto in dtos) { yield return ExternalLoginFactory.BuildEntity(dto); } } /// <summary> /// Count for user tokens /// </summary> /// <param name="query"></param> /// <returns></returns> public int Count(IQuery<IIdentityUserToken> query) { Sql<ISqlContext> sql = Sql().SelectCount().From<ExternalLoginDto>(); return Database.ExecuteScalar<int>(sql); } public void Save(int userId, IEnumerable<IExternalLoginToken> tokens) { // get the existing logins (provider + id) var existingUserLogins = Database .Fetch<ExternalLoginDto>(GetBaseQuery(false).Where<ExternalLoginDto>(x => x.UserId == userId)) .ToDictionary(x => x.LoginProvider, x => x.Id); // deduplicate the tokens tokens = tokens.DistinctBy(x => x.LoginProvider + x.Name).ToList(); var providers = tokens.Select(x => x.LoginProvider).Distinct().ToList(); Sql<ISqlContext> sql = GetBaseTokenQuery(true) .WhereIn<ExternalLoginDto>(x => x.LoginProvider, providers) .Where<ExternalLoginDto>(x => x.UserId == userId); var toUpdate = new Dictionary<int, (IExternalLoginToken externalLoginToken, int externalLoginId)>(); var toDelete = new List<int>(); var toInsert = new List<IExternalLoginToken>(tokens); var existingTokens = Database.Fetch<ExternalLoginTokenDto>(sql); foreach (ExternalLoginTokenDto existing in existingTokens) { IExternalLoginToken found = tokens.FirstOrDefault(x => x.LoginProvider.InvariantEquals(existing.ExternalLoginDto.LoginProvider) && x.Name.InvariantEquals(existing.Name)); if (found != null) { toUpdate.Add(existing.Id, (found, existing.ExternalLoginId)); // if it's an update then it's not an insert toInsert.RemoveAll(x => x.LoginProvider.InvariantEquals(found.LoginProvider) && x.Name.InvariantEquals(found.Name)); } else { toDelete.Add(existing.Id); } } // do the deletes, updates and inserts if (toDelete.Count > 0) { Database.DeleteMany<ExternalLoginTokenDto>().Where(x => toDelete.Contains(x.Id)).Execute(); } foreach (KeyValuePair<int, (IExternalLoginToken externalLoginToken, int externalLoginId)> u in toUpdate) { Database.Update(ExternalLoginFactory.BuildDto(u.Value.externalLoginId, u.Value.externalLoginToken, u.Key)); } var insertDtos = new List<ExternalLoginTokenDto>(); foreach(IExternalLoginToken t in toInsert) { if (!existingUserLogins.TryGetValue(t.LoginProvider, out int externalLoginId)) { throw new InvalidOperationException($"A token was attempted to be saved for login provider {t.LoginProvider} which is not assigned to this user"); } insertDtos.Add(ExternalLoginFactory.BuildDto(externalLoginId, t)); } Database.InsertBulk(insertDtos); } private Sql<ISqlContext> GetBaseTokenQuery(bool forUpdate) => forUpdate ? Sql() .Select<ExternalLoginTokenDto>(r => r.Select(x => x.ExternalLoginDto)) .From<ExternalLoginTokenDto>() .Append(" WITH (UPDLOCK)") // ensure these table values are locked for updates, the ForUpdate ext method does not work here .InnerJoin<ExternalLoginDto>() .On<ExternalLoginTokenDto, ExternalLoginDto>(x => x.ExternalLoginId, x => x.Id) : Sql() .Select<ExternalLoginTokenDto>() .AndSelect<ExternalLoginDto>(x => x.LoginProvider, x => x.UserId) .From<ExternalLoginTokenDto>() .InnerJoin<ExternalLoginDto>() .On<ExternalLoginTokenDto, ExternalLoginDto>(x => x.ExternalLoginId, x => x.Id); } }
// 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.Runtime; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.ObjectModel; namespace System.Collections.Generic { // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T> { private const int _defaultCapacity = 4; private T[] _items; [ContractPublicPropertyName("Count")] private int _size; private int _version; private Object _syncRoot; static readonly T[] _emptyArray = new T[0]; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to 16, and then increased in multiples of two as required. public List() { _items = _emptyArray; } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public List(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (capacity == 0) _items = _emptyArray; else _items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public List(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { int count = c.Count; if (count == 0) { _items = _emptyArray; } else { _items = new T[count]; c.CopyTo(_items, 0); _size = count; } } else { _size = 0; _items = _emptyArray; // This enumerable could be empty. Let Add allocate a new array, if needed. // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Add(en.Current); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return _items.Length; } set { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } Contract.EndContractBlock(); if (value != _items.Length) { if (value > 0) { var items = new T[value]; Array.Copy(_items, 0, items, 0, _size); _items = items; } else { _items = _emptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } bool System.Collections.IList.IsFixedSize { get { return false; } } // Is this List read-only? bool ICollection<T>.IsReadOnly { get { return false; } } bool System.Collections.IList.IsReadOnly { get { return false; } } // Is this List synchronized (thread-safe)? bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. Object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Sets or Gets the element at the given index. // public T this[int index] { get { // Following trick can reduce the range check by one if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } Object System.Collections.IList.this[int index] { get { return this[index]; } set { if (value == null && !(default(T) == null)) throw new ArgumentNullException(nameof(value)); try { this[index] = (T)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(T)), nameof(value)); } } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } int System.Collections.IList.Add(Object item) { if (item == null && !(default(T) == null)) throw new ArgumentNullException(nameof(item)); try { Add((T)item); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item)); } return Count - 1; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public void AddRange(IEnumerable<T> collection) { Contract.Ensures(Count >= Contract.OldValue(Count)); InsertRange(_size, collection); } public ReadOnlyCollection<T> AsReadOnly() { return new ReadOnlyCollection<T>(this); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. // public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() <= index + count); Contract.EndContractBlock(); return Array.BinarySearch<T>(_items, index, count, item, comparer); } public int BinarySearch(T item) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, null); } public int BinarySearch(T item, IComparer<T> comparer) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, comparer); } // Clears the contents of List. public void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public bool Contains(T item) { if ((Object)item == null) { for (int i = 0; i < _size; i++) if ((Object)_items[i] == null) return true; return false; } else { EqualityComparer<T> c = EqualityComparer<T>.Default; for (int i = 0; i < _size; i++) { if (c.Equals(_items[i], item)) return true; } return false; } } bool System.Collections.IList.Contains(Object item) { if (IsCompatibleObject(item)) { return Contains((T)item); } return false; } // Copies this List into array, which must be of a // compatible array type. // public void CopyTo(T[] array) { CopyTo(array, 0); } // Copies this List into array, which must be of a // compatible array type. // void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } Contract.EndContractBlock(); try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. // public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Ensures that the capacity of this list is at least the given minimum // value. If the currect capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast //if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } public bool Exists(Predicate<T> match) { return FindIndex(match) != -1; } public T Find(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { if (match(_items[i])) { return _items[i]; } } return default(T); } public List<T> FindAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); List<T> list = new List<T>(); for (int i = 0; i < _size; i++) { if (match(_items[i])) { list.Add(_items[i]); } } return list; } public int FindIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindIndex(0, _size, match); } public int FindIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + Count); return FindIndex(startIndex, _size - startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { if ((uint)startIndex > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _size - count) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + count); Contract.EndContractBlock(); int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { if (match(_items[i])) return i; } return -1; } public T FindLast(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = _size - 1; i >= 0; i--) { if (match(_items[i])) { return _items[i]; } } return default(T); } public int FindLastIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindLastIndex(_size - 1, _size, match); } public int FindLastIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); return FindLastIndex(startIndex, startIndex + 1, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); Contract.EndContractBlock(); if (_size == 0) { // Special case for 0 length List if (startIndex != -1) { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } } else if ((uint)startIndex >= (uint)_size) // Make sure we're not out of range { throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index); } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { if (match(_items[i])) { return i; } } return -1; } public void ForEach(Action<T> action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } int version = _version; for (int i = 0; i < _size; i++) { if (version != _version) { break; } action(_items[i]); } if (version != _version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public List<T> GetRange(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Contract.Ensures(Contract.Result<List<T>>() != null); Contract.EndContractBlock(); List<T> list = new List<T>(count); Array.Copy(_items, index, list._items, 0, count); list._size = count; return list; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); } int System.Collections.IList.IndexOf(Object item) { if (IsCompatibleObject(item)) { return IndexOf((T)item); } return -1; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index, int count) { if (index > _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); if (count < 0 || index > _size - count) throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, count); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection); } Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = item; _size++; _version++; } void System.Collections.IList.Insert(int index, Object item) { if (item == null && !(default(T) == null)) throw new ArgumentNullException(nameof(item)); try { Insert(index, (T)item); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item)); } } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. // public void InsertRange(int index, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if ((uint)index > (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if (c != null) { // if collection is ICollection<T> int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } // If we're inserting a List into itself, we want to be able to deal with that. if (this == c) { // Copy first part of _items to insert location Array.Copy(_items, 0, _items, index, index); // Copy last part of _items back to inserted location Array.Copy(_items, index + count, _items, index * 2, _size - index); } else { T[] itemsToInsert = new T[count]; c.CopyTo(itemsToInsert, 0); Array.Copy(itemsToInsert, 0, _items, index, count); } _size += count; } } else { using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Insert(index++, en.Current); } } } _version++; } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); if (_size == 0) { // Special case for empty list return -1; } else { return LastIndexOf(item, _size - 1, _size); } } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item, int index) { if (index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); return LastIndexOf(item, index, index + 1); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item, int index, int count) { if ((Count != 0) && (index < 0)) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if ((Count != 0) && (count < 0)) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); if (_size == 0) { // Special case for empty list return -1; } if (index >= _size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (count > index + 1) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count); } return Array.LastIndexOf(_items, item, index, count); } // Removes the element at the given index. The size of the list is // decreased by one. // public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } void System.Collections.IList.Remove(Object item) { if (IsCompatibleObject(item)) { Remove((T)item); } } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count)); Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++; if (freeIndex >= _size) return 0; int current = freeIndex + 1; while (current < _size) { // Find the first item which needs to be kept. while (current < _size && match(_items[current])) current++; if (current < _size) { // copy item to the free slot. _items[freeIndex++] = _items[current++]; } } Array.Clear(_items, freeIndex, _size - freeIndex); int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. // public void RemoveAt(int index) { if ((uint)index >= (uint)_size) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = default(T); _version++; } // Removes a range of elements from this list. // public void RemoveRange(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count > 0) { int i = _size; _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } Array.Clear(_items, _size, count); _version++; } } // Reverses the elements in this list. public void Reverse() { Reverse(0, Count); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // public void Reverse(int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = index; int j = index + count - 1; T[] array = _items; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } _version++; } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() { Sort(0, Count, null); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort(IComparer<T> comparer) { Sort(0, Count, comparer); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. // public void Sort(int index, int count, IComparer<T> comparer) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); Array.Sort<T>(_items, index, count, comparer); _version++; } public void Sort(Comparison<T> comparison) { if (comparison == null) { throw new ArgumentNullException(nameof(comparison)); } Contract.EndContractBlock(); if (_size > 0) { IComparer<T> comparer = Comparer<T>.Create(comparison); Array.Sort(_items, 0, _size, comparer); } } // ToArray returns a new Object array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { Contract.Ensures(Contract.Result<T[]>() != null); Contract.Ensures(Contract.Result<T[]>().Length == Count); if (_size == 0) { return _emptyArray; } T[] array = new T[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimExcess(); // public void TrimExcess() { int threshold = (int)(((double)_items.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } public bool TrueForAll(Predicate<T> match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } Contract.EndContractBlock(); for (int i = 0; i < _size; i++) { if (!match(_items[i])) { return false; } } return true; } public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private List<T> list; private int index; private int version; private T current; internal Enumerator(List<T> list) { this.list = list; index = 0; version = list._version; current = default(T); } public void Dispose() { } public bool MoveNext() { List<T> localList = list; if (version == localList._version && ((uint)index < (uint)localList._size)) { current = localList._items[index]; index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (version != list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = list._size + 1; current = default(T); return false; } public T Current { get { return current; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || index == list._size + 1) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current; } } void System.Collections.IEnumerator.Reset() { if (version != list._version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = 0; current = default(T); } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; /// <summary> /// Exception information provided through /// a call to one of the Logger.*Exception() methods. /// </summary> [LayoutRenderer("exception")] [ThreadAgnostic] public class ExceptionLayoutRenderer : LayoutRenderer { private string _format; private string _innerFormat = string.Empty; private readonly Dictionary<ExceptionRenderingFormat, Action<StringBuilder, Exception>> _renderingfunctions; private static readonly Dictionary<string, ExceptionRenderingFormat> _formatsMapping = new Dictionary<string, ExceptionRenderingFormat>(StringComparer.OrdinalIgnoreCase) { {"MESSAGE",ExceptionRenderingFormat.Message}, {"TYPE", ExceptionRenderingFormat.Type}, {"SHORTTYPE",ExceptionRenderingFormat.ShortType}, {"TOSTRING",ExceptionRenderingFormat.ToString}, {"METHOD",ExceptionRenderingFormat.Method}, {"STACKTRACE", ExceptionRenderingFormat.StackTrace}, {"DATA",ExceptionRenderingFormat.Data}, {"@",ExceptionRenderingFormat.Serialize}, }; /// <summary> /// Initializes a new instance of the <see cref="ExceptionLayoutRenderer" /> class. /// </summary> public ExceptionLayoutRenderer() { Format = "message"; Separator = " "; ExceptionDataSeparator = ";"; InnerExceptionSeparator = EnvironmentHelper.NewLine; MaxInnerExceptionLevel = 0; _renderingfunctions = new Dictionary<ExceptionRenderingFormat, Action<StringBuilder, Exception>>() { {ExceptionRenderingFormat.Message, AppendMessage}, {ExceptionRenderingFormat.Type, AppendType}, {ExceptionRenderingFormat.ShortType, AppendShortType}, {ExceptionRenderingFormat.ToString, AppendToString}, {ExceptionRenderingFormat.Method, AppendMethod}, {ExceptionRenderingFormat.StackTrace, AppendStackTrace}, {ExceptionRenderingFormat.Data, AppendData}, {ExceptionRenderingFormat.Serialize, AppendSerializeObject}, }; } /// <summary> /// Gets or sets the format of the output. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <see cref="Formats"/> /// <see cref="ExceptionRenderingFormat"/> /// <docgen category='Rendering Options' order='10' /> [DefaultParameter] public string Format { get => _format; set { _format = value; Formats = CompileFormat(value); } } /// <summary> /// Gets or sets the format of the output of inner exceptions. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerFormat { get => _innerFormat; set { _innerFormat = value; InnerFormats = CompileFormat(value); } } /// <summary> /// Gets or sets the separator used to concatenate parts specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(" ")] public string Separator { get; set; } /// <summary> /// Gets or sets the separator used to concatenate exception data specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(";")] public string ExceptionDataSeparator { get; set; } /// <summary> /// Gets or sets the maximum number of inner exceptions to include in the output. /// By default inner exceptions are not enabled for compatibility with NLog 1.0. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(0)] public int MaxInnerExceptionLevel { get; set; } /// <summary> /// Gets or sets the separator between inner exceptions. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerExceptionSeparator { get; set; } /// <summary> /// Gets the formats of the output of inner exceptions to be rendered in target. /// </summary> /// <docgen category='Rendering Options' order='10' /> /// <see cref="ExceptionRenderingFormat"/> public List<ExceptionRenderingFormat> Formats { get; private set; } /// <summary> /// Gets the formats of the output to be rendered in target. /// </summary> /// <docgen category='Rendering Options' order='10' /> /// <see cref="ExceptionRenderingFormat"/> public List<ExceptionRenderingFormat> InnerFormats { get; private set; } /// <summary> /// Renders the specified exception information and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Exception primaryException = logEvent.Exception; if (primaryException != null) { AppendException(primaryException, Formats, builder); int currentLevel = 0; if (currentLevel < MaxInnerExceptionLevel) { currentLevel = AppendInnerExceptionTree(primaryException, currentLevel, builder); #if !NET3_5 && !SILVERLIGHT4 AggregateException asyncException = primaryException as AggregateException; if (asyncException != null) { AppendAggregateException(asyncException, currentLevel, builder); } #endif } } } #if !NET3_5 && !SILVERLIGHT4 private void AppendAggregateException(AggregateException primaryException, int currentLevel, StringBuilder builder) { var asyncException = primaryException.Flatten(); if (asyncException.InnerExceptions != null) { for (int i = 0; i < asyncException.InnerExceptions.Count && currentLevel < MaxInnerExceptionLevel; i++, currentLevel++) { var currentException = asyncException.InnerExceptions[i]; if (ReferenceEquals(currentException, primaryException.InnerException)) continue; // Skip firstException when it is innerException if (currentException == null) { InternalLogger.Debug("Skipping rendering exception as exception is null"); continue; } AppendInnerException(currentException, builder); currentLevel++; currentLevel = AppendInnerExceptionTree(currentException, currentLevel, builder); } } } #endif private int AppendInnerExceptionTree(Exception currentException, int currentLevel, StringBuilder sb) { currentException = currentException.InnerException; while (currentException != null && currentLevel < MaxInnerExceptionLevel) { AppendInnerException(currentException, sb); currentLevel++; currentException = currentException.InnerException; } return currentLevel; } private void AppendInnerException(Exception currentException, StringBuilder builder) { // separate inner exceptions builder.Append(InnerExceptionSeparator); AppendException(currentException, InnerFormats ?? Formats, builder); } private void AppendException(Exception currentException, List<ExceptionRenderingFormat> renderFormats, StringBuilder builder) { int orgLength = builder.Length; foreach (ExceptionRenderingFormat renderingFormat in renderFormats) { if (orgLength != builder.Length) { orgLength = builder.Length; builder.Append(Separator); } int beforeRenderLength = builder.Length; var currentRenderFunction = _renderingfunctions[renderingFormat]; currentRenderFunction(builder, currentException); if (builder.Length == beforeRenderLength && builder.Length != orgLength) { builder.Length = orgLength; } } } /// <summary> /// Appends the Message of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The exception containing the Message to append.</param> protected virtual void AppendMessage(StringBuilder sb, Exception ex) { try { sb.Append(ex.Message); } catch (Exception exception) { var message = $"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendMessage(): {exception.GetType().FullName}."; sb.Append("NLog message: "); sb.Append(message); InternalLogger.Warn(exception, message); } } /// <summary> /// Appends the method name from Exception's stack trace to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose method name should be appended.</param> protected virtual void AppendMethod(StringBuilder sb, Exception ex) { #if SILVERLIGHT || NETSTANDARD1_0 sb.Append(ParseMethodNameFromStackTrace(ex.StackTrace)); #else if (ex.TargetSite != null) { sb.Append(ex.TargetSite.ToString()); } #endif } /// <summary> /// Appends the stack trace from an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose stack trace should be appended.</param> protected virtual void AppendStackTrace(StringBuilder sb, Exception ex) { if (!string.IsNullOrEmpty(ex.StackTrace)) sb.Append(ex.StackTrace); } /// <summary> /// Appends the result of calling ToString() on an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose call to ToString() should be appended.</param> protected virtual void AppendToString(StringBuilder sb, Exception ex) { sb.Append(ex.ToString()); } /// <summary> /// Appends the type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose type should be appended.</param> protected virtual void AppendType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().FullName); } /// <summary> /// Appends the short type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose short type should be appended.</param> protected virtual void AppendShortType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().Name); } /// <summary> /// Appends the contents of an Exception's Data property to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose Data property elements should be appended.</param> protected virtual void AppendData(StringBuilder sb, Exception ex) { if (ex.Data != null && ex.Data.Count > 0) { string separator = string.Empty; foreach (var key in ex.Data.Keys) { sb.Append(separator); sb.AppendFormat("{0}: {1}", key, ex.Data[key]); separator = ExceptionDataSeparator; } } } /// <summary> /// Appends all the serialized properties of an Exception into the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose properties should be appended.</param> protected virtual void AppendSerializeObject(StringBuilder sb, Exception ex) { ConfigurationItemFactory.Default.ValueSerializer.SerializeObject(ex, null, null, sb); } /// <summary> /// Split the string and then compile into list of Rendering formats. /// </summary> /// <param name="formatSpecifier"></param> /// <returns></returns> private static List<ExceptionRenderingFormat> CompileFormat(string formatSpecifier) { List<ExceptionRenderingFormat> formats = new List<ExceptionRenderingFormat>(); string[] parts = formatSpecifier.Replace(" ", string.Empty).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in parts) { ExceptionRenderingFormat renderingFormat; if (_formatsMapping.TryGetValue(s, out renderingFormat)) { formats.Add(renderingFormat); } else { InternalLogger.Warn("Unknown exception data target: {0}", s); } } return formats; } #if SILVERLIGHT || NETSTANDARD1_0 /// <summary> /// Find name of method on stracktrace. /// </summary> /// <param name="stackTrace">Full stracktrace</param> /// <returns></returns> protected static string ParseMethodNameFromStackTrace(string stackTrace) { if (string.IsNullOrEmpty(stackTrace)) return string.Empty; // get the first line of the stack trace string stackFrameLine; int p = stackTrace.IndexOfAny(new[] { '\r', '\n' }); if (p >= 0) { stackFrameLine = stackTrace.Substring(0, p); } else { stackFrameLine = stackTrace; } // stack trace is composed of lines which look like this // // at NLog.UnitTests.LayoutRenderers.ExceptionTests.GenericClass`3.Method2[T1,T2,T3](T1 aaa, T2 b, T3 o, Int32 i, DateTime now, Nullable`1 gfff, List`1[] something) // // "at " prefix can be localized so we cannot hard-code it but it's followed by a space, class name (which does not have a space in it) and opening parenthesis int lastSpace = -1; int startPos = 0; int endPos = stackFrameLine.Length; for (int i = 0; i < stackFrameLine.Length; ++i) { switch (stackFrameLine[i]) { case ' ': lastSpace = i; break; case '(': startPos = lastSpace + 1; break; case ')': endPos = i + 1; // end the loop i = stackFrameLine.Length; break; } } return stackTrace.Substring(startPos, endPos - startPos); } #endif } }
/* Copyright 2018 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; //Added references using ArcGIS.Core.CIM; //CIM using ArcGIS.Core.Data; using ArcGIS.Desktop.Core; //Project using ArcGIS.Desktop.Layouts; //Layout class using ArcGIS.Desktop.Framework.Threading.Tasks; //QueuedTask using ArcGIS.Desktop.Mapping; //Export using ArcGIS.Core.Geometry; namespace Layout_HelpExamples { internal class LayoutViewClass : Button { protected override void OnClick() { LayoutViewClassSamples.MethodSnippets(); } } public class LayoutViewClassSamples { async public static void MethodSnippets() { LayoutView layoutView = LayoutView.Active; // cref: LayoutView_ZoomTo_Extent;ArcGIS.Desktop.Layouts.LayoutView.ZoomTo(ArcGIS.Core.Geometry.Geometry,System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_Extent //Set the page extent for a layout view. //Process on worker thread await QueuedTask.Run(() => { var lytExt = layoutView.Extent; layoutView.ZoomTo(lytExt); }); #endregion LayoutView_ZoomTo_Extent // cref: LayoutView_ZoomTo_Percent;ArcGIS.Desktop.Layouts.LayoutView.ZoomTo100Percent(System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_Percent //Set the layout view to 100 percent. //Process on worker thread await QueuedTask.Run(() => { layoutView.ZoomTo100Percent(); }); #endregion LayoutView_ZoomTo_Percent // cref: LayoutView_ZoomTo_Next;ArcGIS.Desktop.Layouts.LayoutView.ZoomToNext(System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_Next //Advance the layout view extent to the previous forward extent //Process on worker thread await QueuedTask.Run(() => { layoutView.ZoomToNext(); }); #endregion LayoutView_ZoomTo_Next // cref: LayoutView_ZoomTo_PageWidth;ArcGIS.Desktop.Layouts.LayoutView.ZoomToPageWidth(System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_PageWidth //Set the layout view extent to accomodate the width of the page. //Process on worker thread await QueuedTask.Run(() => { layoutView.ZoomToPageWidth(); }); #endregion LayoutView_ZoomTo_PageWidth // cref: LayoutView_ZoomTo_Previous;ArcGIS.Desktop.Layouts.LayoutView.ZoomToPrevious(System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_Previous //Set the layout view extent to the previous extent. //Process on worker thread await QueuedTask.Run(() => { layoutView.ZoomToPrevious(); }); #endregion LayoutView_ZoomTo_Previous // cref: LayoutView_ZoomTo_SelectedElements;ArcGIS.Desktop.Layouts.LayoutView.ZoomToSelectedElements(System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_SelectedElements //Set the layout view extent to the selected elements. //Process on worker thread await QueuedTask.Run(() => { layoutView.ZoomToSelectedElements(); }); #endregion LayoutView_ZoomTo_SelectedElements // cref: LayoutView_ZoomTo_WholePage;ArcGIS.Desktop.Layouts.LayoutView.ZoomToWholePage(System.Nullable{System.TimeSpan}) #region LayoutView_ZoomTo_WholePage //Set the layout view extent to fit the entire page. //Process on worker thread await QueuedTask.Run(() => { layoutView.ZoomToWholePage(); }); #endregion LayoutView_ZoomTo_WholePage // cref: LayoutView_Refresh;ArcGIS.Desktop.Layouts.LayoutView.Refresh #region LayoutView_Refresh //Refresh the layout view. //Process on worker thread await QueuedTask.Run(() => layoutView.Refresh()); #endregion // cref: LayoutView_GetSelection;ArcGIS.Desktop.Layouts.LayoutView.GetSelectedElements #region LayoutView_GetSelection //Get the selected layout elements. var selectedElements = layoutView.GetSelectedElements(); #endregion // cref: LayoutView_SetSelection;ArcGIS.Desktop.Layouts.LayoutView.SelectElements(System.Collections.Generic.IReadOnlyList{ArcGIS.Desktop.Layouts.Element}) #region LayoutView_SetSelection //Set the layout's element selection. Element rec = layoutView.Layout.FindElement("Rectangle"); Element rec2 = layoutView.Layout.FindElement("Rectangle 2"); List<Element> elmList = new List<Element>(); elmList.Add(rec); elmList.Add(rec2); layoutView.SelectElements(elmList); #endregion LayoutView_SetSelection // cref: LayoutView_SelectAll;ArcGIS.Desktop.Layouts.LayoutView.SelectAllElements #region LayoutView_SelectAll //Select all element on a layout. layoutView.SelectAllElements(); #endregion LayoutView_SelectAll // cref: LayoutView_ClearSelection;ArcGIS.Desktop.Layouts.LayoutView.ClearElementSelection #region LayoutView_ClearSelection //Clear the layout's element selection. layoutView.ClearElementSelection(); #endregion LayoutView_ClearSelection Layout layout = LayoutFactory.Instance.CreateLayout(5, 5, LinearUnit.Inches); // cref: LayoutView_FindAndCloseLayoutPanes;ArcGIS.Desktop.Core.LayoutFrameworkExtender.CloseLayoutPanes(ArcGIS.Desktop.Framework.PaneCollection,System.String) // cref: LayoutView_FindAndCloseLayoutPanes;ArcGIS.Desktop.Core.LayoutFrameworkExtender.FindLayoutPanes(ArcGIS.Desktop.Framework.PaneCollection,ArcGIS.Desktop.Layouts.Layout) #region LayoutView_FindAndCloseLayoutPanes //Find and close all layout panes associated with a specific layout. LayoutProjectItem findLytItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout")); Layout findLyt = await QueuedTask.Run(() => findLytItem.GetLayout()); //Perform on the worker thread var panes = ProApp.Panes.FindLayoutPanes(findLyt); foreach (Pane pane in panes) { ProApp.Panes.CloseLayoutPanes(findLyt.URI); //Close the pane } #endregion LayoutView_FindandCloseLayoutPanes #region LayoutView_LayoutFrameWorkExtender //This sample checks to see if a layout project item already has an open application pane. //If it does, it checks if it is the active layout view, if not, it creates, activates and opens a new pane. //Reference a layoutitem in a project by name LayoutProjectItem layoutItem = Project.Current.GetItems<LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Layout View")); //Get the layout associated with the layoutitem Layout lyt = await QueuedTask.Run(() => layoutItem.GetLayout()); //Iterate through each pane in the application and check to see if the layout is already open and if so, activate it foreach (var pane in ProApp.Panes) { var layoutPane = pane as ILayoutPane; if (layoutPane == null) //if not a layout pane, continue to the next pane continue; if (layoutPane.LayoutView.Layout == lyt) //if the layout pane does match the layout, activate it. { (layoutPane as Pane).Activate(); layoutPane.Caption = "This is a test"; System.Windows.MessageBox.Show(layoutPane.Caption); return; } } //Otherwise, create, open, and activate the layout if not already open ILayoutPane newPane = await ProApp.Panes.CreateLayoutPaneAsync(lyt); //Zoom to the full extent of the layout await QueuedTask.Run(() => newPane.LayoutView.ZoomTo100Percent()); #endregion LayoutView_LayoutFrameWorkExtender } async public static void LayoutViewExample() { #region LayoutViewClassExample1 //This example references the active layout view. Next it finds a couple of elements and adds them to a collection. //The elements in the collection are selected within the layout view. Finally, the layout view is zoomed to the //extent of the selection. // Make sure the active pane is a layout view and then reference it if (LayoutView.Active != null) { LayoutView lytView = LayoutView.Active; //Reference the layout associated with the layout view Layout lyt = await QueuedTask.Run(() => lytView.Layout); //Find a couple of layout elements and add them to a collection Element map1 = lyt.FindElement("Map1 Map Frame"); Element map2 = lyt.FindElement("Map2 Map Frame"); List<Element> elmList = new List<Element>(); elmList.Add(map1); elmList.Add(map2); //Set the selection on the layout view and zoom to the selected elements await QueuedTask.Run(() => lytView.SelectElements(elmList)); await QueuedTask.Run(() => lytView.ZoomToSelectedElements()); } #endregion LayoutViewClassExample1 } } } namespace Layout_HelpExamples { public class LayoutViewExample2 { async public static Task<bool> SetLayoutViewSelection() { #region LayoutViewClassExample2 // Make sure the active pane is a layout view and then reference it if (LayoutView.Active != null) { LayoutView lytView = LayoutView.Active; //Reference the layout associated with the layout view Layout lyt = await QueuedTask.Run(() => lytView.Layout); //Find a couple of layout elements and add them to a collection Element map1 = lyt.FindElement("Map1 Map Frame"); Element map2 = lyt.FindElement("Map2 Map Frame"); List<Element> elmList = new List<Element>(); elmList.Add(map1); elmList.Add(map2); //Set the selection on the layout view and zoom to the selected elements await QueuedTask.Run(() => lytView.SelectElements(elmList)); await QueuedTask.Run(() => lytView.ZoomToSelectedElements()); return true; } return false; #endregion LayoutViewClassExample2 } } }
// 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 Microsoft.ApiDesignGuidelines.CSharp.Analyzers; using Microsoft.ApiDesignGuidelines.VisualBasic.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests { public class ImplementStandardExceptionConstructorsTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new BasicImplementStandardExceptionConstructorsAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new CSharpImplementStandardExceptionConstructorsAnalyzer(); } #region CSharp Unit Tests [Fact] public void CSharp_CA1032_NoDiagnostic_NotDerivingFromException() { VerifyCSharp(@" //example of a class that doesn't derive from Exception type public class NotDerivingFromException { } "); } [Fact] public void CSharp_CA1032_NoDiagnostic_GoodException1() { VerifyCSharp(@" using System; //example of a class that derives from Exception type with all the minimum needed constructors public class GoodException1 : Exception { public GoodException1() { } public GoodException1(string message): base(message) { } public GoodException1(string message, Exception innerException) : base(message, innerException) { } } "); } [Fact] public void CSharp_CA1032_NoDiagnostic_GoodException2() { VerifyCSharp(@" using System; //example of a class that derives from Exception type with all the minimum needed constructors plus an extra constructor public class GoodException2 : Exception { public GoodException2() { } public GoodException2(string message): base(message) { } public GoodException2(int i, string message) { } public GoodException2(string message, Exception innerException) : base(message, innerException) { } } "); } [Fact] public void CSharp_CA1032_Diagnostic_MissingAllConstructors() { VerifyCSharp(@" using System; //example of a class that derives from Exception type and missing all minimum required constructors - in this case system creates a default parameterless constructor public class BadException1 : Exception { } ", GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "public BadException1(string message)"), GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "public BadException1(string message, Exception innerException)")); } public void CSharp_CA1032_Diagnostic_MissingTwoConstructors() { VerifyCSharp(@" using System; //example of a class that derives from Exception type and missing 2 minimum required constructors public class BadException2 : Exception { public BadException2() { } } ", GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "public BadException2(string message)"), GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "public BadException2(string message, Exception innerException)")); } [Fact] public void CSharp_CA1032_Diagnostic_MissingDefaultConstructor() { VerifyCSharp(@" using System; //example of a class that derives from Exception type with missing default constructor public class BadException3 : Exception { public BadException3(string message): base(message) { } public BadException3(string message, Exception innerException) : base(message, innerException) { } } ", GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException3", constructor: "public BadException3()")); } [Fact] public void CSharp_CA1032_Diagnostic_MissingConstructor2() { VerifyCSharp(@" using System; //example of a class that derives from Exception type with missing constructor containing string type parameter public class BadException4 : Exception { public BadException4() { } public BadException4(string message, Exception innerException) : base(message, innerException) { } } ", GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException4", constructor: "public BadException4(string message)")); } [Fact] public void CSharp_CA1032_Diagnostic_MissingConstructor3() { VerifyCSharp(@" using System; //example of a class that derives from Exception type with missing constructor containing string type and exception type parameter public class BadException5 : Exception { public BadException5() { } public BadException5(string message): base(message) { } } ", GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException5", constructor: "public BadException5(string message, Exception innerException)")); } [Fact] public void CSharp_CA1032_Diagnostic_SurplusButMissingConstructor3() { VerifyCSharp(@" using System; //example of a class that derives from Exception type, and has 3 constructors but missing constructor containing string type parameter only public class BadException6 : Exception { public BadException6() { } public BadException6(int i, string message) { } public BadException6(string message, Exception innerException) : base(message, innerException) { } } ", GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException6", constructor: "public BadException6(string message)")); } #endregion #region VB Unit Test [Fact] public void Basic_CA1032_NoDiagnostic_NotDerivingFromException() { VerifyBasic(@" 'example of a class that doesn't derive from Exception type Public Class NotDerivingFromException End Class "); } [Fact] public void Basic_CA1032_NoDiagnostic_GoodException1() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type with all the minimum needed constructors Public Class GoodException1 : Inherits Exception Sub New() End Sub Sub New(message As String) End Sub Sub New(message As String, innerException As Exception) End Sub End Class "); } [Fact] public void Basic_CA1032_NoDiagnostic_GoodException2() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type with all the minimum needed constructors plus an extra constructor Public Class GoodException2 : Inherits Exception Sub New() End Sub Sub New(message As String) End Sub Sub New(message As String, innerException As Exception) End Sub Sub New(i As Integer, message As String) End Sub End Class "); } [Fact] public void Basic_CA1032_Diagnostic_MissingAllConstructors() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type and missing all minimum required constructors - in this case system creates a default parameterless constructor Public Class BadException1 : Inherits Exception End Class ", GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "Public Sub New(message As String)"), GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "Public Sub New(message As String, innerException As Exception)")); } public void Basic_CA1032_Diagnostic_MissingTwoConstructors() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type and missing 2 minimum required constructors Public Class BadException2 : Inherits Exception Sub New() End Sub End Class ", GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "Public Sub New(message As String)"), GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "Public Sub New(message As String, innerException As Exception)")); } [Fact] public void Basic_CA1032_Diagnostic_MissingDefaultConstructor() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type with missing default constructor Public Class BadException3 : Inherits Exception Sub New(message As String) End Sub Sub New(message As String, innerException As Exception) End Sub End Class ", GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException3", constructor: "Public Sub New()")); } [Fact] public void Basic_CA1032_Diagnostic_MissingConstructor2() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type with missing constructor containing string type parameter Public Class BadException4 : Inherits Exception Sub New() End Sub Sub New(message As String, innerException As Exception) End Sub End Class ", GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException4", constructor: "Public Sub New(message As String)")); } [Fact] public void Basic_CA1032_Diagnostic_MissingConstructor3() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type with missing constructor containing string type and exception type parameter Public Class BadException5 : Inherits Exception Sub New() End Sub Sub New(message As String) End Sub End Class ", GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException5", constructor: "Public Sub New(message As String, innerException As Exception)")); } [Fact] public void Basic_CA1032_Diagnostic_SurplusButMissingConstructor3() { VerifyBasic(@" Imports System 'example of a class that derives from Exception type, and has 3 constructors but missing constructor containing string type parameter only Public Class BadException6 : Inherits Exception Sub New() End Sub Sub New(message As String, innerException As Exception) End Sub Sub New(i As Integer, message As String) End Sub End Class ", GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException6", constructor: "Public Sub New(message As String)")); } #endregion #region Helpers private static DiagnosticResult GetCA1032CSharpMissingConstructorResultAt(int line, int column, string typeName, string constructor) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementStandardExceptionConstructorsMessageMissingConstructor, typeName, constructor); return GetCSharpResultAt(line, column, ImplementStandardExceptionConstructorsAnalyzer.RuleId, message); } private static DiagnosticResult GetCA1032BasicMissingConstructorResultAt(int line, int column, string typeName, string constructor) { // Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'. string message = string.Format(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementStandardExceptionConstructorsMessageMissingConstructor, typeName, constructor); return GetBasicResultAt(line, column, ImplementStandardExceptionConstructorsAnalyzer.RuleId, message); } #endregion } }
using System; using System.Text; using TestLibrary; using System.Globalization; class StringBuilderLength { static int Main() { StringBuilderLength test = new StringBuilderLength(); TestFramework.BeginTestCase("StringBuilder.Length"); if (test.RunTests()) { TestFramework.EndTestCase(); TestFramework.LogInformation("PASS"); return 100; } else { TestFramework.EndTestCase(); TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool ret = true; // Positive Tests ret &= Test1(); ret &= Test2(); ret &= Test3(); ret &= Test4(); ret &= Test5(); // Negative Tests ret &= Test6(); ret &= Test7(); return ret; } public bool Test1() { string id = "Scenario1"; bool result = true; TestFramework.BeginScenario("Scenario 1: Setting Length to 0"); try { StringBuilder sb = new StringBuilder("Test"); sb.Length = 0; string output = sb.ToString(); int length = sb.Length; if (output != string.Empty) { result = false; TestFramework.LogError("001", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: " + string.Empty); } if (length != 0) { result = false; TestFramework.LogError("002", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 0"); } } catch (Exception exc) { result = false; TestFramework.LogError("003", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test2() { string id = "Scenario2"; bool result = true; TestFramework.BeginScenario("Scenario 2: Setting Length to current length"); try { StringBuilder sb = new StringBuilder("Test"); sb.Length = 4; string output = sb.ToString(); int length = sb.Length; if (output != "Test") { result = false; TestFramework.LogError("004", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test"); } if (length != 4) { result = false; TestFramework.LogError("005", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 4"); } } catch (Exception exc) { result = false; TestFramework.LogError("006", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test3() { string id = "Scenario3"; bool result = true; TestFramework.BeginScenario("Scenario 3: Setting Length to > length < capacity"); try { StringBuilder sb = new StringBuilder("Test", 10); sb.Length = 8; string output = sb.ToString(); int length = sb.Length; if (output != "Test\0\0\0\0") { result = false; TestFramework.LogError("007", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test\0\0\0\0"); } if (length != 8) { result = false; TestFramework.LogError("008", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 8"); } } catch (Exception exc) { result = false; TestFramework.LogError("009", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test4() { string id = "Scenario4"; bool result = true; TestFramework.BeginScenario("Scenario 4: Setting Length to > capacity"); try { StringBuilder sb = new StringBuilder("Test", 10); sb.Length = 12; string output = sb.ToString(); int length = sb.Length; if (output != "Test\0\0\0\0\0\0\0\0") { result = false; TestFramework.LogError("010", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test\0\0\0\0\0\0\0\0"); } if (length != 12) { result = false; TestFramework.LogError("011", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 12"); } } catch (Exception exc) { result = false; TestFramework.LogError("012", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test5() { string id = "Scenario5"; bool result = true; TestFramework.BeginScenario("Scenario 5: Setting Length to something very large"); try { StringBuilder sb = new StringBuilder("Test"); sb.Length = 10004; string output = sb.ToString(); int length = sb.Length; if (output != ("Test" + new string('\0',10000))) { result = false; TestFramework.LogError("013", "Error in " + id + ", unexpected string. Actual string " + output + ", Expected: Test"); } if (length != 10004) { result = false; TestFramework.LogError("014", "Error in " + id + ", unexpected legnth. Actual length " + length + ", Expected: 10004"); } } catch (Exception exc) { result = false; TestFramework.LogError("015", "Unexpected exception in " + id + ", excpetion: " + exc.ToString()); } return result; } public bool Test6() { string id = "Scenario6"; bool result = true; TestFramework.BeginScenario("Scenario 6: Setting Length to > max capacity"); try { StringBuilder sb = new StringBuilder(4, 10); sb.Append("Test"); sb.Length = 12; string output = sb.ToString(); result = false; TestFramework.LogError("016", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + typeof(ArgumentOutOfRangeException).ToString()); } catch (Exception exc) { if (exc.GetType() != typeof(ArgumentOutOfRangeException)) { result = false; TestFramework.LogError("017", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } public bool Test7() { string id = "Scenario7"; bool result = true; TestFramework.BeginScenario("Scenario 7: Setting Length to < 0 capacity"); try { StringBuilder sb = new StringBuilder(4, 10); sb.Append("Test"); sb.Length = -1; string output = sb.ToString(); result = false; TestFramework.LogError("018", "Error in " + id + ", Expected exception not thrown. No exception. Actual string " + output + ", Expected: " + typeof(ArgumentOutOfRangeException).ToString()); } catch (Exception exc) { if (exc.GetType() != typeof(ArgumentOutOfRangeException)) { result = false; TestFramework.LogError("018", "Unexpected exception in " + id + ", expected type: " + typeof(ArgumentOutOfRangeException).ToString() + ", Actual excpetion: " + exc.ToString()); } } return result; } }
using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Newtonsoft.Json.Linq; using Orchard.ContentManagement; using Orchard.Data; using Orchard.DisplayManagement; using Orchard.Forms.Services; using Orchard.Localization; using Orchard.Mvc; using Orchard.Mvc.Extensions; using Orchard.Security; using Orchard.Themes; using System; using Orchard.Settings; using Orchard.UI.Navigation; using Orchard.UI.Notify; using Orchard.Workflows.Models; using Orchard.Workflows.Services; using Orchard.Workflows.ViewModels; namespace Orchard.Workflows.Controllers { [ValidateInput(false)] public class AdminController : Controller, IUpdateModel { private readonly ISiteService _siteService; private readonly IRepository<WorkflowDefinitionRecord> _workflowDefinitionRecords; private readonly IRepository<WorkflowRecord> _workflowRecords; private readonly IActivitiesManager _activitiesManager; private readonly IFormManager _formManager; public AdminController( IOrchardServices services, IShapeFactory shapeFactory, ISiteService siteService, IRepository<WorkflowDefinitionRecord> workflowDefinitionRecords, IRepository<WorkflowRecord> workflowRecords, IActivitiesManager activitiesManager, IFormManager formManager ) { _siteService = siteService; _workflowDefinitionRecords = workflowDefinitionRecords; _workflowRecords = workflowRecords; _activitiesManager = activitiesManager; _formManager = formManager; Services = services; T = NullLocalizer.Instance; New = shapeFactory; } dynamic New { get; set; } public IOrchardServices Services { get; set; } public Localizer T { get; set; } public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows"))) return new HttpUnauthorizedResult(); var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); // default options if (options == null) options = new AdminIndexOptions(); var queries = _workflowDefinitionRecords.Table; switch (options.Filter) { case WorkflowDefinitionFilter.All: break; default: throw new ArgumentOutOfRangeException(); } if (!String.IsNullOrWhiteSpace(options.Search)) { queries = queries.Where(w => w.Name.Contains(options.Search)); } var pagerShape = New.Pager(pager).TotalItemCount(queries.Count()); switch (options.Order) { case WorkflowDefinitionOrder.Name: queries = queries.OrderBy(u => u.Name); break; } if (pager.GetStartIndex() > 0) { queries = queries.Skip(pager.GetStartIndex()); } if (pager.PageSize > 0) { queries = queries.Take(pager.PageSize); } var results = queries.ToList(); var model = new AdminIndexViewModel { WorkflowDefinitions = results.Select(x => new WorkflowDefinitionEntry { WorkflowDefinitionRecord = x, WokflowDefinitionId = x.Id, Name = x.Name }).ToList(), Options = options, Pager = pagerShape }; // maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.Order", options.Order); pagerShape.RouteData(routeData); return View(model); } public ActionResult List(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows"))) return new HttpUnauthorizedResult(); var contentItem = Services.ContentManager.Get(id, VersionOptions.Latest); if (contentItem == null) { return HttpNotFound(); } var workflows = _workflowRecords.Table.Where(x => x.ContentItemRecord == contentItem.Record).ToList(); var viewModel = New.ViewModel( ContentItem: contentItem, Workflows: workflows ); return View(viewModel); } public ActionResult Create() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to create workflows"))) return new HttpUnauthorizedResult(); return View(); } [HttpPost, ActionName("Create")] public ActionResult CreatePost(string name) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to create workflows"))) return new HttpUnauthorizedResult(); var workflowDefinitionRecord = new WorkflowDefinitionRecord { Name = name }; _workflowDefinitionRecords.Create(workflowDefinitionRecord); return RedirectToAction("Edit", new { workflowDefinitionRecord.Id }); } public ActionResult Edit(int id, string localId, int? workflowId) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); // convert the workflow definition into its view model var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id); var workflowDefinitionViewModel = CreateWorkflowDefinitionViewModel(workflowDefinitionRecord); var workflow = workflowId.HasValue ? _workflowRecords.Get(workflowId.Value) : null; var viewModel = new AdminEditViewModel { LocalId = String.IsNullOrEmpty(localId) ? Guid.NewGuid().ToString() : localId, IsLocal = !String.IsNullOrEmpty(localId), WorkflowDefinition = workflowDefinitionViewModel, AllActivities = _activitiesManager.GetActivities(), Workflow = workflow }; return View(viewModel); } [HttpPost] public ActionResult Delete(int id) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows"))) return new HttpUnauthorizedResult(); var workflowDefinition = _workflowDefinitionRecords.Get(id); if (workflowDefinition != null) { _workflowDefinitionRecords.Delete(workflowDefinition); Services.Notifier.Information(T("Workflow {0} deleted", workflowDefinition.Name)); } return RedirectToAction("Index"); } [HttpPost] public ActionResult DeleteWorkflow(int id, string returnUrl) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to manage workflows"))) return new HttpUnauthorizedResult(); var workflow = _workflowRecords.Get(id); if (workflow != null) { _workflowRecords.Delete(workflow); Services.Notifier.Information(T("Workflow deleted")); } return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); } private WorkflowDefinitionViewModel CreateWorkflowDefinitionViewModel(WorkflowDefinitionRecord workflowDefinitionRecord) { if (workflowDefinitionRecord == null) { throw new ArgumentNullException("workflowDefinitionRecord"); } var workflowDefinitionModel = new WorkflowDefinitionViewModel { Id = workflowDefinitionRecord.Id, Name = workflowDefinitionRecord.Name }; dynamic workflow = new JObject(); workflow.Activities = new JArray(workflowDefinitionRecord.ActivityRecords.Select(x => { dynamic activity = new JObject(); activity.Name = x.Name; activity.Id = x.Id; activity.ClientId = x.Name + "_" + x.Id; activity.Left = x.X; activity.Top = x.Y; activity.Start = x.StartState; activity.State = FormParametersHelper.FromJsonString(x.State); return activity; })); workflow.Connections = new JArray(workflowDefinitionRecord.TransitionRecords.Select(x => { dynamic connection = new JObject(); connection.Id = x.Id; connection.SourceId = x.SourceActivityRecord.Name + "_" + x.SourceActivityRecord.Id; connection.TargetId = x.DestinationActivityRecord.Name + "_" + x.DestinationActivityRecord.Id; connection.SourceEndpoint = x.SourceEndpoint; return connection; })); workflowDefinitionModel.JsonData = FormParametersHelper.ToJsonString(workflow); return workflowDefinitionModel; } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Save")] public ActionResult EditPost(int id, string localId, string data) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var workflowDefinitionRecord = _workflowDefinitionRecords.Get(id); if (workflowDefinitionRecord == null) { return HttpNotFound(); } workflowDefinitionRecord.Enabled = true; var state = FormParametersHelper.FromJsonString(data); var activitiesIndex = new Dictionary<string, ActivityRecord>(); workflowDefinitionRecord.ActivityRecords.Clear(); foreach (var activity in state.Activities) { ActivityRecord activityRecord; workflowDefinitionRecord.ActivityRecords.Add(activityRecord = new ActivityRecord { Name = activity.Name, X = activity.Left, Y = activity.Top, StartState = activity.Start, State = FormParametersHelper.ToJsonString(activity.State), WorkflowDefinitionRecord = workflowDefinitionRecord }); activitiesIndex.Add((string)activity.ClientId, activityRecord); } workflowDefinitionRecord.TransitionRecords.Clear(); foreach (var connection in state.Connections) { workflowDefinitionRecord.TransitionRecords.Add(new TransitionRecord { SourceActivityRecord = activitiesIndex[(string)connection.SourceId], DestinationActivityRecord = activitiesIndex[(string)connection.TargetId], SourceEndpoint = connection.SourceEndpoint, WorkflowDefinitionRecord = workflowDefinitionRecord }); } Services.Notifier.Information(T("Workflow saved successfully")); return RedirectToAction("Edit", new { id, localId }); } [HttpPost, ActionName("Edit")] [FormValueRequired("submit.Cancel")] public ActionResult EditPostCancel() { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); return View(); } [Themed(false)] [HttpPost] public ActionResult RenderActivity(ActivityViewModel model) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(model.Name); if (activity == null) { return HttpNotFound(); } dynamic shape = New.Activity(activity); if (model.State != null) { var state = FormParametersHelper.ToDynamic(FormParametersHelper.ToString(model.State)); shape.State(state); } else { shape.State(FormParametersHelper.FromJsonString("{}")); } shape.Metadata.Alternates.Add("Activity__" + activity.Name); return new ShapeResult(this, shape); } public ActionResult EditActivity(string localId, string clientId, ActivityViewModel model) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(model.Name); if (activity == null) { return HttpNotFound(); } // build the form, and let external components alter it var form = activity.Form == null ? null : _formManager.Build(activity.Form); // form is bound on client side var viewModel = New.ViewModel(LocalId: localId, ClientId: clientId, Form: form); return View(viewModel); } [HttpPost, ActionName("EditActivity")] [FormValueRequired("_submit.Save")] public ActionResult EditActivityPost(int id, string localId, string name, string clientId, FormCollection formValues) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); var activity = _activitiesManager.GetActivityByName(name); if (activity == null) { return HttpNotFound(); } // validating form values _formManager.Validate(new ValidatingContext { FormName = activity.Form, ModelState = ModelState, ValueProvider = ValueProvider }); // stay on the page if there are validation errors if (!ModelState.IsValid) { // build the form, and let external components alter it var form = activity.Form == null ? null : _formManager.Build(activity.Form); // bind form with existing values. _formManager.Bind(form, ValueProvider); var viewModel = New.ViewModel(Id: id, LocalId: localId, Form: form); return View(viewModel); } var model = new UpdatedActivityModel { ClientId = clientId, Data = HttpUtility.JavaScriptStringEncode(FormParametersHelper.ToJsonString(formValues)) }; TempData["UpdatedViewModel"] = model; return RedirectToAction("Edit", new { id, localId }); } [HttpPost, ActionName("EditActivity")] [FormValueRequired("_submit.Cancel")] public ActionResult EditActivityPostCancel(int id, string localId, string name, string clientId, FormCollection formValues) { if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to edit workflows"))) return new HttpUnauthorizedResult(); return RedirectToAction("Edit", new {id, localId }); } bool IUpdateModel.TryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) { return TryUpdateModel(model, prefix, includeProperties, excludeProperties); } public void AddModelError(string key, LocalizedString errorMessage) { ModelState.AddModelError(key, errorMessage.ToString()); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate.Helpers; using SDKTemplate.Logging; using System; using System.Linq; using System.Threading.Tasks; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Media.Streaming.Adaptive; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Web.Http; using Windows.Web.Http.Filters; namespace SDKTemplate { /// See the README.md for discussion of this scenario. public sealed partial class Scenario2_EventHandlers : Page { private BitrateHelper bitrateHelper; public Scenario2_EventHandlers() { this.InitializeComponent(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { // Release handles on various media objects to ensure a quick clean-up ContentSelectorControl.MediaPlaybackItem = null; var mediaPlayer = mediaPlayerElement.MediaPlayer; if (mediaPlayer != null) { mediaPlayerLogger?.Dispose(); mediaPlayerLogger = null; UnregisterHandlers(mediaPlayer); mediaPlayer.DisposeSource(); mediaPlayerElement.SetMediaPlayer(null); mediaPlayer.Dispose(); } } private void UnregisterHandlers(MediaPlayer mediaPlayer) { AdaptiveMediaSource adaptiveMediaSource = null; MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem; if (mpItem != null) { adaptiveMediaSource = mpItem.Source.AdaptiveMediaSource; } MediaSource source = mediaPlayer.Source as MediaSource; if (source != null) { adaptiveMediaSource = source.AdaptiveMediaSource; } mediaPlaybackItemLogger?.Dispose(); mediaPlaybackItemLogger = null; mediaSourceLogger?.Dispose(); mediaSourceLogger = null; adaptiveMediaSourceLogger?.Dispose(); adaptiveMediaSourceLogger = null; UnregisterForAdaptiveMediaSourceEvents(adaptiveMediaSource); } private void Page_OnLoaded(object sender, RoutedEventArgs e) { // Explicitly create the instance of MediaPlayer if you need to register for its events // (like MediaOpened / MediaFailed) prior to setting an IMediaPlaybackSource. var mediaPlayer = new MediaPlayer(); // We use a helper class that logs all the events for the MediaPlayer: mediaPlayerLogger = new MediaPlayerLogger(LoggerControl, mediaPlayer); // Ensure we have PlayReady support, in case the user enters a DASH/PR Uri in the text box. var prHelper = new PlayReadyHelper(LoggerControl); prHelper.SetUpProtectionManager(mediaPlayer); mediaPlayerElement.SetMediaPlayer(mediaPlayer); // This Scenario focuses on event handling, mostly via the "Logger" helper classes // in the Shared folder. // // In addition, the App can also insert an IHttpFilter into the Windows.Web.Http stack // which is used by the AdaptiveMediaSource. To do so, it must derive a class from // IHttpFilter, provide the HttpBaseProtocolFilter to that class to execute requests, // then use the derived filter as the constructor for the HttpClient. // // The HttpClient is then used in the constructor of the AdaptiveMediaSource. // The App should explicitly set: // CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache // When passing an HttpClient into the constructor of AdpativeMediaSource, // set this on the HttpBaseProtocolFilter. // // More than one IHttpFilter can be nested, for example, an App might // use a filter to modify web requests: see Scenario3 for details. // // In this scenario, we add an AdaptiveMediaSourceHttpFilterLogger to provide additional // verbose logging details for each request. var baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; // Always set WriteBehavior = NoCache var fistLevelFilter = new AdaptiveMediaSourceHttpFilterLogger(LoggerControl, baseProtocolFilter); var httpClient = new HttpClient(fistLevelFilter); ContentSelectorControl.Initialize( mediaPlayer, MainPage.ContentManagementSystemStub.Where(m => !m.Aes), httpClient, LoggerControl, LoadSourceFromUriAsync); } #region Content Loading private async Task<MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null) { UnregisterHandlers(mediaPlayerElement.MediaPlayer); mediaPlayerElement.MediaPlayer?.DisposeSource(); AdaptiveMediaSourceCreationResult result = null; if (httpClient != null) { result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient); } else { result = await AdaptiveMediaSource.CreateFromUriAsync(uri); } MediaSource source; if (result.Status == AdaptiveMediaSourceCreationStatus.Success) { var adaptiveMediaSource = result.MediaSource; // We use a helper class that logs all the events for the AdaptiveMediaSource: adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource); // In addition to logging, we use the callbacks to update some UI elements in this scenario: RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource); // At this point, we have read the manifest of the media source, and all bitrates are known. bitrateHelper = new BitrateHelper(adaptiveMediaSource.AvailableBitrates); // The AdaptiveMediaSource chooses initial playback and download bitrates. // See the Tuning scenario for examples of customizing these bitrates. await UpdatePlaybackBitrateAsync(adaptiveMediaSource.CurrentPlaybackBitrate); await UpdateDownloadBitrateAsync(adaptiveMediaSource.CurrentDownloadBitrate); source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource); } else { Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}"); // In this scenario, we make a second attempt to load any URI that is // not adaptive streaming as a progressive download URI: Log($"Attempting to create a MediaSource from uri: {uri}"); source = MediaSource.CreateFromUri(uri); } // We use a helper class that logs all the events for the MediaSource: mediaSourceLogger = new MediaSourceLogger(LoggerControl, source); // You can save additional information in the CustomPropertySet for future retrieval. // Note: MediaSource.CustomProperties is a ValueSet and therefore can store // only serializable types. // Save the original Uri. source.CustomProperties["uri"] = uri.ToString(); // You're likely to put a content tracking id into the CustomProperties. source.CustomProperties["contentId"] = Guid.NewGuid().ToString(); var mpItem = new MediaPlaybackItem(source); // We use a helper class that logs all the events for the MediaPlaybackItem: mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem); HideDescriptionOnSmallScreen(); return mpItem; } private async void HideDescriptionOnSmallScreen() { // On small screens, hide the description text to make room for the video. await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible; }); } #endregion #region AdaptiveMediaSource Event Handlers private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource) { adaptiveMediaSource.DownloadBitrateChanged += DownloadBitrateChanged; adaptiveMediaSource.PlaybackBitrateChanged += PlaybackBitrateChanged; } private void UnregisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource) { if (adaptiveMediaSource != null) { adaptiveMediaSource.DownloadBitrateChanged -= DownloadBitrateChanged; adaptiveMediaSource.PlaybackBitrateChanged -= PlaybackBitrateChanged; } } private async void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args) { uint downloadBitrate = args.NewValue; await UpdateDownloadBitrateAsync(downloadBitrate); } private async Task UpdateDownloadBitrateAsync(uint downloadBitrate) { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { iconDownloadBitrate.Symbol = bitrateHelper.GetBitrateSymbol(downloadBitrate); txtDownloadBitrate.Text = downloadBitrate.ToString(); })); } private async void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args) { uint playbackBitrate = args.NewValue; await UpdatePlaybackBitrateAsync(playbackBitrate); } private async Task UpdatePlaybackBitrateAsync(uint playbackBitrate) { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { iconPlaybackBitrate.Symbol = bitrateHelper.GetBitrateSymbol(playbackBitrate); txtPlaybackBitrate.Text = playbackBitrate.ToString(); })); } #endregion #region Utilities private void Log(string message) { LoggerControl.Log(message); } MediaPlayerLogger mediaPlayerLogger; MediaSourceLogger mediaSourceLogger; MediaPlaybackItemLogger mediaPlaybackItemLogger; AdaptiveMediaSourceLogger adaptiveMediaSourceLogger; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Expressions.Compiler { internal partial class StackSpiller { /// <summary> /// The source of temporary variables introduced during stack spilling. /// </summary> private readonly TempMaker _tm = new TempMaker(); /// <summary> /// Creates a temporary variable of the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for the temporary variable to create.</param> /// <returns> /// A temporary variable of the specified <paramref name="type"/>. When the temporary /// variable is no longer used, it should be returned by using the <see cref="Mark"/> /// and <see cref="Free"/> mechanism provided. /// </returns> private ParameterExpression MakeTemp(Type type) => _tm.Temp(type); /// <summary> /// Gets a watermark into the stack of used temporary variables. The returned /// watermark value can be passed to <see cref="Free"/> to free all variables /// below the watermark value, allowing them to be reused. /// </summary> /// <returns> /// A watermark value indicating the number of temporary variables currently in use. /// </returns> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> private int Mark() => _tm.Mark(); /// <summary> /// Frees temporaries created since the last marking using <see cref="Mark"/>. /// </summary> /// <param name="mark">The watermark value up to which to recycle used temporary variables.</param> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> private void Free(int mark) => _tm.Free(mark); /// <summary> /// Verifies that all temporary variables get properly returned to the free list /// after stack spilling for a lambda expression has taken place. This is used /// to detect misuse of the <see cref="Mark"/> and <see cref="Free"/> methods. /// </summary> [Conditional("DEBUG")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private void VerifyTemps() => _tm.VerifyTemps(); /// <summary> /// Creates and returns a temporary variable to store the result of evaluating /// the specified <paramref name="expression"/>. /// </summary> /// <param name="expression">The expression to store in a temporary variable.</param> /// <param name="save">An expression that assigns the <paramref name="expression"/> to the created temporary variable.</param> /// <param name="byRef">Indicates whether the <paramref name="expression"/> represents a ByRef value.</param> /// <returns>The temporary variable holding the result of evaluating <paramref name="expression"/>.</returns> private ParameterExpression ToTemp(Expression expression, out Expression save, bool byRef) { Type tempType = byRef ? expression.Type.MakeByRefType() : expression.Type; ParameterExpression temp = MakeTemp(tempType); save = AssignBinaryExpression.Make(temp, expression, byRef); return temp; } /// <summary> /// Utility to create and recycle temporary variables. /// </summary> private sealed class TempMaker { /// <summary> /// Index of the next temporary variable to create. /// This value is used for naming temporary variables using an increasing index. /// </summary> private int _temp; /// <summary> /// List of free temporary variables. These can be recycled for new temporary variables. /// </summary> private List<ParameterExpression> _freeTemps; /// <summary> /// Stack of temporary variables that are currently in use. /// </summary> private Stack<ParameterExpression> _usedTemps; /// <summary> /// List of all temporary variables created by the stack spiller instance. /// </summary> internal List<ParameterExpression> Temps { get; } = new List<ParameterExpression>(); /// <summary> /// Creates a temporary variable of the specified <paramref name="type"/>. /// </summary> /// <param name="type">The type for the temporary variable to create.</param> /// <returns> /// A temporary variable of the specified <paramref name="type"/>. When the temporary /// variable is no longer used, it should be returned by using the <see cref="Mark"/> /// and <see cref="Free"/> mechanism provided. /// </returns> internal ParameterExpression Temp(Type type) { ParameterExpression temp; if (_freeTemps != null) { // Recycle from the free-list if possible. for (int i = _freeTemps.Count - 1; i >= 0; i--) { temp = _freeTemps[i]; if (temp.Type == type) { _freeTemps.RemoveAt(i); return UseTemp(temp); } } } // Not on the free-list, create a brand new one. temp = ParameterExpression.Make(type, "$temp$" + _temp++, isByRef: false); Temps.Add(temp); return UseTemp(temp); } /// <summary> /// Registers the temporary variable in the stack of used temporary variables. /// The <see cref="Mark"/> and <see cref="Free"/> methods use a watermark index /// into this stack to enable recycling temporary variables in bulk. /// </summary> /// <param name="temp">The temporary variable to mark as used.</param> /// <returns>The original temporary variable.</returns> private ParameterExpression UseTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); if (_usedTemps == null) { _usedTemps = new Stack<ParameterExpression>(); } _usedTemps.Push(temp); return temp; } /// <summary> /// Puts the temporary variable on the free list which is used by the /// <see cref="Temp"/> method to reuse temporary variables. /// </summary> /// <param name="temp">The temporary variable to mark as no longer in use.</param> private void FreeTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); if (_freeTemps == null) { _freeTemps = new List<ParameterExpression>(); } _freeTemps.Add(temp); } /// <summary> /// Gets a watermark into the stack of used temporary variables. The returned /// watermark value can be passed to <see cref="Free"/> to free all variables /// below the watermark value, allowing them to be reused. /// </summary> /// <returns> /// A watermark value indicating the number of temporary variables currently in use. /// </returns> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> internal int Mark() => _usedTemps?.Count ?? 0; /// <summary> /// Frees temporaries created since the last marking using <see cref="Mark"/>. /// </summary> /// <param name="mark">The watermark value up to which to recycle used temporary variables.</param> /// <remarks> /// This is a performance optimization to lower the overall number of temporaries needed. /// </remarks> internal void Free(int mark) { // (_usedTemps != null) ==> (mark <= _usedTemps.Count) Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count); // (_usedTemps == null) ==> (mark == 0) Debug.Assert(mark == 0 || _usedTemps != null); if (_usedTemps != null) { while (mark < _usedTemps.Count) { FreeTemp(_usedTemps.Pop()); } } } /// <summary> /// Verifies that all temporary variables get properly returned to the free list /// after stack spilling for a lambda expression has taken place. This is used /// to detect misuse of the <see cref="Mark"/> and <see cref="Free"/> methods. /// </summary> [Conditional("DEBUG")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void VerifyTemps() { Debug.Assert(_usedTemps == null || _usedTemps.Count == 0); } } } }
using System; using System.Collections.Generic; using Wasm.Instructions; namespace Wasm.Interpret { /// <summary> /// The default instruction interpreter implementation. /// </summary> public sealed class DefaultInstructionInterpreter : InstructionInterpreter { /// <summary> /// Creates an instruction interpreter with no operator implementations. /// </summary> public DefaultInstructionInterpreter() { this.operatorImpls = new Dictionary<Operator, Action<Instruction, InterpreterContext>>(); } /// <summary> /// Creates an instruction interpreter that clones the given interpreter's /// operator implementations. /// </summary> public DefaultInstructionInterpreter(DefaultInstructionInterpreter other) { this.operatorImpls = new Dictionary<Operator, Action<Instruction, InterpreterContext>>( other.operatorImpls); } /// <summary> /// A mapping of operators to their implementations. /// </summary> private Dictionary<Operator, Action<Instruction, InterpreterContext>> operatorImpls; /// <summary> /// Implements the given operator as the specified action. /// </summary> /// <param name="op">The operator to implement.</param> /// <param name="implementation">The action that implements the operator.</param> public void ImplementOperator( Operator op, Action<Instruction, InterpreterContext> implementation) { operatorImpls[op] = implementation; } /// <summary> /// Checks if this instruction interpreter implements the given operator. /// </summary> /// <param name="op">A WebAssembly operator.</param> /// <returns><c>true</c> if the given operator is implemented by this interpreter; otherwise, <c>false</c>.</returns> public bool IsImplemented(Operator op) => operatorImpls.ContainsKey(op); /// <summary> /// Interprets the given instruction within the specified context. /// </summary> /// <param name="value">The instruction to interpret.</param> /// <param name="context">The interpreter context.</param> public override void Interpret(Instruction value, InterpreterContext context) { if (context.HasReturned) { return; } Action<Instruction, InterpreterContext> impl; if (operatorImpls.TryGetValue(value.Op, out impl)) { impl(value, context); } else { throw new WasmException("Operator not implemented by interpreter: " + value.Op.ToString()); } } /// <summary> /// The default instruction interpreter with the default list of operator implementations. /// Please don't implement any additional operators in this interpreter instance. /// </summary> public static readonly DefaultInstructionInterpreter Default; static DefaultInstructionInterpreter() { Default = new DefaultInstructionInterpreter(); Default.ImplementOperator(Operators.Unreachable, OperatorImpls.Unreachable); Default.ImplementOperator(Operators.Nop, OperatorImpls.Nop); Default.ImplementOperator(Operators.Block, OperatorImpls.Block); Default.ImplementOperator(Operators.Loop, OperatorImpls.Loop); Default.ImplementOperator(Operators.If, OperatorImpls.If); Default.ImplementOperator(Operators.Br, OperatorImpls.Br); Default.ImplementOperator(Operators.BrIf, OperatorImpls.BrIf); Default.ImplementOperator(Operators.BrTable, OperatorImpls.BrTable); Default.ImplementOperator(Operators.Return, OperatorImpls.Return); Default.ImplementOperator(Operators.Drop, OperatorImpls.Drop); Default.ImplementOperator(Operators.Select, OperatorImpls.Select); Default.ImplementOperator(Operators.Call, OperatorImpls.Call); Default.ImplementOperator(Operators.CallIndirect, OperatorImpls.CallIndirect); Default.ImplementOperator(Operators.GetLocal, OperatorImpls.GetLocal); Default.ImplementOperator(Operators.SetLocal, OperatorImpls.SetLocal); Default.ImplementOperator(Operators.TeeLocal, OperatorImpls.TeeLocal); Default.ImplementOperator(Operators.GetGlobal, OperatorImpls.GetGlobal); Default.ImplementOperator(Operators.SetGlobal, OperatorImpls.SetGlobal); Default.ImplementOperator(Operators.Int32Load, OperatorImpls.Int32Load); Default.ImplementOperator(Operators.Int64Load, OperatorImpls.Int64Load); Default.ImplementOperator(Operators.Int32Load8S, OperatorImpls.Int32Load8S); Default.ImplementOperator(Operators.Int32Load8U, OperatorImpls.Int32Load8U); Default.ImplementOperator(Operators.Int32Load16S, OperatorImpls.Int32Load16S); Default.ImplementOperator(Operators.Int32Load16U, OperatorImpls.Int32Load16U); Default.ImplementOperator(Operators.Int64Load8S, OperatorImpls.Int64Load8S); Default.ImplementOperator(Operators.Int64Load8U, OperatorImpls.Int64Load8U); Default.ImplementOperator(Operators.Int64Load16S, OperatorImpls.Int64Load16S); Default.ImplementOperator(Operators.Int64Load16U, OperatorImpls.Int64Load16U); Default.ImplementOperator(Operators.Int64Load32S, OperatorImpls.Int64Load32S); Default.ImplementOperator(Operators.Int64Load32U, OperatorImpls.Int64Load32U); Default.ImplementOperator(Operators.Float32Load, OperatorImpls.Float32Load); Default.ImplementOperator(Operators.Float64Load, OperatorImpls.Float64Load); Default.ImplementOperator(Operators.Int32Store8, OperatorImpls.Int32Store8); Default.ImplementOperator(Operators.Int32Store16, OperatorImpls.Int32Store16); Default.ImplementOperator(Operators.Int32Store, OperatorImpls.Int32Store); Default.ImplementOperator(Operators.Int64Store8, OperatorImpls.Int64Store8); Default.ImplementOperator(Operators.Int64Store16, OperatorImpls.Int64Store16); Default.ImplementOperator(Operators.Int64Store32, OperatorImpls.Int64Store32); Default.ImplementOperator(Operators.Int64Store, OperatorImpls.Int64Store); Default.ImplementOperator(Operators.Float32Store, OperatorImpls.Float32Store); Default.ImplementOperator(Operators.Float64Store, OperatorImpls.Float64Store); Default.ImplementOperator(Operators.CurrentMemory, OperatorImpls.CurrentMemory); Default.ImplementOperator(Operators.GrowMemory, OperatorImpls.GrowMemory); Default.ImplementOperator(Operators.Int32Const, OperatorImpls.Int32Const); Default.ImplementOperator(Operators.Int64Const, OperatorImpls.Int64Const); Default.ImplementOperator(Operators.Float32Const, OperatorImpls.Float32Const); Default.ImplementOperator(Operators.Float64Const, OperatorImpls.Float64Const); Default.ImplementOperator(Operators.Int32Add, OperatorImpls.Int32Add); Default.ImplementOperator(Operators.Int32And, OperatorImpls.Int32And); Default.ImplementOperator(Operators.Int32Clz, OperatorImpls.Int32Clz); Default.ImplementOperator(Operators.Int32Ctz, OperatorImpls.Int32Ctz); Default.ImplementOperator(Operators.Int32DivS, OperatorImpls.Int32DivS); Default.ImplementOperator(Operators.Int32DivU, OperatorImpls.Int32DivU); Default.ImplementOperator(Operators.Int32Eq, OperatorImpls.Int32Eq); Default.ImplementOperator(Operators.Int32Eqz, OperatorImpls.Int32Eqz); Default.ImplementOperator(Operators.Int32GeS, OperatorImpls.Int32GeS); Default.ImplementOperator(Operators.Int32GeU, OperatorImpls.Int32GeU); Default.ImplementOperator(Operators.Int32GtS, OperatorImpls.Int32GtS); Default.ImplementOperator(Operators.Int32GtU, OperatorImpls.Int32GtU); Default.ImplementOperator(Operators.Int32LeS, OperatorImpls.Int32LeS); Default.ImplementOperator(Operators.Int32LeU, OperatorImpls.Int32LeU); Default.ImplementOperator(Operators.Int32LtS, OperatorImpls.Int32LtS); Default.ImplementOperator(Operators.Int32LtU, OperatorImpls.Int32LtU); Default.ImplementOperator(Operators.Int32Mul, OperatorImpls.Int32Mul); Default.ImplementOperator(Operators.Int32Ne, OperatorImpls.Int32Ne); Default.ImplementOperator(Operators.Int32Or, OperatorImpls.Int32Or); Default.ImplementOperator(Operators.Int32Popcnt, OperatorImpls.Int32Popcnt); Default.ImplementOperator(Operators.Int32ReinterpretFloat32, OperatorImpls.Int32ReinterpretFloat32); Default.ImplementOperator(Operators.Int32RemS, OperatorImpls.Int32RemS); Default.ImplementOperator(Operators.Int32RemU, OperatorImpls.Int32RemU); Default.ImplementOperator(Operators.Int32Rotl, OperatorImpls.Int32Rotl); Default.ImplementOperator(Operators.Int32Rotr, OperatorImpls.Int32Rotr); Default.ImplementOperator(Operators.Int32Shl, OperatorImpls.Int32Shl); Default.ImplementOperator(Operators.Int32ShrS, OperatorImpls.Int32ShrS); Default.ImplementOperator(Operators.Int32ShrU, OperatorImpls.Int32ShrU); Default.ImplementOperator(Operators.Int32Sub, OperatorImpls.Int32Sub); Default.ImplementOperator(Operators.Int32TruncSFloat32, OperatorImpls.Int32TruncSFloat32); Default.ImplementOperator(Operators.Int32TruncSFloat64, OperatorImpls.Int32TruncSFloat64); Default.ImplementOperator(Operators.Int32TruncUFloat32, OperatorImpls.Int32TruncUFloat32); Default.ImplementOperator(Operators.Int32TruncUFloat64, OperatorImpls.Int32TruncUFloat64); Default.ImplementOperator(Operators.Int32WrapInt64, OperatorImpls.Int32WrapInt64); Default.ImplementOperator(Operators.Int32Xor, OperatorImpls.Int32Xor); Default.ImplementOperator(Operators.Int64Add, OperatorImpls.Int64Add); Default.ImplementOperator(Operators.Int64And, OperatorImpls.Int64And); Default.ImplementOperator(Operators.Int64Clz, OperatorImpls.Int64Clz); Default.ImplementOperator(Operators.Int64Ctz, OperatorImpls.Int64Ctz); Default.ImplementOperator(Operators.Int64DivS, OperatorImpls.Int64DivS); Default.ImplementOperator(Operators.Int64DivU, OperatorImpls.Int64DivU); Default.ImplementOperator(Operators.Int64Eq, OperatorImpls.Int64Eq); Default.ImplementOperator(Operators.Int64Eqz, OperatorImpls.Int64Eqz); Default.ImplementOperator(Operators.Int64ExtendSInt32, OperatorImpls.Int64ExtendSInt32); Default.ImplementOperator(Operators.Int64ExtendUInt32, OperatorImpls.Int64ExtendUInt32); Default.ImplementOperator(Operators.Int64GeS, OperatorImpls.Int64GeS); Default.ImplementOperator(Operators.Int64GeU, OperatorImpls.Int64GeU); Default.ImplementOperator(Operators.Int64GtS, OperatorImpls.Int64GtS); Default.ImplementOperator(Operators.Int64GtU, OperatorImpls.Int64GtU); Default.ImplementOperator(Operators.Int64LeS, OperatorImpls.Int64LeS); Default.ImplementOperator(Operators.Int64LeU, OperatorImpls.Int64LeU); Default.ImplementOperator(Operators.Int64LtS, OperatorImpls.Int64LtS); Default.ImplementOperator(Operators.Int64LtU, OperatorImpls.Int64LtU); Default.ImplementOperator(Operators.Int64Mul, OperatorImpls.Int64Mul); Default.ImplementOperator(Operators.Int64Ne, OperatorImpls.Int64Ne); Default.ImplementOperator(Operators.Int64Or, OperatorImpls.Int64Or); Default.ImplementOperator(Operators.Int64Popcnt, OperatorImpls.Int64Popcnt); Default.ImplementOperator(Operators.Int64ReinterpretFloat64, OperatorImpls.Int64ReinterpretFloat64); Default.ImplementOperator(Operators.Int64RemS, OperatorImpls.Int64RemS); Default.ImplementOperator(Operators.Int64RemU, OperatorImpls.Int64RemU); Default.ImplementOperator(Operators.Int64Rotl, OperatorImpls.Int64Rotl); Default.ImplementOperator(Operators.Int64Rotr, OperatorImpls.Int64Rotr); Default.ImplementOperator(Operators.Int64Shl, OperatorImpls.Int64Shl); Default.ImplementOperator(Operators.Int64ShrS, OperatorImpls.Int64ShrS); Default.ImplementOperator(Operators.Int64ShrU, OperatorImpls.Int64ShrU); Default.ImplementOperator(Operators.Int64Sub, OperatorImpls.Int64Sub); Default.ImplementOperator(Operators.Int64TruncSFloat32, OperatorImpls.Int64TruncSFloat32); Default.ImplementOperator(Operators.Int64TruncSFloat64, OperatorImpls.Int64TruncSFloat64); Default.ImplementOperator(Operators.Int64TruncUFloat32, OperatorImpls.Int64TruncUFloat32); Default.ImplementOperator(Operators.Int64TruncUFloat64, OperatorImpls.Int64TruncUFloat64); Default.ImplementOperator(Operators.Int64Xor, OperatorImpls.Int64Xor); Default.ImplementOperator(Operators.Float32Abs, OperatorImpls.Float32Abs); Default.ImplementOperator(Operators.Float32Add, OperatorImpls.Float32Add); Default.ImplementOperator(Operators.Float32Ceil, OperatorImpls.Float32Ceil); Default.ImplementOperator(Operators.Float32ConvertSInt32, OperatorImpls.Float32ConvertSInt32); Default.ImplementOperator(Operators.Float32ConvertSInt64, OperatorImpls.Float32ConvertSInt64); Default.ImplementOperator(Operators.Float32ConvertUInt32, OperatorImpls.Float32ConvertUInt32); Default.ImplementOperator(Operators.Float32ConvertUInt64, OperatorImpls.Float32ConvertUInt64); Default.ImplementOperator(Operators.Float32Copysign, OperatorImpls.Float32Copysign); Default.ImplementOperator(Operators.Float32DemoteFloat64, OperatorImpls.Float32DemoteFloat64); Default.ImplementOperator(Operators.Float32Div, OperatorImpls.Float32Div); Default.ImplementOperator(Operators.Float32Eq, OperatorImpls.Float32Eq); Default.ImplementOperator(Operators.Float32Floor, OperatorImpls.Float32Floor); Default.ImplementOperator(Operators.Float32Ge, OperatorImpls.Float32Ge); Default.ImplementOperator(Operators.Float32Gt, OperatorImpls.Float32Gt); Default.ImplementOperator(Operators.Float32Le, OperatorImpls.Float32Le); Default.ImplementOperator(Operators.Float32Lt, OperatorImpls.Float32Lt); Default.ImplementOperator(Operators.Float32Max, OperatorImpls.Float32Max); Default.ImplementOperator(Operators.Float32Min, OperatorImpls.Float32Min); Default.ImplementOperator(Operators.Float32Mul, OperatorImpls.Float32Mul); Default.ImplementOperator(Operators.Float32Ne, OperatorImpls.Float32Ne); Default.ImplementOperator(Operators.Float32Nearest, OperatorImpls.Float32Nearest); Default.ImplementOperator(Operators.Float32Neg, OperatorImpls.Float32Neg); Default.ImplementOperator(Operators.Float32ReinterpretInt32, OperatorImpls.Float32ReinterpretInt32); Default.ImplementOperator(Operators.Float32Sqrt, OperatorImpls.Float32Sqrt); Default.ImplementOperator(Operators.Float32Sub, OperatorImpls.Float32Sub); Default.ImplementOperator(Operators.Float32Trunc, OperatorImpls.Float32Trunc); Default.ImplementOperator(Operators.Float64Abs, OperatorImpls.Float64Abs); Default.ImplementOperator(Operators.Float64Add, OperatorImpls.Float64Add); Default.ImplementOperator(Operators.Float64Ceil, OperatorImpls.Float64Ceil); Default.ImplementOperator(Operators.Float64ConvertSInt32, OperatorImpls.Float64ConvertSInt32); Default.ImplementOperator(Operators.Float64ConvertSInt64, OperatorImpls.Float64ConvertSInt64); Default.ImplementOperator(Operators.Float64ConvertUInt32, OperatorImpls.Float64ConvertUInt32); Default.ImplementOperator(Operators.Float64ConvertUInt64, OperatorImpls.Float64ConvertUInt64); Default.ImplementOperator(Operators.Float64Copysign, OperatorImpls.Float64Copysign); Default.ImplementOperator(Operators.Float64Div, OperatorImpls.Float64Div); Default.ImplementOperator(Operators.Float64Eq, OperatorImpls.Float64Eq); Default.ImplementOperator(Operators.Float64Floor, OperatorImpls.Float64Floor); Default.ImplementOperator(Operators.Float64Ge, OperatorImpls.Float64Ge); Default.ImplementOperator(Operators.Float64Gt, OperatorImpls.Float64Gt); Default.ImplementOperator(Operators.Float64Le, OperatorImpls.Float64Le); Default.ImplementOperator(Operators.Float64Lt, OperatorImpls.Float64Lt); Default.ImplementOperator(Operators.Float64Max, OperatorImpls.Float64Max); Default.ImplementOperator(Operators.Float64Min, OperatorImpls.Float64Min); Default.ImplementOperator(Operators.Float64Mul, OperatorImpls.Float64Mul); Default.ImplementOperator(Operators.Float64Ne, OperatorImpls.Float64Ne); Default.ImplementOperator(Operators.Float64Nearest, OperatorImpls.Float64Nearest); Default.ImplementOperator(Operators.Float64Neg, OperatorImpls.Float64Neg); Default.ImplementOperator(Operators.Float64PromoteFloat32, OperatorImpls.Float64PromoteFloat32); Default.ImplementOperator(Operators.Float64ReinterpretInt64, OperatorImpls.Float64ReinterpretInt64); Default.ImplementOperator(Operators.Float64Sqrt, OperatorImpls.Float64Sqrt); Default.ImplementOperator(Operators.Float64Sub, OperatorImpls.Float64Sub); Default.ImplementOperator(Operators.Float64Trunc, OperatorImpls.Float64Trunc); } } }
//MIT, 2014-present, WinterDev //MatterHackers //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace PixelFarm.PathReconstruction { public interface IPixelEvaluator { int BufferOffset { get; } int X { get; } int Y { get; } int OrgBitmapWidth { get; } int OrgBitmapHeight { get; } /// <summary> /// set init pos, collect init check data /// </summary> /// <param name="x"></param> /// <param name="y"></param> void SetStartPos(int x, int y); /// <summary> /// move evaluaion point to /// </summary> /// <param name="x"></param> /// <param name="y"></param> void MoveTo(int x, int y); void RestoreMoveToPos(); /// <summary> /// move check position to right side 1 px and check , if not pass, return back to prev pos /// </summary> /// <returns>true if pass condition</returns> bool ReadNext(); /// <summary> /// move check position to left side 1 px, and check, if not pass, return back to prev pos /// </summary> /// <returns>true if pass condition</returns> bool ReadPrev(); /// <summary> /// read current and check /// </summary> /// <returns></returns> bool Read(); void SetSourceDimension(int width, int height); } /// <summary> /// horizontal (scanline) span /// </summary> public readonly struct HSpan { public readonly int startX; /// <summary> /// BEFORE touch endX, not include! /// </summary> public readonly int endX; public readonly int y; public HSpan(int startX, int endX, int y) { this.startX = startX; this.endX = endX; this.y = y; //spanLen= endX-startX } internal bool HorizontalTouchWith(int otherStartX, int otherEndX) { return HorizontalTouchWith(this.startX, this.endX, otherStartX, otherEndX); } internal static bool HorizontalTouchWith(int x0, int x1, int x2, int x3) { if (x0 == x2) { return true; } else if (x0 > x2) { // return x0 <= x3; } else { return x1 >= x2; } } #if DEBUG public override string ToString() { return "line:" + y + ", x_start=" + startX + ",end_x=" + endX + ",len=" + (endX - startX); } #endif } sealed class FloodFillRunner { bool[] _pixelsChecked; SimpleQueue<HSpan> _hspanQueue = new SimpleQueue<HSpan>(9); List<HSpan> _upperSpans = new List<HSpan>(); List<HSpan> _lowerSpans = new List<HSpan>(); int _yCutAt; IPixelEvaluator _pixelEvalutor; public HSpan[] InternalFill(IPixelEvaluator pixelEvalutor, int x, int y, bool collectHSpans) { _pixelEvalutor = pixelEvalutor; _yCutAt = y; //set cut-point if (collectHSpans) { _upperSpans.Clear(); _lowerSpans.Clear(); } int imgW = pixelEvalutor.OrgBitmapWidth; int imgH = pixelEvalutor.OrgBitmapHeight; //reset new buffer, clear mem? _pixelsChecked = new bool[imgW * imgH]; //*** pixelEvalutor.SetStartPos(x, y); TryLinearFill(x, y); while (_hspanQueue.Count > 0) { HSpan hspan = _hspanQueue.Dequeue(); if (collectHSpans) { AddHSpan(hspan); } int downY = hspan.y - 1; int upY = hspan.y + 1; int downPixelOffset = (imgW * (hspan.y - 1)) + hspan.startX; int upPixelOffset = (imgW * (hspan.y + 1)) + hspan.startX; for (int rangeX = hspan.startX; rangeX < hspan.endX; rangeX++) { if (hspan.y > 0 && !_pixelsChecked[downPixelOffset]) { TryLinearFill(rangeX, downY); } if (hspan.y < (imgH - 1) && !_pixelsChecked[upPixelOffset]) { TryLinearFill(rangeX, upY); } upPixelOffset++; downPixelOffset++; } } //reset _hspanQueue.Clear(); _pixelEvalutor = null; return collectHSpans ? SortAndCollectHSpans() : null; } void AddHSpan(HSpan hspan) { if (hspan.y >= _yCutAt) { _lowerSpans.Add(hspan); } else { _upperSpans.Add(hspan); } } HSpan[] SortAndCollectHSpans() { int spanSort(HSpan sp1, HSpan sp2) { //NESTED METHOD //sort asc, if (sp1.y > sp2.y) { return 1; } else if (sp1.y < sp2.y) { return -1; } else { return sp1.startX.CompareTo(sp2.startX); } } //1. _upperSpans.Sort(spanSort); _lowerSpans.Sort(spanSort); HSpan[] hspans = new HSpan[_upperSpans.Count + _lowerSpans.Count]; _upperSpans.CopyTo(hspans); _lowerSpans.CopyTo(hspans, _upperSpans.Count); //clear _upperSpans.Clear(); _lowerSpans.Clear(); return hspans; } /// <summary> /// fill to left side and right side of the line /// </summary> /// <param name="destBuffer"></param> /// <param name="x"></param> /// <param name="y"></param> void TryLinearFill(int x, int y) { _pixelEvalutor.MoveTo(x, y); int pixelOffset = _pixelEvalutor.BufferOffset; if (!_pixelEvalutor.Read()) { //not pass //TODO: review here _pixelsChecked[pixelOffset] = true; //mark as read return; } //if pass then... _pixelsChecked[pixelOffset] = true; //check at current pos //then we will check each pixel on the left side step by step for (; pixelOffset > 0;) { _pixelsChecked[pixelOffset] = true; //mark => current pixel is read pixelOffset--; if ((_pixelsChecked[pixelOffset]) || !_pixelEvalutor.ReadPrev()) { break; } } int leftFillX = _pixelEvalutor.X; //save to use later _pixelEvalutor.RestoreMoveToPos(); pixelOffset = _pixelEvalutor.BufferOffset; for (; pixelOffset < _pixelsChecked.Length - 1;) { _pixelsChecked[pixelOffset] = true; pixelOffset++; if (_pixelsChecked[pixelOffset] || !_pixelEvalutor.ReadNext()) { break; } } _hspanQueue.Enqueue(new HSpan(leftFillX, _pixelEvalutor.X, _pixelEvalutor.Y));//** } class SimpleQueue<T> { T[] _itemArray; int _size; int _head; int _shiftFactor; int _mask; // public SimpleQueue(int shiftFactor) { _shiftFactor = shiftFactor; _mask = (1 << shiftFactor) - 1; _itemArray = new T[1 << shiftFactor]; _head = 0; _size = 0; } public int Count => _size; public T First => _itemArray[_head & _mask]; public void Clear() => _head = 0; public void Enqueue(T itemToQueue) { if (_size == _itemArray.Length) { int headIndex = _head & _mask; _shiftFactor += 1; _mask = (1 << _shiftFactor) - 1; T[] newArray = new T[1 << _shiftFactor]; // copy the from head to the end Array.Copy(_itemArray, headIndex, newArray, 0, _size - headIndex); // copy form 0 to the size Array.Copy(_itemArray, 0, newArray, _size - headIndex, headIndex); _itemArray = newArray; _head = 0; } _itemArray[(_head + (_size++)) & _mask] = itemToQueue; } public T Dequeue() { int headIndex = _head & _mask; T firstItem = _itemArray[headIndex]; if (_size > 0) { _head++; _size--; } return firstItem; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Qwack.Math; using Qwack.Math.Interpolation; using Qwack.Math.Extensions; using Qwack.Transport.BasicTypes; namespace Qwack.Options { /// <summary> /// American (and European) option pricing performed using a trinomial tree /// Includes case of option-on-future where the forward of the underlying future is treated as flat /// </summary> public class TrinomialTree { public static double AmericanPV(double T, double S, double K, double r, double sigma, OptionType CP, double q, int n) => VanillaPV(T, S, K, r, sigma, CP, q, n, true); public static double EuropeanPV(double T, double S, double K, double r, double sigma, OptionType CP, double q, int n) => VanillaPV(T, S, K, r, sigma, CP, q, n, false); public static double AmericanFuturePV(double T, double S, double K, double r, double sigma, OptionType CP, int n) => VanillaPV(T, S, K, r, sigma, CP, r, n, true); public static double EuropeanFuturePV(double T, double S, double K, double r, double sigma, OptionType CP, int n) => VanillaPV(T, S, K, r, sigma, CP, r, n, false); public static double VanillaPV(double T, double S, double K, double r, double sigma, OptionType CP, double q, int n, bool isAmerican) { var deltaT = T / n; var df1p = System.Math.Exp(-r * deltaT); var u = System.Math.Exp(sigma * System.Math.Sqrt(2.0 * deltaT)); var d = System.Math.Exp(-sigma * System.Math.Sqrt(2.0 * deltaT)); //double m = 1; var Z = sigma * System.Math.Sqrt(deltaT / 2.0); //r==q for the case of a flat fwd var pu = (System.Math.Exp((r - q) * deltaT / 2.0) - System.Math.Exp(-Z)) / (System.Math.Exp(Z) - System.Math.Exp(-Z)); var pd = (System.Math.Exp(Z) - System.Math.Exp((r - q) * deltaT / 2.0)) / (System.Math.Exp(Z) - System.Math.Exp(-Z)); pu *= pu; pd *= pd; var pm = 1 - (pu + pd); var p = new double[n * 2 + 1]; double exercise, spot; double cp = CP == OptionType.Call ? 1 : -1; //initial values at time T for (var i = 0; i <= 2 * n; i++) { spot = S * System.Math.Pow(d, n - i); p[i] = System.Math.Max(0, cp * (S * System.Math.Pow(u, System.Math.Max(i - n, 0)) * System.Math.Pow(d, System.Math.Max(n - i, 0)) - K)); } //move back to earlier times for (var j = n - 1; j >= 0; j--) { for (var i = 0; i <= j * 2; i++) { spot = S * System.Math.Pow(u, i - j); p[i] = df1p * (pd * p[i] + pm * p[i + 1] + pu * p[i + 2]); if (isAmerican) { if (CP == OptionType.Put) exercise = K - spot; //exercise value else exercise = spot - K; //exercise value if (p[i] < exercise) p[i] = exercise; } } } return p[0]; } public static double VanillaPV(double T, double S, double K, IInterpolator1D r_interp, double sigma, OptionType CP, IInterpolator1D fwd_interp, int n, bool isAmerican) { var deltaT = T / (double)n; var u = System.Math.Exp(sigma * System.Math.Sqrt(2.0 * deltaT)); var d = System.Math.Exp(-sigma * System.Math.Sqrt(2.0 * deltaT)); var Z = sigma * System.Math.Sqrt(deltaT / 2.0); var p = new double[n * 2 + 1]; double exercise, spot; double cp = CP == OptionType.Call ? 1 : -1; //initial values at time T for (var i = 0; i <= 2 * n; i++) { spot = S * System.Math.Pow(d, n - i); p[i] = System.Math.Max(0, cp * (S * System.Math.Pow(u, System.Math.Max(i - n, 0)) * System.Math.Pow(d, System.Math.Max(n - i, 0)) - K)); } //move back to earlier times for (var j = n - 1; j >= 0; j--) { var t_step = T * (double)j / (double)n; var t_stepPrev = T * (double)(j + 1) / (double)n; var r = System.Math.Log(System.Math.Exp(r_interp.Interpolate(t_stepPrev) * t_stepPrev) / System.Math.Exp(r_interp.Interpolate(t_step) * t_step)) / deltaT; var q = r - System.Math.Log(fwd_interp.Interpolate(t_stepPrev) / fwd_interp.Interpolate(t_step)) / deltaT; var df1p = System.Math.Exp(-r * deltaT); var pu = (System.Math.Exp((r - q) * deltaT / 2.0) - System.Math.Exp(-Z)) / (System.Math.Exp(Z) - System.Math.Exp(-Z)); var pd = (System.Math.Exp(Z) - System.Math.Exp((r - q) * deltaT / 2.0)) / (System.Math.Exp(Z) - System.Math.Exp(-Z)); pu *= pu; pd *= pd; var pm = 1 - (pu + pd); for (var i = 0; i <= j * 2; i++) { spot = S * System.Math.Pow(u, i - j); p[i] = df1p * (pd * p[i] + pm * p[i + 1] + pu * p[i + 2]); if (isAmerican) { if (CP == OptionType.Put) exercise = K - spot; //exercise value else exercise = spot - K; //exercise value if (p[i] < exercise) p[i] = exercise; } } } return p[0]; } public static double AmericanFutureOptionPV(double forward, double strike, double riskFree, double expTime, double volatility, OptionType CP) { var blackPV = BlackFunctions.BlackPV(forward, strike, riskFree, expTime, volatility, CP); if (riskFree == 0) { return blackPV; } var n = System.Math.Max(32, (int)System.Math.Round(365.0 / 2.0 * expTime)); var PV = AmericanPV(expTime, forward, strike, riskFree, volatility, CP, riskFree, n); return PV.SafeMax(blackPV); } public static double AmericanAssetOptionPV(double forward, double strike, double riskFree, double spot, double expTime, double volatility, OptionType CP) { var blackPV = BlackFunctions.BlackPV(forward, strike, riskFree, expTime, volatility, CP); if (riskFree == 0) { return blackPV; } var n = System.Math.Max(32, (int)System.Math.Round(365.0 / 2.0 * expTime)); var assetYield = riskFree - System.Math.Log(forward / spot) / expTime; var PV = AmericanPV(expTime, forward, strike, riskFree, volatility, CP, assetYield, n); return PV.SafeMax(blackPV); } public static double EuropeanFutureOptionPV(double forward, double strike, double riskFree, double expTime, double volatility, OptionType CP) { var n = System.Math.Max(32, (int)System.Math.Round(365.0 / 2.0 * expTime)); var PV = EuropeanPV(expTime, forward, strike, riskFree, volatility, CP, riskFree, n); return PV; } public static object[,] AmericanFutureOption(double forward, double strike, double riskFree, double expTime, double volatility, OptionType CP) { var objArray = new object[5, 2]; var deltaBump = 0.0001; var vegaBump = 0.0001; double PV, PVbumped, PVbumped2; double delta, deltaBumped, gamma, vega, theta; PV = AmericanFutureOptionPV(forward, strike, riskFree, expTime, volatility, CP); objArray[0, 0] = PV; objArray[0, 1] = "PV"; PVbumped = AmericanFutureOptionPV(forward * (1 + deltaBump), strike, riskFree, expTime, volatility, CP); delta = (PVbumped - PV) / (forward * deltaBump); objArray[1, 0] = delta; objArray[1, 1] = "Delta%"; PVbumped2 = AmericanFutureOptionPV(forward * (1 + 2 * deltaBump), strike, riskFree, expTime, volatility, CP); deltaBumped = (PVbumped2 - PVbumped) / (forward * deltaBump); gamma = (deltaBumped - delta) / (deltaBump / 0.01); objArray[2, 0] = gamma; objArray[2, 1] = "Gamma %/%"; PVbumped = AmericanFutureOptionPV(forward, strike, riskFree, expTime, volatility + vegaBump, CP); vega = (PVbumped - PV) / (vegaBump / 0.01); objArray[3, 0] = vega; objArray[3, 1] = "Vega"; PVbumped = AmericanFutureOptionPV(forward, strike, riskFree, System.Math.Max(0, expTime - 1 / 365.0), volatility + vegaBump, CP); theta = PVbumped - PV; objArray[4, 0] = theta; objArray[4, 1] = "Theta"; return objArray; } public static double AmericanFuturesOptionImpliedVol(double forward, double strike, double riskFreeRate, double expTime, double premium, OptionType CP) { Func<double, double> testTrinomial = (vol => { return AmericanFutureOptionPV(forward, strike, riskFreeRate, expTime, vol, CP) - premium; }); var impliedVol = Math.Solvers.Brent.BrentsMethodSolve(testTrinomial, 0.000000001, 5.0000000, 1e-10); return impliedVol; } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Design; using System.Drawing.Text; using System.Data; using System.Windows.Forms; using System.Reflection; namespace Controls { public class ListBoxEx : System.Windows.Forms.ListBox { private int itemMargin = 0; private const int minHeight = 15; private bool antiAlias = true; private Color selectionColor = Color.RoyalBlue; private Color borderColor = Color.Gray; private Color captionColor = Color.Silver; private Font captionFont; private StringFormat stringFormat = new StringFormat(); private bool drawBorder = false; private string captionMember = ""; private Image itemImage; public ListBoxEx() { //this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); this.DrawMode = DrawMode.OwnerDrawVariable; stringFormat = new StringFormat(StringFormatFlags.NoWrap); stringFormat.LineAlignment = StringAlignment.Center; stringFormat.Trimming = StringTrimming.EllipsisCharacter; captionFont = this.Font; } public bool DrawBorder { get { return drawBorder; } set { drawBorder = value; this.Invalidate(); } } [TypeConverter(typeof(ImageConverter)), DefaultValue(typeof(Image), null), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Image ItemImage { get { return itemImage; } set { itemImage = value; this.Invalidate(); } } public int ItemMargin { get { return itemMargin; } set { itemMargin = value; this.Invalidate(); } } public Color CaptionColor { get { return captionColor; } set { captionColor = value; this.Invalidate(); } } public Font CaptionFont { get { return captionFont; } set { captionFont = value; this.Invalidate(); } } public Color BorderColor { get { return borderColor; } set { borderColor = value; this.Invalidate(); } } public Color SelectionColor { get { return selectionColor; } set { selectionColor = value; this.Invalidate(); } } public bool AntiAliasText { get { return antiAlias; } set { antiAlias = value; this.Invalidate(); } } [Browsable(true), Category("Data"), DefaultValue(""), Editor("System.Windows.Forms.Design.DataMemberListEditor", typeof(System.Drawing.Design.UITypeEditor))] public string CaptionMember { get { return captionMember; } set { captionMember = value; this.Invalidate(); } } protected override void OnResize(EventArgs e) { base.OnResize (e); this.Invalidate(); } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged (e); } private Image GetItemImage(object item) { Type itemType = item.GetType(); PropertyInfo propInfo = itemType.GetProperty("Image", typeof(Image)); if (propInfo == null) { FieldInfo fieldInfo = itemType.GetField("Image"); if (fieldInfo != null) return (Image)fieldInfo.GetValue(item); } else { return (Image)propInfo.GetValue(item, null); } return null; } private string GetItemCaption(object item) { if (this.CaptionMember != null && this.CaptionMember.Length > 0 && item is System.Data.DataRowView) { return ((DataRowView)item).Row[this.CaptionMember].ToString(); } else { Type itemType = item.GetType(); PropertyInfo propInfo = itemType.GetProperty("Caption", typeof(string)); if (propInfo == null) { FieldInfo fieldInfo = itemType.GetField("Caption"); if (fieldInfo != null) return (string)fieldInfo.GetValue(item); } else { return (string)propInfo.GetValue(item, null); } } return ""; } private int GetItemImageIndex(object item) { Type itemType = item.GetType(); PropertyInfo propInfo = itemType.GetProperty("ImageIndex", typeof(int)); if(propInfo == null) { FieldInfo fieldInfo = itemType.GetField("ImageIndex"); if(fieldInfo != null) return (int)fieldInfo.GetValue(item); } else { return (int)propInfo.GetValue(item, null); } return -1; } private string GetItemText(object item) { string itemText = item.ToString(); if (this.DisplayMember != null && this.DisplayMember.Length > 0 && item is System.Data.DataRowView) { itemText = ((DataRowView)item).Row[this.DisplayMember].ToString(); } return itemText; } protected override void OnMeasureItem(MeasureItemEventArgs e) { if(this.Items.Count > 0) { e.ItemHeight = MeasureItemHeight(this.Items[e.Index], true); } } private int MeasureItemHeight(object item, bool includeCaption) { int itemHeight = 0; int imageHeight = 0; int textHeight = 0; Image itemImage = GetItemImage(item); if(itemImage != null) imageHeight = itemImage.Height + (itemMargin * 2); using(Graphics g = this.CreateGraphics()) { if(antiAlias) textHeight = (int)g.MeasureString(GetItemText(item), this.Font, 1000, stringFormat).Height + (itemMargin * 2); else textHeight = (int)TextRenderer.MeasureText(g, GetItemText(item), this.Font, new Size(1000, 0), TextFormatFlags.VerticalCenter | TextFormatFlags.Left).Height + (itemMargin * 2); itemHeight = Math.Max(Math.Max(imageHeight, textHeight), minHeight); if(includeCaption) { string caption = GetItemCaption(item); if(caption.Length > 0) { if (antiAlias) itemHeight += (int)g.MeasureString(caption, captionFont, this.Width).Height; else itemHeight += (int)TextRenderer.MeasureText(g, caption, captionFont, new Size(this.Width, 0), TextFormatFlags.Left | TextFormatFlags.WordBreak).Height; } } } return itemHeight; } protected override void OnDrawItem(DrawItemEventArgs e) { e.DrawFocusRectangle(); e.DrawBackground(); if((e.State & DrawItemState.Selected) == DrawItemState.Selected) { using(SolidBrush backBrush = new SolidBrush(selectionColor)) { e.Graphics.FillRectangle(backBrush, e.Bounds); } } if(Items.Count > 0 && e.Index >= 0) { Rectangle stringRect; Image itemImage = GetItemImage(Items[e.Index]); string caption = GetItemCaption(Items[e.Index]); int mainItemHeight = MeasureItemHeight(this.Items[e.Index], false); if (itemImage == null) itemImage = this.itemImage; if(itemImage != null) { Rectangle imageRect = new Rectangle(e.Bounds.Left + itemMargin, e.Bounds.Top + (mainItemHeight - itemImage.Height) / 2, itemImage.Width, itemImage.Height); e.Graphics.DrawImage(itemImage, imageRect); stringRect = new Rectangle(imageRect.Right + 2, e.Bounds.Top, e.Bounds.Width - imageRect.Right - itemMargin, mainItemHeight); } else { stringRect = new Rectangle(e.Bounds.Left + itemMargin, e.Bounds.Top, e.Bounds.Width - itemMargin * 2, mainItemHeight); } using(SolidBrush textBrush = new SolidBrush(ForeColor)) { string itemText = Items[e.Index].ToString(); if (this.DisplayMember != null && Items[e.Index] is System.Data.DataRowView) { itemText = ((DataRowView)Items[e.Index]).Row[this.DisplayMember].ToString(); } if (antiAlias) { e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias; e.Graphics.DrawString(GetItemText(Items[e.Index]), e.Font, textBrush, stringRect, stringFormat); } else { e.Graphics.TextRenderingHint = TextRenderingHint.SystemDefault; TextRenderer.DrawText(e.Graphics, GetItemText(Items[e.Index]), e.Font, stringRect, ForeColor, TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter); } // Draw caption if(caption.Length > 0) { textBrush.Color = captionColor; stringRect.Y = stringRect.Bottom - itemMargin; stringRect.Height = e.Bounds.Bottom - stringRect.Y - itemMargin; if (antiAlias) { e.Graphics.DrawString(caption, captionFont, textBrush, stringRect); } else { TextRenderer.DrawText(e.Graphics, caption, captionFont, stringRect, captionColor, TextFormatFlags.Left | TextFormatFlags.Top | TextFormatFlags.WordBreak); } } } } if(drawBorder) { using(Pen borderPen = new Pen(borderColor)) { e.Graphics.DrawRectangle(borderPen, 0, 0, this.Width - 1, this.Height - 1); } } } } public class ListBoxExItem { private string text = ""; private Image image = null; private string caption = ""; private object tag = null; public ListBoxExItem() { } public ListBoxExItem(string text) { this.Text = text; } public ListBoxExItem(string text, string caption) { this.Text = text; this.Caption = caption; } public ListBoxExItem(string text, Image image) { this.Text = text; this.Image = image; } public ListBoxExItem(string text, string caption, Image image) { this.Text = text; this.Image = image; this.Caption = caption; } public override string ToString() { return this.Text; } public string Text { get { return text; } set { text = value; } } public string Caption { get { return caption; } set { caption = value; } } public Image Image { get { return image; } set { image = value; } } public object Tag { get { return tag; } set { tag = value; } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Web; #endregion internal static class HttpModuleRegistry { private static Dictionary<HttpApplication, IList<IHttpModule>> _moduleListByApp; private static readonly object _lock = new object(); public static bool RegisterInPartialTrust(HttpApplication application, IHttpModule module) { if (application == null) throw new ArgumentNullException("application"); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // On-demand allocate a map of modules per application. // if (_moduleListByApp == null) _moduleListByApp = new Dictionary<HttpApplication, IList<IHttpModule>>(); // // Get the list of modules for the application. If this is // the first registration for the supplied application object // then setup a new and empty list. // var moduleList = _moduleListByApp.Find(application); if (moduleList == null) { moduleList = new List<IHttpModule>(); _moduleListByApp.Add(application, moduleList); } else if (moduleList.Contains(module)) throw new ApplicationException("Duplicate module registration."); // // Add the module to list of registered modules for the // given application object. // moduleList.Add(module); } // // Setup a closure to automatically unregister the module // when the application fires its Disposed event. // Housekeeper housekeeper = new Housekeeper(module); application.Disposed += new EventHandler(housekeeper.OnApplicationDisposed); return true; } private static bool UnregisterInPartialTrust(HttpApplication application, IHttpModule module) { Debug.Assert(application != null); Debug.Assert(module != null); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // Get the module list for the given application object. // if (_moduleListByApp == null) return false; var moduleList = _moduleListByApp.Find(application); if (moduleList == null) return false; // // Remove the module from the list if it's in there. // int index = moduleList.IndexOf(module); if (index < 0) return false; moduleList.RemoveAt(index); // // If the list is empty then remove the application entry. // If this results in the entire map becoming empty then // release it. // if (moduleList.Count == 0) { _moduleListByApp.Remove(application); if (_moduleListByApp.Count == 0) _moduleListByApp = null; } } return true; } public static IEnumerable<IHttpModule> GetModules(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); try { IHttpModule[] modules = new IHttpModule[application.Modules.Count]; application.Modules.CopyTo(modules, 0); return modules; } catch (SecurityException) { // // Pass through because probably this is a partially trusted // environment that does not have access to the modules // collection over HttpApplication so we have to resort // to our own devices... // } lock (_lock) { if (_moduleListByApp == null) return Enumerable.Empty<IHttpModule>(); var moduleList = _moduleListByApp.Find(application); if (moduleList == null) return Enumerable.Empty<IHttpModule>(); IHttpModule[] modules = new IHttpModule[moduleList.Count]; moduleList.CopyTo(modules, 0); return modules; } } private static bool IsHighlyTrusted() { try { AspNetHostingPermission permission = new AspNetHostingPermission(AspNetHostingPermissionLevel.High); permission.Demand(); return true; } catch (SecurityException) { return false; } } internal sealed class Housekeeper { private readonly IHttpModule _module; public Housekeeper(IHttpModule module) { _module = module; } public void OnApplicationDisposed(object sender, EventArgs e) { UnregisterInPartialTrust((HttpApplication) sender, _module); } } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Collections.Generic; using System.Data.SqlClient; using DSL.POS.DTO.DTO; using DSL.POS.DataAccessLayer.Common.Imp; using DSL.POS.DataAccessLayer.Interface; namespace DSL.POS.DataAccessLayer.Imp { /// <summary> /// Summary description for BranchTypeInfoDALImp /// </summary> /// // Error Handling developed by Samad // 05/12/06 public class BranchTypeInfoDALImp : CommonDALImp, IBranchTypeInfoDAL { private void getPKCode(BranchTypeInfoDTO obj) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); string strPKCode = null; int PKSL = 0; string sqlSelect = "Select isnull(Max(BT_Code),0)+1 From BranchTypeInfo"; SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; try { sqlConn.Open(); PKSL = (int)objCmd.ExecuteScalar(); } catch(Exception Exp) { throw Exp; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } strPKCode = PKSL.ToString("0"); obj.BT_Code = strPKCode; //return strPKCode; } public override void Save(object obj) { BranchTypeInfoDTO oBranchTypeInfoDTO = (BranchTypeInfoDTO)obj; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); if (oBranchTypeInfoDTO.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { //string strset = getPKCode(oProductCategoryInfoDTO); String sql = "Insert Into BranchTypeInfo(BT_Code,BT_Name,EntryBy,EntryDate) values(@BT_Code,@BT_Name,@EntryBy,@EntryDate)"; try { getPKCode(oBranchTypeInfoDTO); objCmd.CommandText = sql; objCmd.Parameters.Add(new SqlParameter("@BT_Code", SqlDbType.VarChar, 1)); objCmd.Parameters.Add(new SqlParameter("@BT_Name", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 5)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime)); objCmd.Parameters["@BT_Code"].Value = Convert.ToString(oBranchTypeInfoDTO.BT_Code); objCmd.Parameters["@BT_Name"].Value = Convert.ToString(oBranchTypeInfoDTO.BT_Name); objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oBranchTypeInfoDTO.EntryBy); objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oBranchTypeInfoDTO.EntryDate); sqlConn.Open(); objCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Close(); sqlConn.Dispose(); } } else { String sql = "Update BranchTypeInfo set BT_Name=@BT_Name,EntryBy=@EntryBy,EntryDate=@EntryDate where BT_PK=@BT_PK"; try { objCmd.CommandText = sql; objCmd.Parameters.Add(new SqlParameter("@BT_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters.Add(new SqlParameter("@BT_Name", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 5)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime)); objCmd.Parameters["@BT_PK"].Value = (Guid)oBranchTypeInfoDTO.PrimaryKey; objCmd.Parameters["@BT_Name"].Value = Convert.ToString(oBranchTypeInfoDTO.BT_Name); objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oBranchTypeInfoDTO.EntryBy); objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oBranchTypeInfoDTO.EntryDate); sqlConn.Open(); objCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } } } public override void Delete(object obj) { BranchTypeInfoDTO oSupplierInfoDTO = (BranchTypeInfoDTO)obj; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); String sql = "Delete BranchTypeInfo where BT_PK=@BT_PK"; SqlCommand objCmdDelete = sqlConn.CreateCommand(); objCmdDelete.CommandText = sql; try { objCmdDelete.Parameters.Add("@BT_PK", SqlDbType.UniqueIdentifier, 16); objCmdDelete.Parameters["@BT_PK"].Value = (Guid)oSupplierInfoDTO.PrimaryKey; sqlConn.Open(); objCmdDelete.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmdDelete.Dispose(); objCmdDelete.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } } public BranchTypeInfoDTO findByPKDTO(Guid pk) { BranchTypeInfoDTO oBranchTypeInfoDTO = new BranchTypeInfoDTO(); //oBranchTypeInfoDTO.PrimaryKey = pk; string sqlSelect = "Select BT_PK,BT_Code,BT_Name,EntryBy,EntryDate From BranchTypeInfo where BT_PK=@BT_PK"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; try { objCmd.Parameters.Add("@BT_PK", SqlDbType.UniqueIdentifier, 16); objCmd.Parameters["@BT_PK"].Value = pk; sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { oBranchTypeInfoDTO = populate(thisReader); } thisReader.Close(); thisReader.Dispose(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return oBranchTypeInfoDTO; } public List<BranchTypeInfoDTO> getBranchTypeInfoData() { string sqlSelect = "Select BT_PK,BT_Code,BT_Name,EntryBy,EntryDate From BranchTypeInfo order by BT_Code"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); List<BranchTypeInfoDTO> oArrayList = new List<BranchTypeInfoDTO>(); SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; try { sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { BranchTypeInfoDTO oBranchTypeInfoDTO = populate(thisReader); oArrayList.Add(oBranchTypeInfoDTO); } thisReader.Close(); thisReader.Dispose(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return oArrayList; } public BranchTypeInfoDTO populate(SqlDataReader reader) { try { BranchTypeInfoDTO dto = new BranchTypeInfoDTO(); dto.PrimaryKey = (Guid)reader["BT_PK"]; dto.BT_Code = (string)reader["BT_Code"]; dto.BT_Name = (string)reader["BT_Name"]; dto.EntryBy = (string)reader["EntryBy"]; dto.EntryDate = (DateTime)reader["EntryDate"]; return dto; } catch (Exception Exp) { throw Exp; } } public BranchTypeInfoDALImp() { // // TODO: Add constructor logic here // } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using NUnit.Framework; using Palaso.Code; using Palaso.Data; using Palaso.Tests.Code; using Palaso.WritingSystems; namespace Palaso.Tests.WritingSystems { public class WritingSystemDefinitionIClonableGenericTests : IClonableGenericTests<WritingSystemDefinition> { public override WritingSystemDefinition CreateNewClonable() { return new WritingSystemDefinition(); } public override string ExceptionList { // We do want to clone KnownKeyboards, but I don't think the automatic cloneable test for it can handle a list. get { return "|Modified|MarkedForDeletion|StoreID|_collator|_knownKeyboards|"; } } protected override List<ValuesToSet> DefaultValuesForTypes { get { return new List<ValuesToSet> { new ValuesToSet(3.14f, 2.72f), new ValuesToSet(false, true), new ValuesToSet("to be", "!(to be)"), new ValuesToSet(DateTime.Now, DateTime.MinValue), new ValuesToSet(WritingSystemDefinition.SortRulesType.CustomICU, WritingSystemDefinition.SortRulesType.DefaultOrdering), new ValuesToSet(new RFC5646Tag("en", "Latn", "US", "1901", "test"), RFC5646Tag.Parse("de")), new SubclassValuesToSet<IKeyboardDefinition>(new DefaultKeyboardDefinition() {Layout="mine"}, new DefaultKeyboardDefinition(){Layout="theirs"}) }; } } /// <summary> /// The generic test that clone copies everything can't, I believe, handle lists. /// </summary> [Test] public void CloneCopiesKnownKeyboards() { var original = new WritingSystemDefinition(); var kbd1 = new DefaultKeyboardDefinition() {Layout = "mine"}; var kbd2 = new DefaultKeyboardDefinition() {Layout = "yours"}; original.AddKnownKeyboard(kbd1); original.AddKnownKeyboard(kbd2); var copy = original.Clone(); Assert.That(copy.KnownKeyboards.Count(), Is.EqualTo(2)); Assert.That(copy.KnownKeyboards.First(), Is.EqualTo(kbd1)); Assert.That(ReferenceEquals(copy.KnownKeyboards.First(), kbd1), Is.False); } /// <summary> /// The generic test that Equals compares everything can't, I believe, handle lists. /// </summary> [Test] public void EqualsComparesKnownKeyboards() { var first = new WritingSystemDefinition(); var kbd1 = new DefaultKeyboardDefinition() { Layout = "mine" }; var kbd2 = new DefaultKeyboardDefinition() { Layout = "yours" }; first.AddKnownKeyboard(kbd1); first.AddKnownKeyboard(kbd2); var second = new WritingSystemDefinition(); var kbd3 = new DefaultKeyboardDefinition() { Layout = "mine" }; // equal to kbd1 var kbd4 = new DefaultKeyboardDefinition() {Layout = "theirs"}; Assert.That(first.Equals(second), Is.False, "ws with empty known keyboards should not equal one with some"); second.AddKnownKeyboard(kbd3); Assert.That(first.Equals(second), Is.False, "ws's with different length known keyboard lits should not be equal"); second.AddKnownKeyboard(kbd2.Clone()); Assert.That(first.Equals(second), Is.True, "ws's with same known keyboard lists should be equal"); second = new WritingSystemDefinition(); second.AddKnownKeyboard(kbd3); second.AddKnownKeyboard(kbd4); Assert.That(first.Equals(second), Is.False, "ws with same-length lists of different known keyboards should not be equal"); } } [TestFixture] public class WritingSystemDefinitionPropertyTests { [Test] public void FromRFC5646Subtags_AllArgs_SetsOk() { var ws = WritingSystemDefinition.FromSubtags("en", "Latn", "US", "x-whatever"); Assert.AreEqual(ws.Language, "en"); Assert.AreEqual(ws.Script, "Latn"); Assert.AreEqual(ws.Region, "US"); Assert.AreEqual(ws.Variant, "x-whatever"); } private void AssertWritingSystem(WritingSystemDefinition wsDef, string language, string script, string region, string variant) { Assert.AreEqual(language, wsDef.Language); Assert.AreEqual(script, wsDef.Script); Assert.AreEqual(region, wsDef.Region); Assert.AreEqual(variant, wsDef.Variant); } [Test] public void Parse_HasOnlyPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("x-privuse"); AssertWritingSystem(tag, string.Empty, string.Empty, string.Empty, "x-privuse"); } [Test] public void Parse_HasMultiplePrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("x-private-use"); AssertWritingSystem(tag, string.Empty, string.Empty, string.Empty, "x-private-use"); } [Test] public void Parse_HasLanguage_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de"); AssertWritingSystem(tag, "de", string.Empty, string.Empty, string.Empty); } [Test] public void Parse_HasLanguageAndScript_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-Latn"); AssertWritingSystem(tag, "en", "Latn", string.Empty, string.Empty); } [Test] public void Parse_HasLanguageAndScriptAndRegion_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-Latn-US"); AssertWritingSystem(tag, "en", "Latn", "US", string.Empty); } [Test] public void Parse_HasLanguageAndScriptAndRegionAndVariant_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de-Latn-DE-1901"); AssertWritingSystem(tag, "de", "Latn", "DE", "1901"); } [Test] public void Parse_HasLanguageAndScriptAndRegionAndMultipleVariants_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de-Latn-DE-1901-bauddha"); AssertWritingSystem(tag, "de", "Latn", "DE", "1901-bauddha"); } [Test] public void Parse_HasLanguageAndScriptAndRegionAndMultipleVariantsAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de-Latn-DE-1901-bauddha-x-private"); AssertWritingSystem(tag, "de", "Latn", "DE", "1901-bauddha-x-private"); } [Test] public void Parse_HasLanguageAndScriptAndRegionAndMultipleVariantsAndMultiplePrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de-Latn-DE-1901-bauddha-x-private-use"); AssertWritingSystem(tag, "de", "Latn", "DE", "1901-bauddha-x-private-use"); } [Test] public void Parse_HasLanguageAndScriptAndRegionAndVariantAndMultiplePrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de-Latn-DE-bauddha-x-private-use"); AssertWritingSystem(tag, "de", "Latn", "DE", "bauddha-x-private-use"); } [Test] public void Parse_HasLanguageAndRegionAndVariantAndMultiplePrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("de-DE-bauddha-x-private-use"); AssertWritingSystem(tag, "de", string.Empty, "DE", "bauddha-x-private-use"); } [Test] public void Parse_HasLanguageAndVariant_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-alalc97"); AssertWritingSystem(tag, "en", string.Empty, string.Empty, "alalc97"); } [Test] public void Parse_HasBadSubtag_Throws() { Assert.Throws<ValidationException>(() => WritingSystemDefinition.Parse("qaa-dupl1")); } [Test] public void Parse_HasLanguageAndMultipleVariants_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-alalc97-aluku"); AssertWritingSystem(tag, "en", string.Empty, string.Empty, "alalc97-aluku"); } [Test] public void Parse_HasLanguageAndRegion_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-US"); AssertWritingSystem(tag, "en", string.Empty, "US", string.Empty); } [Test] public void Parse_HasLanguageAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-x-private-use"); AssertWritingSystem(tag, "en", string.Empty, String.Empty, "x-private-use"); } [Test] public void Parse_HasLanguageAndVariantAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-1901-bauddha-x-private-use"); AssertWritingSystem(tag, "en", string.Empty, String.Empty, "1901-bauddha-x-private-use"); } [Test] public void Parse_HasLanguageAndRegionAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-US-x-private-use"); AssertWritingSystem(tag, "en", string.Empty, "US", "x-private-use"); } [Test] public void Parse_HasLanguageAndRegionAndVariant_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-US-1901-bauddha"); AssertWritingSystem(tag, "en", string.Empty, "US", "1901-bauddha"); } [Test] public void Parse_HasLanguageAndRegionAndVariantAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-US-1901-bauddha-x-private-use"); AssertWritingSystem(tag, "en", string.Empty, "US", "1901-bauddha-x-private-use"); } [Test] public void Parse_HasLanguageAndScriptAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-Latn-x-private-use"); AssertWritingSystem(tag, "en", "Latn", String.Empty, "x-private-use"); } [Test] public void Parse_HasLanguageAndScriptAndRegionAndPrivateUse_WritingSystemHasExpectedFields() { var tag = WritingSystemDefinition.Parse("en-Latn-US-x-private-use"); AssertWritingSystem(tag, "en", "Latn", "US", "x-private-use"); } [Test] public void DisplayLabelWhenUnknown() { var ws = new WritingSystemDefinition(); Assert.AreEqual("???", ws.DisplayLabel); } [Test] public void DisplayLabel_NoAbbreviation_UsesRFC5646() { var ws = new WritingSystemDefinition(); ws.Language = "en"; ws.Variant = "1901"; Assert.AreEqual("en-1901", ws.DisplayLabel); } [Test] public void DisplayLabel_LanguageTagIsDefaultHasAbbreviation_ShowsAbbreviation() { var ws = new WritingSystemDefinition(); ws.Abbreviation = "xyz"; Assert.AreEqual("xyz", ws.DisplayLabel); } [Test] public void Variant_ConsistsOnlyOfRfc5646Variant_VariantIsSetCorrectly() { var ws = new WritingSystemDefinition(); ws.Variant = "fonipa"; Assert.AreEqual("fonipa", ws.Variant); } [Test] public void InvalidTagOkWhenRequiresValidTagFalse() { var ws = new WritingSystemDefinition(); ws.RequiresValidTag = false; ws.Language = "Kalaba"; Assert.That(ws.Language, Is.EqualTo("Kalaba")); } [Test] public void DuplicatePrivateUseOkWhenRequiresValidTagFalse() { var ws = new WritingSystemDefinition(); ws.RequiresValidTag = false; ws.Variant = "x-nong-nong"; Assert.That(ws.Variant, Is.EqualTo("x-nong-nong")); } [Test] public void InvalidTagThrowsWhenRequiresValidTagSetToTrue() { var ws = new WritingSystemDefinition(); ws.RequiresValidTag = false; ws.Language = "Kalaba"; Assert.Throws(typeof (ValidationException), () => ws.RequiresValidTag = true); } [Test] public void DuplicatePrivateUseThrowsWhenRequiresValidTagSetToTrue() { var ws = new WritingSystemDefinition(); ws.RequiresValidTag = false; ws.Variant = "x-nong-nong"; Assert.Throws(typeof(ValidationException), () => ws.RequiresValidTag = true); } [Test] public void Variant_ConsistsOnlyOfRfc5646PrivateUse_VariantIsSetCorrectly() { var ws = new WritingSystemDefinition(); ws.Variant = "x-test"; Assert.AreEqual("x-test", ws.Variant); } [Test] public void Variant_ConsistsOfBothRfc5646VariantandprivateUse_VariantIsSetCorrectly() { var ws = new WritingSystemDefinition(); ws.Variant = "fonipa-x-etic"; Assert.AreEqual("fonipa-x-etic", ws.Variant); } [Test] public void DisplayLabel_OnlyHasLanguageName_UsesFirstPartOfLanguageName() { var ws = new WritingSystemDefinition(); ws.LanguageName = "abcdefghijk"; Assert.AreEqual("abcd", ws.DisplayLabel); } [Test] public void LanguageName_Default_ReturnsUnknownLanguage() { var ws = new WritingSystemDefinition(); Assert.AreEqual("Language Not Listed", ws.LanguageName); } [Test] public void LanguageName_SetLanguageEn_ReturnsEnglish() { var ws = new WritingSystemDefinition(); ws.Language = "en"; Assert.AreEqual("English", ws.LanguageName); } [Test] public void LanguageName_SetCustom_ReturnsCustomName() { var ws = new WritingSystemDefinition(); ws.LanguageName = "CustomName"; Assert.AreEqual("CustomName", ws.LanguageName); } [Test] public void Rfc5646_HasOnlyAbbreviation_ReturnsQaa() { var ws = new WritingSystemDefinition {Abbreviation = "hello"}; Assert.AreEqual("qaa", ws.Bcp47Tag); } [Test] public void Rfc5646WhenJustISO() { var ws = new WritingSystemDefinition("en","","","","", false); Assert.AreEqual("en", ws.Bcp47Tag); } [Test] public void Rfc5646WhenIsoAndScript() { var ws = new WritingSystemDefinition("en", "Zxxx", "", "", "", false); Assert.AreEqual("en-Zxxx", ws.Bcp47Tag); } [Test] public void Rfc5646WhenIsoAndRegion() { var ws = new WritingSystemDefinition("en", "", "US", "", "", false); Assert.AreEqual("en-US", ws.Bcp47Tag); } [Test] public void Rfc5646WhenIsoScriptRegionVariant() { var ws = new WritingSystemDefinition("en", "Zxxx", "US", "1901", "", false); Assert.AreEqual("en-Zxxx-US-1901", ws.Bcp47Tag); } [Test] public void Constructor_OnlyVariantContainingOnlyPrivateUseisPassedIn_RfcTagConsistsOfOnlyPrivateUse() { var ws = new WritingSystemDefinition("", "", "", "x-private", "", false); Assert.AreEqual("x-private", ws.Bcp47Tag); } [Test] public void Parse_OnlyPrivateUseIsPassedIn_RfcTagConsistsOfOnlyPrivateUse() { var ws = WritingSystemDefinition.Parse("x-private"); Assert.AreEqual("x-private", ws.Bcp47Tag); } [Test] public void FromRFC5646Subtags_OnlyVariantContainingOnlyPrivateUseisPassedIn_RfcTagConsistsOfOnlyPrivateUse() { var ws = WritingSystemDefinition.FromSubtags("", "", "", "x-private"); Assert.AreEqual("x-private", ws.Bcp47Tag); } [Test] public void Constructor_OnlyVariantIsPassedIn_Throws() { Assert.Throws<ValidationException>(()=>new WritingSystemDefinition("", "", "", "bogus", "", false)); } [Test] public void ReadsISORegistry() { Assert.Greater(StandardTags.ValidIso639LanguageCodes.Count, 100); } [Test] public void ModifyingDefinitionSetsModifiedFlag() { // Put any properties to ignore in this string surrounded by "|" // ObsoleteWindowsLcid has no public setter; it only gets a value by reading from an old file. const string ignoreProperties = "|Modified|MarkedForDeletion|StoreID|DateModified|Rfc5646TagOnLoad|RequiresValidTag|WindowsLcid|"; // special test values to use for properties that are particular Dictionary<string, object> firstValueSpecial = new Dictionary<string, object>(); Dictionary<string, object> secondValueSpecial = new Dictionary<string, object>(); firstValueSpecial.Add("Variant", "1901"); secondValueSpecial.Add("Variant", "biske"); firstValueSpecial.Add("Region", "US"); secondValueSpecial.Add("Region", "GB"); firstValueSpecial.Add("ISO639", "en"); secondValueSpecial.Add("ISO639", "de"); firstValueSpecial.Add("Language", "en"); secondValueSpecial.Add("Language", "de"); firstValueSpecial.Add("ISO", "en"); secondValueSpecial.Add("ISO", "de"); firstValueSpecial.Add("Script", "Zxxx"); secondValueSpecial.Add("Script", "Latn"); firstValueSpecial.Add("DuplicateNumber", 0); secondValueSpecial.Add("DuplicateNumber", 1); firstValueSpecial.Add("LocalKeyboard", new DefaultKeyboardDefinition() {Layout="mine"}); secondValueSpecial.Add("LocalKeyboard", new DefaultKeyboardDefinition() { Layout = "yours" }); //firstValueSpecial.Add("SortUsing", "CustomSimple"); //secondValueSpecial.Add("SortUsing", "CustomICU"); // test values to use based on type Dictionary<Type, object> firstValueToSet = new Dictionary<Type, object>(); Dictionary<Type, object> secondValueToSet = new Dictionary<Type, object>(); firstValueToSet.Add(typeof (float), 2.18281828459045f); secondValueToSet.Add(typeof (float), 3.141592653589f); firstValueToSet.Add(typeof (bool), true); secondValueToSet.Add(typeof (bool), false); firstValueToSet.Add(typeof (string), "X"); secondValueToSet.Add(typeof (string), "Y"); firstValueToSet.Add(typeof (DateTime), new DateTime(2007, 12, 31)); secondValueToSet.Add(typeof (DateTime), new DateTime(2008, 1, 1)); firstValueToSet.Add(typeof(WritingSystemDefinition.SortRulesType), WritingSystemDefinition.SortRulesType.CustomICU); secondValueToSet.Add(typeof(WritingSystemDefinition.SortRulesType), WritingSystemDefinition.SortRulesType.CustomSimple); firstValueToSet.Add(typeof(RFC5646Tag), new RFC5646Tag("de", "Latn", "", "1901","audio")); firstValueToSet.Add(typeof(IpaStatusChoices), IpaStatusChoices.IpaPhonemic); secondValueToSet.Add(typeof(IpaStatusChoices), IpaStatusChoices.NotIpa); foreach (PropertyInfo propertyInfo in typeof(WritingSystemDefinition).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { // skip read-only or ones in the ignore list if (!propertyInfo.CanWrite || ignoreProperties.Contains("|" + propertyInfo.Name + "|")) { continue; } var ws = new WritingSystemDefinition(); ws.Modified = false; // We need to ensure that all values we are setting are actually different than the current values. // This could be accomplished by comparing with the current value or by setting twice with different values. // We use the setting twice method so we don't require a getter on the property. try { if (firstValueSpecial.ContainsKey(propertyInfo.Name) && secondValueSpecial.ContainsKey(propertyInfo.Name)) { propertyInfo.SetValue(ws, firstValueSpecial[propertyInfo.Name], null); propertyInfo.SetValue(ws, secondValueSpecial[propertyInfo.Name], null); } else if (firstValueToSet.ContainsKey(propertyInfo.PropertyType) && secondValueToSet.ContainsKey(propertyInfo.PropertyType)) { propertyInfo.SetValue(ws, firstValueToSet[propertyInfo.PropertyType], null); propertyInfo.SetValue(ws, secondValueToSet[propertyInfo.PropertyType], null); } else { Assert.Fail("Unhandled property type - please update the test to handle type {0}", propertyInfo.PropertyType.Name); } } catch(Exception error) { Assert.Fail("Error setting property WritingSystemDefinition.{0},{1}", propertyInfo.Name, error.ToString()); } Assert.IsTrue(ws.Modified, "Modifying WritingSystemDefinition.{0} did not change modified flag.", propertyInfo.Name); } } [Test] public void CloneCopiesAllNeededMembers() { // Put any fields to ignore in this string surrounded by "|" // _knownKeyboards and _localKeyboard are tested by the similar test in WritingSystemDefintionICloneableGenericTests. // I (JohnT) suspect that this whole test is redundant but am keeping it in case this version // confirms something subtly different. const string ignoreFields = "|Modified|MarkedForDeletion|StoreID|_collator|_knownKeyboards|_localKeyboard|"; // values to use for testing different types var valuesToSet = new Dictionary<Type, object> { {typeof (float), 3.14f}, {typeof (bool), true}, {typeof (string), "Foo"}, {typeof (DateTime), DateTime.Now}, {typeof (WritingSystemDefinition.SortRulesType), WritingSystemDefinition.SortRulesType.CustomICU}, {typeof (RFC5646Tag), new RFC5646Tag("en", "Latn", "US", "1901", "test")} }; foreach (var fieldInfo in typeof(WritingSystemDefinition).GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { var fieldName = fieldInfo.Name; if (fieldInfo.Name.Contains("<")) { var splitResult = fieldInfo.Name.Split(new[] {'<', '>'}); fieldName = splitResult[1]; } if (ignoreFields.Contains("|" + fieldName + "|")) { continue; } var ws = new WritingSystemDefinition(); if (valuesToSet.ContainsKey(fieldInfo.FieldType)) { fieldInfo.SetValue(ws, valuesToSet[fieldInfo.FieldType]); } else { Assert.Fail("Unhandled field type - please update the test to handle type {0}. The field that uses this type is {1}.", fieldInfo.FieldType.Name, fieldName); } var theClone = ws.Clone(); if(fieldInfo.GetValue(ws).GetType() != typeof(string)) //strings are special in .net so we won't worry about checking them here. { Assert.AreNotSame(fieldInfo.GetValue(ws), fieldInfo.GetValue(theClone), "The field {0} refers to the same object, it was not copied.", fieldName); } Assert.AreEqual(valuesToSet[fieldInfo.FieldType], fieldInfo.GetValue(theClone), "Field {0} not copied on WritingSystemDefinition.Clone()", fieldName); } } [Test] public void SortUsingDefaultOrdering_ValidateSortRulesWhenEmpty_IsTrue() { var ws = new WritingSystemDefinition(); string message; Assert.IsTrue(ws.ValidateCollationRules(out message)); } [Test] public void SortUsingDefaultOrdering_ValidateSortRulesWhenNotEmpty_IsFalse() { var ws = new WritingSystemDefinition(); ws.SortRules = "abcd"; string message; Assert.IsFalse(ws.ValidateCollationRules(out message)); } [Test] public void SortUsingOtherLanguage_NullRules_DoesNotThrow() { // This is the current policy for 'OtherLanguage' which currently returns a SystemCollator. // If SystemCollator can't determine the other langauge it uses Invariant very quietly. // review: Is this the behaviour we want? CP 2011-04 var ws = new WritingSystemDefinition(); ws.SortUsingOtherLanguage("NotAValidLanguageCode"); var collator = ws.Collator; int result1 = collator.Compare("b", "A"); int result2 = collator.Compare("b", "a"); Assert.AreEqual(result1, result2); } [Test] public void SetIsVoice_SetToTrue_SetsScriptRegionAndVariantCorrectly() { var ws = new WritingSystemDefinition { Script = "Latn", Region = "US", Variant = "1901", IsVoice = true }; Assert.AreEqual(WellKnownSubTags.Audio.Script, ws.Script); Assert.AreEqual("US", ws.Region); Assert.AreEqual("1901-x-audio", ws.Variant); Assert.AreEqual("qaa-Zxxx-US-1901-x-audio", ws.Bcp47Tag); } [Test] public void SetIsVoice_ToTrue_LeavesIsoCodeAlone() { var ws = new WritingSystemDefinition { Language = "en", IsVoice = true }; Assert.AreEqual("en", ws.Language); } [Test] public void SetVoice_FalseFromTrue_ClearsScript() { var ws = new WritingSystemDefinition(); ws.IsVoice = true; ws.IsVoice = false; Assert.AreEqual("", ws.Script); Assert.AreEqual("", ws.Region); Assert.AreEqual("", ws.Variant); } [Test] public void Script_ChangedToSomethingOtherThanZxxxWhileIsVoiceIsTrue_Throws() { var ws = new WritingSystemDefinition { IsVoice = true }; Assert.Throws<ValidationException>(() => ws.Script = "change!"); } [Test] public void SetAllRfc5646LanguageTagComponents_ScriptSetToZxxxAndVariantSetToXDashAudio_SetsIsVoiceToTrue() { var ws = new WritingSystemDefinition(); ws.SetAllComponents( "th", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Audio.PrivateUseSubtag ); Assert.IsTrue(ws.IsVoice); } [Test] public void SetAllRfc5646LanguageTagComponents_ScriptSetToZxXxAndVariantSetToXDashAuDiO_SetsIsVoiceToTrue() { var ws = new WritingSystemDefinition(); ws.SetAllComponents( "th", "ZxXx", "", "x-AuDiO" ); Assert.IsTrue(ws.IsVoice); } [Test] public void Variant_ChangedToSomethingOtherThanXDashAudioWhileIsVoiceIsTrue_IsVoiceIsChangedToFalse() { var ws = new WritingSystemDefinition(); ws.IsVoice = true; ws.Variant = "1901"; Assert.AreEqual("1901", ws.Variant); Assert.IsFalse(ws.IsVoice); } [Test] public void Iso639_SetValidLanguage_IsSet() { var ws = new WritingSystemDefinition(); ws.Language = "th"; Assert.AreEqual("th", ws.Language); } [Test] public void Iso639_SetInvalidLanguage_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "xyz"); } [Test] public void IsVoice_ToggledAfterVariantHasBeenSet_DoesNotRemoveVariant() { var ws = new WritingSystemDefinition { Variant = "1901", IsVoice = true }; ws.IsVoice = false; Assert.AreEqual("1901", ws.Variant); } [Test] public void IsVoice_ToggledAfterRegionHasBeenSet_DoesNotRemoveRegion() { var ws = new WritingSystemDefinition() { Region = "US" }; ws.IsVoice = true; ws.IsVoice = false; Assert.AreEqual("US", ws.Region); } [Test] public void IsVoice_ToggledAfterScriptHasBeenSet_ScriptIsCleared() { var ws = new WritingSystemDefinition() { Script = "Latn" }; ws.IsVoice = true; ws.IsVoice = false; Assert.AreEqual("", ws.Script); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsIpa_IpaStatusIsSetToNotIpa() { var ws = new WritingSystemDefinition { IpaStatus = IpaStatusChoices.Ipa, IsVoice = true }; Assert.AreEqual(IpaStatusChoices.NotIpa, ws.IpaStatus); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsIpaPhontetic_IpaStatusIsSetToNotIpa() { var ws = new WritingSystemDefinition { IpaStatus = IpaStatusChoices.IpaPhonetic, IsVoice = true }; Assert.AreEqual(IpaStatusChoices.NotIpa, ws.IpaStatus); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsIpaPhonemic_IpaStatusIsSetToNotIpa() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.IpaPhonemic; ws.IsVoice = true; Assert.AreEqual(IpaStatusChoices.NotIpa, ws.IpaStatus); } [Test] public void Script_ScriptNull_EmptyString() { var ws = new WritingSystemDefinition(); ws.Script = null; Assert.That("", Is.EqualTo(ws.Script)); } [Test] public void Variant_VariantNull_EmptyString() { var ws = new WritingSystemDefinition(); ws.Variant = null; Assert.That("", Is.EqualTo(ws.Variant)); } [Test] public void Region_RegionNull_EmptyString() { var ws = new WritingSystemDefinition(); ws.Region = null; Assert.That("", Is.EqualTo(ws.Region)); } [Test] public void Language_LangaugeNull_EmptyString() { var ws = new WritingSystemDefinition(); // Set private use so that we can legally set the language to null ws.Variant = "x-any"; ws.Language = null; Assert.That("", Is.EqualTo(ws.Language)); } [Test] public void Variant_ResetToEmptyString_ClearsVariant() { var ws = new WritingSystemDefinition(); ws.Variant = "Biske"; Assert.AreEqual("Biske", ws.Variant); ws.Variant = ""; Assert.AreEqual("", ws.Variant); } [Test] public void Variant_IsSetWithDuplicateTags_DontKnowWhatToDo() { Assert.Throws<ValidationException>( () => new WritingSystemDefinition {Variant = "duplicate-duplicate"} ); } [Test] public void Variant_SetToXDashAudioWhileScriptIsNotZxxx_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>(() => ws.Variant = WellKnownSubTags.Audio.PrivateUseSubtag); } [Test] public void Script_SetToOtherThanZxxxWhileVariantIsXDashAudio_Throws() { var ws = new WritingSystemDefinition(); ws.SetAllComponents( "th", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Audio.PrivateUseSubtag ); Assert.Throws<ValidationException>(() => ws.Script = "Ltn"); } [Test] public void SetAllRfc5646LanguageTagComponents_VariantSetToPrivateUseOnly_VariantIsSet() { var ws = new WritingSystemDefinition(); ws.SetAllComponents( "th", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Audio.PrivateUseSubtag ); Assert.AreEqual(ws.Variant, WellKnownSubTags.Audio.PrivateUseSubtag); } [Test] public void Variant_SetToxDashCapitalAUDIOWhileScriptIsNotZxxx_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>(() => ws.Variant = "x-AUDIO"); } [Test] public void Script_SetToOtherThanZxxxWhileVariantIsxDashCapitalAUDIO_Throws() { var ws = new WritingSystemDefinition(); ws.SetAllComponents( "th", WellKnownSubTags.Audio.Script, "", "x-AUDIO" ); Assert.Throws<ValidationException>(() => ws.Script = "Ltn"); } [Test] public void IsVoice_VariantIsxDashPrefixaudioPostFix_ReturnsFalse() { var ws = new WritingSystemDefinition (); ws.SetAllComponents( "th", WellKnownSubTags.Audio.Script, "", "x-PrefixaudioPostfix" ); Assert.IsFalse(ws.IsVoice); } [Test] public void Variant_ContainsXDashAudioDashFonipa_VariantIsSet() { var ws = new WritingSystemDefinition(); ws.SetAllComponents( "th", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Audio.PrivateUseSubtag + "-" + WellKnownSubTags.Ipa.VariantSubtag ); Assert.AreEqual("x-audio-fonipa", ws.Variant); } [Test] public void Variant_ContainsXDashAudioAndFonipa_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Ipa.VariantSubtag + "-" + WellKnownSubTags.Audio.PrivateUseSubtag)); } [Test] public void Variant_ContainsXDashEticAndNotFonipaInVariant_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", "", "", WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag)); } [Test] public void Variant_ContainsXDashEmicAndNotFonipaInVariant_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", "", "", WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag)); } [Test] public void Variant_ContainsXDashEticAndFonipaInPrivateUse_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", "", "", WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag + '-' + WellKnownSubTags.Ipa.VariantSubtag)); } [Test] public void Variant_ContainsXDashEmicAndAndFonipaInPrivateUse_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", "", "", WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag + '-' + WellKnownSubTags.Ipa.VariantSubtag)); } [Test] public void Variant_ContainsXDashAudioAndPhoneticMarker_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Audio.PrivateUseSubtag + "-" + "etic")); } [Test] public void Variant_ContainsXDashAudioAndPhonemicMarker_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ArgumentException>( () => ws.SetAllComponents("qaa", WellKnownSubTags.Audio.Script, "", WellKnownSubTags.Audio.PrivateUseSubtag + "-" + "emic")); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsIpa_IsVoiceIsTrue() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.Ipa; ws.IsVoice = true; Assert.IsTrue(ws.IsVoice); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsIpa_IpaStatusIsNotIpa() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.Ipa; ws.IsVoice = true; Assert.AreEqual(IpaStatusChoices.NotIpa, ws.IpaStatus); } [Test] public void IsVoice_SetToFalseWhileIpaStatusIsIpa_IsVoiceIsFalse() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.Ipa; ws.IsVoice = false; Assert.IsFalse(ws.IsVoice); } [Test] public void IsVoice_SetToTrueOnEntirelyPrivateUseLanguageTag_markerForUnlistedLanguageIsInserted() { var ws = WritingSystemDefinition.Parse("x-private"); Assert.That(ws.Variant, Is.EqualTo("x-private")); ws.IsVoice = true; Assert.That(ws.Language, Is.EqualTo(WellKnownSubTags.Unlisted.Language)); Assert.That(ws.Script, Is.EqualTo(WellKnownSubTags.Unwritten.Script)); Assert.That(ws.Region, Is.EqualTo("")); Assert.That(ws.Variant, Is.EqualTo("x-private-audio")); } [Test] public void IsVoice_SetToFalseWhileIpaStatusIsIpa_IpaStatusIsIpa() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.Ipa; ws.IsVoice = false; Assert.AreEqual(IpaStatusChoices.Ipa, ws.IpaStatus); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsPhonetic_IsVoiceIsTrue() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.IpaPhonetic; ws.IsVoice = true; Assert.IsTrue(ws.IsVoice); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsPhonetic_IpaStatusIsNotIpa() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.IpaPhonetic; ws.IsVoice = true; Assert.AreEqual(IpaStatusChoices.NotIpa, ws.IpaStatus); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsPhonemic_IsVoiceIsTrue() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.IpaPhonemic; ws.IsVoice = true; Assert.IsTrue(ws.IsVoice); } [Test] public void IsVoice_SetToTrueWhileIpaStatusIsPhonemic_IpaStatusIsNotIpa() { var ws = new WritingSystemDefinition(); ws.IpaStatus = IpaStatusChoices.IpaPhonemic; ws.IsVoice = true; Assert.AreEqual(IpaStatusChoices.NotIpa, ws.IpaStatus); } [Test] public void Iso639_SetEmpty_ThrowsValidationException() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(()=>ws.Language = String.Empty); } [Test] public void Variant_ContainsUnderscore_Throws() { var ws = new WritingSystemDefinition(); ws.Language = "de"; Assert.Throws<ValidationException>(() => ws.Variant = "x_audio"); } [Test] public void Variant_ContainsxDashCapitalAUDIOAndScriptIsNotZxxx_Throws() { var ws = new WritingSystemDefinition(); ws.Language = "de"; ws.Script = "Latn"; Assert.Throws<ArgumentException>(() => ws.Variant = "x-AUDIO"); } [Test] public void Variant_IndicatesThatWsIsAudioAndScriptIsCapitalZXXX_ReturnsTrue() { var ws = new WritingSystemDefinition(); ws.Language = "de"; ws.Script = "ZXXX"; ws.Variant = WellKnownSubTags.Audio.PrivateUseSubtag; Assert.IsTrue(ws.IsVoice); } [Test] public void IsValidWritingSystem_VariantIndicatesThatWsIsAudioButContainsotherThanJustTheNecassaryXDashAudioTagAndScriptIsNotZxxx_Throws() { var ws = new WritingSystemDefinition(); ws.Language = "de"; ws.Script = "latn"; Assert.Throws<ArgumentException>(()=>ws.Variant = "x-private-audio"); } [Test] public void LanguageSubtag_ContainsXDashAudio_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "de-x-audio"); } [Test] public void Language_ContainsZxxx_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "de-Zxxx"); } [Test] public void LanguageSubtag_ContainsCapitalXDashAudio_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "de-X-AuDiO"); } [Test] public void Language_SetWithInvalidLanguageTag_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "bogus"); } [Test] public void Script_SetWithInvalidScriptTag_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "bogus"); } [Test] public void Region_SetWithInvalidRegionTag_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>(() => ws.Language = "bogus"); } [Test] public void Variant_SetWithPrivateUseTag_VariantisSet() { var ws = new WritingSystemDefinition(); ws.Variant = "x-lalala"; Assert.AreEqual("x-lalala", ws.Variant); } [Test] public void SetRfc5646LanguageTagComponents_Language_IsSet() { var ws = new WritingSystemDefinition(); ws.SetAllComponents("th", "", "", ""); Assert.AreEqual("th", ws.Language); } [Test] public void SetRfc5646LanguageTagComponents_BadLanguage_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>( () => ws.SetAllComponents("BadLanguage", "", "", "") ); } [Test] public void SetRfc5646LanguageTagComponents_Script_IsSet() { var ws = new WritingSystemDefinition(); ws.SetAllComponents("th", "Thai", "", ""); Assert.AreEqual("Thai", ws.Script); } [Test] public void SetRfc5646LanguageTagComponents_BadScript_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>( () => ws.SetAllComponents("th", "BadScript", "", "") ); } [Test] public void SetRfc5646LanguageTagComponents_Region_IsSet() { var ws = new WritingSystemDefinition(); ws.SetAllComponents("th", "Thai", "TH", ""); Assert.AreEqual("TH", ws.Region); } [Test] public void SetRfc5646LanguageTagComponents_BadRegion_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>( () => ws.SetAllComponents("th", "Thai", "BadRegion", "") ); } [Test] public void SetRfc5646LanguageTagComponents_Variant_IsSet() { var ws = new WritingSystemDefinition(); ws.SetAllComponents("th", "Thai", "TH", "1901"); Assert.AreEqual("1901", ws.Variant); } [Test] public void SetRfc5646LanguageTagComponents_BadVariant_Throws() { var ws = new WritingSystemDefinition(); Assert.Throws<ValidationException>( () => ws.SetAllComponents("th", "Thai", "TH", "BadVariant") ); } [Test] public void Abbreviation_Sets_GetsSame() { var ws = new WritingSystemDefinition(); ws.Abbreviation = "en"; Assert.AreEqual("en", ws.Abbreviation); } [Test] public void Abbreviation_Uninitialized_ReturnsISO639() { var writingSystem = new WritingSystemDefinition("en"); Assert.AreEqual("en", writingSystem.Abbreviation); } [Test] public void IpaStatus_SetToIpaRfcTagStartsWithxDash_InsertsUnknownlanguagemarkerAsLanguageSubtag() { var writingSystem = new WritingSystemDefinition("x-bogus"); writingSystem.IpaStatus = IpaStatusChoices.Ipa; Assert.AreEqual(WellKnownSubTags.Unlisted.Language, writingSystem.Language); Assert.AreEqual("qaa-fonipa-x-bogus", writingSystem.Bcp47Tag); } [Test] public void IpaStatus_SetToPhoneticRfcTagStartsWithxDash_InsertsUnknownlanguagemarkerAsLanguageSubtag() { var writingSystem = new WritingSystemDefinition("x-bogus"); writingSystem.IpaStatus = IpaStatusChoices.IpaPhonetic; Assert.AreEqual(WellKnownSubTags.Unlisted.Language, writingSystem.Language); Assert.AreEqual("qaa-fonipa-x-bogus-etic", writingSystem.Bcp47Tag); } [Test] public void IpaStatus_SetToPhonemicRfcTagStartsWithxDash_InsertsUnknownlanguagemarkerAsLanguageSubtag() { var writingSystem = new WritingSystemDefinition("x-bogus"); writingSystem.IpaStatus = IpaStatusChoices.IpaPhonemic; Assert.AreEqual(WellKnownSubTags.Unlisted.Language, writingSystem.Language); Assert.AreEqual("qaa-fonipa-x-bogus-emic", writingSystem.Bcp47Tag); } [Test] public void CloneContructor_VariantStartsWithxDash_VariantIsCopied() { var writingSystem = new WritingSystemDefinition(new WritingSystemDefinition("x-bogus")); Assert.AreEqual("x-bogus", writingSystem.Bcp47Tag); } [Test] public void Language_Set_Idchanged() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.Language = "de"; Assert.AreEqual("de-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void Script_Set_Idchanged() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-bogus"); writingSystem.Script = "Latn"; Assert.AreEqual("en-Latn-1901-x-bogus", writingSystem.Id); } [Test] public void Region_Set_Idchanged() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-bogus"); writingSystem.Region = "US"; Assert.AreEqual("en-Zxxx-US-1901-x-bogus", writingSystem.Id); } [Test] public void Variant_Set_Idchanged() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-bogus"); writingSystem.Variant = "x-audio"; Assert.AreEqual("en-Zxxx-x-audio", writingSystem.Id); } [Test] public void Ctor1_IdIsSet() { var writingSystem = new WritingSystemDefinition(); Assert.AreEqual("qaa", writingSystem.Id); } [Test] public void Ctor2_IdIsSet() { var writingSystem = new WritingSystemDefinition("en","Zxxx","","1901-x-audio","abb",true); Assert.AreEqual("en-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void Ctor3_IdIsSet() { var writingSystem = new WritingSystemDefinition("en-Zxxx-1901-x-audio"); Assert.AreEqual("en-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void Ctor4_IdIsSet() { var writingSystem = new WritingSystemDefinition(new WritingSystemDefinition("en-Zxxx-1901-x-audio")); Assert.AreEqual("en-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void Parse_IdIsSet() { var writingSystem = WritingSystemDefinition.Parse("en-Zxxx-1901-x-audio"); Assert.AreEqual("en-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void FromLanguage_IdIsSet() { var writingSystem = WritingSystemDefinition.Parse("en-Zxxx-1901-x-audio"); Assert.AreEqual("en-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void FromRfc5646Subtags_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); Assert.AreEqual("en-Zxxx-1901-x-audio", writingSystem.Id); } [Test] public void IpaStatus_Set_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.IpaStatus = IpaStatusChoices.IpaPhonetic; Assert.AreEqual("en-Zxxx-1901-fonipa-x-etic", writingSystem.Id); } [Test] public void IsVoice_Set_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.IsVoice = false; Assert.AreEqual("en-1901", writingSystem.Id); } [Test] public void AddToVariant_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.AddToVariant("bauddha"); Assert.AreEqual("en-Zxxx-1901-bauddha-x-audio", writingSystem.Id); } [Test] public void AddToVariant_NonRegisteredVariant_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.AddToVariant("bogus"); Assert.AreEqual("en-Zxxx-1901-x-audio-bogus", writingSystem.Id); } [Test] public void SetAllRfc5646LanguageTagComponents_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.SetAllComponents("de","Latn","US","fonipa-x-etic"); Assert.AreEqual("de-Latn-US-fonipa-x-etic", writingSystem.Id); } [Test] public void SetAllRfc5646LanguageTagComponents_IdChanged_ModifiedisTrue() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.SetAllComponents("de", "Latn", "US", "fonipa-x-etic"); Assert.AreEqual(writingSystem.Modified, true); } [Test] public void SetAllRfc5646LanguageTagComponents_IdUnchanged_ModifiedisTrue() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.SetAllComponents("en", "Zxxx", "", "1901-x-audio"); Assert.AreEqual(writingSystem.Modified, false); } [Test] public void SetRfc5646FromString_IdIsSet() { var writingSystem = WritingSystemDefinition.FromSubtags("en", "Zxxx", "", "1901-x-audio"); writingSystem.SetTagFromString("de-Latn-US-fonipa-x-etic"); Assert.AreEqual("de-Latn-US-fonipa-x-etic", writingSystem.Id); } [Test] public void MakeUnique_IsAlreadyUnique_NothingChanges() { var existingTags = new[] {"en-Zxxx-x-audio"}; var ws = new WritingSystemDefinition("de"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, existingTags); Assert.That(newWs.Id, Is.EqualTo("de")); } [Test] public void MakeUnique_IsNotUnique_DuplicateMarkerIsAppended() { var existingTags = new[] { "en-Zxxx-x-audio" }; var ws = new WritingSystemDefinition("en-Zxxx-x-audio"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, existingTags); Assert.That(newWs.Id, Is.EqualTo("en-Zxxx-x-audio-dupl0")); } [Test] public void MakeUnique_ADuplicateAlreadyExists_DuplicatemarkerWithHigherNumberIsAppended() { var existingTags = new[] { "en-Zxxx-x-audio", "en-Zxxx-x-audio-dupl0" }; var ws = new WritingSystemDefinition("en-Zxxx-x-audio"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, existingTags); Assert.That(newWs.Id, Is.EqualTo("en-Zxxx-x-audio-dupl1")); } [Test] public void MakeUnique_ADuplicatewithHigherNumberAlreadyExists_DuplicateMarkerWithLowNumberIsAppended() { var existingTags = new[] { "en-Zxxx-x-audio", "en-Zxxx-x-audio-dupl1" }; var ws = new WritingSystemDefinition("en-Zxxx-x-audio"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, existingTags); Assert.That(newWs.Id, Is.EqualTo("en-Zxxx-x-audio-dupl0")); } [Test] public void MakeUnique_StoreIdIsNull() { var existingTags = new[] { "en-Zxxx-x-audio" }; var ws = new WritingSystemDefinition("de"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, existingTags); Assert.That(newWs.StoreID, Is.EqualTo(null)); } [Test] public void MakeUnique_IdAlreadyContainsADuplicateMarker_DuplicateNumberIsMaintainedAndNewOneIsIntroduced() { var existingTags = new[] { "en-Zxxx-x-dupl0-audio", "en-Zxxx-x-audio-dupl1" }; var ws = new WritingSystemDefinition("en-Zxxx-x-dupl0-audio"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, existingTags); Assert.That(newWs.Id, Is.EqualTo("en-Zxxx-x-dupl0-audio-dupl1")); } [Test] public void GetDefaultFontSizeOrMinimum_DefaultConstructor_GreaterThanSix() { Assert.Greater(new WritingSystemDefinition().GetDefaultFontSizeOrMinimum(),6); } [Test] public void GetDefaultFontSizeOrMinimum_SetAt0_GreaterThanSix() { var ws = new WritingSystemDefinition() { DefaultFontSize = 0 }; Assert.Greater(ws.GetDefaultFontSizeOrMinimum(), 6); } [Test] public void ListLabel_ScriptRegionVariantEmpty_LabelIsLanguage() { var ws = new WritingSystemDefinition("de"); Assert.That(ws.ListLabel, Is.EqualTo("German")); } [Test] public void ListLabel_ScriptSet_LabelIsLanguageWithScriptInBrackets() { var ws = new WritingSystemDefinition("de"); ws.Script = "Armi"; Assert.That(ws.ListLabel, Is.EqualTo("German (Armi)")); } [Test] public void ListLabel_RegionSet_LabelIsLanguageWithRegionInBrackets() { var ws = new WritingSystemDefinition("de"); ws.Region = "US"; Assert.That(ws.ListLabel, Is.EqualTo("German (US)")); } [Test] public void ListLabel_ScriptRegionSet_LabelIsLanguageWithScriptandRegionInBrackets() { var ws = new WritingSystemDefinition("de"); ws.Script = "Armi"; ws.Region = "US"; Assert.That(ws.ListLabel, Is.EqualTo("German (Armi-US)")); } [Test] public void ListLabel_ScriptVariantSet_LabelIsLanguageWithScriptandVariantInBrackets() { var ws = new WritingSystemDefinition("de"); ws.Script = "Armi"; ws.AddToVariant("smth"); Assert.That(ws.ListLabel, Is.EqualTo("German (Armi-x-smth)")); } [Test] public void ListLabel_RegionVariantSet_LabelIsLanguageWithRegionAndVariantInBrackets() { var ws = new WritingSystemDefinition("de"); ws.Region = "US"; ws.AddToVariant("smth"); Assert.That(ws.ListLabel, Is.EqualTo("German (US-x-smth)")); } [Test] public void ListLabel_VariantSetToIpa_LabelIsLanguageWithIPAInBrackets() { var ws = new WritingSystemDefinition("de"); ws.Variant = WellKnownSubTags.Ipa.VariantSubtag; Assert.That(ws.ListLabel, Is.EqualTo("German (IPA)")); } [Test] public void ListLabel_VariantSetToPhonetic_LabelIsLanguageWithIPADashEticInBrackets() { var ws = new WritingSystemDefinition("de"); ws.IpaStatus = IpaStatusChoices.IpaPhonetic; Assert.That(ws.ListLabel, Is.EqualTo("German (IPA-etic)")); } [Test] public void ListLabel_VariantSetToPhonemic_LabelIsLanguageWithIPADashEmicInBrackets() { var ws = new WritingSystemDefinition("de"); ws.IpaStatus = IpaStatusChoices.IpaPhonemic; Assert.That(ws.ListLabel, Is.EqualTo("German (IPA-emic)")); } [Test] public void ListLabel_WsIsVoice_LabelIsLanguageWithVoiceInBrackets() { var ws = new WritingSystemDefinition("de"); ws.IsVoice = true; Assert.That(ws.ListLabel, Is.EqualTo("German (Voice)")); } [Test] public void ListLabel_VariantContainsDuplwithNumber_LabelIsLanguageWithCopyAndNumberInBrackets() { var ws = new WritingSystemDefinition("de"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, new[]{"de", "de-x-dupl0"}); Assert.That(newWs.ListLabel, Is.EqualTo("German (Copy1)")); } [Test] public void ListLabel_VariantContainsDuplwithZero_LabelIsLanguageWithCopyAndNoNumberInBrackets() { var ws = new WritingSystemDefinition("de"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, new[] { "de" }); Assert.That(newWs.ListLabel, Is.EqualTo("German (Copy)")); } [Test] public void ListLabel_VariantContainsmulitpleDuplswithNumber_LabelIsLanguageWithCopyAndNumbersInBrackets() { var ws = new WritingSystemDefinition("de-x-dupl0"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, new[] { "de", "de-x-dupl0" }); Assert.That(newWs.ListLabel, Is.EqualTo("German (Copy-Copy1)")); } [Test] public void ListLabel_VariantContainsUnknownVariant_LabelIsLanguageWithVariantInBrackets() { var ws = new WritingSystemDefinition("de"); ws.AddToVariant("garble"); Assert.That(ws.ListLabel, Is.EqualTo("German (x-garble)")); } [Test] public void ListLabel_AllSortsOfThingsSet_LabelIsCorrect() { var ws = new WritingSystemDefinition("de-x-dupl0"); var newWs = WritingSystemDefinition.CreateCopyWithUniqueId(ws, new[] { "de", "de-x-dupl0" }); newWs.Region = "US"; newWs.Script = "Armi"; newWs.IpaStatus = IpaStatusChoices.IpaPhonetic; newWs.AddToVariant("garble"); newWs.AddToVariant("1901"); Assert.That(newWs.ListLabel, Is.EqualTo("German (IPA-etic-Copy-Copy1-Armi-US-1901-x-garble)")); } [Test] public void OtherAvailableKeyboards_DefaultsToAllAvailable() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() {Layout = "something", Locale="en-US"}; var kbd2 = new DefaultKeyboardDefinition() { Layout = "somethingElse", Locale = "en-GB" }; var controller = new MockKeyboardController(); var keyboardList = new List<IKeyboardDefinition>(); keyboardList.Add(kbd1); keyboardList.Add(kbd2); controller.AllAvailableKeyboards = keyboardList; Keyboard.Controller = controller; var result = ws.OtherAvailableKeyboards; Assert.That(result, Has.Member(kbd1)); Assert.That(result, Has.Member(kbd2)); } [Test] public void OtherAvailableKeyboards_OmitsKnownKeyboards() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; var kbd2 = new DefaultKeyboardDefinition() { Layout = "somethingElse", Locale = "en-GB" }; var kbd3 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; // equal to kbd1 var controller = new MockKeyboardController(); var keyboardList = new List<IKeyboardDefinition>(); keyboardList.Add(kbd1); keyboardList.Add(kbd2); controller.AllAvailableKeyboards = keyboardList; Keyboard.Controller = controller; ws.AddKnownKeyboard(kbd3); var result = ws.OtherAvailableKeyboards.ToList(); Assert.That(result, Has.Member(kbd2)); Assert.That(result, Has.No.Member(kbd1)); } class MockKeyboardController : IKeyboardController { /// <summary> /// Tries to get the keyboard with the specified <paramref name="layoutName"/>. /// </summary> /// <returns> /// Returns <c>KeyboardDescription.Zero</c> if no keyboard can be found. /// </returns> public IKeyboardDefinition GetKeyboard(string layoutName) { throw new NotImplementedException(); } public IKeyboardDefinition GetKeyboard(string layoutName, string locale) { throw new NotImplementedException(); } /// <summary> /// Tries to get the keyboard for the specified <paramref name="writingSystem"/>. /// </summary> /// <returns> /// Returns <c>KeyboardDescription.Zero</c> if no keyboard can be found. /// </returns> public IKeyboardDefinition GetKeyboard(IWritingSystemDefinition writingSystem) { throw new NotImplementedException(); } public IKeyboardDefinition GetKeyboard(IInputLanguage language) { throw new NotImplementedException(); } /// <summary> /// Sets the keyboard /// </summary> public void SetKeyboard(IKeyboardDefinition keyboard) { throw new NotImplementedException(); } public void SetKeyboard(string layoutName) { throw new NotImplementedException(); } public void SetKeyboard(string layoutName, string locale) { throw new NotImplementedException(); } public void SetKeyboard(IWritingSystemDefinition writingSystem) { throw new NotImplementedException(); } public void SetKeyboard(IInputLanguage language) { throw new NotImplementedException(); } /// <summary> /// Activates the keyboard of the default input language /// </summary> public void ActivateDefaultKeyboard() { throw new NotImplementedException(); } public IEnumerable<IKeyboardDefinition> AllAvailableKeyboards { get; set; } public IKeyboardDefinition Default; public IWritingSystemDefinition ArgumentPassedToDefault; public void UpdateAvailableKeyboards() { throw new NotImplementedException(); } public IKeyboardDefinition DefaultForWritingSystem(IWritingSystemDefinition ws) { ArgumentPassedToDefault = ws; return Default; } public IKeyboardDefinition LegacyForWritingSystem(IWritingSystemDefinition ws) { throw new NotImplementedException(); } /// <summary> /// Creates and returns a keyboard definition object based on the layout and locale. /// </summary> /// <remarks>The keyboard controller implementing this method will have to check the /// availability of the keyboard and what engine provides it.</remarks> public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale) { throw new NotImplementedException(); } /// <summary> /// Gets or sets the currently active keyboard /// </summary> public IKeyboardDefinition ActiveKeyboard { get; set; } #region Implementation of IDisposable /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { GC.SuppressFinalize(this); } #endregion } [Test] public void SettingLocalKeyboard_AddsToKnownKeyboards() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; ws.LocalKeyboard = kbd1; Assert.That(ws.LocalKeyboard, Is.EqualTo(kbd1)); Assert.That(ws.KnownKeyboards.ToList(), Has.Member(kbd1)); } /// <summary> /// This incidentally tests that AddKnownKeyboard sets the Modified flag when it DOES change something. /// </summary> [Test] public void AddKnownKeyboard_DoesNotMakeDuplicates() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; var kbd2 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; ws.AddKnownKeyboard(kbd1); Assert.That(ws.Modified, Is.True); ws.Modified = false; ws.AddKnownKeyboard(kbd2); Assert.That(ws.Modified, Is.False); Assert.That(ws.KnownKeyboards.Count(), Is.EqualTo(1)); } [Test] public void SetLocalKeyboard_ToAlreadyKnownKeyboard_SetsModifiedFlag() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; var kbd2 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; ws.AddKnownKeyboard(kbd1); ws.LocalKeyboard = kbd2; Assert.That(ws.Modified, Is.True); // worth checking, but it doesn't really prove the point, since it will have also changed KnownKeyboards ws.Modified = false; ws.LocalKeyboard = kbd1; // This time it's already a known keyboard so only the LocalKeyboard setter can be responsibe for setting the flag. Assert.That(ws.Modified, Is.True); } [Test] public void AddKnownKeyboard_Null_DoesNothing() { var ws = new WritingSystemDefinition("de-x-dupl0"); Assert.DoesNotThrow(() => ws.AddKnownKeyboard(null)); } [Test] public void LocalKeyboard_DefaultsToFirstKnownAvailable() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; var kbd2 = new DefaultKeyboardDefinition() { Layout = "somethingElse", Locale = "en-US" }; var kbd3 = new DefaultKeyboardDefinition() { Layout = "somethingElse", Locale = "en-US" }; ws.AddKnownKeyboard(kbd1); ws.AddKnownKeyboard(kbd2); var controller = new MockKeyboardController(); var keyboardList = new List<IKeyboardDefinition>(); keyboardList.Add(kbd3); controller.AllAvailableKeyboards = keyboardList; Keyboard.Controller = controller; Assert.That(ws.LocalKeyboard, Is.EqualTo(kbd2)); } [Test] public void LocalKeyboard_DefersToController_WhenNoKnownAvailable() { var ws = new WritingSystemDefinition("de-x-dupl0"); var kbd1 = new DefaultKeyboardDefinition() { Layout = "something", Locale = "en-US" }; var controller = new MockKeyboardController(); var keyboardList = new List<IKeyboardDefinition>(); controller.AllAvailableKeyboards = keyboardList; controller.Default = kbd1; Keyboard.Controller = controller; Assert.That(ws.LocalKeyboard, Is.EqualTo(kbd1)); Assert.That(controller.ArgumentPassedToDefault, Is.EqualTo(ws)); } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.OpsWorks.Model { /// <summary> /// <para>Describes a load-based auto scaling upscaling or downscaling threshold configuration, which specifies when AWS OpsWorks starts or /// stops load-based instances.</para> /// </summary> public class AutoScalingThresholds { private int? instanceCount; private int? thresholdsWaitTime; private int? ignoreMetricsTime; private double? cpuThreshold; private double? memoryThreshold; private double? loadThreshold; /// <summary> /// The number of instances to add or remove when the load exceeds a threshold. /// /// </summary> public int InstanceCount { get { return this.instanceCount ?? default(int); } set { this.instanceCount = value; } } /// <summary> /// Sets the InstanceCount property /// </summary> /// <param name="instanceCount">The value to set for the InstanceCount property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AutoScalingThresholds WithInstanceCount(int instanceCount) { this.instanceCount = instanceCount; return this; } // Check to see if InstanceCount property is set internal bool IsSetInstanceCount() { return this.instanceCount.HasValue; } /// <summary> /// The amount of time, in minutes, that the load must exceed a threshold before more instances are added or removed. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Range</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public int ThresholdsWaitTime { get { return this.thresholdsWaitTime ?? default(int); } set { this.thresholdsWaitTime = value; } } /// <summary> /// Sets the ThresholdsWaitTime property /// </summary> /// <param name="thresholdsWaitTime">The value to set for the ThresholdsWaitTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AutoScalingThresholds WithThresholdsWaitTime(int thresholdsWaitTime) { this.thresholdsWaitTime = thresholdsWaitTime; return this; } // Check to see if ThresholdsWaitTime property is set internal bool IsSetThresholdsWaitTime() { return this.thresholdsWaitTime.HasValue; } /// <summary> /// The amount of time (in minutes) after a scaling event occurs that AWS OpsWorks should ignore metrics and not raise any additional scaling /// events. For example, AWS OpsWorks adds new instances following an upscaling event but the instances won't start reducing the load until they /// have been booted and configured. There is no point in raising additional scaling events during that operation, which typically takes several /// minutes. <c>IgnoreMetricsTime</c> allows you to direct AWS OpsWorks to not raise any scaling events long enough to get the new instances /// online. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Range</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public int IgnoreMetricsTime { get { return this.ignoreMetricsTime ?? default(int); } set { this.ignoreMetricsTime = value; } } /// <summary> /// Sets the IgnoreMetricsTime property /// </summary> /// <param name="ignoreMetricsTime">The value to set for the IgnoreMetricsTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AutoScalingThresholds WithIgnoreMetricsTime(int ignoreMetricsTime) { this.ignoreMetricsTime = ignoreMetricsTime; return this; } // Check to see if IgnoreMetricsTime property is set internal bool IsSetIgnoreMetricsTime() { return this.ignoreMetricsTime.HasValue; } /// <summary> /// The CPU utilization threshold, as a percent of the available CPU. /// /// </summary> public double CpuThreshold { get { return this.cpuThreshold ?? default(double); } set { this.cpuThreshold = value; } } /// <summary> /// Sets the CpuThreshold property /// </summary> /// <param name="cpuThreshold">The value to set for the CpuThreshold property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AutoScalingThresholds WithCpuThreshold(double cpuThreshold) { this.cpuThreshold = cpuThreshold; return this; } // Check to see if CpuThreshold property is set internal bool IsSetCpuThreshold() { return this.cpuThreshold.HasValue; } /// <summary> /// The memory utilization threshold, as a percent of the available memory. /// /// </summary> public double MemoryThreshold { get { return this.memoryThreshold ?? default(double); } set { this.memoryThreshold = value; } } /// <summary> /// Sets the MemoryThreshold property /// </summary> /// <param name="memoryThreshold">The value to set for the MemoryThreshold property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AutoScalingThresholds WithMemoryThreshold(double memoryThreshold) { this.memoryThreshold = memoryThreshold; return this; } // Check to see if MemoryThreshold property is set internal bool IsSetMemoryThreshold() { return this.memoryThreshold.HasValue; } /// <summary> /// The load threshold. For more information about how load is computed, see <a href="http://en.wikipedia.org/wiki/Load_%28computing%29">Load /// (computing)</a>. /// /// </summary> public double LoadThreshold { get { return this.loadThreshold ?? default(double); } set { this.loadThreshold = value; } } /// <summary> /// Sets the LoadThreshold property /// </summary> /// <param name="loadThreshold">The value to set for the LoadThreshold property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AutoScalingThresholds WithLoadThreshold(double loadThreshold) { this.loadThreshold = loadThreshold; return this; } // Check to see if LoadThreshold property is set internal bool IsSetLoadThreshold() { return this.loadThreshold.HasValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using StructureMap.Building.Interception; using StructureMap.Configuration.DSL; using StructureMap.Configuration.DSL.Expressions; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.TypeRules; namespace StructureMap { /// <summary> /// A Registry class provides methods and grammars for configuring a Container or ObjectFactory. /// Using a Registry subclass is the recommended way of configuring a StructureMap Container. /// </summary> /// <example> /// public class MyRegistry : Registry /// { /// public MyRegistry() /// { /// ForRequestedType(typeof(IService)).TheDefaultIsConcreteType(typeof(Service)); /// } /// } /// </example> public class Registry : IRegistry { private readonly IList<Action<PluginGraph>> _actions = new List<Action<PluginGraph>>(); internal readonly IList<AssemblyScanner> Scanners = new List<AssemblyScanner>(); internal Action<PluginGraph> alter { set { _actions.Add(value); } } /// <summary> /// Adds the concreteType as an Instance of the pluginType. Mostly useful /// for conventions /// </summary> /// <param name="pluginType"></param> /// <param name="concreteType"></param> public void AddType(Type pluginType, Type concreteType) { alter = g => g.AddType(pluginType, concreteType); } /// <summary> /// Adds the concreteType as an Instance of the pluginType with a name. Mostly /// useful for conventions /// </summary> /// <param name="pluginType"></param> /// <param name="concreteType"></param> /// <param name="name"></param> public virtual void AddType(Type pluginType, Type concreteType, string name) { alter = g => g.AddType(pluginType, concreteType, name); } /// <summary> /// Imports the configuration from another registry into this registry. /// </summary> /// <typeparam name="T"></typeparam> public void IncludeRegistry<T>() where T : Registry, new() { IncludeRegistry(new T()); } /// <summary> /// Imports the configuration from another registry into this registry. /// </summary> /// <param name="registry"></param> public void IncludeRegistry(Registry registry) { foreach (var scanner in registry.Scanners) { Scanners.Add(scanner); } foreach (var action in registry._actions) { _actions.Add(action); } } /// <summary> /// This method is a shortcut for specifying the default constructor and /// setter arguments for a ConcreteType. ForConcreteType is shorthand for: /// For[T]().Use[T].************** /// when the PluginType and ConcreteType are the same Type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public BuildWithExpression<T> ForConcreteType<T>() { var instance = For<T>().Use<T>(); return new BuildWithExpression<T>(instance); } /// <summary> /// Convenience method. Equivalent of ForRequestedType[PluginType]().Singletons() /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> ForSingletonOf<TPluginType>() { return For<TPluginType>().Singleton(); } /// <summary> /// Shorthand way of saying For(pluginType).Singleton() /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public GenericFamilyExpression ForSingletonOf(Type pluginType) { return For(pluginType).Singleton(); } /// <summary> /// An alternative way to use CreateProfile that uses ProfileExpression /// as a Nested Closure. This usage will result in cleaner code for /// multiple declarations /// </summary> /// <param name="profileName"></param> /// <param name="action"></param> public void Profile(string profileName, Action<IProfileRegistry> action) { var registry = new Registry(); action(registry); alter = x => registry.Configure(x.Profile(profileName)); } /// <summary> /// Designates a policy for scanning assemblies to auto /// register types /// </summary> /// <returns></returns> public void Scan(Action<IAssemblyScanner> action) { var scanner = new AssemblyScanner(); if (GetType().GetTypeInfo().Assembly == typeof(Registry).GetTypeInfo().Assembly) { scanner.Description = "Scanner #" + (Scanners.Count + 1); } else { scanner.Description = "{0} Scanner #{1}".ToFormat(GetType().Name, (Scanners.Count + 1)); } action(scanner); if (!scanner.Conventions.Any()) { throw new StructureMapConfigurationException($"Must be at least one {nameof(IRegistrationConvention)} in the scanning operation"); } Scanners.Add(scanner); } /// <summary> /// All requests For the "TO" types will be filled by fetching the "FROM" /// type and casting it to "TO" /// GetInstance(typeof(TO)) basically becomes (TO)GetInstance(typeof(FROM)) /// </summary> /// <typeparam name="TFrom"></typeparam> /// <typeparam name="TTo"></typeparam> public void Forward<TFrom, TTo>() where TFrom : class where TTo : class { For<TTo>().AddInstances(x => x.ConstructedBy(c => c.GetInstance<TFrom>() as TTo)); } /// <summary> /// Expression Builder used to define policies for a PluginType including /// Scoping, the Default Instance, and interception. BuildInstancesOf() /// and ForRequestedType() are synonyms /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <param name="lifecycle">Optionally specify the instance scoping for this PluginType</param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> For<TPluginType>(ILifecycle lifecycle = null) { return new CreatePluginFamilyExpression<TPluginType>(this, lifecycle); } /// <summary> /// Expression Builder used to define policies for a PluginType including /// Scoping, the Default Instance, and interception. This method is specifically /// meant for registering open generic types /// </summary> /// <param name="lifecycle">Optionally specify the instance scoping for this PluginType</param> /// <returns></returns> public GenericFamilyExpression For(Type pluginType, ILifecycle lifecycle = null) { return new GenericFamilyExpression(pluginType, lifecycle, this); } /// <summary> /// Shortcut to make StructureMap return the default object of U casted to T /// whenever T is requested. I.e.: /// For<T>().TheDefault.Is.ConstructedBy(c => c.GetInstance<U>() as T); /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// <returns></returns> public LambdaInstance<T, T> Redirect<T, U>() where T : class where U : class { return For<T>() .Use( "Redirect requests for {0} to the configured default of {1} with a cast".ToFormat( typeof (T).GetFullName(), typeof (U).GetFullName()), c => { var raw = c.GetInstance<U>(); var t = raw as T; if (t == null) throw new InvalidCastException(raw.GetType().AssemblyQualifiedName + " could not be cast to " + typeof (T).AssemblyQualifiedName); return t; }); } /// <summary> /// Advanced Usage Only! Skips the Registry and goes right to the inner /// Semantic Model of StructureMap. Use with care /// </summary> /// <param name="configure"></param> public void Configure(Action<PluginGraph> configure) { alter = configure; } internal void Configure(PluginGraph graph) { _actions.Each(action => action(graph)); } public TransientTracking TransientTracking { set { _transients = value; alter = graph => graph.TransientTracking = value; } } internal TransientTracking? GetTransientTracking() { return _transients; } internal static bool IsPublicRegistry(Type type) { var ti = type.GetTypeInfo(); if (Equals(ti.Assembly, typeof (Registry).GetTypeInfo().Assembly)) { return false; } if (!typeof (Registry).GetTypeInfo().IsAssignableFrom(ti)) { return false; } if (ti.IsInterface || ti.IsAbstract || ti.IsGenericType) { return false; } return (type.GetConstructor(new Type[0]) != null); } public bool Equals(Registry other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (other.GetType() == typeof (Registry) && GetType() == typeof (Registry)) return false; if (other.GetType() == GetType() || other.GetType().AssemblyQualifiedName == GetType().AssemblyQualifiedName) { return !GetType().GetTypeInfo().IsNotPublic; } return false; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (!typeof(Registry).GetTypeInfo().IsAssignableFrom(obj.GetType().GetTypeInfo())) return false; return Equals((Registry) obj); } public override int GetHashCode() { return GetType().GetHashCode(); } /// <summary> /// Define the constructor and setter arguments for the default T /// </summary> /// <typeparam name="T"></typeparam> public class BuildWithExpression<T> { private readonly SmartInstance<T, T> _instance; public BuildWithExpression(SmartInstance<T, T> instance) { _instance = instance; } public SmartInstance<T, T> Configure { get { return _instance; } } } /// <summary> /// Configure Container-wide policies and conventions /// </summary> public PoliciesExpression Policies { get { return new PoliciesExpression(this); } } public class PoliciesExpression { private readonly Registry _parent; private Action<PluginGraph> alter { set { _parent.PoliciesChanged = true; _parent.alter = value; } } public PoliciesExpression(Registry parent) { _parent = parent; } /// <summary> /// Adds a new instance policy to this container /// that can apply to every object instance created /// by this container /// </summary> /// <param name="policy"></param> public void Add(IInstancePolicy policy) { alter = graph => graph.Policies.Add(policy); } /// <summary> /// Adds a new instance policy to this container /// that can apply to every object instance created /// by this container /// </summary> public void Add<T>() where T : IInstancePolicy, new() { Add(new T()); } /// <summary> /// Register an interception policy /// </summary> /// <param name="policy"></param> public void Interceptors(IInterceptorPolicy policy) { alter = graph => graph.Policies.Add(policy); } /// <summary> /// Register a strategy for automatically resolving "missing" families /// when an unknown PluginType is first encountered /// </summary> /// <typeparam name="T"></typeparam> public void OnMissingFamily<T>() where T : IFamilyPolicy, new() { alter = graph => graph.AddFamilyPolicy(new T()); } /// <summary> /// Register a strategy for automatically resolving "missing" families /// when an unknown PluginType is first encountered /// </summary> /// <param name="policy"></param> public void OnMissingFamily(IFamilyPolicy policy) { alter = graph => graph.AddFamilyPolicy(policy); } /// <summary> /// Register a custom constructor selection policy /// </summary> /// <typeparam name="T"></typeparam> public void ConstructorSelector<T>() where T : IConstructorSelector, new() { ConstructorSelector(new T()); } /// <summary> /// Register a custom constructor selection policy /// </summary> /// <param name="constructorSelector"></param> public void ConstructorSelector(IConstructorSelector constructorSelector) { alter = x => x.Policies.ConstructorSelector.Add(constructorSelector); } /// <summary> /// Creates automatic "policies" for which public setters are considered mandatory /// properties by StructureMap that will be "setter injected" as part of the /// construction process. /// </summary> /// <param name="action"></param> public void SetAllProperties(Action<SetterConvention> action) { var convention = new SetterConvention(); action(convention); alter = graph => convention.As<SetterConventionRule>().Configure(graph.Policies.SetterRules); } /// <summary> /// Directs StructureMap to always inject dependencies into any and all public Setter properties /// of the type TPluginType. /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> FillAllPropertiesOfType<TPluginType>() { Func<PropertyInfo, bool> predicate = prop => prop.PropertyType == typeof (TPluginType); alter = graph => graph.Policies.SetterRules.Add(predicate); return _parent.For<TPluginType>(); } } internal bool PoliciesChanged { get; set; } private static int mutation = 0; private TransientTracking? _transients; public static bool RegistryExists(IEnumerable<Registry> all, Registry registry) { if (all.Contains(registry)) return true; var type = registry.GetType(); if (type == typeof (Registry)) return false; if (type == typeof (ConfigurationExpression)) return false; var constructors = type.GetConstructors(); if (constructors.Count() == 1 && !constructors.Single().GetParameters().Any()) { if (all.Any(x => x.GetType() == type)) return true; if (all.Any(x => x.GetType().AssemblyQualifiedName == type.AssemblyQualifiedName)) return true; } return false; } } }
using System; using System.Collections; using System.Data.SqlClient; using System.IO; using Rainbow.Framework; using Rainbow.Framework.Content.Data; using Rainbow.Framework.Data; using Rainbow.Framework.DataTypes; using Rainbow.Framework.Helpers; using Rainbow.Framework.Web.UI.WebControls; using History=Rainbow.Framework.History; namespace Rainbow.Content.Web.Modules { /// <summary> /// Author: Joe Audette /// Created: 1/18/2004 /// Last Modified: 2/8/2004 /// </summary> [History("jminond", "march 2005", "Changes for moving Tab to Page")] [History("Hongwei Shen", "September 2005", "gouped the module specific settings")] public partial class Blog : PortalModuleControl { protected string Feedback; /// <summary> /// /// </summary> protected bool ShowDate { get { // Hide/show date return bool.Parse(Settings["ShowDate"].ToString()); } } /// <summary> /// The Page_Load event handler on this User Control is used to /// obtain a DataReader of Blog information from the Blogs /// table, and then databind the results to a templated DataList /// server control. It uses the Rainbow.BlogDB() /// data component to encapsulate all data functionality. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Page_Load(object sender, EventArgs e) { // Added EsperantusKeys for Localization // Mario Endara mario@softworks.com.uy june-1-2004 Feedback = General.GetString("BLOG_FEEDBACK"); if (!IsPostBack) { lnkRSS.HRef = HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Blog/RSS.aspx", PageID, "&mID=" + ModuleID); imgRSS.Src = HttpUrlBuilder.BuildUrl("~/DesktopModules/CommunityModules/Blog/xml.gif"); lblCopyright.Text = Settings["Copyright"].ToString(); // Obtain Blogs information from the Blogs table // and bind to the datalist control BlogDB blogData = new BlogDB(); myDataList.DataSource = blogData.GetBlogs(ModuleID); myDataList.DataBind(); dlArchive.DataSource = blogData.GetBlogMonthArchive(ModuleID); dlArchive.DataBind(); SqlDataReader dr = blogData.GetBlogStats(ModuleID); try { if (dr.Read()) { lblEntryCount.Text = General.GetString("BLOG_ENTRIES", "Entries", null) + " (" + (string) dr["EntryCount"].ToString() + ")"; lblCommentCount.Text = General.GetString("BLOG_COMMENTS", "Comments", null) + " (" + (string) dr["CommentCount"].ToString() + ")"; } } finally { // close the datareader dr.Close(); } } } public Blog() { // by Hongwei Shen(hongwei.shen@gmail.com) 9/12/2005 SettingItemGroup group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; int groupBase = (int) group; // end of modification // Set Editor Settings jviladiu@portalservices.net 2004/07/30 // by Hongwei Shen // HtmlEditorDataType.HtmlEditorSettings (this._baseSettings, SettingItemGroup.MODULE_SPECIAL_SETTINGS); HtmlEditorDataType.HtmlEditorSettings(_baseSettings, group); //Number of entries to display SettingItem EntriesToShow = new SettingItem(new IntegerDataType()); EntriesToShow.Value = "10"; // by Hongwei Shen // EntriesToShow.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // EntriesToShow.Order = 10; EntriesToShow.Group = group; EntriesToShow.Order = groupBase + 20; // end of modification _baseSettings.Add("Entries To Show", EntriesToShow); //Channel Description SettingItem Description = new SettingItem(new StringDataType()); Description.Value = "Description"; // by Hongwei Shen // Description.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // Description.Order = 20; Description.Group = group; Description.Order = groupBase + 25; // end of modification _baseSettings.Add("Description", Description); //Channel Copyright SettingItem Copyright = new SettingItem(new StringDataType()); Copyright.Value = "Copyright"; // by Hongwei Shen // Copyright.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // Copyright.Order = 30; Copyright.Group = group; Copyright.Order = groupBase + 30; // end of modification _baseSettings.Add("Copyright", Copyright); //Channel Language SettingItem Language = new SettingItem(new StringDataType()); Language.Value = "en-us"; // by Hongwei Shen // Language.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // Language.Order = 40; Language.Group = group; Language.Order = groupBase + 40; // end of modification _baseSettings.Add("Language", Language); //Author SettingItem Author = new SettingItem(new StringDataType()); Author.Value = "Author"; // by Hongwei Shen // Author.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // Author.Order = 50; Author.Group = group; Author.Order = groupBase + 50; // end of modification _baseSettings.Add("Author", Author); //Author Email SettingItem AuthorEmail = new SettingItem(new StringDataType()); AuthorEmail.Value = "author@portal.com"; // by Hongwei Shen // AuthorEmail.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // AuthorEmail.Order = 60; AuthorEmail.Group = group; AuthorEmail.Order = groupBase + 60; // end of modification _baseSettings.Add("Author Email", AuthorEmail); //Time to live in minutes for RSS //how long a channel can be cached before refreshing from the source SettingItem TimeToLive = new SettingItem(new IntegerDataType()); TimeToLive.Value = "120"; // by Hongwei Shen // TimeToLive.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // TimeToLive.Order = 70; TimeToLive.Group = group; TimeToLive.Order = groupBase + 70; // end of modification _baseSettings.Add("RSS Cache Time In Minutes", TimeToLive); } #region General Implementation /// <summary> /// Guid /// </summary> public override Guid GuidID { get { return new Guid("{55EF407B-C9D6-47e3-B627-EFA6A5EEF4B2}"); } } #region Search Implementation /// <summary> /// Searchable module /// </summary> public override bool Searchable { get { return true; } } /// <summary> /// Searchable module implementation /// </summary> /// <param name="portalID">The portal ID</param> /// <param name="userID">ID of the user is searching</param> /// <param name="searchString">The text to search</param> /// <param name="searchField">The fields where perfoming the search</param> /// <returns>The SELECT sql to perform a search on the current module</returns> public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField) { SearchDefinition s = new SearchDefinition("rb_Blogs", "Title", "Excerpt", "CreatedByUser", "CreatedDate", searchField); //Add extra search fields here, this way s.ArrSearchFields.Add("itm.Description"); return s.SearchSqlSelect(portalID, userID, searchString); } #endregion # region Install / Uninstall Implementation public override void Install(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql"); ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } public override void Uninstall(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql"); ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } # endregion #endregion #region Web Form Designer generated code /// <summary> /// Raises Init event /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { InitializeComponent(); this.EnableViewState = false; this.AddText = "ADD_ARTICLE"; this.AddUrl = "~/DesktopModules/CommunityModules/Blog/BlogEdit.aspx"; base.OnInit(e); } private void InitializeComponent() { this.Load += new EventHandler(this.Page_Load); if (!this.Page.IsCssFileRegistered("Mod_Blogs")) this.Page.RegisterCssFile("Mod_Blogs"); } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Streams; using Microsoft.Extensions.Options; using Orleans.Configuration; using Azure.Messaging.EventHubs; using Azure.Messaging.EventHubs.Producer; namespace Orleans.ServiceBus.Providers { /// <summary> /// Queue adapter factory which allows the PersistentStreamProvider to use EventHub as its backend persistent event queue. /// </summary> public class EventHubAdapterFactory : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache { private readonly ILoggerFactory loggerFactory; /// <summary> /// Data adapter /// </summary> protected readonly IEventHubDataAdapter dataAdapter; /// <summary> /// Orleans logging /// </summary> protected ILogger logger; /// <summary> /// Framework service provider /// </summary> protected IServiceProvider serviceProvider; /// <summary> /// Stream provider settings /// </summary> private EventHubOptions ehOptions; private EventHubStreamCachePressureOptions cacheOptions; private EventHubReceiverOptions receiverOptions; private StreamStatisticOptions statisticOptions; private StreamCacheEvictionOptions cacheEvictionOptions; private IEventHubQueueMapper streamQueueMapper; private string[] partitionIds; private ConcurrentDictionary<QueueId, EventHubAdapterReceiver> receivers; private EventHubProducerClient client; private ITelemetryProducer telemetryProducer; /// <summary> /// Name of the adapter. Primarily for logging purposes /// </summary> public string Name { get; } /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction { get; protected set; } = StreamProviderDirection.ReadWrite; /// <summary> /// Creates a message cache for an eventhub partition. /// </summary> protected Func<string, IStreamQueueCheckpointer<string>, ILoggerFactory, ITelemetryProducer, IEventHubQueueCache> CacheFactory { get; set; } /// <summary> /// Creates a partition checkpointer. /// </summary> private IStreamQueueCheckpointerFactory checkpointerFactory; /// <summary> /// Creates a failure handler for a partition. /// </summary> protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; } /// <summary> /// Create a queue mapper to map EventHub partitions to queues /// </summary> protected Func<string[], IEventHubQueueMapper> QueueMapperFactory { get; set; } /// <summary> /// Create a receiver monitor to report performance metrics. /// Factory function should return an IEventHubReceiverMonitor. /// </summary> protected Func<EventHubReceiverMonitorDimensions, ILoggerFactory, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory { get; set; } //for testing purpose, used in EventHubGeneratorStreamProvider /// <summary> /// Factory to create a IEventHubReceiver /// </summary> protected Func<EventHubPartitionSettings, string, ILogger, ITelemetryProducer, IEventHubReceiver> EventHubReceiverFactory; internal ConcurrentDictionary<QueueId, EventHubAdapterReceiver> EventHubReceivers { get { return this.receivers; } } internal IEventHubQueueMapper EventHubQueueMapper { get { return this.streamQueueMapper; } } public EventHubAdapterFactory( string name, EventHubOptions ehOptions, EventHubReceiverOptions receiverOptions, EventHubStreamCachePressureOptions cacheOptions, StreamCacheEvictionOptions cacheEvictionOptions, StreamStatisticOptions statisticOptions, IEventHubDataAdapter dataAdapter, IServiceProvider serviceProvider, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory) { this.Name = name; this.cacheEvictionOptions = cacheEvictionOptions ?? throw new ArgumentNullException(nameof(cacheEvictionOptions)); this.statisticOptions = statisticOptions ?? throw new ArgumentNullException(nameof(statisticOptions)); this.ehOptions = ehOptions ?? throw new ArgumentNullException(nameof(ehOptions)); this.cacheOptions = cacheOptions?? throw new ArgumentNullException(nameof(cacheOptions)); this.dataAdapter = dataAdapter ?? throw new ArgumentNullException(nameof(dataAdapter)); this.receiverOptions = receiverOptions?? throw new ArgumentNullException(nameof(receiverOptions)); this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); } public virtual void Init() { this.receivers = new ConcurrentDictionary<QueueId, EventHubAdapterReceiver>(); this.telemetryProducer = this.serviceProvider.GetService<ITelemetryProducer>(); InitEventHubClient(); if (this.CacheFactory == null) { this.CacheFactory = CreateCacheFactory(this.cacheOptions).CreateCache; } if (this.StreamFailureHandlerFactory == null) { //TODO: Add a queue specific default failure handler with reasonable error reporting. this.StreamFailureHandlerFactory = partition => Task.FromResult<IStreamFailureHandler>(new NoOpStreamDeliveryFailureHandler()); } if (this.QueueMapperFactory == null) { this.QueueMapperFactory = partitions => new EventHubQueueMapper(partitions, this.Name); } if (this.ReceiverMonitorFactory == null) { this.ReceiverMonitorFactory = (dimensions, logger, telemetryProducer) => new DefaultEventHubReceiverMonitor(dimensions, telemetryProducer); } this.logger = this.loggerFactory.CreateLogger($"{this.GetType().FullName}.{this.ehOptions.EventHubName}"); } //should only need checkpointer on silo side, so move its init logic when it is used private void InitCheckpointerFactory() { this.checkpointerFactory = this.serviceProvider.GetRequiredServiceByName<IStreamQueueCheckpointerFactory>(this.Name); } /// <summary> /// Create queue adapter. /// </summary> /// <returns></returns> public async Task<IQueueAdapter> CreateAdapter() { if (this.streamQueueMapper == null) { this.partitionIds = await GetPartitionIdsAsync(); this.streamQueueMapper = this.QueueMapperFactory(this.partitionIds); } return this; } /// <summary> /// Create queue message cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Create queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { //TODO: CreateAdapter must be called first. Figure out how to safely enforce this return this.streamQueueMapper; } /// <summary> /// Acquire delivery failure handler for a queue /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return this.StreamFailureHandlerFactory(this.streamQueueMapper.QueueToPartition(queueId)); } /// <summary> /// Writes a set of events to the queue as a single batch associated with the provided streamId. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamId"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public virtual Task QueueMessageBatchAsync<T>(StreamId streamId, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { EventData eventData = this.dataAdapter.ToQueueMessage(streamId, events, token, requestContext); string partitionKey = this.dataAdapter.GetPartitionKey(streamId); return this.client.SendAsync(new[] { eventData }, new SendEventOptions { PartitionKey = partitionKey }); } /// <summary> /// Creates a queue receiver for the specified queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { return GetOrCreateReceiver(queueId); } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { return GetOrCreateReceiver(queueId); } private EventHubAdapterReceiver GetOrCreateReceiver(QueueId queueId) { return this.receivers.GetOrAdd(queueId, q => MakeReceiver(queueId)); } protected virtual void InitEventHubClient() { var connectionOptions = ehOptions.ConnectionOptions; var connection = ehOptions.CreateConnection(connectionOptions); this.client = new EventHubProducerClient(connection, new EventHubProducerClientOptions { ConnectionOptions = connectionOptions }); } /// <summary> /// Create a IEventHubQueueCacheFactory. It will create a EventHubQueueCacheFactory by default. /// User can override this function to return their own implementation of IEventHubQueueCacheFactory, /// and other customization of IEventHubQueueCacheFactory if they may. /// </summary> /// <returns></returns> protected virtual IEventHubQueueCacheFactory CreateCacheFactory(EventHubStreamCachePressureOptions eventHubCacheOptions) { var eventHubPath = this.ehOptions.EventHubName; var sharedDimensions = new EventHubMonitorAggregationDimensions(eventHubPath); return new EventHubQueueCacheFactory(eventHubCacheOptions, cacheEvictionOptions, statisticOptions, this.dataAdapter, sharedDimensions); } private EventHubAdapterReceiver MakeReceiver(QueueId queueId) { var config = new EventHubPartitionSettings { Hub = ehOptions, Partition = this.streamQueueMapper.QueueToPartition(queueId), ReceiverOptions = this.receiverOptions }; var receiverMonitorDimensions = new EventHubReceiverMonitorDimensions { EventHubPartition = config.Partition, EventHubPath = config.Hub.EventHubName, }; if (this.checkpointerFactory == null) InitCheckpointerFactory(); return new EventHubAdapterReceiver(config, this.CacheFactory, this.checkpointerFactory.Create, this.loggerFactory, this.ReceiverMonitorFactory(receiverMonitorDimensions, this.loggerFactory, this.telemetryProducer), this.serviceProvider.GetRequiredService<IOptions<LoadSheddingOptions>>().Value, this.telemetryProducer, this.EventHubReceiverFactory); } /// <summary> /// Get partition Ids from eventhub /// </summary> /// <returns></returns> protected virtual async Task<string[]> GetPartitionIdsAsync() { return await client.GetPartitionIdsAsync(); } public static EventHubAdapterFactory Create(IServiceProvider services, string name) { var ehOptions = services.GetOptionsByName<EventHubOptions>(name); var receiverOptions = services.GetOptionsByName<EventHubReceiverOptions>(name); var cacheOptions = services.GetOptionsByName<EventHubStreamCachePressureOptions>(name); var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name); var evictionOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name); IEventHubDataAdapter dataAdapter = services.GetServiceByName<IEventHubDataAdapter>(name) ?? services.GetService<IEventHubDataAdapter>() ?? ActivatorUtilities.CreateInstance<EventHubDataAdapter>(services); var factory = ActivatorUtilities.CreateInstance<EventHubAdapterFactory>(services, name, ehOptions, receiverOptions, cacheOptions, evictionOptions, statisticOptions, dataAdapter); factory.Init(); return factory; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.WebSites.Models; namespace Microsoft.WindowsAzure.Management.WebSites.Models { /// <summary> /// The Get Configuration Web Site operation response. /// </summary> public partial class WebSiteGetConfigurationResponse : OperationResponse { private bool? _alwaysOn; /// <summary> /// Optional. Indicates if site's Always On feature is enabled. /// </summary> public bool? AlwaysOn { get { return this._alwaysOn; } set { this._alwaysOn = value; } } private IDictionary<string, string> _appSettings; /// <summary> /// Optional. A set of name/value pairs that contain application /// settings for a web site. /// </summary> public IDictionary<string, string> AppSettings { get { return this._appSettings; } set { this._appSettings = value; } } private string _autoSwapSlotName; /// <summary> /// Optional. Gets the slot name to swap with after successful /// deployment. /// </summary> public string AutoSwapSlotName { get { return this._autoSwapSlotName; } set { this._autoSwapSlotName = value; } } private IList<WebSiteGetConfigurationResponse.ConnectionStringInfo> _connectionStrings; /// <summary> /// Optional. The connection strings for database and other external /// resources. /// </summary> public IList<WebSiteGetConfigurationResponse.ConnectionStringInfo> ConnectionStrings { get { return this._connectionStrings; } set { this._connectionStrings = value; } } private IList<string> _defaultDocuments; /// <summary> /// Optional. One or more string elements that list, in order of /// preference, the name of the file that a web site returns when the /// web site's domain name is requested by itself. For example, if the /// default document for http://contoso.com is default.htm, the page /// http://www.contoso.com/default.htm is returned when the browser is /// pointed to http://www.contoso.com. /// </summary> public IList<string> DefaultDocuments { get { return this._defaultDocuments; } set { this._defaultDocuments = value; } } private bool? _detailedErrorLoggingEnabled; /// <summary> /// Optional. Indicates if detailed error logging is enabled. /// </summary> public bool? DetailedErrorLoggingEnabled { get { return this._detailedErrorLoggingEnabled; } set { this._detailedErrorLoggingEnabled = value; } } private string _documentRoot; /// <summary> /// Optional. The document root. /// </summary> public string DocumentRoot { get { return this._documentRoot; } set { this._documentRoot = value; } } private IList<WebSiteGetConfigurationResponse.HandlerMapping> _handlerMappings; /// <summary> /// Optional. Specifies custom executable programs for handling /// requests for specific file name extensions. /// </summary> public IList<WebSiteGetConfigurationResponse.HandlerMapping> HandlerMappings { get { return this._handlerMappings; } set { this._handlerMappings = value; } } private bool? _httpLoggingEnabled; /// <summary> /// Optional. Indicates if HTTP error logging is enabled. /// </summary> public bool? HttpLoggingEnabled { get { return this._httpLoggingEnabled; } set { this._httpLoggingEnabled = value; } } private string _javaContainer; /// <summary> /// Optional. The web site Java Container. Supported values are TOMCAT, /// JETTY /// </summary> public string JavaContainer { get { return this._javaContainer; } set { this._javaContainer = value; } } private string _javaContainerVersion; /// <summary> /// Optional. The web site Java Container Version. Supported values are /// 7.0.50 if Java Container is TOMCAT and 9.1.0.20131115 if Java /// Container is JETTY /// </summary> public string JavaContainerVersion { get { return this._javaContainerVersion; } set { this._javaContainerVersion = value; } } private string _javaVersion; /// <summary> /// Optional. The web site JDK version. Supported values are an empty /// string (an empty string disables Java), 1.7.0_51 /// </summary> public string JavaVersion { get { return this._javaVersion; } set { this._javaVersion = value; } } private int? _logsDirectorySizeLimit; /// <summary> /// Optional. The size limit of the logs directory. /// </summary> public int? LogsDirectorySizeLimit { get { return this._logsDirectorySizeLimit; } set { this._logsDirectorySizeLimit = value; } } private Microsoft.WindowsAzure.Management.WebSites.Models.ManagedPipelineMode? _managedPipelineMode; /// <summary> /// Optional. The managed pipeline mode. /// </summary> public Microsoft.WindowsAzure.Management.WebSites.Models.ManagedPipelineMode? ManagedPipelineMode { get { return this._managedPipelineMode; } set { this._managedPipelineMode = value; } } private IDictionary<string, string> _metadata; /// <summary> /// Optional. Name/value pairs for source control or other information. /// </summary> public IDictionary<string, string> Metadata { get { return this._metadata; } set { this._metadata = value; } } private string _netFrameworkVersion; /// <summary> /// Optional. The .NET Framework version. Supported values are v2.0 and /// v4.0. /// </summary> public string NetFrameworkVersion { get { return this._netFrameworkVersion; } set { this._netFrameworkVersion = value; } } private int? _numberOfWorkers; /// <summary> /// Optional. The number of web workers allotted to the web site. If /// the web site mode is Free, this value is 1. If the web site mode /// is Shared, this value can range from 1 through 6. If the web site /// mode is Standard, this value can range from 1 through 10. /// </summary> public int? NumberOfWorkers { get { return this._numberOfWorkers; } set { this._numberOfWorkers = value; } } private string _phpVersion; /// <summary> /// Optional. The web site PHP version. Supported values are an empty /// string (an empty string disables PHP), 5.3, and 5.4. /// </summary> public string PhpVersion { get { return this._phpVersion; } set { this._phpVersion = value; } } private string _publishingPassword; /// <summary> /// Optional. Hash value of the password used for publishing the web /// site. /// </summary> public string PublishingPassword { get { return this._publishingPassword; } set { this._publishingPassword = value; } } private string _publishingUserName; /// <summary> /// Optional. The user name used for publishing the web site. This is /// normally a dollar sign prepended to the web site name (for /// example, "$contoso"). /// </summary> public string PublishingUserName { get { return this._publishingUserName; } set { this._publishingUserName = value; } } private bool? _remoteDebuggingEnabled; /// <summary> /// Optional. Indicates if remote debugging is enabled. /// </summary> public bool? RemoteDebuggingEnabled { get { return this._remoteDebuggingEnabled; } set { this._remoteDebuggingEnabled = value; } } private Microsoft.WindowsAzure.Management.WebSites.Models.RemoteDebuggingVersion? _remoteDebuggingVersion; /// <summary> /// Optional. The remote debugging version. /// </summary> public Microsoft.WindowsAzure.Management.WebSites.Models.RemoteDebuggingVersion? RemoteDebuggingVersion { get { return this._remoteDebuggingVersion; } set { this._remoteDebuggingVersion = value; } } private bool? _requestTracingEnabled; /// <summary> /// Optional. Indicates if request tracing is enabled. /// </summary> public bool? RequestTracingEnabled { get { return this._requestTracingEnabled; } set { this._requestTracingEnabled = value; } } private System.DateTime? _requestTracingExpirationTime; /// <summary> /// Optional. Time remaining until request tracing expires. /// </summary> public System.DateTime? RequestTracingExpirationTime { get { return this._requestTracingExpirationTime; } set { this._requestTracingExpirationTime = value; } } private IList<RoutingRule> _routingRules; /// <summary> /// Optional. List of routing rules for the website. /// </summary> public IList<RoutingRule> RoutingRules { get { return this._routingRules; } set { this._routingRules = value; } } private string _scmType; /// <summary> /// Optional. The source control method that the web site is using (for /// example, Local Git). If deployment from source control has not /// been set up for the web site, this value is None. /// </summary> public string ScmType { get { return this._scmType; } set { this._scmType = value; } } private bool? _use32BitWorkerProcess; /// <summary> /// Optional. Indicates if 32-bit mode is enabled. /// </summary> public bool? Use32BitWorkerProcess { get { return this._use32BitWorkerProcess; } set { this._use32BitWorkerProcess = value; } } private bool? _webSocketsEnabled; /// <summary> /// Optional. Indicates if Web Sockets are enabled. /// </summary> public bool? WebSocketsEnabled { get { return this._webSocketsEnabled; } set { this._webSocketsEnabled = value; } } /// <summary> /// Initializes a new instance of the WebSiteGetConfigurationResponse /// class. /// </summary> public WebSiteGetConfigurationResponse() { this.AppSettings = new LazyDictionary<string, string>(); this.ConnectionStrings = new LazyList<WebSiteGetConfigurationResponse.ConnectionStringInfo>(); this.DefaultDocuments = new LazyList<string>(); this.HandlerMappings = new LazyList<WebSiteGetConfigurationResponse.HandlerMapping>(); this.Metadata = new LazyDictionary<string, string>(); this.RoutingRules = new LazyList<RoutingRule>(); } /// <summary> /// Connection string for database and other external resources. /// </summary> public partial class ConnectionStringInfo { private string _connectionString; /// <summary> /// Optional. The database connection string. /// </summary> public string ConnectionString { get { return this._connectionString; } set { this._connectionString = value; } } private string _name; /// <summary> /// Optional. The name of the connection string. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private ConnectionStringType _type; /// <summary> /// Optional. The type of the connection string (for example, /// "MySQL"). /// </summary> public ConnectionStringType Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the ConnectionStringInfo class. /// </summary> public ConnectionStringInfo() { } } /// <summary> /// Specifies a custom executable program for handling requests for /// specific file name extensions. /// </summary> public partial class HandlerMapping { private string _arguments; /// <summary> /// Optional. A string that contains optional arguments for the /// script processor specified by the /// SiteConfig.HandlerMappings.HandlerMapping.ScriptProcessor /// element. /// </summary> public string Arguments { get { return this._arguments; } set { this._arguments = value; } } private string _extension; /// <summary> /// Optional. A string that specifies the extension of the file /// type that the script processor will handle (for example, /// *.php). /// </summary> public string Extension { get { return this._extension; } set { this._extension = value; } } private string _scriptProcessor; /// <summary> /// Optional. The absolute path to the location of the executable /// file that will handle the files specified in the /// SiteConfig.HandlerMappings.HandlerMapping.Extension element. /// </summary> public string ScriptProcessor { get { return this._scriptProcessor; } set { this._scriptProcessor = value; } } /// <summary> /// Initializes a new instance of the HandlerMapping class. /// </summary> public HandlerMapping() { } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using GeoAPI.Geometries; namespace DotSpatial.NTSExtension { /// <summary> /// A float based 3 dimensional vector class, implementing all interesting features of vectors. /// </summary> public struct FloatVector3 { #region Fields /// <summary> /// X /// </summary> public float X; /// <summary> /// Y /// </summary> public float Y; /// <summary> /// Z /// </summary> public float Z; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="FloatVector3"/> struct. /// Copies the X, Y and Z values from the CoordinateF without doing a conversion. /// </summary> /// <param name="coord">X, Y Z</param> public FloatVector3(CoordinateF coord) { X = coord.X; Y = coord.Y; Z = coord.Z; } /// <summary> /// Initializes a new instance of the <see cref="FloatVector3"/> struct with the specified values. /// </summary> /// <param name="xValue">X</param> /// <param name="yValue">Y</param> /// <param name="zValue">Z</param> public FloatVector3(float xValue, float yValue, float zValue) { X = xValue; Y = yValue; Z = zValue; } /// <summary> /// Initializes a new instance of the <see cref="FloatVector3"/> structusing the X, Y and Z values from the coordinate. /// </summary> /// <param name="coord">The coordinate to obtain X, Y and Z values from</param> public FloatVector3(Coordinate coord) { X = Convert.ToSingle(coord.X); Y = Convert.ToSingle(coord.Y); Z = Convert.ToSingle(coord.Z); } #endregion #region Properties /// <summary> /// Gets the length of the vector. /// </summary> public float Length => Convert.ToSingle(Math.Sqrt((X * X) + (Y * Y) + (Z * Z))); /// <summary> /// Gets the square of length of this vector. /// </summary> public float LengthSq => Convert.ToSingle((X * X) + (Y * Y) + (Z * Z)); #endregion #region Operators /// <summary> /// Adds the vectors lhs and V using vector addition, which adds the corresponding components. /// </summary> /// <param name="lhs">One vector to be added</param> /// <param name="rhs">A second vector to be added</param> /// <returns>The sum of the vectors</returns> public static FloatVector3 operator +(FloatVector3 lhs, FloatVector3 rhs) { return new FloatVector3 { X = lhs.X + rhs.X, Y = lhs.Y + rhs.Y, Z = lhs.Z + rhs.Z }; } /// <summary> /// Divides the components of vector lhs by the respective components /// ov vector V and returns the resulting vector. /// </summary> /// <param name="lhs">FloatVector3 Dividend (Numbers to be divided)</param> /// <param name="rhs">FloatVector3 Divisor (Numbers to divide by)</param> /// <returns>A FloatVector3 quotient of lhs and V</returns> /// <remarks>To prevent divide by 0, if a 0 is in V, it will return 0 in the result</remarks> public static FloatVector3 operator /(FloatVector3 lhs, FloatVector3 rhs) { FloatVector3 result = default(FloatVector3); if (rhs.X > 0) result.X = lhs.X / rhs.X; if (rhs.Y > 0) result.Y = lhs.Y / rhs.Y; if (rhs.Z > 0) result.Z = lhs.Z / rhs.Z; return result; } /// <summary> /// Multiplies each component of vector lhs by the Scalar value /// </summary> /// <param name="lhs">A vector representing the vector to be multiplied</param> /// <param name="scalar">Double, the scalar value to mulitiply the vector components by</param> /// <returns>A FloatVector3 representing the vector product of vector lhs and the Scalar</returns> /// <exception cref="ArgumentException">Thrown if scalar is 0.</exception> public static FloatVector3 operator /(FloatVector3 lhs, float scalar) { if (scalar == 0) throw new ArgumentException("Divisor cannot be 0."); return new FloatVector3 { X = lhs.X / scalar, Y = lhs.Y / scalar, Z = lhs.Z / scalar }; } /// <summary> /// Tests two float vectors for equality. /// </summary> /// <param name="lhs">The left hand side FloatVector3 to test.</param> /// <param name="rhs">The right hand side FloatVector3 to test.</param> /// <returns>Returns true if X, Y and Z are all equal.</returns> public static bool operator ==(FloatVector3 lhs, FloatVector3 rhs) { return lhs.X == rhs.X && lhs.Y == rhs.Y && lhs.Z == rhs.Z; } /// <summary> /// Returns the Cross Product of two vectors lhs and rhs. /// </summary> /// <param name="lhs">Vector, the first input vector</param> /// <param name="rhs">Vector, the second input vector</param> /// <returns>A FloatVector3 containing the cross product of lhs and V</returns> public static FloatVector3 operator ^(FloatVector3 lhs, FloatVector3 rhs) { return new FloatVector3 { X = (lhs.Y * rhs.Z) - (lhs.Z * rhs.Y), Y = (lhs.Z * rhs.X) - (lhs.X * rhs.Z), Z = (lhs.X * rhs.Y) - (lhs.Y * rhs.X) }; } /// <summary> /// Tests two float vectors for inequality. /// </summary> /// <param name="lhs">The left hand side FloatVector3 to test.</param> /// <param name="rhs">The right hand side FloatVector3 to test.</param> /// <returns>Returns true if any of X, Y and Z are unequal.</returns> public static bool operator !=(FloatVector3 lhs, FloatVector3 rhs) { return lhs.X != rhs.X || lhs.Y != rhs.Y || lhs.Z != rhs.Z; } /// <summary> /// Returns the Inner Product also known as the dot product of two vectors, lhs and V /// </summary> /// <param name="lhs">The input vector</param> /// <param name="rhs">The vector to take the inner product against lhs</param> /// <returns>a Double containing the dot product of lhs and V</returns> public static float operator *(FloatVector3 lhs, FloatVector3 rhs) { return (lhs.X * rhs.X) + (lhs.Y * rhs.Y) + (lhs.Z * rhs.Z); } /// <summary> /// Multiplies the vectors lhs and V using vector multiplication, /// which adds the corresponding components /// </summary> /// <param name="scalar">A scalar to multpy to the vector</param> /// <param name="rhs">A vector to be multiplied</param> /// <returns>The scalar product for the vectors</returns> public static FloatVector3 operator *(float scalar, FloatVector3 rhs) { return new FloatVector3 { X = scalar * rhs.X, Y = scalar * rhs.Y, Z = scalar * rhs.Z }; } /// <summary> /// Multiplies each component of vector lhs by the Scalar value /// </summary> /// <param name="lhs">A vector representing the vector to be multiplied</param> /// <param name="scalar">Double, the scalar value to mulitiply the vector components by</param> /// <returns>A FloatVector3 representing the vector product of vector lhs and the Scalar</returns> public static FloatVector3 operator *(FloatVector3 lhs, float scalar) { return new FloatVector3 { X = lhs.X * scalar, Y = lhs.Y * scalar, Z = lhs.Z * scalar }; } /// <summary> /// Subtracts FloatVector3 V from FloatVector3 lhs /// </summary> /// <param name="lhs">A FloatVector3 to subtract from</param> /// <param name="rhs">A FloatVector3 to subtract</param> /// <returns>The FloatVector3 difference lhs - V</returns> public static FloatVector3 operator -(FloatVector3 lhs, FloatVector3 rhs) { FloatVector3 result; result.X = lhs.X - rhs.X; result.Y = lhs.Y - rhs.Y; result.Z = lhs.Z - rhs.Z; return result; } #endregion #region Methods /// <summary> /// Adds all the scalar members of the the two vectors. /// </summary> /// <param name="lhs">Left hand side</param> /// <param name="rhs">Right hand side</param> /// <returns>The resulting vector.</returns> public static FloatVector3 Add(FloatVector3 lhs, FloatVector3 rhs) { return new FloatVector3(lhs.X + rhs.X, lhs.Y + rhs.Y, lhs.Z + rhs.Z); } /// <summary> /// Returns the Cross Product of two vectors lhs and V. /// </summary> /// <param name="lhs">Vector, the first input vector</param> /// <param name="rhs">Vector, the second input vector</param> /// <returns>A FloatVector3 containing the cross product of lhs and V</returns> public static FloatVector3 CrossProduct(FloatVector3 lhs, FloatVector3 rhs) { FloatVector3 result = new FloatVector3 { X = (lhs.Y * rhs.Z) - (lhs.Z * rhs.Y), Y = (lhs.Z * rhs.X) - (lhs.X * rhs.Z), Z = (lhs.X * rhs.Y) - (lhs.Y * rhs.X) }; return result; } /// <summary> /// Multiplies all the scalar members of the the two vectors. /// </summary> /// <param name="lhs">Left hand side</param> /// <param name="rhs">Right hand side</param> /// <returns>The resulting value.</returns> public static float Dot(FloatVector3 lhs, FloatVector3 rhs) { return (lhs.X * rhs.X) + (lhs.Y * rhs.Y) + (lhs.Z * rhs.Z); } /// <summary> /// Multiplies the source vector by a scalar. /// </summary> /// <param name="source">The vector.</param> /// <param name="scalar">The scalar.</param> /// <returns>The resulting vector.</returns> public static FloatVector3 Multiply(FloatVector3 source, float scalar) { return new FloatVector3(source.X * scalar, source.Y * scalar, source.Z * scalar); } /// <summary> /// Subtracts all the scalar members of the the two vectors. /// </summary> /// <param name="lhs">Left hand side</param> /// <param name="rhs">Right hand side</param> /// <returns>The resulting vector.</returns> public static FloatVector3 Subtract(FloatVector3 lhs, FloatVector3 rhs) { return new FloatVector3(lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z); } /// <summary> /// Adds the specified v /// </summary> /// <param name="vector">A FloatVector3 to add to this vector</param> public void Add(FloatVector3 vector) { X += vector.X; Y += vector.Y; Z += vector.Z; } /// <summary> /// Tests to see if the specified object has the same X, Y and Z values. /// </summary> /// <param name="obj">object to test against.</param> /// <returns>True, if the X, Y, Z values of the two vectors are equal.</returns> public override bool Equals(object obj) { if (!(obj is FloatVector3)) return false; FloatVector3 fv = (FloatVector3)obj; return fv.X == X && fv.Y == Y && fv.Z == Z; } /// <summary> /// Not sure what I should be doing here since Int can't really contain this much info very well /// </summary> /// <returns>The generated hash code.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Multiplies this vector by a scalar value. /// </summary> /// <param name="scalar">The scalar to multiply by</param> public void Multiply(float scalar) { X *= scalar; Y *= scalar; Z *= scalar; } /// <summary> /// Normalizes the vectors. /// </summary> public void Normalize() { float length = Length; X = X / length; Y = Y / length; Z = Z / length; } /// <summary> /// Subtracts the specified value. /// </summary> /// <param name="vector">A FloatVector3</param> public void Subtract(FloatVector3 vector) { X -= vector.X; Y -= vector.Y; Z -= vector.Z; } #endregion } }
/* The MIT License * * Copyright (c) 2010 Intel Corporation. * All rights reserved. * * Based on the convexdecomposition library from * <http://codesuppository.googlecode.com> by John W. Ratcliff and Stan Melax. * * 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 OpenSim.Region.Physics.ConvexDecompositionDotNet { public class Quaternion : float4 { public Quaternion() { x = y = z = 0.0f; w = 1.0f; } public Quaternion(float3 v, float t) { v = float3.normalize(v); w = (float)Math.Cos(t / 2.0f); v = v * (float)Math.Sin(t / 2.0f); x = v.x; y = v.y; z = v.z; } public Quaternion(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } public float angle() { return (float)Math.Acos(w) * 2.0f; } public float3 axis() { float3 a = new float3(x, y, z); if (Math.Abs(angle()) < 0.0000001f) return new float3(1f, 0f, 0f); return a * (1 / (float)Math.Sin(angle() / 2.0f)); } public float3 xdir() { return new float3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); } public float3 ydir() { return new float3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); } public float3 zdir() { return new float3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); } public float3x3 getmatrix() { return new float3x3(xdir(), ydir(), zdir()); } public static implicit operator float3x3(Quaternion q) { return q.getmatrix(); } public static Quaternion operator *(Quaternion a, Quaternion b) { Quaternion c = new Quaternion(); c.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z; c.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y; c.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x; c.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w; return c; } public static float3 operator *(Quaternion q, float3 v) { // The following is equivalent to: //return (q.getmatrix() * v); float qx2 = q.x * q.x; float qy2 = q.y * q.y; float qz2 = q.z * q.z; float qxqy = q.x * q.y; float qxqz = q.x * q.z; float qxqw = q.x * q.w; float qyqz = q.y * q.z; float qyqw = q.y * q.w; float qzqw = q.z * q.w; return new float3((1 - 2 * (qy2 + qz2)) * v.x + (2 * (qxqy - qzqw)) * v.y + (2 * (qxqz + qyqw)) * v.z, (2 * (qxqy + qzqw)) * v.x + (1 - 2 * (qx2 + qz2)) * v.y + (2 * (qyqz - qxqw)) * v.z, (2 * (qxqz - qyqw)) * v.x + (2 * (qyqz + qxqw)) * v.y + (1 - 2 * (qx2 + qy2)) * v.z); } public static Quaternion operator +(Quaternion a, Quaternion b) { return new Quaternion(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } public static Quaternion operator *(Quaternion a, float b) { return new Quaternion(a.x *b, a.y *b, a.z *b, a.w *b); } public static Quaternion normalize(Quaternion a) { float m = (float)Math.Sqrt(a.w * a.w + a.x * a.x + a.y * a.y + a.z * a.z); if (m < 0.000000001f) { a.w = 1; a.x = a.y = a.z = 0; return a; } return a * (1f / m); } public static float dot(Quaternion a, Quaternion b) { return (a.w * b.w + a.x * b.x + a.y * b.y + a.z * b.z); } public static Quaternion slerp(Quaternion a, Quaternion b, float interp) { if (dot(a, b) < 0.0) { a.w = -a.w; a.x = -a.x; a.y = -a.y; a.z = -a.z; } float d = dot(a, b); if (d >= 1.0) { return a; } float theta = (float)Math.Acos(d); if (theta == 0.0f) { return (a); } return a * ((float)Math.Sin(theta - interp * theta) / (float)Math.Sin(theta)) + b * ((float)Math.Sin(interp * theta) / (float)Math.Sin(theta)); } public static Quaternion Interpolate(Quaternion q0, Quaternion q1, float alpha) { return slerp(q0, q1, alpha); } public static Quaternion Inverse(Quaternion q) { return new Quaternion(-q.x, -q.y, -q.z, q.w); } public static Quaternion YawPitchRoll(float yaw, float pitch, float roll) { roll *= (3.14159264f / 180.0f); yaw *= (3.14159264f / 180.0f); pitch *= (3.14159264f / 180.0f); return new Quaternion(new float3(0.0f, 0.0f, 1.0f), yaw) * new Quaternion(new float3(1.0f, 0.0f, 0.0f), pitch) * new Quaternion(new float3(0.0f, 1.0f, 0.0f), roll); } public static float Yaw(Quaternion q) { float3 v = q.ydir(); return (v.y == 0.0 && v.x == 0.0) ? 0.0f : (float)Math.Atan2(-v.x, v.y) * (180.0f / 3.14159264f); } public static float Pitch(Quaternion q) { float3 v = q.ydir(); return (float)Math.Atan2(v.z, Math.Sqrt(v.x * v.x + v.y * v.y)) * (180.0f / 3.14159264f); } public static float Roll(Quaternion q) { q = new Quaternion(new float3(0.0f, 0.0f, 1.0f), -Yaw(q) * (3.14159264f / 180.0f)) * q; q = new Quaternion(new float3(1.0f, 0.0f, 0.0f), -Pitch(q) * (3.14159264f / 180.0f)) * q; return (float)Math.Atan2(-q.xdir().z, q.xdir().x) * (180.0f / 3.14159264f); } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using StructureMap.Configuration.DSL.Expressions; using StructureMap.Graph; using StructureMap.Interceptors; using StructureMap.Pipeline; namespace StructureMap.Configuration.DSL { /// <summary> /// A Registry class provides methods and grammars for configuring a Container or ObjectFactory. /// Using a Registry subclass is the recommended way of configuring a StructureMap Container. /// </summary> /// <example> /// public class MyRegistry : Registry /// { /// public MyRegistry() /// { /// ForRequestedType(typeof(IService)).TheDefaultIsConcreteType(typeof(Service)); /// } /// } /// </example> public class Registry : IRegistry, IPluginGraphConfiguration { private readonly List<Action<PluginGraph>> _actions = new List<Action<PluginGraph>>(); private readonly List<Action> _basicActions = new List<Action>(); private readonly List<Action<PluginGraphBuilder>> _builders = new List<Action<PluginGraphBuilder>>(); internal Action<PluginGraph> alter { set { _actions.Add(value); } } private Action<PluginGraphBuilder> register { set { _builders.Add(value); } } /// <summary> /// Adds the concreteType as an Instance of the pluginType. Mostly useful /// for conventions /// </summary> /// <param name="pluginType"></param> /// <param name="concreteType"></param> public void AddType(Type pluginType, Type concreteType) { alter = g => g.AddType(pluginType, concreteType); } /// <summary> /// Adds the concreteType as an Instance of the pluginType with a name. Mostly /// useful for conventions /// </summary> /// <param name="pluginType"></param> /// <param name="concreteType"></param> /// <param name="name"></param> public virtual void AddType(Type pluginType, Type concreteType, string name) { alter = g => g.AddType(pluginType, concreteType, name); } /// <summary> /// Imports the configuration from another registry into this registry. /// </summary> /// <typeparam name="T"></typeparam> public void IncludeRegistry<T>() where T : Registry, new() { IncludeRegistry(new T()); } /// <summary> /// Imports the configuration from another registry into this registry. /// </summary> /// <param name="registry"></param> public void IncludeRegistry(Registry registry) { alter = graph => { registry.As<IPluginGraphConfiguration>().Configure(graph); }; } /// <summary> /// This method is a shortcut for specifying the default constructor and /// setter arguments for a ConcreteType. ForConcreteType is shorthand for: /// For[T]().Use[T].************** /// when the PluginType and ConcreteType are the same Type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public BuildWithExpression<T> ForConcreteType<T>() { SmartInstance<T> instance = For<T>().Use<T>(); return new BuildWithExpression<T>(instance); } /// <summary> /// Convenience method. Equivalent of ForRequestedType[PluginType]().Singletons() /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> ForSingletonOf<TPluginType>() { return For<TPluginType>().Singleton(); } /// <summary> /// Shorthand way of saying For(pluginType).Singleton() /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public GenericFamilyExpression ForSingletonOf(Type pluginType) { return For(pluginType).Singleton(); } /// <summary> /// An alternative way to use CreateProfile that uses ProfileExpression /// as a Nested Closure. This usage will result in cleaner code for /// multiple declarations /// </summary> /// <param name="profileName"></param> /// <param name="action"></param> public void Profile(string profileName, Action<Registry> action) { var registry = new Registry(); action(registry); alter = x => registry.As<IPluginGraphConfiguration>().Configure(x.Profile(profileName)); } /// <summary> /// Registers a new TypeInterceptor object with the Container /// </summary> /// <param name="interceptor"></param> public void RegisterInterceptor(TypeInterceptor interceptor) { alter = x => x.InterceptorLibrary.AddInterceptor(interceptor); } /// <summary> /// Allows you to define a TypeInterceptor inline with Lambdas or anonymous delegates /// </summary> /// <param name="match"></param> /// <returns></returns> /// <example> /// IfTypeMatches( ... ).InterceptWith( o => new ObjectWrapper(o) ); /// </example> public MatchedTypeInterceptor IfTypeMatches(Predicate<Type> match) { var interceptor = new MatchedTypeInterceptor(match); alter = graph => graph.InterceptorLibrary.AddInterceptor(interceptor); return interceptor; } /// <summary> /// Designates a policy for scanning assemblies to auto /// register types /// </summary> /// <returns></returns> public void Scan(Action<IAssemblyScanner> action) { var scanner = new AssemblyScanner(); action(scanner); register = x => x.AddScanner(scanner); } /// <summary> /// Directs StructureMap to always inject dependencies into any and all public Setter properties /// of the type TPluginType. /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> FillAllPropertiesOfType<TPluginType>() { Func<PropertyInfo, bool> predicate = prop => prop.PropertyType == typeof (TPluginType); alter = graph => graph.SetterRules.Add(predicate); return For<TPluginType>(); } /// <summary> /// Creates automatic "policies" for which public setters are considered mandatory /// properties by StructureMap that will be "setter injected" as part of the /// construction process. /// </summary> /// <param name="action"></param> public void SetAllProperties(Action<SetterConvention> action) { var convention = new SetterConvention(); action(convention); alter = graph => convention.As<SetterConventionRule>().Configure(graph.SetterRules); } /// <summary> /// All requests For the "TO" types will be filled by fetching the "FROM" /// type and casting it to "TO" /// GetInstance(typeof(TO)) basically becomes (TO)GetInstance(typeof(FROM)) /// </summary> /// <typeparam name="TFrom"></typeparam> /// <typeparam name="TTo"></typeparam> public void Forward<TFrom, TTo>() where TFrom : class where TTo : class { For<TTo>().AddInstances(x => x.ConstructedBy(c => c.GetInstance<TFrom>() as TTo)); } /// <summary> /// Expression Builder used to define policies for a PluginType including /// Scoping, the Default Instance, and interception. BuildInstancesOf() /// and ForRequestedType() are synonyms /// </summary> /// <typeparam name="TPluginType"></typeparam> /// <param name="lifecycle">Optionally specify the instance scoping for this PluginType</param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> For<TPluginType>(ILifecycle lifecycle = null) { if (lifecycle == null) { lifecycle = Lifecycles.Transient; } return new CreatePluginFamilyExpression<TPluginType>(this, lifecycle); } /// <summary> /// Expression Builder used to define policies for a PluginType including /// Scoping, the Default Instance, and interception. This method is specifically /// meant for registering open generic types /// </summary> /// <param name="lifecycle">Optionally specify the instance scoping for this PluginType</param> /// <returns></returns> public GenericFamilyExpression For(Type pluginType, ILifecycle lifecycle = null) { if (lifecycle == null) { lifecycle = Lifecycles.Transient; } return new GenericFamilyExpression(pluginType, lifecycle, this); } /// <summary> /// Shortcut to make StructureMap return the default object of U casted to T /// whenever T is requested. I.e.: /// For<T>().TheDefault.Is.ConstructedBy(c => c.GetInstance<U>() as T); /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// <returns></returns> public LambdaInstance<T> Redirect<T, U>() where T : class where U : class { return For<T>().Use(c => { var raw = c.GetInstance<U>(); var t = raw as T; if (t == null) throw new ApplicationException(raw.GetType().AssemblyQualifiedName + " could not be cast to " + typeof (T).AssemblyQualifiedName); return t; }); } /// <summary> /// Advanced Usage Only! Skips the Registry and goes right to the inner /// Semantic Model of StructureMap. Use with care /// </summary> /// <param name="configure"></param> public void Configure(Action<PluginGraph> configure) { alter = configure; } protected void registerAction(Action action) { _basicActions.Add(action); } void IPluginGraphConfiguration.Configure(PluginGraph graph) { if (graph.Registries.Contains(this)) return; graph.Log.StartSource("Registry: " + GetType().AssemblyQualifiedName); _basicActions.ForEach(action => action()); _actions.ForEach(action => action(graph)); graph.Registries.Add(this); } void IPluginGraphConfiguration.Register(PluginGraphBuilder builder) { _builders.Each(x => x(builder)); } internal static bool IsPublicRegistry(Type type) { if (type.Assembly == typeof (Registry).Assembly) { return false; } if (!typeof (Registry).IsAssignableFrom(type)) { return false; } if (type.IsInterface || type.IsAbstract || type.IsGenericType) { return false; } return (type.GetConstructor(new Type[0]) != null); } public bool Equals(Registry other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if(other.GetType() == typeof(Registry) && GetType() == typeof(Registry)) return false; if (Equals(other.GetType(), GetType())) { return !GetType().IsNotPublic; } return false; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (!typeof (Registry).IsAssignableFrom(obj.GetType())) return false; return Equals((Registry) obj); } public override int GetHashCode() { return GetType().GetHashCode(); } /// <summary> /// Define the constructor and setter arguments for the default T /// </summary> /// <typeparam name="T"></typeparam> public class BuildWithExpression<T> { private readonly SmartInstance<T> _instance; public BuildWithExpression(SmartInstance<T> instance) { _instance = instance; } public SmartInstance<T> Configure { get { return _instance; } } } /// <summary> /// Gives a <see cref="IPluginGraphConfiguration"/> the possibility to interact with the current <see cref="PluginGraphBuilder"/> /// via <see cref="IPluginGraphConfiguration.Register"/>. /// </summary> public void RegisterPluginGraphConfiguration<T>() where T : IPluginGraphConfiguration, new() { RegisterPluginGraphConfiguration(new T()); } /// <summary> /// See <see cref="RegisterPluginGraphConfiguration{T}"/> /// </summary> public void RegisterPluginGraphConfiguration(IPluginGraphConfiguration pluginGraphConfig) { register = pluginGraphConfig.Register; } /// <summary> /// Gives a <see cref="IPluginGraphConfiguration"/> the possibility to interact with the resulting <see cref="PluginGraph"/>, /// i.e. as opposed to <see cref="RegisterPluginGraphConfiguration"/>, the PluginGraph is built, and the provided /// PluginGraph config obtains access to saig graph. /// </summary> /// <typeparam name="T"></typeparam> public void ConfigurePluginGraph<T>() where T : IPluginGraphConfiguration, new() { ConfigurePluginGraph(new T()); } /// <summary> /// <see cref="ConfigurePluginGraph{T}"/> /// </summary> public void ConfigurePluginGraph(IPluginGraphConfiguration pluginGraphConfig) { alter = pluginGraphConfig.Configure; } } }
// 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.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal abstract class AbstractCommandHandlerTestState : IDisposable { public readonly TestWorkspace Workspace; public readonly IEditorOperations EditorOperations; public readonly ITextUndoHistoryRegistry UndoHistoryRegistry; private readonly ITextView _textView; private readonly ITextBuffer _subjectBuffer; public AbstractCommandHandlerTestState( XElement workspaceElement, ComposableCatalog extraParts = null, bool useMinimumCatalog = false, string workspaceKind = null) : this(workspaceElement, GetExportProvider(useMinimumCatalog, extraParts), workspaceKind) { } /// <summary> /// This can use input files with an (optionally) annotated span 'Selection' and a cursor position ($$), /// and use it to create a selected span in the TextView. /// /// For instance, the following will create a TextView that has a multiline selection with the cursor at the end. /// /// Sub Foo /// {|Selection:SomeMethodCall() /// AnotherMethodCall()$$|} /// End Sub /// </summary> public AbstractCommandHandlerTestState( XElement workspaceElement, ExportProvider exportProvider, string workspaceKind) { this.Workspace = TestWorkspaceFactory.CreateWorkspace( workspaceElement, exportProvider: exportProvider, workspaceKind: workspaceKind); var cursorDocument = this.Workspace.Documents.First(d => d.CursorPosition.HasValue); _textView = cursorDocument.GetTextView(); _subjectBuffer = cursorDocument.GetTextBuffer(); IList<Text.TextSpan> selectionSpanList; if (cursorDocument.AnnotatedSpans.TryGetValue("Selection", out selectionSpanList)) { var span = selectionSpanList.First(); var cursorPosition = cursorDocument.CursorPosition.Value; Assert.True(cursorPosition == span.Start || cursorPosition == span.Start + span.Length, "cursorPosition wasn't at an endpoint of the 'Selection' annotated span"); _textView.Selection.Select( new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(span.Start, span.Length)), isReversed: cursorPosition == span.Start); if (selectionSpanList.Count > 1) { _textView.Selection.Mode = TextSelectionMode.Box; foreach (var additionalSpan in selectionSpanList.Skip(1)) { _textView.Selection.Select( new SnapshotSpan(_subjectBuffer.CurrentSnapshot, new Span(additionalSpan.Start, additionalSpan.Length)), isReversed: false); } } } else { _textView.Caret.MoveTo( new SnapshotPoint( _textView.TextBuffer.CurrentSnapshot, cursorDocument.CursorPosition.Value)); } this.EditorOperations = GetService<IEditorOperationsFactoryService>().GetEditorOperations(_textView); this.UndoHistoryRegistry = GetService<ITextUndoHistoryRegistry>(); } public void Dispose() { Workspace.Dispose(); } public T GetService<T>() { return Workspace.GetService<T>(); } private static ExportProvider GetExportProvider(bool useMinimumCatalog, ComposableCatalog extraParts) { var baseCatalog = useMinimumCatalog ? TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic : TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic; if (extraParts == null) { return MinimalTestExportProvider.CreateExportProvider(baseCatalog); } return MinimalTestExportProvider.CreateExportProvider(baseCatalog.WithParts(extraParts)); } public virtual ITextView TextView { get { return _textView; } } public virtual ITextBuffer SubjectBuffer { get { return _subjectBuffer; } } #region MEF public Lazy<TExport, TMetadata> GetExport<TExport, TMetadata>() { return (Lazy<TExport, TMetadata>)(object)Workspace.ExportProvider.GetExport<TExport, TMetadata>(); } public IEnumerable<Lazy<TExport, TMetadata>> GetExports<TExport, TMetadata>() { return Workspace.ExportProvider.GetExports<TExport, TMetadata>(); } public T GetExportedValue<T>() { return Workspace.ExportProvider.GetExportedValue<T>(); } public IEnumerable<T> GetExportedValues<T>() { return Workspace.ExportProvider.GetExportedValues<T>(); } protected static IEnumerable<Lazy<TProvider, OrderableLanguageMetadata>> CreateLazyProviders<TProvider>( TProvider[] providers, string languageName) { if (providers == null) { return Array.Empty<Lazy<TProvider, OrderableLanguageMetadata>>(); } return providers.Select(p => new Lazy<TProvider, OrderableLanguageMetadata>( () => p, new OrderableLanguageMetadata( new Dictionary<string, object> { {"Language", languageName }, {"Name", string.Empty }}), true)); } protected static IEnumerable<Lazy<TProvider, OrderableLanguageAndRoleMetadata>> CreateLazyProviders<TProvider>( TProvider[] providers, string languageName, string[] roles) { if (providers == null) { return Array.Empty<Lazy<TProvider, OrderableLanguageAndRoleMetadata>>(); } return providers.Select(p => new Lazy<TProvider, OrderableLanguageAndRoleMetadata>( () => p, new OrderableLanguageAndRoleMetadata( new Dictionary<string, object> { {"Language", languageName }, {"Name", string.Empty }, {"Roles", roles }}), true)); } #endregion #region editor related operation public void SendBackspace() { EditorOperations.Backspace(); } public void SendDelete() { EditorOperations.Delete(); } public void SendRightKey(bool extendSelection = false) { EditorOperations.MoveToNextCharacter(extendSelection); } public void SendLeftKey(bool extendSelection = false) { EditorOperations.MoveToPreviousCharacter(extendSelection); } public void SendMoveToPreviousCharacter(bool extendSelection = false) { EditorOperations.MoveToPreviousCharacter(extendSelection); } public void SendDeleteWordToLeft() { EditorOperations.DeleteWordToLeft(); } public void SendUndo(int count = 1) { var history = UndoHistoryRegistry.GetHistory(SubjectBuffer); history.Undo(count); } #endregion #region test/information/verification public ITextSnapshotLine GetLineFromCurrentCaretPosition() { var caretPosition = GetCaretPoint(); return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition.BufferPosition); } public string GetLineTextFromCaretPosition() { var caretPosition = Workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value; return SubjectBuffer.CurrentSnapshot.GetLineFromPosition(caretPosition).GetText(); } public string GetDocumentText() { return SubjectBuffer.CurrentSnapshot.GetText(); } public CaretPosition GetCaretPoint() { return TextView.Caret.Position; } /// <summary> /// Used in synchronous methods to ensure all outstanding <see cref="IAsyncToken"/> work has been /// completed. /// </summary> public void AssertNoAsynchronousOperationsRunning() { var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>(); Assert.False(waiters.Any(x => x.HasPendingWork), "IAsyncTokens unexpectedly alive. Call WaitForAsynchronousOperationsAsync before this method"); } public async Task WaitForAsynchronousOperationsAsync() { var waiters = Workspace.ExportProvider.GetExportedValues<IAsynchronousOperationWaiter>(); await waiters.WaitAllAsync().ConfigureAwait(true); } public void AssertMatchesTextStartingAtLine(int line, string text) { var lines = text.Split('\r'); foreach (var expectedLine in lines) { Assert.Equal(expectedLine.Trim(), SubjectBuffer.CurrentSnapshot.GetLineFromLineNumber(line).GetText().Trim()); line += 1; } } #endregion #region command handler public void SendBackspace(Action<BackspaceKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new BackspaceKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendDelete(Action<DeleteKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new DeleteKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendWordDeleteToStart(Action<WordDeleteToStartCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new WordDeleteToStartCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendEscape(Action<EscapeKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new EscapeKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendUpKey(Action<UpKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new UpKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendDownKey(Action<DownKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new DownKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendTab(Action<TabKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new TabKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendBackTab(Action<BackTabKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new BackTabKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendReturn(Action<ReturnKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new ReturnKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendPageUp(Action<PageUpKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new PageUpKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendPageDown(Action<PageDownKeyCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new PageDownKeyCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendCut(Action<CutCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new CutCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendPaste(Action<PasteCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new PasteCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendInvokeCompletionList(Action<InvokeCompletionListCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new InvokeCompletionListCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendCommitUniqueCompletionListItem(Action<CommitUniqueCompletionListItemCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new CommitUniqueCompletionListItemCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendInsertSnippetCommand(Action<InsertSnippetCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new InsertSnippetCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendSurroundWithCommand(Action<SurroundWithCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new SurroundWithCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendInvokeSignatureHelp(Action<InvokeSignatureHelpCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new InvokeSignatureHelpCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendTypeChar(char typeChar, Action<TypeCharCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new TypeCharCommandArgs(TextView, SubjectBuffer, typeChar), nextHandler); } public void SendTypeChars(string typeChars, Action<TypeCharCommandArgs, Action> commandHandler) { foreach (var ch in typeChars) { var localCh = ch; SendTypeChar(ch, commandHandler, () => EditorOperations.InsertText(localCh.ToString())); } } public void SendSave(Action<SaveCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new SaveCommandArgs(TextView, SubjectBuffer), nextHandler); } public void SendSelectAll(Action<SelectAllCommandArgs, Action> commandHandler, Action nextHandler) { commandHandler(new SelectAllCommandArgs(TextView, SubjectBuffer), nextHandler); } #endregion } }
using UnityEditor; using UnityEngine; using UnityEngine.Timeline; using UnityEngine.Playables; using System.Collections.Generic; using UnityEditor.Experimental.AssetImporters; using System.Linq; using System.IO; using System; /// TODO: /// - Setup audio sources /// - Camera FOV /// namespace ANIMVR { public enum AudioImportSetting { None, ClipsOnly, ClipsAndTracks } [Serializable] public struct AnimVRImporterSettings { public bool ApplyStageTransform; public DirectorWrapMode DefaultWrapMode; public AudioImportSetting AudioImport; public bool ImportCameras; public bool UnlitByDefault; public string Shader; public float SimplifyFactor; } [Serializable] public struct SerializableIdentifier { public string name; public string type; public string assembly; public SerializableIdentifier(UnityEngine.Object asset) { if (asset == null) { throw new ArgumentNullException("asset"); } type = asset.GetType().Name; name = asset.name; assembly = asset.GetType().Assembly.GetName().Name; } } [ScriptedImporter(1, "stage")] public class AnimVRImporter : ScriptedImporter { public AnimVRImporterSettings Settings = new AnimVRImporterSettings() { ApplyStageTransform = false, DefaultWrapMode = DirectorWrapMode.None, AudioImport = AudioImportSetting.ClipsAndTracks, ImportCameras = true, UnlitByDefault = true, Shader = "AnimVR/ImportedLine", SimplifyFactor = 1.0f }; public List<SerializableIdentifier> m_Materials = new List<SerializableIdentifier>(); public bool needsAudioReimport; public Texture2D PreviewTexture; public string InfoString; public bool HasFades; [NonSerialized] StageData stage; Dictionary<AudioDataPool.AudioPoolKey, AudioClip> savedClips; Material baseMaterial; int totalVertices; int totalLines; static Dictionary<AnimVR.LoopType, TimelineClip.ClipExtrapolation> LOOP_MAPPING = new Dictionary<AnimVR.LoopType, TimelineClip.ClipExtrapolation>() { {AnimVR.LoopType.Hold, TimelineClip.ClipExtrapolation.Hold }, {AnimVR.LoopType.Loop, TimelineClip.ClipExtrapolation.Loop }, {AnimVR.LoopType.OneShot, TimelineClip.ClipExtrapolation.None } }; static Dictionary<AnimVR.TrimLoopType, TimelineClip.ClipExtrapolation> TRIM_LOOP_MAPPING = new Dictionary<AnimVR.TrimLoopType, TimelineClip.ClipExtrapolation>() { {AnimVR.TrimLoopType.Hold, TimelineClip.ClipExtrapolation.Hold }, {AnimVR.TrimLoopType.Loop, TimelineClip.ClipExtrapolation.Loop }, {AnimVR.TrimLoopType.OneShot, TimelineClip.ClipExtrapolation.None }, {AnimVR.TrimLoopType.Infinity, TimelineClip.ClipExtrapolation.Continue } }; public override void OnImportAsset(AssetImportContext ctx) { stage = AnimData.LoadFromFile(ctx.assetPath); if (stage == null) { return; } MeshUtils.SimplifyStage(stage, Settings.SimplifyFactor); savedClips = new Dictionary<AudioDataPool.AudioPoolKey, AudioClip>(); totalVertices = 0; totalLines = 0; HasFades = false; m_Materials.Clear(); PreviewTexture = new Texture2D(1, 1); PreviewTexture.LoadImage(stage.previewFrames[0], false); PreviewTexture.Apply(); if (Settings.Shader == null || Settings.Shader == "AnimVR/Standard") { Debug.Log("Resetting shader"); Settings.Shader = "AnimVR/ImportedLine"; } baseMaterial = new Material(Shader.Find(Settings.Shader)); baseMaterial.SetFloat("_Unlit", Settings.UnlitByDefault ? 1 : 0); baseMaterial.SetFloat("_Gamma", PlayerSettings.colorSpace == ColorSpace.Gamma ? 1.0f : 2.2f); baseMaterial.name = Path.GetFileNameWithoutExtension(ctx.assetPath) + "_BaseMaterial"; needsAudioReimport = false; GenerateUnityObject(stage, ctx); //var externalObjects = GetExternalObjectMap(); ctx.AddObjectToAsset(Path.GetFileNameWithoutExtension(ctx.assetPath) + "_BaseMaterial", baseMaterial); m_Materials.Add(new SerializableIdentifier(baseMaterial)); InfoString = "FPS: " + stage.fps + ", " + stage.timelineLength + " frames \n" + totalVertices + " verts, " + totalLines + " lines"; savedClips = null; stage = null; } public struct Context { public Transform parentTransform, rootTransform; public PlayableDirector director; public Animator animator; public AssetImportContext ctx; public TimelineAsset parentTimeline; public float fps; public int frameOffset; } public GameObject GenerateUnityObject(StageData stage, AssetImportContext ctx) { var stageObj = new GameObject(stage.name); ctx.AddObjectToAsset(stage.name, stageObj, PreviewTexture); ctx.SetMainObject(stageObj); Context context = new Context(); context.fps = stage.fps; context.parentTransform = context.rootTransform = stageObj.transform; context.director = stageObj.AddComponent<PlayableDirector>(); context.director.extrapolationMode = Settings.DefaultWrapMode; var timelineAsset = TimelineAsset.CreateInstance<TimelineAsset>(); timelineAsset.name = stage.name + "_Timeline"; timelineAsset.editorSettings.fps = stage.fps; timelineAsset.durationMode = TimelineAsset.DurationMode.FixedLength; timelineAsset.fixedDuration = stage.timelineLength * 1.0 / stage.fps; ctx.AddObjectToAsset(timelineAsset.name, timelineAsset); context.director.playableAsset = timelineAsset; context.animator = stageObj.AddComponent<Animator>(); context.ctx = ctx; context.parentTimeline = timelineAsset; foreach (var symbol in stage.Symbols) { var symbolObj = GenerateUnityObject(symbol, context); symbolObj.transform.SetParent(stageObj.transform, false); if (Settings.ApplyStageTransform) { symbolObj.transform.localPosition += stage.transform.pos; symbolObj.transform.localRotation *= stage.transform.rot; var scl = symbolObj.transform.localScale; var s = stage.transform.scl; symbolObj.transform.localScale = new Vector3(scl.x * s.x, scl.y * s.y, scl.z * s.z); } } //hacky fix cause fixed duration from code is broken timelineAsset.fixedDuration = (stage.timelineLength - 1) * 1.0 / stage.fps; return stageObj; } public GameObject GenerateUnityObject(PlayableData playable, Context ctx) { if (playable.FadeIn != 0 || playable.FadeOut != 0) HasFades = true; if (playable is SymbolData) return GenerateUnityObject(playable as SymbolData, ctx); else if (playable is TimeLineData) return GenerateUnityObject(playable as TimeLineData, ctx); // No audio support on Mac #if UNITY_EDITOR_WIN else if (playable is AudioData && Settings.AudioImport != AudioImportSetting.None) return GenerateUnityObject(playable as AudioData, ctx); #endif else if (playable is CameraData && Settings.ImportCameras) return GenerateUnityObject(playable as CameraData, ctx); else if (playable is StaticMeshData) return GenerateUnityObject(playable as StaticMeshData, ctx); else return null; } public GameObject MakePlayableBaseObject(PlayableData playable, ref Context ctx, float start, float duration) { start += ctx.frameOffset / ctx.fps; var hackyStart = Mathf.Max(0, start); var clipIn = hackyStart - start; start = hackyStart; var playableObj = new GameObject(playable.displayName ?? "Layer"); playableObj.transform.parent = ctx.parentTransform; playableObj.transform.localPosition = playable.transform.pos.V3; playableObj.transform.localRotation = playable.transform.rot.Q; playableObj.transform.localScale = playable.transform.scl.V3; playableObj.SetActive(playable.isVisible); var path = AnimationUtility.CalculateTransformPath(playableObj.transform, ctx.rootTransform); var director = playableObj.AddComponent<PlayableDirector>(); var timelineAsset = TimelineAsset.CreateInstance<TimelineAsset>(); timelineAsset.name = path + "_Timeline"; timelineAsset.editorSettings.fps = stage.fps; timelineAsset.durationMode = TimelineAsset.DurationMode.FixedLength; timelineAsset.fixedDuration = playable.TrimLoopOut == AnimVR.TrimLoopType.Infinity ? duration : 1000000; ctx.ctx.AddObjectToAsset(timelineAsset.name, timelineAsset); director.extrapolationMode = playable.TrimLoopOut == AnimVR.TrimLoopType.OneShot ? DirectorWrapMode.None : playable.TrimLoopOut == AnimVR.TrimLoopType.Loop ? DirectorWrapMode.Loop : playable.TrimLoopOut == AnimVR.TrimLoopType.Hold ? DirectorWrapMode.Hold : DirectorWrapMode.Hold; director.playableAsset = timelineAsset; ctx.animator = playableObj.AddComponent<Animator>(); var controlTrack = ctx.parentTimeline.CreateTrack<AnimVR.Timeline.AnimControlTrack>(null, playableObj.name); ctx.ctx.AddObjectToAsset(path + "_Control", controlTrack); var controlClip = controlTrack.CreateDefaultClip(); controlClip.displayName = playableObj.name; controlClip.start = start == 0 ? start : (start - 0.000001); controlClip.duration = (start == 0 ? -0.000001 : 0) + duration - clipIn; controlClip.clipIn = clipIn; controlClip.blendInCurveMode = controlClip.blendOutCurveMode = TimelineClip.BlendCurveMode.Manual; controlClip.mixInCurve = AnimationCurve.Linear(0, 0, 1, 1); controlClip.mixOutCurve = AnimationCurve.Linear(0, 1, 1, 0); controlClip.easeInDuration = playable.TrimLoopIn == AnimVR.TrimLoopType.Infinity || playable.FadeIn < 0.01f ? 0 : playable.FadeIn / ctx.fps; controlClip.easeOutDuration = playable.TrimLoopOut == AnimVR.TrimLoopType.Infinity || playable.FadeOut < 0.01f ? 0 : playable.FadeOut / ctx.fps; typeof(TimelineClip).GetProperty("preExtrapolationMode").SetValue(controlClip, TRIM_LOOP_MAPPING[playable.TrimLoopIn], null); typeof(TimelineClip).GetProperty("postExtrapolationMode").SetValue(controlClip, TRIM_LOOP_MAPPING[playable.TrimLoopOut], null); var controlAsset = controlClip.asset as AnimVR.Timeline.AnimControlPlayableAsset; controlAsset.name = playable.name; ctx.director.SetGenericBinding(controlAsset, playableObj); ctx.ctx.AddObjectToAsset(path + "_ControlAsset", controlAsset); ctx.parentTimeline = timelineAsset; ctx.director = director; ctx.parentTransform = playableObj.transform; return playableObj; } public GameObject GenerateUnityObject(SymbolData symbol, Context ctx) { if (symbol.Playables.Count == 0) return null; int frameStart = symbol.GetLocalTrimStart(ctx.fps); int frameEnd = symbol.GetLocalTrimEnd(ctx.fps); int frameLength = frameEnd - frameStart; if (ctx.parentTransform == ctx.rootTransform) { frameStart = 0; frameLength = stage.timelineLength; } var symbolObj = MakePlayableBaseObject(symbol, ref ctx, frameStart / ctx.fps, frameLength / ctx.fps); ctx.frameOffset = symbol.AbsoluteTimeOffset - frameStart; foreach (var playbale in symbol.Playables) { if (playbale.isVisible) { GenerateUnityObject(playbale, ctx); } } return symbolObj; } public GameObject GenerateUnityObject(TimeLineData playable, Context ctx) { int startFrame = playable.AbsoluteTimeOffset - playable.TrimIn; int frameCount = playable.GetFrameCount(stage.fps) + playable.TrimIn + playable.TrimOut; var playableObj = MakePlayableBaseObject(playable, ref ctx, startFrame / ctx.fps, frameCount / ctx.fps); var pathForName = AnimationUtility.CalculateTransformPath(playableObj.transform, ctx.rootTransform); // GROUP var groupTrack = ctx.parentTimeline.CreateTrack<GroupTrack>(null, playable.displayName); ctx.ctx.AddObjectToAsset(pathForName + "_GroupTrack", groupTrack); // ANIMATION var animationTrack = ctx.parentTimeline.CreateTrack<AnimVRTrack>(groupTrack, pathForName + "_animation"); ctx.ctx.AddObjectToAsset(pathForName + "_animation", animationTrack); var animationClip = animationTrack.CreateDefaultClip(); animationClip.duration = playable.GetFrameCount(stage.fps) / stage.fps; animationClip.start = playable.TrimIn / stage.fps; typeof(TimelineClip).GetProperty("preExtrapolationMode").SetValue(animationClip, LOOP_MAPPING[playable.LoopIn], null); typeof(TimelineClip).GetProperty("postExtrapolationMode").SetValue(animationClip, LOOP_MAPPING[playable.LoopOut], null); var animAsset = animationClip.asset as AnimVRFramesAsset; animAsset.FPS = stage.fps; if (playable.Frames.Count > 0) { animAsset.FadeIn = playable.Frames[0].FadeModeIn; animAsset.FadeOut = playable.Frames[0].FadeModeOut; } ctx.director.SetGenericBinding(animAsset, playableObj); ctx.ctx.AddObjectToAsset(pathForName + "_animAsset", animAsset); int frameIndex = -1; foreach (var frame in playable.Frames) { if (!frame.isInstance) { var frameObj = GenerateUnityObject(frame, ctx, ++frameIndex); if (frameIndex != 0) frameObj.SetActive(false); frameObj.transform.SetAsLastSibling(); } animAsset.FrameIndices.Add(frameIndex); } return playableObj; } public GameObject GenerateUnityObject(AudioData playable, Context ctx) { AudioClip clip = null; var dir = Application.dataPath + Path.GetDirectoryName(ctx.ctx.assetPath).Substring(6); var clipPath = dir + "/" + Path.GetFileNameWithoutExtension(ctx.ctx.assetPath) + "_audio/" + playable.displayName + "_audio.wav"; if (savedClips.ContainsKey(playable.audioDataKey)) { clip = savedClips[playable.audioDataKey]; } else { var assetPath = clipPath.Replace(Application.dataPath, "Assets"); if (!File.Exists(clipPath)) { clip = stage.AudioDataPool.RetrieveClipFromPool(playable.audioDataKey); if (clip) { clip.name = playable.displayName + "_audio"; SavWav.Save(clipPath, clip); AssetDatabase.ImportAsset(assetPath); if (Settings.AudioImport != AudioImportSetting.ClipsAndTracks) needsAudioReimport = true; } } clip = AssetDatabase.LoadAssetAtPath<AudioClip>(assetPath); savedClips[playable.audioDataKey] = clip; } if (Settings.AudioImport != AudioImportSetting.ClipsAndTracks) return null; float start = playable.AbsoluteTimeOffset / stage.fps - playable.TrimIn; float duration = clip ? clip.length : 1 + playable.TrimIn + playable.TrimOut; var playableObj = MakePlayableBaseObject(playable, ref ctx, start, duration); var audioSource = playableObj.AddComponent<AudioSource>(); audioSource.spatialBlend = playable.Spatialize ? 1 : 0; audioSource.spatialize = playable.Spatialize; audioSource.spatializePostEffects = playable.Spatialize; var pathForName = AnimationUtility.CalculateTransformPath(playableObj.transform, ctx.rootTransform); var groupTrack = ctx.parentTimeline.CreateTrack<GroupTrack>(null, playable.displayName); ctx.ctx.AddObjectToAsset(pathForName + "_GroupTrack", groupTrack); var track = ctx.parentTimeline.CreateTrack<AudioTrack>(groupTrack, playable.displayName); ctx.ctx.AddObjectToAsset(pathForName + "_audioTrack", track); bool loop = playable.LoopType == AnimVR.LoopType.Loop; audioSource.loop = loop; var audioTrackClip = track.CreateDefaultClip(); audioTrackClip.displayName = playable.displayName; (audioTrackClip.asset as AudioPlayableAsset).clip = clip; typeof(AudioPlayableAsset).GetField("m_Loop", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance). SetValue(audioTrackClip.asset, loop); if (loop) { audioTrackClip.start = 0; audioTrackClip.duration = ctx.parentTimeline.fixedDuration; audioTrackClip.clipIn = duration - start % duration; } else { audioTrackClip.start = playable.TrimIn / ctx.fps; audioTrackClip.duration = duration; } ctx.ctx.AddObjectToAsset(pathForName + "_asset", audioTrackClip.asset); ctx.director.SetGenericBinding(track, audioSource); return playableObj; } public GameObject GenerateUnityObject(CameraData playable, Context ctx) { float start = playable.AbsoluteTimeOffset - playable.TrimIn; float duration = playable.RecordingTime + (playable.TrimIn + playable.TrimOut) / ctx.fps; var playableObj = MakePlayableBaseObject(playable, ref ctx, start / ctx.fps, duration); var transformAnchor = new GameObject("TransformAnchor"); playable.CurrentShotOffset.ApplyTo(transformAnchor.transform); transformAnchor.transform.SetParent(playableObj.transform, false); var cam = transformAnchor.AddComponent<Camera>(); cam.backgroundColor = stage.backgroundColor; cam.clearFlags = CameraClearFlags.SolidColor; // TODO: Field of view cam.stereoTargetEye = StereoTargetEyeMask.None; cam.nearClipPlane = 0.001f; var pathForName = AnimationUtility.CalculateTransformPath(transformAnchor.transform, ctx.rootTransform); var groupTrack = ctx.parentTimeline.CreateTrack<GroupTrack>(null, playable.displayName); ctx.ctx.AddObjectToAsset(pathForName + "_GroupTrack", groupTrack); if (playable.Timeline.Frames.Count > 0) { var animTrack = ctx.parentTimeline.CreateTrack<AnimationTrack>(groupTrack, pathForName + "_TransformTrack"); ctx.director.SetGenericBinding(animTrack, ctx.animator); ctx.ctx.AddObjectToAsset(pathForName + "_TransformTrack", animTrack); var animationClip = MakeAnimationClip(playable.Timeline, AnimationUtility.CalculateTransformPath(transformAnchor.transform, ctx.parentTransform)); ctx.ctx.AddObjectToAsset(pathForName + "_animation", animationClip); var timelineClip = animTrack.CreateClip(animationClip); timelineClip.start = playable.TrimIn; timelineClip.displayName = playable.displayName; typeof(TimelineClip).GetProperty("preExtrapolationMode").SetValue(timelineClip, LOOP_MAPPING[playable.LoopIn], null); typeof(TimelineClip).GetProperty("postExtrapolationMode").SetValue(timelineClip, LOOP_MAPPING[playable.LoopOut], null); ctx.ctx.AddObjectToAsset(pathForName + "_asset", timelineClip.asset); } return playableObj; } public GameObject GenerateUnityObject(StaticMeshData playable, Context ctx) { int frameStart = playable.AbsoluteTimeOffset - playable.TrimIn; int frameLength = playable.GetFrameCount(ctx.fps) + playable.TrimIn + playable.TrimOut; var playableObj = MakePlayableBaseObject(playable, ref ctx, frameStart / ctx.fps, frameLength / ctx.fps); var transformAnchor = new GameObject("TransformAnchor"); transformAnchor.transform.SetParent(playableObj.transform, false); var pathForName = AnimationUtility.CalculateTransformPath(transformAnchor.transform, ctx.rootTransform); List<Material> materials = new List<Material>(); int matIndex = 0; foreach (var matData in playable.Materials) { var mat = MeshUtils.MaterialFromData(matData, baseMaterial); mat.name = pathForName + "_material" + (matIndex++).ToString(); ctx.ctx.AddObjectToAsset(mat.name, mat); if (mat.mainTexture) { ctx.ctx.AddObjectToAsset(mat.name + "_diffuse", mat.mainTexture); } materials.Add(mat); m_Materials.Add(new SerializableIdentifier(mat)); } int partIndex = 0; foreach (var part in playable.Frames) { var partObj = new GameObject("MeshPart"); var mf = partObj.AddComponent<MeshFilter>(); var mr = partObj.AddComponent<MeshRenderer>(); partObj.transform.SetParent(transformAnchor.transform, false); part.Transform.ApplyTo(partObj.transform); mr.sharedMaterial = materials[part.MaterialIndex]; mf.sharedMesh = MeshUtils.MeshFromData(part); mf.sharedMesh.name = pathForName + "_mesh" + (partIndex).ToString(); ctx.ctx.AddObjectToAsset(mf.sharedMesh.name, mf.sharedMesh); totalVertices += mf.sharedMesh.vertexCount; } var groupTrack = ctx.parentTimeline.CreateTrack<GroupTrack>(null, playable.displayName); ctx.ctx.AddObjectToAsset(pathForName + "_GroupTrack", groupTrack); double clipDuration = 1.0 / stage.fps; if (playable.InstanceMap.Count > 1) { var animTrack = ctx.parentTimeline.CreateTrack<AnimationTrack>(groupTrack, pathForName + "_TransformTrack"); ctx.director.SetGenericBinding(animTrack, ctx.animator); ctx.ctx.AddObjectToAsset(pathForName + "_TransformTrack", animTrack); var animationClip = MakeAnimationClip(playable.InstanceMap, null, AnimationUtility.CalculateTransformPath(transformAnchor.transform, ctx.parentTransform)); animationClip.name = pathForName + "_animation"; ctx.ctx.AddObjectToAsset(pathForName + "_animation", animationClip); var timelineClip = animTrack.CreateClip(animationClip); timelineClip.start = playable.TrimIn; timelineClip.displayName = playable.displayName; typeof(TimelineClip).GetProperty("preExtrapolationMode").SetValue(timelineClip, LOOP_MAPPING[playable.LoopIn], null); typeof(TimelineClip).GetProperty("postExtrapolationMode").SetValue(timelineClip, LOOP_MAPPING[playable.LoopOut], null); clipDuration = timelineClip.duration; ctx.ctx.AddObjectToAsset(pathForName + "_asset", timelineClip.asset); } else { playable.InstanceMap[0].ApplyTo(transformAnchor.transform); } /* var activeTrack = ctx.parentTimeline.CreateTrack<ActivationTrack>(groupTrack, pathForName + "_Activation"); ctx.ctx.AddObjectToAsset(pathForName + "_Activation", activeTrack); ctx.director.SetGenericBinding(activeTrack, playableObj); var clip = activeTrack.CreateDefaultClip(); clip.start = playable.LoopIn != AnimVR.LoopType.OneShot ? 0 : playable.TrimIn; clip.duration = playable.LoopOut != AnimVR.LoopType.OneShot ? ctx.parentTimeline.fixedDuration - clip.start : (playable.TrimIn - clip.start) + clipDuration; ctx.ctx.AddObjectToAsset(pathForName + "_activeAsset", clip.asset);*/ return playableObj; } public GameObject GenerateUnityObject(FrameData frame, Context ctx, int index) { var playableObj = new GameObject(index.ToString()); playableObj.transform.parent = ctx.parentTransform; playableObj.transform.localPosition = frame.transform.pos.V3; playableObj.transform.localRotation = frame.transform.rot.Q; playableObj.transform.localScale = frame.transform.scl.V3; var pathForName = AnimationUtility.CalculateTransformPath(playableObj.transform, ctx.rootTransform); List<List<CombineInstance>> instances = new List<List<CombineInstance>>(); List<CombineInstance> currentList = new List<CombineInstance>(); instances.Add(currentList); int vCount = 0; foreach (var line in frame.RuntimeLines) { try { List<Vector3> verts = new List<Vector3>(); List<int> indices = new List<int>(); List<Vector4> colors = new List<Vector4>(); List<Vector2> uvs = new List<Vector2>(); List<Vector3> normals = new List<Vector3>(); MeshUtils.GeneratePositionData(line, verts, indices, colors, uvs, normals); CombineInstance instance = new CombineInstance(); if (verts.Count == 0) continue; Mesh mesh = new Mesh(); mesh.SetVertices(verts); mesh.SetTriangles(indices, 0); mesh.SetColors(colors.Select(c => new Color(c.x, c.y, c.z, c.w)).ToList()); mesh.SetUVs(0, uvs); mesh.SetNormals(normals); instance.mesh = mesh; vCount += verts.Count; if (vCount > 60000) { currentList = new List<CombineInstance>(); instances.Add(currentList); vCount -= 60000; } currentList.Add(instance); totalLines++; } catch (Exception e) { Debug.LogWarning(e.Message); } } totalVertices += vCount; int meshId = 0; foreach (var mesh in instances) { var subObj = new GameObject("Submesh" + meshId); subObj.transform.SetParent(playableObj.transform, false); var mf = subObj.AddComponent<MeshFilter>(); var mr = subObj.AddComponent<MeshRenderer>(); Mesh combinedMesh = new Mesh(); combinedMesh.CombineMeshes(mesh.ToArray(), true, false, false); combinedMesh.name = pathForName + meshId; mf.sharedMesh = combinedMesh; mr.sharedMaterial = baseMaterial; ctx.ctx.AddObjectToAsset(pathForName + "_mesh" + meshId, mf.sharedMesh); meshId++; } return playableObj; } public AnimationClip MakeAnimationClip(List<SerializableTransform> frames, List<float> times, string path) { var xCurve = new AnimationCurve(); var yCurve = new AnimationCurve(); var zCurve = new AnimationCurve(); var rotXCurve = new AnimationCurve(); var rotYCurve = new AnimationCurve(); var rotZCurve = new AnimationCurve(); var rotWCurve = new AnimationCurve(); var scaleXCurve = new AnimationCurve(); var scaleYCurve = new AnimationCurve(); var scaleZCurve = new AnimationCurve(); for (int i = 0; i < frames.Count; i++) { var frame = frames[i]; var time = times != null ? times[i] : (i / stage.fps); xCurve.AddKey(new Keyframe(time, frame.pos.x));//, float.NegativeInfinity, float.PositiveInfinity)); yCurve.AddKey(new Keyframe(time, frame.pos.y));//, float.NegativeInfinity, float.PositiveInfinity)); zCurve.AddKey(new Keyframe(time, frame.pos.z));//, float.NegativeInfinity, float.PositiveInfinity)); rotXCurve.AddKey(new Keyframe(time, frame.rot.x));//, float.NegativeInfinity, float.PositiveInfinity)); rotYCurve.AddKey(new Keyframe(time, frame.rot.y));//, float.NegativeInfinity, float.PositiveInfinity)); rotZCurve.AddKey(new Keyframe(time, frame.rot.z));//, float.NegativeInfinity, float.PositiveInfinity)); rotWCurve.AddKey(new Keyframe(time, frame.rot.w));//, float.NegativeInfinity, float.PositiveInfinity)); scaleXCurve.AddKey(new Keyframe(time, frame.scl.x));//, float.NegativeInfinity, float.PositiveInfinity)); scaleYCurve.AddKey(new Keyframe(time, frame.scl.y));//, float.NegativeInfinity, float.PositiveInfinity)); scaleZCurve.AddKey(new Keyframe(time, frame.scl.z));//, float.NegativeInfinity, float.PositiveInfinity)); AnimationUtility.SetKeyBroken(xCurve, i, true); AnimationUtility.SetKeyBroken(yCurve, i, true); AnimationUtility.SetKeyBroken(zCurve, i, true); AnimationUtility.SetKeyBroken(scaleXCurve, i, true); AnimationUtility.SetKeyBroken(scaleYCurve, i, true); AnimationUtility.SetKeyBroken(scaleZCurve, i, true); AnimationUtility.SetKeyBroken(rotXCurve, i, true); AnimationUtility.SetKeyBroken(rotYCurve, i, true); AnimationUtility.SetKeyBroken(rotZCurve, i, true); AnimationUtility.SetKeyBroken(rotWCurve, i, true); AnimationUtility.SetKeyLeftTangentMode(xCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(yCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(zCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(rotXCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(rotYCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(rotZCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(rotWCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(scaleXCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(scaleYCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyLeftTangentMode(scaleZCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(xCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(yCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(zCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(rotXCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(rotYCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(rotZCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(rotWCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(scaleXCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(scaleYCurve, i, AnimationUtility.TangentMode.Constant); AnimationUtility.SetKeyRightTangentMode(scaleZCurve, i, AnimationUtility.TangentMode.Constant); } var animationClip = new AnimationClip(); #pragma warning disable CS0618 // Type or member is obsolete AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localPosition.x", xCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localPosition.y", yCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localPosition.z", zCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localRotation.x", rotXCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localRotation.y", rotYCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localRotation.z", rotZCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localRotation.w", rotWCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localScale.x", scaleXCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localScale.y", scaleYCurve); AnimationUtility.SetEditorCurve(animationClip, path, typeof(Transform), "localScale.z", scaleZCurve); #pragma warning restore CS0618 // Type or member is obsolete animationClip.frameRate = stage.fps; return animationClip; } public AnimationClip MakeAnimationClip(TransformTimelineData timeline, string path) { return MakeAnimationClip(timeline.Frames, timeline.FrameTimes, path); } } }
//Copyright 2014 Spin Services Limited //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Linq; using SS.Integration.Adapter.MarketRules.Interfaces; using SS.Integration.Adapter.Model; using SS.Integration.Adapter.Model.Interfaces; namespace SS.Integration.Adapter.MarketRules.Model { [Serializable] internal class SelectionState : IUpdatableSelectionState { private Dictionary<string, string> _tags; /// <summary> /// DO NOT USE - this constructor is for copying object only /// </summary> public SelectionState() { _tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); } public SelectionState(Selection selection, bool fullSnapshot) : this() { Id = selection.Id; IsRollingSelection = selection is RollingSelection; Update(selection, fullSnapshot); } #region ISelectionState public string Id { get; private set; } public string Name { get; private set; } public double? Price { get; private set; } public bool? Tradability { get; private set; } public string Status { get; private set; } public double? Line { get; private set; } public bool IsRollingSelection { get; private set; } public ISelectionResultState Result { get; private set; } public ISelectionResultState PlaceResult { get; private set; } #region Tags public IEnumerable<string> TagKeys { get { return _tags.Keys; } } public string GetTagValue(string tagKey) { return !string.IsNullOrEmpty(tagKey) && _tags.ContainsKey(tagKey.ToLower()) ? _tags[tagKey.ToLower()] : null; } public bool IsTagValueMatch(string tagKey, string value) => IsTagValueMatch(tagKey, value, false); public bool IsTagValueMatch(string tagKey, string value, bool caseSensitive) => !string.IsNullOrEmpty(tagKey) && !string.IsNullOrEmpty(value) && value.Equals(GetTagValue(tagKey), caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase); public int TagsCount { get { return _tags.Count; } } public bool HasTag(string tagKey) { return !string.IsNullOrEmpty(tagKey) && _tags.ContainsKey(tagKey); } #endregion public bool IsEqualTo(ISelectionState selection) { if (selection == null) throw new ArgumentNullException("selection", "selection is null in SelectionState comparison"); if (ReferenceEquals(this, selection)) return true; if (selection.Id != Id) throw new Exception("Cannot compare two selections with different Ids"); bool ret = (selection.Name == null || selection.Name == this.Name) && this.Price == selection.Price && this.Tradability == selection.Tradability && this.Status == selection.Status; if (IsRollingSelection) ret &= Line == selection.Line; if(Result != null) { if(selection.Result == null) return false; ret &= Result.IsEqualTo(selection.Result); } else if(selection.Result != null) return false; if (PlaceResult != null) { if (selection.PlaceResult == null) return false; ret &= PlaceResult.IsEqualTo(selection.PlaceResult); } else if (selection.PlaceResult != null) return false; return ret; } public bool IsEquivalentTo(Selection selection, bool checkTags) { if (selection == null) return false; if (selection.Id != Id) return false; if (checkTags) { if (selection.TagsCount != TagsCount) return false; if (selection.TagKeys.Any(tag => !HasTag(tag) || GetTagValue(tag) != selection.GetTagValue(tag))) return false; // if we are here, there is no difference between the stored tags // and those contained within the selection object... // we can then proceed to check the selection's fields // Note that Selection.Name is a shortcut for Selection.GetTagValue("name") // as Result and PlaceResult are only present when dealing with full snapshots // we only check these properties if checkTags is true if (selection.Result != null) { if (Result == null) return false; if (!Result.IsEquivalentTo(selection.Result)) return false; } if (selection.PlaceResult != null) { if (PlaceResult == null) return false; if (!PlaceResult.IsEquivalentTo(selection.PlaceResult)) return false; } } var result = Price == selection.Price && Status == selection.Status && Tradability == selection.Tradable; if (IsRollingSelection) return result &= Line == ((RollingSelection)selection).Line; return result; } #endregion #region IUpdatableSelectionState public void Update(Selection selection, bool fullSnapshot) { Price = selection.Price; Status = selection.Status; Tradability = selection.Tradable; if (fullSnapshot) { _tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (var key in selection.TagKeys) _tags.Add(key, selection.GetTagValue(key)); Name = selection.Name; // Result and PlaceResult (in the context of racing fixtures) // are only present on a full snapshot if (selection.Result != null) { if (Result == null) Result = new SelectionResultState(selection.Result); else ((IUpdatableSelectionResultState)Result).Update(selection.Result); } if (selection.PlaceResult != null) { if (PlaceResult == null) PlaceResult = new SelectionResultState(selection.PlaceResult); else ((IUpdatableSelectionResultState)PlaceResult).Update(selection.PlaceResult); } } UpdateLineOnRollingSelection(selection); } private void UpdateLineOnRollingSelection(Selection selection) { var rollingSelection = selection as RollingSelection; if(rollingSelection == null) return; this.Line = rollingSelection.Line; } public IUpdatableSelectionState Clone() { SelectionState clone = new SelectionState { Id = this.Id, Name = this.Name, Price = this.Price, Tradability = this.Tradability, Status = this.Status, Line = this.Line, IsRollingSelection = this.IsRollingSelection }; if (Result != null) clone.Result = ((IUpdatableSelectionResultState)Result).Clone(); if (PlaceResult != null) clone.PlaceResult = ((IUpdatableSelectionResultState)Result).Clone(); foreach (var key in this.TagKeys) clone._tags.Add(key, this.GetTagValue(key)); return clone; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Handlers.Hypergrid; using OpenSim.Services.Connectors.Hypergrid; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Avatar.InstantMessage { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGMessageTransferModule")] public class HGMessageTransferModule : ISharedRegionModule, IMessageTransferModule, IInstantMessageSimConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled = false; protected bool m_EnableObjectIM = true; private ThreadedClasses.RwLockedList<Scene> m_Scenes = new ThreadedClasses.RwLockedList<Scene>(); protected IInstantMessage m_IMService; public event UndeliveredMessage OnUndeliveredMessage; IUserManagement m_uMan; IUserManagement UserManagementModule { get { if (m_uMan == null) m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>(); return m_uMan; } } public virtual void Initialise(IConfigSource config) { IConfig cnf = config.Configs["Messaging"]; if (cnf != null && cnf.GetString( "MessageTransferModule", "MessageTransferModule") != Name) { m_log.Debug("[HG MESSAGE TRANSFER]: Disabled by configuration"); return; } if(cnf != null) { m_EnableObjectIM = cnf.GetBoolean("EnableGridWideObjectIM", true); } InstantMessageServerConnector imServer = new InstantMessageServerConnector(config, MainServer.Instance, this); m_IMService = imServer.GetService(); m_Enabled = true; } public virtual void AddRegion(Scene scene) { if (!m_Enabled) return; m_log.DebugFormat("[HG MESSAGE TRANSFER]: Message transfer module {0} active", Name); scene.RegisterModuleInterface<IMessageTransferModule>(this); m_Scenes.Add(scene); } public virtual void PostInitialise() { if (!m_Enabled) return; } public virtual void RegionLoaded(Scene scene) { } public virtual void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_Scenes.Remove(scene); } public virtual void Close() { } public virtual string Name { get { return "HGMessageTransferModule"; } } public virtual Type ReplaceableInterface { get { return null; } } public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result) { UUID toAgentID = new UUID(im.toAgentID); try { // Try root avatar only first m_Scenes.ForEach(delegate(Scene scene) { // m_log.DebugFormat( // "[HG INSTANT MESSAGE]: Looking for root agent {0} in {1}", // toAgentID.ToString(), scene.RegionInfo.RegionName); ScenePresence sp = scene.GetScenePresence(toAgentID); if (sp != null && !sp.IsChildAgent) { // Local message // m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", user.Name, toAgentID); sp.ControllingClient.SendInstantMessage(im); // Message sent result(true); throw new ThreadedClasses.ReturnValueException<bool>(true); } }); // try child avatar second m_Scenes.ForEach(delegate(Scene scene) { // m_log.DebugFormat( // "[HG INSTANT MESSAGE]: Looking for child of {0} in {1}", // toAgentID, scene.RegionInfo.RegionName); ScenePresence sp = scene.GetScenePresence(toAgentID); if (sp != null) { // Local message // m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", user.Name, toAgentID); sp.ControllingClient.SendInstantMessage(im); // Message sent result(true); throw new ThreadedClasses.ReturnValueException<bool>(true); } }); } catch(ThreadedClasses.ReturnValueException<bool>) { return; } // m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID); // Is the user a local user? string url = string.Empty; bool foreigner = false; byte dialog = im.dialog; if(dialog == (byte)InstantMessageDialog.MessageFromObject && !m_EnableObjectIM) { return; } if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(toAgentID)) // foreign user { url = UserManagementModule.GetUserServerURL(toAgentID, "IMServerURI"); foreigner = true; } Util.FireAndForget(delegate { bool success = false; if (foreigner && url == string.Empty) // we don't know about this user { string recipientUUI = TryGetRecipientUUI(new UUID(im.fromAgentID), toAgentID); m_log.DebugFormat("[HG MESSAGE TRANSFER]: Got UUI {0}", recipientUUI); if (recipientUUI != string.Empty) { UUID id; string u = string.Empty, first = string.Empty, last = string.Empty, secret = string.Empty; if (Util.ParseUniversalUserIdentifier(recipientUUI, out id, out u, out first, out last, out secret)) { ServicePointManagerTimeoutSupport.ResetHosts(); success = m_IMService.OutgoingInstantMessage(im, u, true); if (success) UserManagementModule.AddUser(toAgentID, u + ";" + first + " " + last); } } } else { ServicePointManagerTimeoutSupport.ResetHosts(); success = m_IMService.OutgoingInstantMessage(im, url, foreigner); } if (!success && !foreigner) HandleUndeliveredMessage(im, result); else result(success); }); return; } protected bool SendIMToScene(GridInstantMessage gim, UUID toAgentID) { try { m_Scenes.ForEach(delegate(Scene scene) { ScenePresence sp = scene.GetScenePresence(toAgentID); if (sp != null && !sp.IsChildAgent) { scene.EventManager.TriggerIncomingInstantMessage(gim); throw new ThreadedClasses.ReturnValueException<bool>(true); } }); } catch(ThreadedClasses.ReturnValueException<bool>) { return true; } // If the message can't be delivered to an agent, it // is likely to be a group IM. On a group IM, the // imSessionID = toAgentID = group id. Raise the // unhandled IM event to give the groups module // a chance to pick it up. We raise that in a random // scene, since the groups module is shared. // m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim); return false; } protected void HandleUndeliveredMessage(GridInstantMessage im, MessageResultNotification result) { UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage; // If this event has handlers, then an IM from an agent will be // considered delivered. This will suppress the error message. // if (handlerUndeliveredMessage != null) { handlerUndeliveredMessage(im); if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent) result(true); else result(false); return; } //m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable"); result(false); } private string TryGetRecipientUUI(UUID fromAgent, UUID toAgent) { // Let's call back the fromAgent's user agent service // Maybe that service knows about the toAgent IClientAPI client = LocateClientObject(fromAgent); if (client != null) { AgentCircuitData circuit = m_Scenes[0].AuthenticateHandler.GetAgentCircuitData(client.AgentId); if (circuit != null) { if (circuit.ServiceURLs.ContainsKey("HomeURI")) { string uasURL = circuit.ServiceURLs["HomeURI"].ToString(); m_log.DebugFormat("[HG MESSAGE TRANSFER]: getting UUI of user {0} from {1}", toAgent, uasURL); UserAgentServiceConnector uasConn = new UserAgentServiceConnector(uasURL); string agentUUI = string.Empty; try { agentUUI = uasConn.GetUUI(fromAgent, toAgent); } catch (Exception e) { m_log.Debug("[HG MESSAGE TRANSFER]: GetUUI call failed ", e); } return agentUUI; } } } return string.Empty; } /// <summary> /// Find the root client for a ID /// </summary> public IClientAPI LocateClientObject(UUID agentID) { try { m_Scenes.ForEach(delegate(Scene scene) { ScenePresence presence = scene.GetScenePresence(agentID); if (presence != null && !presence.IsChildAgent) throw new ThreadedClasses.ReturnValueException<IClientAPI>(presence.ControllingClient); }); } catch(ThreadedClasses.ReturnValueException<IClientAPI> e) { return e.Value; } return null; } #region IInstantMessageSimConnector public bool SendInstantMessage(GridInstantMessage im) { //m_log.DebugFormat("[XXX] Hook SendInstantMessage {0}", im.message); UUID agentID = new UUID(im.toAgentID); return SendIMToScene(im, agentID); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsUInt64() { var test = new VectorAs__AsUInt64(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsUInt64 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<UInt64> value; value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector128<UInt64> value; value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<byte> byteResult = value.As<UInt64, byte>(); ValidateResult(byteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<double> doubleResult = value.As<UInt64, double>(); ValidateResult(doubleResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<short> shortResult = value.As<UInt64, short>(); ValidateResult(shortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<int> intResult = value.As<UInt64, int>(); ValidateResult(intResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<long> longResult = value.As<UInt64, long>(); ValidateResult(longResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<sbyte> sbyteResult = value.As<UInt64, sbyte>(); ValidateResult(sbyteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<float> floatResult = value.As<UInt64, float>(); ValidateResult(floatResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<ushort> ushortResult = value.As<UInt64, ushort>(); ValidateResult(ushortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<uint> uintResult = value.As<UInt64, uint>(); ValidateResult(uintResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); Vector128<ulong> ulongResult = value.As<UInt64, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector128<UInt64> value; value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object byteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsByte)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<byte>)(byteResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object doubleResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsDouble)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<double>)(doubleResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object shortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt16)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<short>)(shortResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object intResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt32)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<int>)(intResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object longResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt64)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<long>)(longResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object sbyteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSByte)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<sbyte>)(sbyteResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object floatResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSingle)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<float>)(floatResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object ushortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt16)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ushort>)(ushortResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object uintResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt32)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<uint>)(uintResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt64()); object ulongResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt64)) .MakeGenericMethod(typeof(UInt64)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector128<T> result, Vector128<UInt64> value, [CallerMemberName] string method = "") where T : struct { UInt64[] resultElements = new UInt64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result); UInt64[] valueElements = new UInt64[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(UInt64[] resultElements, UInt64[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt64>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SingleAppExample.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Linq; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.Experimental.VFX; namespace UnityEditor.VFX { class VFXExpressionTRSToMatrix : VFXExpression { public VFXExpressionTRSToMatrix() : this(new VFXExpression[] { VFXValue<Vector3>.Default, VFXValue<Vector3>.Default, VFXValue<Vector3>.Default } ) { } public VFXExpressionTRSToMatrix(params VFXExpression[] parents) : base(VFXExpression.Flags.None, parents) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.TRSToMatrix; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var posReduce = constParents[0]; var rotReduce = constParents[1]; var scaleReduce = constParents[2]; var pos = posReduce.Get<Vector3>(); var rot = rotReduce.Get<Vector3>(); var scale = scaleReduce.Get<Vector3>(); var quat = Quaternion.Euler(rot); Matrix4x4 matrix = new Matrix4x4(); matrix.SetTRS(pos, quat, scale); return VFXValue.Constant(matrix); } public override string GetCodeString(string[] parents) { return string.Format("GetTRSMatrix({0}, {1}, {2})", parents[0], parents[1], parents[2]); } } class VFXExpressionInverseMatrix : VFXExpression { public VFXExpressionInverseMatrix() : this(VFXValue<Matrix4x4>.Default) {} public VFXExpressionInverseMatrix(VFXExpression parent) : base(VFXExpression.Flags.InvalidOnGPU, parent) {} sealed public override VFXExpressionOperation operation { get { return VFXExpressionOperation.InverseMatrix; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrix = constParents[0].Get<Matrix4x4>(); return VFXValue.Constant(matrix.inverse); } } class VFXExpressionTransposeMatrix : VFXExpression { public VFXExpressionTransposeMatrix() : this(VFXValue<Matrix4x4>.Default) {} public VFXExpressionTransposeMatrix(VFXExpression parent) : base(Flags.None, parent) {} public sealed override VFXExpressionOperation operation { get { return VFXExpressionOperation.TransposeMatrix; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrix = constParents[0].Get<Matrix4x4>(); return VFXValue.Constant(matrix.transpose); } public override string GetCodeString(string[] parents) { return string.Format("transpose({0})", parents[0]); } } class VFXExpressionInverseTRSMatrix : VFXExpression { public VFXExpressionInverseTRSMatrix() : this(VFXValue<Matrix4x4>.Default) {} public VFXExpressionInverseTRSMatrix(VFXExpression parent) : base(VFXExpression.Flags.None, parent) {} sealed public override VFXExpressionOperation operation { get { return VFXExpressionOperation.InverseTRSMatrix; } } // Invert 3D transformation matrix (not perspective). Adapted from graphics gems 2. // Inverts upper left by calculating its determinant and multiplying it to the symmetric // adjust matrix of each element. Finally deals with the translation by transforming the // original translation using by the calculated inverse. //https://github.com/erich666/GraphicsGems/blob/master/gemsii/inverse.c static bool inputvertMatrix4x4_General3D(Matrix4x4 input, ref Matrix4x4 output) //*WIP* This function is not exposed, we will add an helper in Matrix4 bindings { #if UNITY_2019_2_OR_NEWER return Matrix4x4.Inverse3DAffine(input, ref output); #else output = Matrix4x4.identity; float pos, neg, t; float det; // Calculate the determinant of upper left 3x3 sub-matrix and // determine if the matrix is singular. pos = neg = 0.0f; t = input[0, 0] * input[1, 1] * input[2, 2]; if (t >= 0.0f) pos += t; else neg += t; t = input[1, 0] * input[2, 1] * input[0, 2]; if (t >= 0.0f) pos += t; else neg += t; t = input[2, 0] * input[0, 1] * input[1, 2]; if (t >= 0.0f) pos += t; else neg += t; t = -input[2, 0] * input[1, 1] * input[0, 2]; if (t >= 0.0f) pos += t; else neg += t; t = -input[1, 0] * input[0, 1] * input[2, 2]; if (t >= 0.0f) pos += t; else neg += t; t = -input[0, 0] * input[2, 1] * input[1, 2]; if (t >= 0.0f) pos += t; else neg += t; det = pos + neg; if (det * det < 1e-25f) return false; det = 1.0f / det; output[0, 0] = (input[1, 1] * input[2, 2] - input[2, 1] * input[1, 2]) * det; output[0, 1] = -(input[0, 1] * input[2, 2] - input[2, 1] * input[0, 2]) * det; output[0, 2] = (input[0, 1] * input[1, 2] - input[1, 1] * input[0, 2]) * det; output[1, 0] = -(input[1, 0] * input[2, 2] - input[2, 0] * input[1, 2]) * det; output[1, 1] = (input[0, 0] * input[2, 2] - input[2, 0] * input[0, 2]) * det; output[1, 2] = -(input[0, 0] * input[1, 2] - input[1, 0] * input[0, 2]) * det; output[2, 0] = (input[1, 0] * input[2, 1] - input[2, 0] * input[1, 1]) * det; output[2, 1] = -(input[0, 0] * input[2, 1] - input[2, 0] * input[0, 1]) * det; output[2, 2] = (input[0, 0] * input[1, 1] - input[1, 0] * input[0, 1]) * det; // Do the translation part output[0, 3] = -(input[0, 3] * output[0, 0] + input[1, 3] * output[0, 1] + input[2, 3] * output[0, 2]); output[1, 3] = -(input[0, 3] * output[1, 0] + input[1, 3] * output[1, 1] + input[2, 3] * output[1, 2]); output[2, 3] = -(input[0, 3] * output[2, 0] + input[1, 3] * output[2, 1] + input[2, 3] * output[2, 2]); output[3, 0] = 0.0f; output[3, 1] = 0.0f; output[3, 2] = 0.0f; output[3, 3] = 1.0f; return true; #endif } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrix = constParents[0].Get<Matrix4x4>(); var result = Matrix4x4.identity; if (!inputvertMatrix4x4_General3D(matrix, ref result)) { throw new InvalidOperationException("VFXExpressionInverseTRSMatrix used on a not TRS Matrix"); } return VFXValue.Constant(result); } public override string GetCodeString(string[] parents) { return string.Format("VFXInverseTRSMatrix({0})", parents[0]); } } class VFXExpressionExtractPositionFromMatrix : VFXExpression { public VFXExpressionExtractPositionFromMatrix() : this(VFXValue<Matrix4x4>.Default) { } public VFXExpressionExtractPositionFromMatrix(VFXExpression parent) : base(VFXExpression.Flags.None, new VFXExpression[] { parent }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.ExtractPositionFromMatrix; } } protected sealed override VFXExpression Reduce(VFXExpression[] reducedParents) { var parent = reducedParents[0]; if (parent is VFXExpressionTRSToMatrix) return parent.parents[0]; return base.Reduce(reducedParents); } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrixReduce = constParents[0]; var matrix = matrixReduce.Get<Matrix4x4>(); return VFXValue.Constant<Vector3>(matrix.GetColumn(3)); } public override string GetCodeString(string[] parents) { return string.Format("{0}[3].xyz", parents[0]); } } class VFXExpressionExtractAnglesFromMatrix : VFXExpression { public VFXExpressionExtractAnglesFromMatrix() : this(VFXValue<Matrix4x4>.Default) { } public VFXExpressionExtractAnglesFromMatrix(VFXExpression parent) : base(VFXExpression.Flags.InvalidOnGPU, new VFXExpression[] { parent }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.ExtractAnglesFromMatrix; } } protected sealed override VFXExpression Reduce(VFXExpression[] reducedParents) { var parent = reducedParents[0]; if (parent is VFXExpressionTRSToMatrix) return parent.parents[1]; return base.Reduce(reducedParents); } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrixReduce = constParents[0]; var matrix = matrixReduce.Get<Matrix4x4>(); matrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); return VFXValue.Constant(matrix.rotation.eulerAngles); } } class VFXExpressionExtractScaleFromMatrix : VFXExpression { public VFXExpressionExtractScaleFromMatrix() : this(VFXValue<Matrix4x4>.Default) { } public VFXExpressionExtractScaleFromMatrix(VFXExpression parent) : base(VFXExpression.Flags.InvalidOnGPU, new VFXExpression[] { parent }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.ExtractScaleFromMatrix; } } protected sealed override VFXExpression Reduce(VFXExpression[] reducedParents) { var parent = reducedParents[0]; if (parent is VFXExpressionTRSToMatrix) return parent.parents[2]; return base.Reduce(reducedParents); } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrixReduce = constParents[0]; var matrix = matrixReduce.Get<Matrix4x4>(); matrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); return VFXValue.Constant(matrix.lossyScale); } } class VFXExpressionTransformMatrix : VFXExpression { public VFXExpressionTransformMatrix() : this(VFXValue<Matrix4x4>.Default, VFXValue<Matrix4x4>.Default) { } public VFXExpressionTransformMatrix(VFXExpression left, VFXExpression right) : base(VFXExpression.Flags.None, new VFXExpression[] { left, right }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.TransformMatrix; } } protected sealed override VFXExpression Evaluate(VFXExpression[] constParents) { var left = constParents[0].Get<Matrix4x4>(); var right = constParents[1].Get<Matrix4x4>(); return VFXValue.Constant(left * right); } public override string GetCodeString(string[] parents) { return string.Format("mul({0}, {1})", parents[0], parents[1]); } } class VFXExpressionTransformPosition : VFXExpression { public VFXExpressionTransformPosition() : this(VFXValue<Matrix4x4>.Default, VFXValue<Vector3>.Default) { } public VFXExpressionTransformPosition(VFXExpression matrix, VFXExpression position) : base(VFXExpression.Flags.None, new VFXExpression[] { matrix, position }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.TransformPos; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrixReduce = constParents[0]; var positionReduce = constParents[1]; var matrix = matrixReduce.Get<Matrix4x4>(); var position = positionReduce.Get<Vector3>(); return VFXValue.Constant(matrix.MultiplyPoint(position)); } public override string GetCodeString(string[] parents) { return string.Format("mul({0}, float4({1}, 1.0)).xyz", parents[0], parents[1]); } } class VFXExpressionTransformVector : VFXExpression { public VFXExpressionTransformVector() : this(VFXValue<Matrix4x4>.Default, VFXValue<Vector3>.Default) { } public VFXExpressionTransformVector(VFXExpression matrix, VFXExpression vector) : base(VFXExpression.Flags.None, new VFXExpression[] { matrix, vector }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.TransformVec; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrixReduce = constParents[0]; var positionReduce = constParents[1]; var matrix = matrixReduce.Get<Matrix4x4>(); var vector = positionReduce.Get<Vector3>(); return VFXValue.Constant(matrix.MultiplyVector(vector)); } public override string GetCodeString(string[] parents) { return string.Format("mul((float3x3){0}, {1})", parents[0], parents[1]); } } class VFXExpressionTransformDirection : VFXExpression { public VFXExpressionTransformDirection() : this(VFXValue<Matrix4x4>.Default, VFXValue<Vector3>.Default) { } public VFXExpressionTransformDirection(VFXExpression matrix, VFXExpression vector) : base(VFXExpression.Flags.None, new VFXExpression[] { matrix, vector }) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.TransformDir; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matrixReduce = constParents[0]; var positionReduce = constParents[1]; var matrix = matrixReduce.Get<Matrix4x4>(); var vector = positionReduce.Get<Vector3>(); return VFXValue.Constant(matrix.MultiplyVector(vector).normalized); } public override string GetCodeString(string[] parents) { return string.Format("normalize(mul((float3x3){0}, {1}))", parents[0], parents[1]); } } class VFXExpressionVector3sToMatrix : VFXExpression { public VFXExpressionVector3sToMatrix() : this(new VFXExpression[] { new VFXValue<Vector3>(Vector3.right), new VFXValue<Vector3>(Vector3.up), new VFXValue<Vector3>(Vector3.forward), VFXValue<Vector3>.Default } ) { } public VFXExpressionVector3sToMatrix(params VFXExpression[] parents) : base(VFXExpression.Flags.None, parents) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.Vector3sToMatrix; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var xReduce = constParents[0]; var yReduce = constParents[1]; var zReduce = constParents[2]; var wReduce = constParents[3]; var x = xReduce.Get<Vector3>(); var y = yReduce.Get<Vector3>(); var z = zReduce.Get<Vector3>(); var w = wReduce.Get<Vector3>(); Matrix4x4 matrix = new Matrix4x4(); matrix.SetColumn(0, new Vector4(x.x, x.y, x.z, 0.0f)); matrix.SetColumn(1, new Vector4(y.x, y.y, y.z, 0.0f)); matrix.SetColumn(2, new Vector4(z.x, z.y, z.z, 0.0f)); matrix.SetColumn(3, new Vector4(w.x, w.y, w.z, 1.0f)); return VFXValue.Constant(matrix); } public override string GetCodeString(string[] parents) { return string.Format("float4x4(float4({0}, 0.0), float4({1}, 0.0), float4({2}, 0.0), float4({3}, 1.0));", parents[0], parents[1], parents[2], parents[3]); } } class VFXExpressionVector4sToMatrix : VFXExpression { public VFXExpressionVector4sToMatrix() : this(new VFXExpression[] { new VFXValue<Vector4>(new Vector4(1, 0, 0, 0)), new VFXValue<Vector4>(new Vector4(0, 1, 0, 0)), new VFXValue<Vector4>(new Vector4(0, 0, 1, 0)), new VFXValue<Vector4>(new Vector4(0, 0, 0, 1)) } ) { } public VFXExpressionVector4sToMatrix(params VFXExpression[] parents) : base(VFXExpression.Flags.None, parents) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.Vector4sToMatrix; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var xReduce = constParents[0]; var yReduce = constParents[1]; var zReduce = constParents[2]; var wReduce = constParents[3]; var x = xReduce.Get<Vector4>(); var y = yReduce.Get<Vector4>(); var z = zReduce.Get<Vector4>(); var w = wReduce.Get<Vector4>(); Matrix4x4 matrix = new Matrix4x4(); matrix.SetColumn(0, x); matrix.SetColumn(1, y); matrix.SetColumn(2, z); matrix.SetColumn(3, w); return VFXValue.Constant(matrix); } public override string GetCodeString(string[] parents) { return string.Format("float4x4({0}, {1}, {2}, {3});", parents[0], parents[1], parents[2], parents[3]); } } class VFXExpressionMatrixToVector3s : VFXExpression { public VFXExpressionMatrixToVector3s() : this(new VFXExpression[] { VFXValue<Matrix4x4>.Default, VFXValue.Constant<int>(0) } // TODO row index should not be an expression! ) { } public VFXExpressionMatrixToVector3s(params VFXExpression[] parents) : base(VFXExpression.Flags.None, parents) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.MatrixToVector3s; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matReduce = constParents[0]; var axisReduce = constParents[1]; var mat = matReduce.Get<Matrix4x4>(); var axis = axisReduce.Get<int>(); return VFXValue.Constant<Vector3>(mat.GetColumn(axis)); } public override string GetCodeString(string[] parents) { return string.Format("{0}[{1}].xyz", parents[0], parents[1]); } } class VFXExpressionMatrixToVector4s : VFXExpression { public VFXExpressionMatrixToVector4s() : this(new VFXExpression[] { VFXValue<Matrix4x4>.Default, VFXValue.Constant<int>(0) } // TODO row index should not be an expression! ) { } public VFXExpressionMatrixToVector4s(params VFXExpression[] parents) : base(VFXExpression.Flags.None, parents) { } public override VFXExpressionOperation operation { get { return VFXExpressionOperation.MatrixToVector4s; } } sealed protected override VFXExpression Evaluate(VFXExpression[] constParents) { var matReduce = constParents[0]; var axisReduce = constParents[1]; var mat = matReduce.Get<Matrix4x4>(); var axis = axisReduce.Get<int>(); return VFXValue.Constant(mat.GetColumn(axis)); } public override string GetCodeString(string[] parents) { return string.Format("{0}[{1}]", parents[0], parents[1]); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.UnitTests.Targets { using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using NLog.Common; using NLog.Config; using NLog.Targets; using Xunit; using Xunit.Extensions; public class DatabaseTargetTests : NLogTestBase { #if !MONO static DatabaseTargetTests() { var data = (DataSet)ConfigurationManager.GetSection("system.data"); var providerFactories = data.Tables["DBProviderFactories"]; providerFactories.Rows.Add("MockDb Provider", "MockDb Provider", "MockDb", typeof(MockDbFactory).AssemblyQualifiedName); providerFactories.AcceptChanges(); } #endif [Fact] public void SimpleDatabaseTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') Close() Dispose() Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') Close() Dispose() Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void SimpleBatchedDatabaseTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenBatchedTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "FooBar", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('FooBar'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenTest2() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "Database=${logger}", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); List<Exception> exceptions = new List<Exception>(); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add)); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add)); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') Close() Dispose() Open('Database=MyLogger2'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') Close() Dispose() Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void KeepConnectionOpenBatchedTest2() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES('${message}')", ConnectionString = "Database=${logger}", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger2", "msg3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "MyLogger", "msg4").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Database=MyLogger'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg1') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg2') ExecuteNonQuery: INSERT INTO FooBar VALUES('msg4') Close() Dispose() Open('Database=MyLogger2'). ExecuteNonQuery: INSERT INTO FooBar VALUES('msg3') "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void ParameterTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, Parameters = { new DatabaseParameterInfo("msg", "${message}"), new DatabaseParameterInfo("lvl", "${level}"), new DatabaseParameterInfo("lg", "${logger}") } }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database List<Exception> exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Value=msg1 Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Value=Info Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=MyLogger Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Value=msg3 Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Value=Debug Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=MyLogger2 Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) "; AssertLog(expectedLog); MockDbConnection.ClearLog(); dt.Close(); expectedLog = @"Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void ParameterFacetTest() { MockDbConnection.ClearLog(); DatabaseTarget dt = new DatabaseTarget() { CommandText = "INSERT INTO FooBar VALUES(@msg, @lvl, @lg)", DBProvider = typeof(MockDbConnection).AssemblyQualifiedName, KeepConnection = true, Parameters = { new DatabaseParameterInfo("msg", "${message}") { Precision = 3, Scale = 7, Size = 9, }, new DatabaseParameterInfo("lvl", "${level}") { Scale = 7 }, new DatabaseParameterInfo("lg", "${logger}") { Precision = 0 }, } }; dt.Initialize(null); Assert.Same(typeof(MockDbConnection), dt.ConnectionType); // when we pass multiple log events in an array, the target will bucket-sort them by // connection string and group all commands for the same connection string together // to minimize number of db open/close operations // in this case msg1, msg2 and msg4 will be written together to MyLogger database // and msg3 will be written to MyLogger2 database var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "MyLogger", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "MyLogger2", "msg3").WithContinuation(exceptions.Add), }; dt.WriteAsyncLogEvents(events); dt.Close(); foreach (var ex in exceptions) { Assert.Null(ex); } string expectedLog = @"Open('Server=.;Trusted_Connection=SSPI;'). CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Size=9 Parameter #0 Precision=3 Parameter #0 Scale=7 Parameter #0 Value=msg1 Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Scale=7 Parameter #1 Value=Info Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=MyLogger Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) CreateParameter(0) Parameter #0 Direction=Input Parameter #0 Name=msg Parameter #0 Size=9 Parameter #0 Precision=3 Parameter #0 Scale=7 Parameter #0 Value=msg3 Add Parameter Parameter #0 CreateParameter(1) Parameter #1 Direction=Input Parameter #1 Name=lvl Parameter #1 Scale=7 Parameter #1 Value=Debug Add Parameter Parameter #1 CreateParameter(2) Parameter #2 Direction=Input Parameter #2 Name=lg Parameter #2 Value=MyLogger2 Add Parameter Parameter #2 ExecuteNonQuery: INSERT INTO FooBar VALUES(@msg, @lvl, @lg) Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void ConnectionStringBuilderTest1() { DatabaseTarget dt; dt = new DatabaseTarget(); Assert.Equal("Server=.;Trusted_Connection=SSPI;", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "${logger}"; Assert.Equal("Server=Logger1;Trusted_Connection=SSPI;", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; Assert.Equal("Server=HOST1;Trusted_Connection=SSPI;Database=Logger1", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; dt.DBUserName = "user1"; dt.DBPassword = "password1"; Assert.Equal("Server=HOST1;User id=user1;Password=password1;Database=Logger1", this.GetConnectionString(dt)); dt = new DatabaseTarget(); dt.ConnectionString = "customConnectionString42"; dt.DBHost = "HOST1"; dt.DBDatabase = "${logger}"; dt.DBUserName = "user1"; dt.DBPassword = "password1"; Assert.Equal("customConnectionString42", this.GetConnectionString(dt)); } [Fact] public void DatabaseExceptionTest1() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotconnect"; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; db.Initialize(null); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.Close(); Assert.Equal(1, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.Equal("Cannot open fake database.", exceptions[0].Message); Assert.Equal("Open('cannotconnect').\r\n", MockDbConnection.Log); } [Fact] public void DatabaseExceptionTest2() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; db.Initialize(null); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.Close(); Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void DatabaseExceptionTest3() { MockDbConnection.ClearLog(); var exceptions = new List<Exception>(); var db = new DatabaseTarget(); db.CommandText = "not important"; db.ConnectionString = "cannotexecute"; db.KeepConnection = true; db.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; db.Initialize(null); db.WriteAsyncLogEvents( LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add), LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add)); db.Close(); Assert.Equal(3, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.Equal("Failure during ExecuteNonQuery", exceptions[0].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[1].Message); Assert.Equal("Failure during ExecuteNonQuery", exceptions[2].Message); string expectedLog = @"Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() Open('cannotexecute'). ExecuteNonQuery: not important Close() Dispose() "; AssertLog(expectedLog); } [Fact] public void ConnectionStringNameInitTest() { var dt = new DatabaseTarget { ConnectionStringName = "MyConnectionString", CommandText = "notimportant", }; Assert.Same(ConfigurationManager.ConnectionStrings, dt.ConnectionStringsSettings); dt.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("MyConnectionString", "cs1", "MockDb"), }; dt.Initialize(null); Assert.Same(MockDbFactory.Instance, dt.ProviderFactory); Assert.Equal("cs1", dt.ConnectionString.Render(LogEventInfo.CreateNullEvent())); } [Fact] public void ConnectionStringNameNegativeTest_if_ThrowConfigExceptions() { LogManager.ThrowConfigExceptions = true; var dt = new DatabaseTarget { ConnectionStringName = "MyConnectionString", CommandText = "notimportant", ConnectionStringsSettings = new ConnectionStringSettingsCollection(), }; try { dt.Initialize(null); Assert.True(false, "Exception expected."); } catch (NLogConfigurationException configurationException) { Assert.Equal("Connection string 'MyConnectionString' is not declared in <connectionStrings /> section.", configurationException.Message); } } [Fact] public void ProviderFactoryInitTest() { var dt = new DatabaseTarget(); dt.DBProvider = "MockDb"; dt.CommandText = "Notimportant"; dt.Initialize(null); Assert.Same(MockDbFactory.Instance, dt.ProviderFactory); dt.OpenConnection("myConnectionString"); Assert.Equal(1, MockDbConnection2.OpenCount); Assert.Equal("myConnectionString", MockDbConnection2.LastOpenConnectionString); } [Fact] public void SqlServerShorthandNotationTest() { foreach (string provName in new[] { "microsoft", "msde", "mssql", "sqlserver" }) { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = provName, ConnectionString = "notimportant", CommandText = "notimportant", }; dt.Initialize(null); Assert.Equal(typeof(System.Data.SqlClient.SqlConnection), dt.ConnectionType); } } [Fact] public void OleDbShorthandNotationTest() { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = "oledb", ConnectionString = "notimportant", CommandText = "notimportant", }; dt.Initialize(null); Assert.Equal(typeof(System.Data.OleDb.OleDbConnection), dt.ConnectionType); } [Fact] public void OdbcShorthandNotationTest() { var dt = new DatabaseTarget() { Name = "myTarget", DBProvider = "odbc", ConnectionString = "notimportant", CommandText = "notimportant", }; dt.Initialize(null); Assert.Equal(typeof(System.Data.Odbc.OdbcConnection), dt.ConnectionType); } [Fact] public void GetProviderNameFromAppConfig() { LogManager.ThrowExceptions = true; var databaseTarget = new DatabaseTarget() { Name = "myTarget", ConnectionStringName = "test_connectionstring_with_providerName", CommandText = "notimportant", }; databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("test_connectionstring_without_providerName","some connectionstring"), new ConnectionStringSettings("test_connectionstring_with_providerName","some connectionstring","System.Data.SqlClient"), }; databaseTarget.Initialize(null); Assert.NotNull(databaseTarget.ProviderFactory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType()); } [Fact] public void DontRequireProviderNameInAppConfig() { LogManager.ThrowExceptions = true; var databaseTarget = new DatabaseTarget() { Name = "myTarget", ConnectionStringName = "test_connectionstring_without_providerName", CommandText = "notimportant", DBProvider = "System.Data.SqlClient" }; databaseTarget.ConnectionStringsSettings = new ConnectionStringSettingsCollection() { new ConnectionStringSettings("test_connectionstring_without_providerName","some connectionstring"), new ConnectionStringSettings("test_connectionstring_with_providerName","some connectionstring","System.Data.SqlClient"), }; databaseTarget.Initialize(null); Assert.NotNull(databaseTarget.ProviderFactory); Assert.Equal(typeof(System.Data.SqlClient.SqlClientFactory), databaseTarget.ProviderFactory.GetType()); } [Theory] [InlineData("usetransactions='false'", true)] [InlineData("usetransactions='true'", true)] [InlineData("", false)] public void WarningForObsoleteUseTransactions(string property, bool printWarning) { LoggingConfiguration c = CreateConfigurationFromString(string.Format(@" <nlog ThrowExceptions='true'> <targets> <target type='database' {0} name='t1' commandtext='fake sql' connectionstring='somewhere' /> </targets> <rules> <logger name='*' writeTo='t1'> </logger> </rules> </nlog>", property)); StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; var t = c.FindTargetByName<DatabaseTarget>("t1"); t.Initialize(null); var internalLog = writer1.ToString(); if (printWarning) { Assert.Contains("obsolete", internalLog, StringComparison.InvariantCultureIgnoreCase); Assert.Contains("usetransactions", internalLog, StringComparison.InvariantCultureIgnoreCase); } else { Assert.DoesNotContain("obsolete", internalLog, StringComparison.InvariantCultureIgnoreCase); Assert.DoesNotContain("usetransactions", internalLog, StringComparison.InvariantCultureIgnoreCase); } } private static void AssertLog(string expectedLog) { Assert.Equal(expectedLog.Replace("\r", ""), MockDbConnection.Log.Replace("\r", "")); } private string GetConnectionString(DatabaseTarget dt) { MockDbConnection.ClearLog(); dt.DBProvider = typeof(MockDbConnection).AssemblyQualifiedName; dt.CommandText = "NotImportant"; var exceptions = new List<Exception>(); dt.Initialize(null); dt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "msg1").WithContinuation(exceptions.Add)); dt.Close(); return MockDbConnection.LastConnectionString; } public class MockDbConnection : IDbConnection { public static string Log { get; private set; } public static string LastConnectionString { get; private set; } public MockDbConnection() { } public MockDbConnection(string connectionString) { this.ConnectionString = connectionString; } public IDbTransaction BeginTransaction(IsolationLevel il) { throw new NotImplementedException(); } public IDbTransaction BeginTransaction() { throw new NotImplementedException(); } public void ChangeDatabase(string databaseName) { throw new NotImplementedException(); } public void Close() { AddToLog("Close()"); } public string ConnectionString { get; set; } public int ConnectionTimeout { get { throw new NotImplementedException(); } } public IDbCommand CreateCommand() { return new MockDbCommand() { Connection = this }; } public string Database { get { throw new NotImplementedException(); } } public void Open() { LastConnectionString = this.ConnectionString; AddToLog("Open('{0}').", this.ConnectionString); if (this.ConnectionString == "cannotconnect") { throw new InvalidOperationException("Cannot open fake database."); } } public ConnectionState State { get { throw new NotImplementedException(); } } public void Dispose() { AddToLog("Dispose()"); } public static void ClearLog() { Log = string.Empty; } public void AddToLog(string message, params object[] args) { if (args.Length > 0) { message = string.Format(CultureInfo.InvariantCulture, message, args); } Log += message + "\r\n"; } } private class MockDbCommand : IDbCommand { private int paramCount; private IDataParameterCollection parameters; public MockDbCommand() { this.parameters = new MockParameterCollection(this); } public void Cancel() { throw new NotImplementedException(); } public string CommandText { get; set; } public int CommandTimeout { get; set; } public CommandType CommandType { get; set; } public IDbConnection Connection { get; set; } public IDbDataParameter CreateParameter() { ((MockDbConnection)this.Connection).AddToLog("CreateParameter({0})", this.paramCount); return new MockDbParameter(this, paramCount++); } public int ExecuteNonQuery() { ((MockDbConnection)this.Connection).AddToLog("ExecuteNonQuery: {0}", this.CommandText); if (this.Connection.ConnectionString == "cannotexecute") { throw new InvalidOperationException("Failure during ExecuteNonQuery"); } return 0; } public IDataReader ExecuteReader(CommandBehavior behavior) { throw new NotImplementedException(); } public IDataReader ExecuteReader() { throw new NotImplementedException(); } public object ExecuteScalar() { throw new NotImplementedException(); } public IDataParameterCollection Parameters { get { return parameters; } } public void Prepare() { throw new NotImplementedException(); } public IDbTransaction Transaction { get; set; } public UpdateRowSource UpdatedRowSource { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } } private class MockDbParameter : IDbDataParameter { private readonly MockDbCommand mockDbCommand; private readonly int paramId; private string parameterName; private object parameterValue; private DbType parameterType; public MockDbParameter(MockDbCommand mockDbCommand, int paramId) { this.mockDbCommand = mockDbCommand; this.paramId = paramId; } public DbType DbType { get { return this.parameterType; } set { this.parameterType = value; } } public ParameterDirection Direction { get { throw new NotImplementedException(); } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Direction={1}", paramId, value); } } public bool IsNullable { get { throw new NotImplementedException(); } } public string ParameterName { get { return this.parameterName; } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Name={1}", paramId, value); this.parameterName = value; } } public string SourceColumn { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public DataRowVersion SourceVersion { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public object Value { get { return this.parameterValue; } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Value={1}", paramId, value); this.parameterValue = value; } } public byte Precision { get { throw new NotImplementedException(); } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Precision={1}", paramId, value); } } public byte Scale { get { throw new NotImplementedException(); } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Scale={1}", paramId, value); } } public int Size { get { throw new NotImplementedException(); } set { ((MockDbConnection)mockDbCommand.Connection).AddToLog("Parameter #{0} Size={1}", paramId, value); } } public override string ToString() { return "Parameter #" + this.paramId; } } private class MockParameterCollection : IDataParameterCollection { private readonly MockDbCommand command; public MockParameterCollection(MockDbCommand command) { this.command = command; } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public int Add(object value) { ((MockDbConnection)command.Connection).AddToLog("Add Parameter {0}", value); return 0; } public bool Contains(object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public int IndexOf(object value) { throw new NotImplementedException(); } public void Insert(int index, object value) { throw new NotImplementedException(); } public void Remove(object value) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } object IList.this[int index] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public bool IsFixedSize { get { throw new NotImplementedException(); } } public bool Contains(string parameterName) { throw new NotImplementedException(); } public int IndexOf(string parameterName) { throw new NotImplementedException(); } public void RemoveAt(string parameterName) { throw new NotImplementedException(); } object IDataParameterCollection.this[string parameterName] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } public class MockDbFactory : DbProviderFactory { public static readonly MockDbFactory Instance = new MockDbFactory(); public override DbConnection CreateConnection() { return new MockDbConnection2(); } } public class MockDbConnection2 : DbConnection { public static int OpenCount { get; private set; } public static string LastOpenConnectionString { get; private set; } protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { throw new NotImplementedException(); } public override void ChangeDatabase(string databaseName) { throw new NotImplementedException(); } public override void Close() { throw new NotImplementedException(); } public override string ConnectionString { get; set; } protected override DbCommand CreateDbCommand() { throw new NotImplementedException(); } public override string DataSource { get { throw new NotImplementedException(); } } public override string Database { get { throw new NotImplementedException(); } } public override void Open() { LastOpenConnectionString = this.ConnectionString; OpenCount++; } public override string ServerVersion { get { throw new NotImplementedException(); } } public override ConnectionState State { get { throw new NotImplementedException(); } } } } } #endif
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.ComponentModel; using System.Collections.Generic; using System.Collections.Specialized; using WebsitePanel.Providers.ResultObjects; namespace WebsitePanel.Providers.Web { /// <summary> /// Summary description for WebSiteItem. /// </summary> [Serializable] public class WebSite : WebVirtualDirectory { #region String constants public const string IIS7_SITE_ID = "WebSiteId_IIS7"; public const string IIS7_LOG_EXT_FILE_FIELDS = "IIS7_LogExtFileFields"; #endregion private string siteId; private string siteIPAddress; private int siteIPAddressId; private bool isDedicatedIP; private string dataPath; private ServerBinding[] bindings; private bool frontPageAvailable; private bool frontPageInstalled; private bool coldFusionAvailable; private bool createCFVirtualDirectories; private bool createCFVirtualDirectoriesPol; private string frontPageAccount; private string frontPagePassword; private string coldFusionVersion; private ServerState siteState; private bool securedFoldersInstalled; private bool heliconApeInstalled; private bool heliconApeEnabled; private HeliconApeStatus heliconApeStatus; private bool sniEnabled; public WebSite() { } [Persistent] public string SiteId { get { return siteId; } set { siteId = value; } } public string SiteIPAddress { get { return siteIPAddress; } set { siteIPAddress = value; } } [Persistent] public int SiteIPAddressId { get { return siteIPAddressId; } set { siteIPAddressId = value; } } public bool IsDedicatedIP { get { return isDedicatedIP; } set { isDedicatedIP = value; } } /// <summary> /// Gets or sets logs path for the web site /// </summary> [Persistent] public string LogsPath { get; set; } [Persistent] public string DataPath { get { return dataPath; } set { dataPath = value; } } public ServerBinding[] Bindings { get { return bindings; } set { bindings = value; } } [Persistent] public string FrontPageAccount { get { return this.frontPageAccount; } set { this.frontPageAccount = value; } } [Persistent] public string FrontPagePassword { get { return this.frontPagePassword; } set { this.frontPagePassword = value; } } public bool FrontPageAvailable { get { return this.frontPageAvailable; } set { this.frontPageAvailable = value; } } public bool FrontPageInstalled { get { return this.frontPageInstalled; } set { this.frontPageInstalled = value; } } public bool ColdFusionAvailable { get { return this.coldFusionAvailable; } set { this.coldFusionAvailable = value; } } public string ColdFusionVersion { get { return this.coldFusionVersion; } set { this.coldFusionVersion = value; } } public bool CreateCFVirtualDirectories { get { return this.createCFVirtualDirectories; } set { this.createCFVirtualDirectories = value; } } public bool CreateCFVirtualDirectoriesPol { get { return this.createCFVirtualDirectoriesPol; } set { this.createCFVirtualDirectoriesPol = value; } } public ServerState SiteState { get { return this.siteState; } set { this.siteState = value; } } public bool SecuredFoldersInstalled { get { return this.securedFoldersInstalled; } set { this.securedFoldersInstalled = value; } } public bool HeliconApeInstalled { get { return this.heliconApeInstalled; } set { this.heliconApeInstalled = value; } } public bool HeliconApeEnabled { get { return this.heliconApeEnabled; } set { this.heliconApeEnabled = value; } } public HeliconApeStatus HeliconApeStatus { get { return this.heliconApeStatus; } set { this.heliconApeStatus = value; } } public bool SniEnabled { get { return this.sniEnabled; } set { this.sniEnabled = value; } } } [Flags] public enum SiteAppPoolMode { Dedicated = 1, Shared = 2, Classic = 4, Integrated = 8, dotNetFramework1 = 16, dotNetFramework2 = 32, dotNetFramework4 = 64 }; public class WSHelper { public const int IIS6 = 0; public const int IIS7 = 1; // public static Dictionary<SiteAppPoolMode, string[]> MMD = new Dictionary<SiteAppPoolMode, string[]> { { SiteAppPoolMode.dotNetFramework1, new string[] {"", "v1.1"} }, { SiteAppPoolMode.dotNetFramework2, new string[] {"2.0", "v2.0"} }, { SiteAppPoolMode.dotNetFramework4, new string[] {"4.0", "v4.0"} }, }; public static string InferAppPoolName(string formatString, string siteName, SiteAppPoolMode NHRT) { if (String.IsNullOrEmpty(formatString)) throw new ArgumentNullException("formatString"); // NHRT |= SiteAppPoolMode.Dedicated; // formatString = formatString.Replace("#SITE-NAME#", siteName); // foreach (var fwVersionKey in MMD.Keys) { if ((NHRT & fwVersionKey) == fwVersionKey) { formatString = formatString.Replace("#IIS6-ASPNET-VERSION#", MMD[fwVersionKey][IIS6]); formatString = formatString.Replace("#IIS7-ASPNET-VERSION#", MMD[fwVersionKey][IIS7]); // break; } } // SiteAppPoolMode pipeline = NHRT & (SiteAppPoolMode.Classic | SiteAppPoolMode.Integrated); formatString = formatString.Replace("#PIPELINE-MODE#", pipeline.ToString()); // return formatString.Trim(); } public static string WhatFrameworkVersionIs(SiteAppPoolMode value) { SiteAppPoolMode dotNetVersion = value & (SiteAppPoolMode.dotNetFramework1 | SiteAppPoolMode.dotNetFramework2 | SiteAppPoolMode.dotNetFramework4); // return String.Format("v{0}", MMD[dotNetVersion][IIS7]); } } }
//ADAPTED FROM: http://www.codeguru.com/csharp/csharp/cs_syntax/controls/article.php/c5849/Docking-Control-in-C-That-Can-Be-Dragged-and-Resized.htm //AGB: Changed the HotLength to 25% of window size when dragging the control around to re-dock it. //AGB: Added a show/hide functionality. using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; //class ExampleForm : Form //{ // public static void Main() // { // Application.Run( new ExampleForm() ); // } // public ExampleForm() // { // Controls.Add( new DockingControl( this, DockStyle.Left, new MonthCalendar() ) ); // Controls.Add( new DockingControl( this, DockStyle.Top, new RichTextBox() ) ); // } //} namespace liquicode.AppTools { //===================================================================== //===================================================================== // Allow an arbitrary control to be moved between docking positions and resized public class DockingControl : UserControl { //===================================================================== private Form _HostForm; // The Form hosting this docking control private DockingControlResizer _ResizeControl; // Provide resizing functionality private DockingControlDragger _HandleControl; // Handle for grabbing and moving private DockingControlBorder _BorderControl; // Wrapper to place border around user control //===================================================================== public int MinimumControlSize = 10; public int HiddenControlSize = 30; private bool _IsHidden = false; private int _LastShownSize = 300; private int _LastShownClientSize = 300; //===================================================================== public DockingControl( Form form, DockStyle ds, Control userControl ) { // Remember the form we are hosted on this._HostForm = form; // Create the resizing bar, gripper handle and border control this._ResizeControl = new DockingControlResizer( ds ); this._HandleControl = new DockingControlDragger( this, ds ); this._BorderControl = new DockingControlBorder( userControl ); // Wrapper should always fill remaining area this._BorderControl.Dock = DockStyle.Fill; // Define our own initial docking position for when we are added to host form this.Dock = ds; // NOTE: Order of array contents is important // Controls in the array are positioned from right to left when the // form makes size/position calculations for docking controls, so the // _BorderControl is placed last in calculation (therefore first in array) // because we want it to fill the remaining space. Controls.AddRange( new Control[] { this._BorderControl, this._HandleControl, this._ResizeControl } ); return; } //===================================================================== public Form HostForm { get { return this._HostForm; } } //===================================================================== public int LastShownSize { get { return this._LastShownSize; } } //===================================================================== public bool IsHidden { get { return this._IsHidden; } set { if( value ) { if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { if( this._IsHidden == false ) { this._LastShownClientSize = this.ClientSize.Height; } this._IsHidden = true; this.ClientSize = new Size( 0, this.HiddenControlSize ); } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { if( this._IsHidden == false ) { this._LastShownClientSize = this.ClientSize.Width; } this._IsHidden = true; this.ClientSize = new Size( this.HiddenControlSize, 0 ); } } else { if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { this._IsHidden = false; this.ClientSize = new Size( 0, this._LastShownClientSize ); } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { this._IsHidden = false; this.ClientSize = new Size( this._LastShownClientSize, 0 ); } } this.Invalidate(); return; } } //===================================================================== protected override void OnResize( EventArgs e ) { if( this._IsHidden == false ) { if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { if( this.Height < this.MinimumControlSize ) { this.Height = this.MinimumControlSize; } this._LastShownSize = this.Height; this._LastShownClientSize = this.ClientSize.Height; } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { if( this.Width < this.MinimumControlSize ) { this.Width = this.MinimumControlSize; } this._LastShownSize = this.Width; this._LastShownClientSize = this.ClientSize.Width; } } base.OnResize( e ); return; } //===================================================================== public override DockStyle Dock { get { return base.Dock; } set { // Our size before docking position is changed Size size = this.ClientSize; // Remember the current docking position DockStyle dsOldResize = this._ResizeControl.Dock; // New handle size is dependant on the orientation of the new docking position this._HandleControl.SizeToOrientation( value ); // Modify docking position of child controls based on our new docking position this._ResizeControl.Dock = DockingControl.ResizeStyleFromControlStyle( value ); this._HandleControl.Dock = DockingControl.HandleStyleFromControlStyle( value ); // Now safe to update ourself through base class base.Dock = value; // Change in orientation occured? if( dsOldResize != this._ResizeControl.Dock ) { // Must update our client size to ensure the correct size is used when // the docking position changes. We have to transfer the value that determines // the vector of the control to the opposite dimension if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { size.Height = size.Width; } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { size.Width = size.Height; } this.ClientSize = size; } // Repaint of the our controls _HandleControl.Invalidate(); _ResizeControl.Invalidate(); return; } } //===================================================================== // Static variables defining colours for drawing private static Pen _lightPen = new Pen( Color.FromKnownColor( KnownColor.ControlLightLight ) ); private static Pen _darkPen = new Pen( Color.FromKnownColor( KnownColor.ControlDark ) ); private static Brush _plainBrush = Brushes.LightGray; //===================================================================== // Static properties for read-only access to drawing colours public static Pen LightPen { get { return _lightPen; } } public static Pen DarkPen { get { return _darkPen; } } public static Brush PlainBrush { get { return _plainBrush; } } //===================================================================== public static DockStyle ResizeStyleFromControlStyle( DockStyle ds ) { switch( ds ) { case DockStyle.Left: return DockStyle.Right; case DockStyle.Top: return DockStyle.Bottom; case DockStyle.Right: return DockStyle.Left; case DockStyle.Bottom: return DockStyle.Top; default: // Should never happen! throw new ApplicationException( "Invalid DockStyle argument" ); } } //===================================================================== public static DockStyle HandleStyleFromControlStyle( DockStyle ds ) { switch( ds ) { case DockStyle.Left: return DockStyle.Top; case DockStyle.Top: return DockStyle.Left; case DockStyle.Right: return DockStyle.Top; case DockStyle.Bottom: return DockStyle.Left; default: // Should never happen! throw new ApplicationException( "Invalid DockStyle argument" ); } } } //===================================================================== //===================================================================== // A bar used to resize the parent DockingControl public class DockingControlResizer : UserControl { //===================================================================== private const int FIXED_LENGTH = 6; //===================================================================== private Point _PointStart; private Point _PointLast; private Size _Size; //===================================================================== public DockingControlResizer( DockStyle ds ) { this.Dock = DockingControl.ResizeStyleFromControlStyle( ds ); this.Size = new Size( DockingControlResizer.FIXED_LENGTH, DockingControlResizer.FIXED_LENGTH ); return; } //===================================================================== protected override void OnMouseDown( MouseEventArgs e ) { // Remember the mouse position and client size when capture occured this._PointStart = this._PointLast = PointToScreen( new Point( e.X, e.Y ) ); this._Size = Parent.ClientSize; // Ensure delegates are called base.OnMouseDown( e ); return; } //===================================================================== protected override void OnMouseMove( MouseEventArgs e ) { DockingControl docking_control = (DockingControl)this.Parent; if( docking_control.IsHidden ) { this.Cursor = Cursors.Default; base.OnMouseMove( e ); return; } // Cursor depends on if we a vertical or horizontal resize if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { this.Cursor = Cursors.HSplit; } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { this.Cursor = Cursors.VSplit; } // Can only resize if we have captured the mouse if( this.Capture ) { // Find the new mouse position Point point = PointToScreen( new Point( e.X, e.Y ) ); // Have we actually moved the mouse? if( point != this._PointLast ) { // Update the last processed mouse position this._PointLast = point; // Find delta from original position int xDelta = this._PointLast.X - this._PointStart.X; int yDelta = this._PointLast.Y - this._PointStart.Y; // Resizing from bottom or right of form means inverse movements if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Left) ) { xDelta = -xDelta; yDelta = -yDelta; } // New size is original size plus delta if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { Parent.ClientSize = new Size( this._Size.Width, this._Size.Height + yDelta ); } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { Parent.ClientSize = new Size( this._Size.Width + xDelta, this._Size.Height ); } // Force a repaint of parent so we can see changed appearance Parent.Refresh(); } } // Ensure delegates are called base.OnMouseMove( e ); return; } //===================================================================== protected override void OnPaint( PaintEventArgs pe ) { // Create objects used for drawing Point[] ptLight = new Point[ 2 ]; Point[] ptDark = new Point[ 2 ]; Rectangle rectMiddle = new Rectangle(); // Drawing is relative to client area Size sizeClient = this.ClientSize; // Painting depends on orientation if( (this.Dock == DockStyle.Top) || (this.Dock == DockStyle.Bottom) ) { // Draw as a horizontal bar ptDark[ 1 ].Y = ptDark[ 0 ].Y = sizeClient.Height - 1; ptLight[ 1 ].X = ptDark[ 1 ].X = sizeClient.Width; rectMiddle.Width = sizeClient.Width; rectMiddle.Height = sizeClient.Height - 2; rectMiddle.X = 0; rectMiddle.Y = 1; } else if( (this.Dock == DockStyle.Left) || (this.Dock == DockStyle.Right) ) { // Draw as a vertical bar ptDark[ 1 ].X = ptDark[ 0 ].X = sizeClient.Width - 1; ptLight[ 1 ].Y = ptDark[ 1 ].Y = sizeClient.Height; rectMiddle.Width = sizeClient.Width - 2; rectMiddle.Height = sizeClient.Height; rectMiddle.X = 1; rectMiddle.Y = 0; } // Use colours defined by docking control that is using us pe.Graphics.DrawLine( DockingControl.LightPen, ptLight[ 0 ], ptLight[ 1 ] ); pe.Graphics.DrawLine( DockingControl.DarkPen, ptDark[ 0 ], ptDark[ 1 ] ); pe.Graphics.FillRectangle( DockingControl.PlainBrush, rectMiddle ); // Ensure delegates are called base.OnPaint( pe ); return; } } //===================================================================== //===================================================================== // The visible handle used to drag the parent DockingControl around. public class DockingControlDragger : UserControl { //===================================================================== // Class constants private const int FIXED_LENGTH = 12; private const int MINIMUM_HOT_LENGTH = 20; private const int OFFSET = 3; private const int INSET = 3; //===================================================================== private DockingControl _DockingControl = null; //===================================================================== public DockingControlDragger( DockingControl DockingControl, DockStyle ds ) { this.Cursor = Cursors.Hand; this._DockingControl = DockingControl; this.Dock = DockingControl.HandleStyleFromControlStyle( ds ); SizeToOrientation( ds ); return; } //===================================================================== public void SizeToOrientation( DockStyle ds ) { if( (ds == DockStyle.Top) || (ds == DockStyle.Bottom) ) { this.ClientSize = new Size( DockingControlDragger.FIXED_LENGTH, 0 ); } else if( (ds == DockStyle.Left) || (ds == DockStyle.Right) ) { this.ClientSize = new Size( 0, DockingControlDragger.FIXED_LENGTH ); } return; } //===================================================================== protected override void OnMouseDoubleClick( MouseEventArgs e ) { this._DockingControl.IsHidden = !this._DockingControl.IsHidden; // Ensure delegates are called base.OnMouseDoubleClick( e ); return; } //===================================================================== protected override void OnMouseMove( MouseEventArgs e ) { // Can only move the DockingControl is we have captured the // mouse otherwise the mouse is not currently pressed if( this.Capture ) { // Must have reference to parent object if( null != this._DockingControl ) { this.Cursor = Cursors.SizeAll; // Convert from client point of DockingHandle to client of DockingControl Point screenPoint = PointToScreen( new Point( e.X, e.Y ) ); Point parentPoint = this._DockingControl.HostForm.PointToClient( screenPoint ); // Find the client rectangle of the form int hot_length = 0; Size parentSize = this._DockingControl.HostForm.ClientSize; if( parentSize.Width > parentSize.Height ) { hot_length = (int)(parentSize.Height * 0.25); } else { hot_length = (int)(parentSize.Width * 0.25); } if( hot_length < DockingControlDragger.MINIMUM_HOT_LENGTH ) { hot_length = DockingControlDragger.MINIMUM_HOT_LENGTH; } // New docking position is defaulted to current style DockStyle ds = this._DockingControl.Dock; // Find new docking position if( parentPoint.X < hot_length ) { ds = DockStyle.Left; } else if( parentPoint.Y < hot_length ) { ds = DockStyle.Top; } else if( parentPoint.X >= (parentSize.Width - hot_length) ) { ds = DockStyle.Right; } else if( parentPoint.Y >= (parentSize.Height - hot_length) ) { ds = DockStyle.Bottom; } // Update docking position of DockingControl we are part of if( this._DockingControl.Dock != ds ) this._DockingControl.Dock = ds; } } else { this.Cursor = Cursors.Hand; } // Ensure delegates are called base.OnMouseMove( e ); return; } //===================================================================== protected override void OnPaint( PaintEventArgs pe ) { Size sizeClient = this.ClientSize; Point[] ptLight = new Point[ 4 ]; Point[] ptDark = new Point[ 4 ]; // Depends on orientation if( (this._DockingControl.Dock == DockStyle.Top) || (this._DockingControl.Dock == DockStyle.Bottom) ) { int iBottom = sizeClient.Height - INSET - 1; int iRight = OFFSET + 2; ptLight[ 3 ].X = ptLight[ 2 ].X = ptLight[ 0 ].X = OFFSET; ptLight[ 2 ].Y = ptLight[ 1 ].Y = ptLight[ 0 ].Y = INSET; ptLight[ 1 ].X = OFFSET + 1; ptLight[ 3 ].Y = iBottom; ptDark[ 2 ].X = ptDark[ 1 ].X = ptDark[ 0 ].X = iRight; ptDark[ 3 ].Y = ptDark[ 2 ].Y = ptDark[ 1 ].Y = iBottom; ptDark[ 0 ].Y = INSET; ptDark[ 3 ].X = iRight - 1; } else { int iBottom = OFFSET + 2; int iRight = sizeClient.Width - INSET - 1; ptLight[ 3 ].X = ptLight[ 2 ].X = ptLight[ 0 ].X = INSET; ptLight[ 1 ].Y = ptLight[ 2 ].Y = ptLight[ 0 ].Y = OFFSET; ptLight[ 1 ].X = iRight; ptLight[ 3 ].Y = OFFSET + 1; ptDark[ 2 ].X = ptDark[ 1 ].X = ptDark[ 0 ].X = iRight; ptDark[ 3 ].Y = ptDark[ 2 ].Y = ptDark[ 1 ].Y = iBottom; ptDark[ 0 ].Y = OFFSET; ptDark[ 3 ].X = INSET; } Pen lightPen = DockingControl.LightPen; Pen darkPen = DockingControl.DarkPen; pe.Graphics.DrawLine( lightPen, ptLight[ 0 ], ptLight[ 1 ] ); pe.Graphics.DrawLine( lightPen, ptLight[ 2 ], ptLight[ 3 ] ); pe.Graphics.DrawLine( darkPen, ptDark[ 0 ], ptDark[ 1 ] ); pe.Graphics.DrawLine( darkPen, ptDark[ 2 ], ptDark[ 3 ] ); // Shift coordinates to draw section grab bar if( (this._DockingControl.Dock == DockStyle.Top) || (this._DockingControl.Dock == DockStyle.Bottom) ) { for( int i = 0; i < 4; i++ ) { ptLight[ i ].X += 4; ptDark[ i ].X += 4; } } else { for( int i = 0; i < 4; i++ ) { ptLight[ i ].Y += 4; ptDark[ i ].Y += 4; } } pe.Graphics.DrawLine( lightPen, ptLight[ 0 ], ptLight[ 1 ] ); pe.Graphics.DrawLine( lightPen, ptLight[ 2 ], ptLight[ 3 ] ); pe.Graphics.DrawLine( darkPen, ptDark[ 0 ], ptDark[ 1 ] ); pe.Graphics.DrawLine( darkPen, ptDark[ 2 ], ptDark[ 3 ] ); // Ensure delegates are called base.OnPaint( pe ); return; } } //===================================================================== //===================================================================== // Position the provided control inside a border to give a portrait picture effect. public class DockingControlBorder : UserControl { //===================================================================== private int _BorderWidth = 3; private Control _UserControl = null; //===================================================================== public DockingControlBorder( Control userControl ) { this._UserControl = userControl; Controls.Add( this._UserControl ); return; } //===================================================================== public int BorderWidth { get { return this._BorderWidth; } set { // Only interested if value has changed if( this._BorderWidth != value ) { this._BorderWidth = value; // Force resize of control to get the embedded control // respositioned according to new border width this.Size = this.Size; } return; } } //===================================================================== // Must reposition the embedded control whenever we change size protected override void OnResize( EventArgs e ) { // Can be called before instance constructor if( null != this._UserControl ) { Size sizeClient = this.Size; // Move the user control to enforce the border area we want this._UserControl.Location = new Point( this._BorderWidth, this._BorderWidth ); this._UserControl.Size = new Size( sizeClient.Width - (2 * this._BorderWidth), sizeClient.Height - (2 * this._BorderWidth) ); } // Ensure delegates are called base.OnResize( e ); return; } } }
// // FilePath.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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. // /* * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ namespace Sharpen { using System; using System.Collections.Generic; using System.IO; using System.Threading; internal class FilePath { private readonly string path; private static long tempCounter; public FilePath () { } public FilePath (string path) : this ((string) null, path) { } public FilePath (FilePath other, string child) : this ((string) other, child) { } public FilePath (string other, string child) { if (other == null) { this.path = child; } else { while (!String.IsNullOrEmpty (child) && (child [0] == Path.DirectorySeparatorChar || child [0] == Path.AltDirectorySeparatorChar)) child = child.Substring (1); if (!string.IsNullOrEmpty(other) && other[other.Length - 1] == Path.VolumeSeparatorChar) other += Path.DirectorySeparatorChar; this.path = Path.Combine (other, child); } } public static implicit operator FilePath (string name) { return new FilePath (name); } public static implicit operator string (FilePath filePath) { return filePath == null ? null : filePath.path; } public static implicit operator FilePath (FileInfo file) { return new FilePath(file.FullName); } public static implicit operator FileInfo (FilePath file) { return new FileInfo(file.path); } public override bool Equals (object obj) { FilePath other = obj as FilePath; if (other == null) return false; return GetCanonicalPath () == other.GetCanonicalPath (); } public override int GetHashCode () { return path.GetHashCode (); } public bool CanRead () { return FileHelper.Instance.CanRead (this); } public bool CanWrite () { return FileHelper.Instance.CanWrite (this); } public bool CreateNewFile () { try { File.Open (path, FileMode.CreateNew).Close (); return true; } catch { return false; } } public static FilePath CreateTempFile () { return new FilePath (Path.GetTempFileName ()); } public static FilePath CreateTempFile (string prefix, string suffix) { return CreateTempFile (prefix, suffix, null); } public static FilePath CreateTempFile (string prefix, string suffix, FilePath directory) { string file; if (prefix == null) { throw new ArgumentNullException ("prefix"); } if (prefix.Length < 3) { throw new ArgumentException ("prefix must have at least 3 characters"); } string str = (directory == null) ? Path.GetTempPath () : directory.GetPath (); do { file = Path.Combine (str, prefix + Interlocked.Increment (ref tempCounter) + suffix); } while (File.Exists (file)); new FileOutputStream (file).Close (); return new FilePath (file); } public bool Delete () { try { return FileHelper.Instance.Delete (this); } catch (Exception exception) { Console.WriteLine (exception); return false; } } public void DeleteOnExit () { } public bool Exists () { return FileHelper.Instance.Exists (this); } public FilePath GetAbsoluteFile () { return new FilePath (Path.GetFullPath (path)); } public string GetAbsolutePath () { return Path.GetFullPath (path); } public FilePath GetCanonicalFile () { return new FilePath (GetCanonicalPath ()); } public string GetCanonicalPath () { var p = Path.GetFullPath (path); p.TrimEnd (Path.DirectorySeparatorChar); return p; } public string GetName () { return Path.GetFileName (path); } public FilePath GetParentFile () { return new FilePath (Path.GetDirectoryName (path)); } public string GetPath () { return path; } public bool IsAbsolute () { return Path.IsPathRooted (path); } public bool IsDirectory () { return FileHelper.Instance.IsDirectory (this); } public bool IsFile () { return FileHelper.Instance.IsFile (this); } public long LastModified () { return FileHelper.Instance.LastModified (this); } public long Length () { return FileHelper.Instance.Length (this); } public string[] List () { return List (null); } public string[] List (FilenameFilter filter) { try { if (IsFile ()) return null; List<string> list = new List<string> (); foreach (string filePth in Directory.GetFileSystemEntries (path)) { string fileName = Path.GetFileName (filePth); if ((filter == null) || filter.Accept (this, fileName)) { list.Add (fileName); } } return list.ToArray (); } catch { return null; } } public FilePath[] ListFiles () { try { if (IsFile ()) return null; List<FilePath> list = new List<FilePath> (); foreach (string filePath in Directory.GetFileSystemEntries (path)) { list.Add (new FilePath (filePath)); } return list.ToArray (); } catch { return null; } } static void MakeDirWritable (string dir) { FileHelper.Instance.MakeDirWritable (dir); } static void MakeFileWritable (string file) { FileHelper.Instance.MakeFileWritable (file); } public bool Mkdir () { try { if (Directory.Exists (path)) return false; Directory.CreateDirectory (path); return true; } catch (Exception) { return false; } } public bool Mkdirs () { try { if (Directory.Exists (path)) return false; Directory.CreateDirectory (this.path); return true; } catch { return false; } } public bool RenameTo (FilePath file) { return RenameTo (file.path); } public bool RenameTo (string name) { return FileHelper.Instance.RenameTo (this, name); } public bool SetLastModified (long milis) { return FileHelper.Instance.SetLastModified(this, milis); } public bool SetReadOnly () { return FileHelper.Instance.SetReadOnly (this); } public Uri ToURI () { return new Uri (path); } // Don't change the case of this method, since ngit does reflection on it public bool canExecute () { return FileHelper.Instance.CanExecute (this); } // Don't change the case of this method, since ngit does reflection on it public bool setExecutable (bool exec) { return FileHelper.Instance.SetExecutable (this, exec); } public string GetParent () { string p = Path.GetDirectoryName (path); if (string.IsNullOrEmpty(p) || p == path) return null; else return p; } public override string ToString () { return path; } static internal string pathSeparator { get { return Path.PathSeparator.ToString (); } } static internal char pathSeparatorChar { get { return Path.PathSeparator; } } static internal char separatorChar { get { return Path.DirectorySeparatorChar; } } static internal string separator { get { return Path.DirectorySeparatorChar.ToString (); } } } }
using System; using System.Collections.Generic; using CocosSharp; namespace tests { public class BitmapFontMultiLineAlignment : AtlasDemo { private const string LongSentencesExample = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; private const string LineBreaksExample = "Lorem ipsum dolor\nsit amet\nconsectetur adipisicing elit\nblah\nblah"; private const string MixedExample = "ABC\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt\nDEF"; private const float ArrowsMax = 0.95f; private const float ArrowsMin = 0.7f; private const int LeftAlign = 0; private const int CenterAlign = 1; private const int RightAlign = 2; private const int LongSentences = 0; private const int LineBreaks = 1; private const int Mixed = 2; private static float alignmentItemPadding = 50f; private static float menuItemPaddingCenter = 50f; private CCSprite arrowsBar; private CCSprite arrows; private CCLabelBMFont label; private bool drag; private CCMenuItemFont lastAlignmentItem; private CCMenuItemFont lastSentenceItem; public BitmapFontMultiLineAlignment() { // Register Touch Event var touchListener = new CCEventListenerTouchAllAtOnce(); touchListener.OnTouchesBegan = onTouchesBegan; touchListener.OnTouchesMoved = onTouchesMoved; touchListener.OnTouchesEnded = onTouchesEnded; AddEventListener(touchListener); } protected override void AddedToScene() { base.AddedToScene(); // ask director the the window size var size = VisibleBoundsWorldspace.Size; // create and initialize a Label label = new CCLabelBMFont(LongSentencesExample, "fonts/markerFelt.fnt", size.Width / 3f, CCTextAlignment.Center); arrowsBar = new CCSprite("Images/arrowsBar"); arrows = new CCSprite("Images/arrows"); CCMenuItemFont.FontSize = 20; CCMenuItemFont.FontName = "arial"; var longSentences = new CCMenuItemFont("Long Flowing Sentences", stringChanged); var lineBreaks = new CCMenuItemFont("Short Sentences With Intentional Line Breaks", stringChanged); var mixed = new CCMenuItemFont("Long Sentences Mixed With Intentional Line Breaks", stringChanged); var stringMenu = new CCMenu(longSentences, lineBreaks, mixed); stringMenu.AlignItemsVertically(); longSentences.Color = CCColor3B.Red; lastSentenceItem = longSentences; longSentences.Tag = LongSentences; lineBreaks.Tag = LineBreaks; mixed.Tag = Mixed; CCMenuItemFont.FontSize = 30; var left = new CCMenuItemFont("Left", alignmentChanged); var center = new CCMenuItemFont("Center", alignmentChanged); var right = new CCMenuItemFont("Right", alignmentChanged); var alignmentMenu = new CCMenu(left, center, right); alignmentMenu.AlignItemsHorizontally(alignmentItemPadding); center.Color = CCColor3B.Red; lastAlignmentItem = center; left.Tag = LeftAlign; center.Tag = CenterAlign; right.Tag = RightAlign; // position the label on the center of the screen label.Position = size.Center; arrowsBar.Visible = false; float arrowsWidth = (ArrowsMax - ArrowsMin) * size.Width; arrowsBar.ScaleX = (arrowsWidth / arrowsBar.ContentSize.Width); arrowsBar.Position = new CCPoint(((ArrowsMax + ArrowsMin) / 2) * size.Width, label.Position.Y); snapArrowsToEdge(); stringMenu.Position = new CCPoint(size.Width / 2, size.Height - menuItemPaddingCenter); alignmentMenu.Position = new CCPoint(size.Width / 2, menuItemPaddingCenter + 15); AddChild(label); AddChild(arrowsBar); AddChild(arrows); AddChild(stringMenu); AddChild(alignmentMenu); } private void stringChanged(object sender) { var item = (CCMenuItemFont) sender; item.Color = CCColor3B.Red; lastAlignmentItem.Color = CCColor3B.White; lastAlignmentItem = item; switch (item.Tag) { case LongSentences: label.Text = LongSentencesExample; break; case LineBreaks: label.Text = LineBreaksExample; break; case Mixed: label.Text = MixedExample; break; default: break; } snapArrowsToEdge(); } private void alignmentChanged(object sender) { var item = (CCMenuItemFont) sender; item.Color = CCColor3B.Red; lastAlignmentItem.Color = CCColor3B.White; lastAlignmentItem = item; switch (item.Tag) { case LeftAlign: label.HorizontalAlignment = CCTextAlignment.Left; break; case CenterAlign: label.HorizontalAlignment = CCTextAlignment.Center; break; case RightAlign: label.HorizontalAlignment = CCTextAlignment.Right; break; default: break; } snapArrowsToEdge(); } void onTouchesBegan(List<CCTouch> pTouches, CCEvent touchEvent) { CCTouch touch = pTouches[0]; CCPoint location = touch.Location; if (arrows.BoundingBox.ContainsPoint(location)) { drag = true; arrowsBar.Visible = true; } } void onTouchesEnded(List<CCTouch> pTouches, CCEvent touchEvent) { drag = false; snapArrowsToEdge(); arrowsBar.Visible = false; } void onTouchesMoved(List<CCTouch> pTouches, CCEvent touchEvent) { if (!drag) { return; } CCTouch touch = pTouches[0]; CCPoint location = touch.Location; CCSize winSize = VisibleBoundsWorldspace.Size; arrows.Position = new CCPoint(Math.Max(Math.Min(location.X, ArrowsMax * winSize.Width), ArrowsMin * winSize.Width), arrows.Position.Y); float labelWidth = Math.Abs(arrows.Position.X - label.Position.X); label.Dimensions = new CCSize(labelWidth, 0); } private void snapArrowsToEdge() { arrows.PositionX = label.Position.X + label.ContentSize.Width; arrows.PositionY = label.Position.Y; } public override string title() { return ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Drawing; namespace RubyClr.Tests { public interface ICalc { int Add(int x, int y); int Subtract(int x, int y); } public struct MyPoint { int x_; int y_; public MyPoint(Size s) { x_ = s.Width; y_ = s.Height; } public int X { get { return x_; } set { x_ = value; } } public int Y { get { return y_; } set { y_ = value; } } } public class Person : IComparable { string name_; public Person(string name) { name_ = name; } public string Name { get { return name_; } } public static Person Create() { return new Person("John"); } public static Person Create(string name) { return new Person(name); } public int CompareTo(object other) { return Name.CompareTo(((Person)other).Name); } } public class MarshalerHelper { public MarshalerHelper() { Name = "Hello"; } public virtual int[] GetOneDimensionalArray() { return new int[] { 0, 1, 2, 3 }; } public int[,] GetTwoDimensionalArray() { return new int[,] { {0, 1}, {1, 0} }; } public static int[] StaticGetOneDimensionalArray() { return new int[] { 0, 1, 2, 3 }; } public static int[,] StaticGetTwoDimensionalArray() { return new int[,] { {0, 1}, {1, 0} }; } public static int[,,] StaticGetThreeDimensionalArray() { return new int[,,] { { {0, 1}, {1, 0} }, { {0, 1}, {1, 0} } }; } public static decimal GetDecimal() { return 3.14159m; } public Person GetPerson() { return Person.Create(); } public string Name; public static Point UsePoint(Point p) { p.X += 1; p.Y += 1; return p; } public static Point GetPoint() { return new Point(3, 4); } } public class CallbackTests { public string Name; public event EventHandler Event; public CallbackTests(string name) { Name = name; } public void CallMeBack() { Event(this, EventArgs.Empty); } } public delegate void AddResultEventHandler(object sender, int result); public class DelegateCalc { private int x_; private int y_; public event AddResultEventHandler AddResult; public static event AddResultEventHandler StaticAddResult; public DelegateCalc(int x, int y) { x_ = x; y_ = y; } public void Add() { AddResult(this, x_ + y_); } public static void StaticTest() { StaticAddResult(null, 42); } } public class CoVarianceTarget { public int Method(string value) { return 1; } public string Method(int value) { return "1"; } public static int StaticMethod(string value) { return 1; } public static string StaticMethod(int value) { return "1"; } }; public class ParentClass { public class NestedClass { public class MoreNestedClass { public static int Method() { return 100; } } public static int Method() { return 42; } } } public class PropertyOverloads { private int[] _values; private static int _value; // private static int _overloadedValue; public PropertyOverloads() { _values = new int[10]; } public static int StaticProperty { get { return _value; } set { _value = value; } } // Can't do this from C#, so this C++ code is included here for posterity. // Its corresponding test has also been commented out for posterity. //static property int OverloadedProperty { // int get() { return 1; } //} //static property int OverloadedProperty[int] { // int get(int x) { return _overloadedValue; } // void set(int x, int value) { _overloadedValue = value; } //} public int this[int index] { get { return _values[index]; } set { _values[index] = value; } } public int this[string index] { get { return _values[Convert.ToInt32(index)]; } set { _values[Convert.ToInt32(index)] = value; } } } public class MethodOverloads { public int Method(int p1, object p2) { return 1; } public int Method(string p1, object p2) { return 2; } public int Method(DataColumn p1, object p2) { return 3; } } public class DisposableClass : IDisposable { public static bool Disposed = false; public void BadMethod() { throw new Exception(); } public void GoodMethod() {} public void Dispose() { Disposed = true; } } public class AnotherDisposableClass : IDisposable { public static bool Disposed = false; public void BadMethod() { throw new Exception(); } public void GoodMethod() { } public void Dispose() { Disposed = true; } } public class GenericTestHelper { public static List<String> GetNames() { List<String> names = new List<String>(); names.Add("John"); names.Add("Paul"); names.Add("George"); names.Add("Ringo"); return names; } public static void AddName(String name, List<String> names) { names.Add(name); } } public class DataBinderTestHelper { public static List<String> Bind(IList dataSource) { List<String> result = new List<String>(); foreach (String name in dataSource) result.Add(name); return result; } public static void AddElementsToRubyArray(IList array) { array.Add(3); array.Add(4); } public static void ClearElements(IList array) { array.Clear(); } public static void InsertElementsAtStartOfRubyArray(IList array) { array.Insert(0, 2); array.Insert(0, 1); } public static bool ContainsAOne(IList array) { return array.Contains(1); } public static int GetIndexOfFour(IList array) { return array.IndexOf(4); } public static void RemoveThree(IList array) { array.Remove(3); } public static void RemoveFirstElement(IList array) { array.RemoveAt(0); } public static void RemoveSecondElement(IList array) { array.RemoveAt(1); } public static void AddOneToEachElement(IList array) { for (int i = 0; i < array.Count; ++i) array[i] = (int)array[i] + 1; } } public class ArrayTestHelper { public static void AddOne(Int32[] elements) { for (int i = 0; i < elements.Length; ++i) elements[i] += 1; } } // Generics test targets public class Test { public static Type[] GetTypes() { return new Type[0]; } } public class Test<T> { public static Type[] GetTypes() { return new Type[] { typeof(T) }; } } public class Test<T, U> { public static Type[] GetTypes() { return new Type[] { typeof(T), typeof(U) }; } } public class NullablePropertyTestTargets { private Person _person; public NullablePropertyTestTargets() { _data = "default"; } private String _data; public String Property { get { return _data; } set { _data = value; } } public Person Person { get { return _person; } set { _person = value; } } public IComparable GetInterface() { return new Person("Steve"); } public IComparable GetNullInterface() { return null; } } public class DateTimeTestTargets { static DateTime _now; public static DateTime GetCurrentDate() { _now = new DateTime(1000); // DateTime.Now; return _now; } public static bool CompareWithNow(DateTime date) { return _now == date; } } public class ActiveRecordTestHelper { } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.Util; namespace Encog.MathUtil.Matrices.Decomposition { /// <summary> /// LU Decomposition. /// /// For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n unit /// lower triangular matrix L, an n-by-n upper triangular matrix U, and a /// permutation vector piv of length m so that A(piv,:) = L*U. If m less than n, then L /// is m-by-m and U is m-by-n. /// /// The LU decompostion with pivoting always exists, even if the matrix is /// singular, so the constructor will never fail. The primary use of the LU /// decomposition is in the solution of square systems of simultaneous linear /// equations. This will fail if isNonsingular() returns false. /// /// This file based on a class from the public domain JAMA package. /// http://math.nist.gov/javanumerics/jama/ /// </summary> public class LUDecomposition { /// <summary> /// Array for internal storage of decomposition. /// </summary> private readonly double[][] LU; /// <summary> /// column dimension. /// </summary> private readonly int m; /// <summary> /// row dimension. /// </summary> private readonly int n; /// <summary> /// Internal storage of pivot vector. /// </summary> private readonly int[] piv; /// <summary> /// pivot sign. /// </summary> private readonly int pivsign; /// <summary> /// LU Decomposition /// </summary> /// <param name="A">Rectangular matrix</param> public LUDecomposition(Matrix A) { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. LU = A.GetArrayCopy(); m = A.Rows; n = A.Cols; piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; double[] LUrowi; var LUcolj = new double[m]; // Outer loop. for (int j = 0; j < n; j++) { // Make a copy of the j-th column to localize references. for (int i = 0; i < m; i++) { LUcolj[i] = LU[i][j]; } // Apply previous transformations. for (int i = 0; i < m; i++) { LUrowi = LU[i]; // Most of the time is spent in the following dot product. int kmax = Math.Min(i, j); double s = 0.0; for (int k = 0; k < kmax; k++) { s += LUrowi[k]*LUcolj[k]; } LUrowi[j] = LUcolj[i] -= s; } // Find pivot and exchange if necessary. int p = j; for (int i = j + 1; i < m; i++) { if (Math.Abs(LUcolj[i]) > Math.Abs(LUcolj[p])) { p = i; } } if (p != j) { for (int k = 0; k < n; k++) { double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; } int temp = piv[p]; piv[p] = piv[j]; piv[j] = temp; pivsign = -pivsign; } // Compute multipliers. if (j < m & LU[j][j] != 0.0) { for (int i = j + 1; i < m; i++) { LU[i][j] /= LU[j][j]; } } } } /// <summary> /// Is the matrix nonsingular? /// </summary> public bool IsNonsingular { get { for (int j = 0; j < n; j++) { if (LU[j][j] == 0) return false; } return true; } } /// <summary> /// Return lower triangular factor /// </summary> public Matrix L { get { var x = new Matrix(m, n); double[][] l = x.Data; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { l[i][j] = LU[i][j]; } else if (i == j) { l[i][j] = 1.0; } else { l[i][j] = 0.0; } } } return x; } } /** * Return upper triangular factor * * @return U */ public Matrix U { get { var x = new Matrix(n, n); double[][] u = x.Data; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i <= j) { u[i][j] = LU[i][j]; } else { u[i][j] = 0.0; } } } return x; } } /// <summary> /// Return pivot permutation vector /// </summary> public int[] Pivot { get { var p = new int[m]; for (int i = 0; i < m; i++) { p[i] = piv[i]; } return p; } } /// <summary> /// Return pivot permutation vector as a one-dimensional double array /// </summary> public double[] DoublePivot { get { var vals = new double[m]; for (int i = 0; i < m; i++) { vals[i] = piv[i]; } return vals; } } /// <summary> /// Determinant /// </summary> /// <returns>det(A)</returns> public double Det() { if (m != n) { throw new MatrixError("Matrix must be square."); } double d = pivsign; for (int j = 0; j < n; j++) { d *= LU[j][j]; } return d; } /// <summary> /// Solve A*X = B /// </summary> /// <param name="B">A Matrix with as many rows as A and any number of columns.</param> /// <returns>so that L*U*X = B(piv,:)</returns> public Matrix Solve(Matrix B) { if (B.Rows != m) { throw new MatrixError( "Matrix row dimensions must agree."); } if (!IsNonsingular) { throw new MatrixError("Matrix is singular."); } // Copy right hand side with pivoting int nx = B.Cols; Matrix Xmat = B.GetMatrix(piv, 0, nx - 1); double[][] X = Xmat.Data; // Solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k + 1; i < n; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } // Solve U*X = Y; for (int k = n - 1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= LU[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } return Xmat; } /// <summary> /// Solve the matrix for a 1d array. /// </summary> /// <param name="value_ren">The value to solve for.</param> /// <returns>The solved matrix.</returns> public double[] Solve(double[] value_ren) { if (value_ren == null) { throw new MatrixError("value"); } if (value_ren.Length != LU.Length) { throw new MatrixError("Invalid matrix dimensions."); } if (!IsNonsingular) { throw new MatrixError("Matrix is singular"); } // Copy right hand side with pivoting int count = value_ren.Length; var b = new double[count]; for (int i = 0; i < b.Length; i++) { b[i] = value_ren[piv[i]]; } int rows = LU[0].Length; int columns = LU[0].Length; double[][] lu = LU; // Solve L*Y = B var X = new double[count]; for (int i = 0; i < rows; i++) { X[i] = b[i]; for (int j = 0; j < i; j++) { X[i] -= lu[i][j]*X[j]; } } // Solve U*X = Y; for (int i = rows - 1; i >= 0; i--) { // double sum = 0.0; for (int j = columns - 1; j > i; j--) { X[i] -= lu[i][j]*X[j]; } X[i] /= lu[i][i]; } return X; } /// <summary> /// Solves a set of equation systems of type <c>A * X = B</c>. /// </summary> /// <returns>Matrix <c>X</c> so that <c>L * U * X = B</c>.</returns> public double[][] Inverse() { if (!IsNonsingular) { throw new MatrixError("Matrix is singular"); } int rows = LU.Length; int columns = LU[0].Length; int count = rows; double[][] lu = LU; double[][] X = EngineArray.AllocateDouble2D(rows, columns); for (int i = 0; i < rows; i++) { int k = piv[i]; X[i][k] = 1.0; } // Solve L*Y = B(piv,:) for (int k = 0; k < columns; k++) { for (int i = k + 1; i < columns; i++) { for (int j = 0; j < count; j++) { X[i][j] -= X[k][j]*lu[i][k]; } } } // Solve U*X = Y; for (int k = columns - 1; k >= 0; k--) { for (int j = 0; j < count; j++) { X[k][j] /= lu[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < count; j++) { X[i][j] -= X[k][j]*lu[i][k]; } } } return X; } } }
using System; using System.Xml; using System.IO; using System.Collections; using System.Diagnostics; using System.Threading; using System.Text; using System.Text.RegularExpressions; namespace Tools.XmlConfigMerge { // Adapted from: http://www.codeproject.com/Articles/7406/XmlConfigMerge-Merge-config-file-settings /// <summary> /// Manages config file reading and writing, and optional merging of two config files. /// </summary> [Serializable] public class ConfigFileManager { public ConfigFileManager(string masterConfigPath) : this(masterConfigPath, null) { } public ConfigFileManager(string masterConfigPath, string mergeFromConfigPath) : this(masterConfigPath, mergeFromConfigPath, false) { // makeMergeFromConfigPathTheSavePath } /// <summary> /// /// </summary> /// <param name="masterConfigPath"></param> /// <param name="mergeFromConfigPath"></param> /// <param name="makeMergeFromConfigPathTheSavePath"></param> /// <exception cref="Exception">if mergeFromConfigPath is specified but does not exist, and makeMergeFromConfigPathTheSavePath is false</exception> public ConfigFileManager(string masterConfigPath, string mergeFromConfigPath, bool makeMergeFromConfigPathTheSavePath) { _masterConfigPath = masterConfigPath; _configPath = masterConfigPath; _fromLastInstallConfigPath = mergeFromConfigPath; if (mergeFromConfigPath != null && ( ! File.Exists(mergeFromConfigPath) ) && ! makeMergeFromConfigPathTheSavePath) { throw new ApplicationException("Specified mergeFromConfigPath does not exist: " + mergeFromConfigPath); } try { using (FileStream rd = new FileStream(ConfigPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) ) { _xmlDocument.Load(rd); } } catch (Exception ex) { throw new ApplicationException("Could not open '" + ConfigPath + "': " + ex.Message); } if (mergeFromConfigPath != null && File.Exists(mergeFromConfigPath) ) { Debug.WriteLine("Merging from " + mergeFromConfigPath); //Merge approach: // x Use from-last-install config as base // x Merge in any non-existing keyvalue pairs from distrib-config // x Use this merged config, and leave the last-install-config file in place for reference //Merge, preserving any comments from distrib-one only XmlDocument reInstallConfig = new XmlDocument(); try { reInstallConfig.Load(mergeFromConfigPath); } catch (Exception ex) { _fromLastInstallConfigPath = null; throw new ApplicationException("Could not read existing config '" + mergeFromConfigPath + "': " + ex.Message, ex); } UpdateExistingElementsAndAttribs(reInstallConfig, _xmlDocument); } if (makeMergeFromConfigPathTheSavePath) { _configPath = _fromLastInstallConfigPath; } } private string _configPath; public string ConfigPath { get { return _configPath; } } private string _masterConfigPath; public string MasterConfigPath { get { return _masterConfigPath; } } private string _fromLastInstallConfigPath = null; public string FromLastInstallConfigPath { get { return _fromLastInstallConfigPath; } } public bool FromLastInstallConfigPathExists() { if (FromLastInstallConfigPath == null) { return false; } return File.Exists(FromLastInstallConfigPath); } public string GetXPathValue(string xPath) { XmlNode node = XmlDocument.SelectSingleNode(xPath); if (node == null) { return null; } return node.InnerText; } public string[] ReplaceXPathValues(string xPath, string replaceWith) { return ReplaceXPathValues(xPath, replaceWith, null); } /// <summary> /// Search and replace on one or more specified values as specified by a single xpath expressino /// </summary> /// <param name="xPath"></param> /// <param name="replaceWith"></param> /// <param name="regexPattern">Optionally specify a regex pattern to search within the found values. /// If a single () group is found within this expression, only this portion is replaced.</param> /// <returns></returns> /// <exception cref="ApplicationException">When no nodes match xpath-expression and no regexPattern is specified (is null), /// and can't auto-create the node (is not an appSettings expression).</exception> public string[] ReplaceXPathValues(string xPath, string replaceWith, Regex regexPattern) { if (xPath == null || xPath == string.Empty) { throw new ApplicationException("Required xPath is blank or null"); } if (replaceWith == null) { throw new ApplicationException("Required replaceWith is null"); } ArrayList ret = new ArrayList(); XmlNodeList nodes = _xmlDocument.SelectNodes(xPath); //Check if no existing nodes match if (nodes.Count == 0) { if (regexPattern != null) { return (string[] ) ret.ToArray(typeof(string) ); //no error or auto-create attempt when a pattern was specified } //Check special case of fully-qualified appSetting key/value pair Regex regex = new Regex(@"/configuration/appSettings/add\[\@key=['""](.*)['""]\]/\@value"); Match match = regex.Match(xPath); if ( ! match.Success) { throw new ApplicationException("'" + xPath + "' does not match any nodes, and may not be auto-created since it is not of form '" + regex.ToString() + "'"); //is an error when no pattern specified and can't auto-create } //Auto create this one string key = match.Result("$1"); SetKeyValue(key, ""); //Value is set below (unless no regex match) ret.Add("add/@key" + " created for key '" + key + "'"); nodes = _xmlDocument.SelectNodes(xPath); } //Proceed with replacements bool replacedOneOrMore = false; foreach (XmlNode node in nodes) { string replText = null; if (regexPattern != null) { Match match = regexPattern.Match(node.InnerText); if (match.Success) { //Determine if group match applies switch (match.Groups.Count) { case 1: replText = regexPattern.Replace(node.InnerText, replaceWith); break; case 2: replText = string.Empty; if (match.Groups[2 - 1].Index > 0) { replText += node.InnerText.Substring(0, match.Groups[2 - 1].Index); } replText += replaceWith; int firstPostGroupPos = match.Groups[2 - 1].Index + match.Groups[2 - 1].Length; if (node.InnerText.Length > firstPostGroupPos) { replText += node.InnerText.Substring(firstPostGroupPos); } break; default: throw new ApplicationException("> 1 regex replace group not supported (" + match.Groups.Count + ") for regex expr: '" + regexPattern.ToString() + "'"); } } } else { replText = replaceWith; } if (replText != null) { replacedOneOrMore = true; node.InnerText = replText; if (node is XmlAttribute) { XmlAttribute keyAttrib = ( (XmlAttribute) node).OwnerElement.Attributes["key"]; if (keyAttrib == null) { ret.Add(( (XmlAttribute) node).OwnerElement.Name + "/@" + node.Name + " set to '" + replText + "'"); } else { ret.Add(( (XmlAttribute) node).OwnerElement.Name + "[@key='" + keyAttrib.InnerText + "']/@" + node.Name + " set to '" + replText + "'"); } } else { ret.Add(node.Name + " set to '" + replText); } } } if ( ! replacedOneOrMore) { ret.Add("No values matched replace pattern '" + regexPattern.ToString() + "' for '" + xPath + "'"); } return (string[] ) ret.ToArray(typeof(string) ); } private XmlDocument _xmlDocument = new XmlDocument(); public XmlDocument XmlDocument { get { return _xmlDocument; } } public virtual void Save() { Save(ConfigPath); } public virtual void Save(string saveAsName) { //Ensure not set r/o if (File.Exists(saveAsName)) { ClearSpecifiedFileAttributes(saveAsName, FileAttributes.ReadOnly); } _xmlDocument.Save(saveAsName); } public string GetKeyValue(string key) { if (key == null || key == string.Empty) { throw new ApplicationException("Required key is blank or null"); } XmlNode node = GetKeyValueNode(key); if (node == null) { return null; } return node.Attributes["value"].InnerText; } private XmlNode GetKeyValueNode(string key) { XmlNodeList nodes = XmlDocument.SelectNodes("/configuration/appSettings/add[@key='" + key + "']"); if (nodes.Count == 0) { return null; } return nodes[nodes.Count - 1]; //Return last (to be compat with System.Configuration behavior) } public Hashtable GetAllKeyValuePairs() { Hashtable ret = new Hashtable(); foreach (XmlNode node in XmlDocument.SelectNodes("/configuration/appSettings/add")) { ret.Add(node.Attributes["key"].InnerText, node.Attributes["value"].InnerText); } return ret; } public void SetKeyValue(string key, string value) { if (key == null || key == string.Empty) { throw new ApplicationException("Required key is blank or null"); } if (value == null) { throw new ApplicationException("Required value is null"); } XmlNode node = GetKeyValueNode(key); if (node == null) { XmlNode top = XmlDocument.SelectSingleNode("/configuration"); if (top == null) { top = XmlDocument.AppendChild(XmlDocument.CreateElement("configuration") ); } XmlNode app = top.SelectSingleNode("appSettings"); if (app == null) { app = top.AppendChild(XmlDocument.CreateElement("appSettings") ); } node = app.AppendChild(XmlDocument.CreateElement("add") ); node.Attributes.Append(XmlDocument.CreateAttribute("key") ).InnerText = key; node.Attributes.Append(XmlDocument.CreateAttribute("value") ); } node.Attributes["value"].InnerText = value; } private void ClearSpecifiedFileAttributes(string path, FileAttributes fileAttributes) { File.SetAttributes(path, File.GetAttributes(path) & (FileAttributes) ( (FileAttributes) 0x7FFFFFFF - fileAttributes) ); } /// <summary> /// Merge element and attribute values from one xml doc to another. /// </summary> /// <param name="fromXdoc"></param> /// <param name="toXdoc"></param> /// <remarks> /// Multiple same-named peer elements, are merged in the ordinal order they appear. /// </remarks> public static void UpdateExistingElementsAndAttribs(XmlDocument fromXdoc, XmlDocument toXdoc) { UpdateExistingElementsAndAttribsRecurse(fromXdoc.ChildNodes, toXdoc); } private static void UpdateExistingElementsAndAttribsRecurse(XmlNodeList fromNodes, XmlNode toParentNode) { int iSameElement = 0; XmlNode lastElement = null; foreach (XmlNode node in fromNodes) { if (node.NodeType != XmlNodeType.Element) { continue; } if (lastElement != null && node.Name == lastElement.Name && node.NamespaceURI == lastElement.NamespaceURI) { iSameElement++; } else { iSameElement = 0; } lastElement = node; XmlNode toNode; if (node.Attributes["key"] != null) { toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, node.Attributes["key"] ); } else if (node.Attributes["name"] != null) { toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, node.Attributes["name"] ); } else if (node.Attributes["type"] != null) { toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, node.Attributes["type"] ); } else { toNode = SelectSingleNodeMatchingNamespaceURI(toParentNode, node, iSameElement); } if (toNode == null) { if (node == null) { throw new ApplicationException("node == null"); } if (node.Name == null) { throw new ApplicationException("node.Name == null"); } if (toParentNode == null) { throw new ApplicationException("toParentNode == null"); } if (toParentNode.OwnerDocument == null) { throw new ApplicationException("toParentNode.OwnerDocument == null"); } Debug.WriteLine("app: " + toParentNode.Name + "/" + node.Name); if (node.ParentNode.Name != toParentNode.Name) { throw new ApplicationException("node.ParentNode.Name != toParentNode.Name: " + node.ParentNode.Name + " !=" + toParentNode.Name); } try { toNode = toParentNode.AppendChild(toParentNode.OwnerDocument.CreateElement(node.Name) ); } catch (Exception ex) { throw new ApplicationException("ex during toNode = toParentNode.AppendChild(: " + ex.Message); } } //Copy element content if any XmlNode textEl = GetTextElement(node); if (textEl != null) { toNode.InnerText = textEl.InnerText; } //Copy attribs if any foreach (XmlAttribute attrib in node.Attributes) { XmlAttribute toAttrib = toNode.Attributes[attrib.Name]; if (toAttrib == null) { Debug.WriteLine("attr: " + toNode.Name + "@" + attrib.Name); toAttrib = toNode.Attributes.Append(toNode.OwnerDocument.CreateAttribute(attrib.Name)); } toAttrib.InnerText = attrib.InnerText; } ((XmlElement) toNode).IsEmpty = ! toNode.HasChildNodes; //Ensure no endtag when not needed UpdateExistingElementsAndAttribsRecurse(node.ChildNodes, toNode); } } private static XmlNode GetTextElement(XmlNode node) { foreach (XmlNode subNode in node.ChildNodes) { if (subNode.NodeType == XmlNodeType.Text) { return subNode; } } return null; } private static XmlNode SelectSingleNodeMatchingNamespaceURI(XmlNode node, XmlNode nodeName) { return SelectSingleNodeMatchingNamespaceURI(node, nodeName, null); } private static XmlNode SelectSingleNodeMatchingNamespaceURI(XmlNode node, XmlNode nodeName, int iSameElement) { return SelectSingleNodeMatchingNamespaceURI(node, nodeName, null, iSameElement); } private static XmlNode SelectSingleNodeMatchingNamespaceURI(XmlNode node, XmlNode nodeName, XmlAttribute keyAttrib) { return SelectSingleNodeMatchingNamespaceURI(node, nodeName, keyAttrib, 0); } private static Regex _typeParsePattern = new Regex(@"([^,]+),"); private static XmlNode SelectSingleNodeMatchingNamespaceURI(XmlNode node, XmlNode nodeName, XmlAttribute keyAttrib, int iSameElement) { XmlNode matchNode = null; int iNodeNameElements = 0 - 1; foreach (XmlNode subNode in node.ChildNodes) { if (subNode.Name != nodeName.Name || subNode.NamespaceURI != nodeName.NamespaceURI) { continue; } iNodeNameElements++; if (keyAttrib == null) { if (iNodeNameElements == iSameElement) { return subNode; } else { continue; } } if (subNode.Attributes[keyAttrib.Name] != null && subNode.Attributes[keyAttrib.Name].InnerText == keyAttrib.InnerText) { matchNode = subNode; } else if (keyAttrib != null && keyAttrib.Name == "type") { Match subNodeMatch = _typeParsePattern.Match(subNode.Attributes[keyAttrib.Name].InnerText); Match keyAttribMatch = _typeParsePattern.Match(keyAttrib.InnerText); if (subNodeMatch.Success && keyAttribMatch.Success && subNodeMatch.Result("$1") == keyAttribMatch.Result("$1") ) { matchNode = subNode; // Have type class match (ignoring assembly-name suffix) } } } return matchNode; //return last match if > 1 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing.Drawing2D { /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle"]/*' /> /// <devdoc> /// Specifies the different patterns available /// for <see cref='System.Drawing.Drawing2D.HatchBrush'/> objects. /// </devdoc> public enum HatchStyle { /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Horizontal"]/*' /> /// <devdoc> /// <para> /// A pattern of horizontal lines. /// </para> /// </devdoc> Horizontal = 0, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Vertical"]/*' /> /// <devdoc> /// <para> /// A pattern of vertical lines. /// </para> /// </devdoc> Vertical = 1, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.ForwardDiagonal"]/*' /> /// <devdoc> /// <para> /// A pattern of lines on a diagonal from top-left to bottom-right. /// </para> /// </devdoc> ForwardDiagonal = 2, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.BackwardDiagonal"]/*' /> /// <devdoc> /// A pattern of lines on a diagonal from /// top-right to bottom-left. /// </devdoc> BackwardDiagonal = 3, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Cross"]/*' /> /// <devdoc> /// <para> /// A pattern of criss-cross horizontal and vertical lines. /// </para> /// </devdoc> Cross = 4, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DiagonalCross"]/*' /> /// <devdoc> /// <para> /// A pattern of criss-cross diagonal lines. /// </para> /// </devdoc> DiagonalCross = 5, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent05"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent05 = 6, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent10"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent10 = 7, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent20"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent20 = 8, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent25"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent25 = 9, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent30"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent30 = 10, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent40"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent40 = 11, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent50"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent50 = 12, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent60"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent60 = 13, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent70"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent70 = 14, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent75"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent75 = 15, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent80"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent80 = 16, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Percent90"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Percent90 = 17, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LightDownwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LightDownwardDiagonal = 18, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LightUpwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LightUpwardDiagonal = 19, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DarkDownwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DarkDownwardDiagonal = 20, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DarkUpwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DarkUpwardDiagonal = 21, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.WideDownwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> WideDownwardDiagonal = 22, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.WideUpwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> WideUpwardDiagonal = 23, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LightVertical"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LightVertical = 24, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LightHorizontal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LightHorizontal = 25, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.NarrowVertical"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> NarrowVertical = 26, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.NarrowHorizontal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> NarrowHorizontal = 27, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DarkVertical"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DarkVertical = 28, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DarkHorizontal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DarkHorizontal = 29, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DashedDownwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DashedDownwardDiagonal = 30, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DashedUpwardDiagonal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DashedUpwardDiagonal = 31, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DashedHorizontal"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DashedHorizontal = 32, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DashedVertical"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DashedVertical = 33, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.SmallConfetti"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> SmallConfetti = 34, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LargeConfetti"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LargeConfetti = 35, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.ZigZag"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> ZigZag = 36, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Wave"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Wave = 37, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DiagonalBrick"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DiagonalBrick = 38, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.HorizontalBrick"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> HorizontalBrick = 39, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Weave"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Weave = 40, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Plaid"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Plaid = 41, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Divot"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Divot = 42, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DottedGrid"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DottedGrid = 43, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.DottedDiamond"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> DottedDiamond = 44, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Shingle"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Shingle = 45, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Trellis"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Trellis = 46, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Sphere"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Sphere = 47, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.SmallGrid"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> SmallGrid = 48, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.SmallCheckerBoard"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> SmallCheckerBoard = 49, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LargeCheckerBoard"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LargeCheckerBoard = 50, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.OutlinedDiamond"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> OutlinedDiamond = 51, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.SolidDiamond"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> SolidDiamond = 52, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.LargeGrid"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> LargeGrid = Cross, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Min"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Min = Horizontal, /// <include file='doc\HatchStyle.uex' path='docs/doc[@for="HatchStyle.Max"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> Max = LargeGrid }; }
using System; using OpenTK; namespace Game.Model { public class Spider : IControlledCreature { #region Constants and Fields private const float MaxPitch = 1; private readonly World world; private Basis animationEnd; private float animationProgress; private Basis animationStart; private Vector3 contactPointNormal = new Vector3(0, 0, 1); private bool isAimated; private float pitch; private Basis position = new Basis(); private float speed = 9.0f; #endregion #region Constructors and Destructors public Spider(World world, Vector3 startPosition) { this.world = world; this.position.Origin = startPosition; this.UpdateBasis(); } #endregion #region Public Properties public Vector3 LookDirection { get { var b = this.Position.Clone(); b.Rotate(b.Y, this.Pitch); return b.X; } } public bool IsInMove { get; set; } public int Score { get; set; } public string Name { get; set; } public float Pitch { get { return this.pitch; } set { this.pitch = Math.Max(-MaxPitch, Math.Min(MaxPitch, value)); } } public Basis Position { get { return this.position; } private set { this.position = value; } } #endregion #region Public Methods and Operators public void Move(Vector3 direction, float stepScale) { if (this.isAimated) { return; } if (stepScale == 0) { return; } if (stepScale < 0) { direction = -direction; stepScale = -stepScale; } stepScale *= this.speed; // calculate direction in wold coordinates direction = (this.Position.X * direction.X + this.Position.Y * direction.Y + this.Position.Z * direction.Z); // calculate direction according to cuurent contact normal direction = direction - this.contactPointNormal * Vector3.Dot(direction, this.contactPointNormal); direction.Normalize(); var prevPos = this.Position.Origin; var newPos = prevPos + direction * stepScale; Vector3 n; if (this.world.TraceBox(prevPos, ref newPos, out n)) { this.StartAnimation(newPos, n); return; } prevPos = newPos; newPos = prevPos - this.contactPointNormal * 0.5f; if (!this.world.TraceBox(prevPos, ref newPos, out n)) { prevPos = newPos; newPos = prevPos - direction; if (this.world.TraceBox(prevPos, ref newPos, out n)) { this.StartAnimation(newPos, n); } return; } this.Position.Origin = prevPos; } public void Rotate(float angle) { if (this.isAimated) { return; } this.Position.Rotate(this.Position.Z, angle * 2.0f); } public void Update(TimeSpan dt) { if (this.isAimated) { this.animationProgress = (float)Math.Min(1, this.animationProgress + dt.TotalSeconds * this.speed); var kStart = (1 - this.animationProgress); var kEnd = (this.animationProgress); this.Position.Origin = this.animationStart.Origin * kStart + this.animationEnd.Origin * kEnd; var n = this.animationStart.Z * kStart + this.animationEnd.Z * kEnd; this.pitch = this.pitch * 0.7f; var x = Vector3.Cross(this.Position.Y, n); if (float.IsNaN(x.X) || x.LengthSquared <= 1e-6) { var y = Vector3.Cross(n, this.Position.X); x = Vector3.Cross(y, n); } this.Position.SetRotation(x, n); if (this.animationProgress >= 1.0f) { this.contactPointNormal = this.animationEnd.Z; this.isAimated = false; } } } #endregion #region Methods private bool StartAnimation(Vector3 newPos, Vector3 n) { var animateToPos = newPos + n * 0.5f; animateToPos.X = 0.5f + (float)Math.Floor(animateToPos.X); animateToPos.Y = 0.5f + (float)Math.Floor(animateToPos.Y); animateToPos.Z = 0.5f + (float)Math.Floor(animateToPos.Z); this.animationStart = this.Position.Clone(); var x = Vector3.Cross(this.Position.Y, n); if (float.IsNaN(x.X) || x.LengthSquared <= 1e-6) { var y= Vector3.Cross(n, this.Position.X); x = Vector3.Cross(y, n); } this.animationEnd = new Basis(animateToPos, x.Normalized(), n); this.animationProgress = 0; if (!this.world.IsEmpty(animateToPos)) { return true; } this.isAimated = true; return false; } private void UpdateBasis() { } #endregion } }