context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osuTK.Graphics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Rulesets.Objects.Drawables; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using osu.Game.Rulesets.Mania.UI.Components; using osu.Game.Rulesets.UI.Scrolling; using osuTK; namespace osu.Game.Rulesets.Mania.UI { public class Column : ScrollingPlayfield, IKeyBindingHandler<ManiaAction>, IHasAccentColour { public const float COLUMN_WIDTH = 80; private const float special_column_width = 70; /// <summary> /// The index of this column as part of the whole playfield. /// </summary> public readonly int Index; public readonly Bindable<ManiaAction> Action = new Bindable<ManiaAction>(); private readonly ColumnBackground background; private readonly ColumnKeyArea keyArea; private readonly ColumnHitObjectArea hitObjectArea; internal readonly Container TopLevelContainer; private readonly Container explosionContainer; public Column(int index) { Index = index; RelativeSizeAxes = Axes.Y; Width = COLUMN_WIDTH; background = new ColumnBackground { RelativeSizeAxes = Axes.Both }; Container hitTargetContainer; InternalChildren = new[] { // For input purposes, the background is added at the highest depth, but is then proxied back below all other elements background.CreateProxy(), hitTargetContainer = new Container { Name = "Hit target + hit objects", RelativeSizeAxes = Axes.Both, Children = new Drawable[] { hitObjectArea = new ColumnHitObjectArea(HitObjectContainer) { RelativeSizeAxes = Axes.Both, }, explosionContainer = new Container { Name = "Hit explosions", RelativeSizeAxes = Axes.Both, } } }, keyArea = new ColumnKeyArea { RelativeSizeAxes = Axes.X, Height = ManiaStage.HIT_TARGET_POSITION, }, background, TopLevelContainer = new Container { RelativeSizeAxes = Axes.Both } }; TopLevelContainer.Add(explosionContainer.CreateProxy()); Direction.BindValueChanged(dir => { hitTargetContainer.Padding = new MarginPadding { Top = dir.NewValue == ScrollingDirection.Up ? ManiaStage.HIT_TARGET_POSITION : 0, Bottom = dir.NewValue == ScrollingDirection.Down ? ManiaStage.HIT_TARGET_POSITION : 0, }; explosionContainer.Padding = new MarginPadding { Top = dir.NewValue == ScrollingDirection.Up ? NotePiece.NOTE_HEIGHT / 2 : 0, Bottom = dir.NewValue == ScrollingDirection.Down ? NotePiece.NOTE_HEIGHT / 2 : 0 }; keyArea.Anchor = keyArea.Origin = dir.NewValue == ScrollingDirection.Up ? Anchor.TopLeft : Anchor.BottomLeft; }, true); } public override Axes RelativeSizeAxes => Axes.Y; private bool isSpecial; public bool IsSpecial { get => isSpecial; set { if (isSpecial == value) return; isSpecial = value; Width = isSpecial ? special_column_width : COLUMN_WIDTH; } } private Color4 accentColour; public Color4 AccentColour { get => accentColour; set { if (accentColour == value) return; accentColour = value; background.AccentColour = value; keyArea.AccentColour = value; hitObjectArea.AccentColour = value; } } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); dependencies.CacheAs<IBindable<ManiaAction>>(Action); return dependencies; } /// <summary> /// Adds a DrawableHitObject to this Playfield. /// </summary> /// <param name="hitObject">The DrawableHitObject to add.</param> public override void Add(DrawableHitObject hitObject) { hitObject.AccentColour.Value = AccentColour; hitObject.OnNewResult += OnNewResult; HitObjectContainer.Add(hitObject); } public override bool Remove(DrawableHitObject h) { if (!base.Remove(h)) return false; h.OnNewResult -= OnNewResult; return true; } internal void OnNewResult(DrawableHitObject judgedObject, JudgementResult result) { if (!result.IsHit || !judgedObject.DisplayResult || !DisplayJudgements.Value) return; explosionContainer.Add(new HitExplosion(judgedObject.AccentColour.Value, judgedObject is DrawableHoldNoteTick) { Anchor = Direction.Value == ScrollingDirection.Up ? Anchor.TopCentre : Anchor.BottomCentre, Origin = Anchor.Centre }); } public bool OnPressed(ManiaAction action) { if (action != Action.Value) return false; var nextObject = HitObjectContainer.AliveObjects.FirstOrDefault(h => h.HitObject.StartTime > Time.Current) ?? // fallback to non-alive objects to find next off-screen object HitObjectContainer.Objects.FirstOrDefault(h => h.HitObject.StartTime > Time.Current) ?? HitObjectContainer.Objects.LastOrDefault(); nextObject?.PlaySamples(); return true; } public void OnReleased(ManiaAction action) { } public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) // This probably shouldn't exist as is, but the columns in the stage are separated by a 1px border => DrawRectangle.Inflate(new Vector2(ManiaStage.COLUMN_SPACING / 2, 0)).Contains(ToLocalSpace(screenSpacePos)); } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using Facebook.MiniJSON; using SimpleJSON; public class DynamicsHandler : MonoBehaviour { public static DynamicsHandler Instance { get; private set; } public float GearFriction { get; set; } public int GearShapeType { get; set; } public int GameTime { get; set; } public string Split1Name { get; set; } private GameMatchData m_matchData; public GameMatchData getMatchData() { return m_matchData; } /* ----------------------------------------------------- Awake ----------------------------------------------------- */ void Awake () { Debug.Log ("DynamicsHandler Awake"); if (Instance != null && Instance != this) { //destroy other instances Destroy (gameObject); } else if( Instance == null ) { } Instance = this; DontDestroyOnLoad(gameObject); } /* ----------------------------------------------------- Start ----------------------------------------------------- */ void Start () { Debug.Log ("DynamicsHandler Start"); GearFriction = 0.98f; GearShapeType = 5; GameTime = 7; Split1Name = "none"; //get stored dynamic values if (PlayerPrefs.HasKey ("gearfriction")) { GearFriction = PlayerPrefs.GetFloat("gearfriction"); } if (PlayerPrefs.HasKey ("geartype")) { GearShapeType = PlayerPrefs.GetInt("geartype"); } if (PlayerPrefs.HasKey ("gametime")) { GameTime = PlayerPrefs.GetInt("gametime"); } if (PlayerPrefs.HasKey ("splitgroup")) { Split1Name = PlayerPrefs.GetString("splitgroup"); } if (PlayerPrefs.HasKey ("numLaunches")) { int numLaunches = PlayerPrefs.GetInt ("numLaunches"); numLaunches++; PlayerPrefs.SetInt("numLaunches", numLaunches); } setUserConditions (); } public void SetMatchScore(int scoreValue, int speedValue) { Debug.Log ("SetMatchScore = " + scoreValue); m_matchData.MatchScore = scoreValue; m_matchData.MatchMaxSpeed = speedValue; //hmmm, better clean up this check if (m_matchData.ValidMatchData == true) { m_matchData.MatchComplete = true; } } /* ----------------------------------------------------- Update ----------------------------------------------------- */ void Update () { } /* ----------------------------------------------------- Access to mainmenu this pointer ----------------------------------------------------- */ private InitMainMenu getMainMenuClass() { GameObject _mainmenu = GameObject.Find("InitMainMenu"); if (_mainmenu != null) { InitMainMenu _mainmenuScript = _mainmenu.GetComponent<InitMainMenu> (); if(_mainmenuScript != null) { return _mainmenuScript; } throw new Exception(); } throw new Exception(); } public const int MATCH_TYPE_SINGLE = 0; public void launchSinglePlayerGame() { m_matchData.MatchType = MATCH_TYPE_SINGLE; m_matchData.ValidMatchData = false; NotificationCenter.DefaultCenter.PostNotification (getMainMenuClass(), "LaunchGamePlay"); } /* --------------------------------------------------------------------- Fuel Dynamics --------------------------------------------------------------------- */ private bool isDeviceTablet () { bool isTablet = false; #if UNITY_IOS if (Application.platform == RuntimePlatform.IPhonePlayer) { if(UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadUnknown || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad2Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad3Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad4Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini1Gen) { isTablet = true; } } #endif return isTablet; } private int getNumLaunches () { int numLaunches = 0; if (PlayerPrefs.HasKey ("numLaunches")) { numLaunches = PlayerPrefs.GetInt ("numLaunches"); } Debug.Log ("....numLaunches = " + numLaunches); return numLaunches; } private int getNumSessions () { int numSessions = 0; if (PlayerPrefs.HasKey ("numSessions")) { numSessions = PlayerPrefs.GetInt ("numSessions"); } Debug.Log ("....numSessions = " + numSessions); return numSessions; } private int getUserAge () { TimeSpan span = DateTime.Now.Subtract (new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)); int _currentTimeStamp = (int)span.TotalSeconds; int _seconds = 0; if (PlayerPrefs.HasKey ("installTimeStamp")) { int _installTimeStamp = PlayerPrefs.GetInt ("installTimeStamp"); _seconds = _currentTimeStamp - _installTimeStamp; } int userAge = _seconds / 86400; Debug.Log ("....userAge = " + userAge + " <--- " + _seconds + "/ 86400"); return userAge; } public void setUserConditions () { Debug.Log ("setUserConditions"); String isTablet = "FALSE"; if( isDeviceTablet() == true) { isTablet = "TRUE"; } int userAge = getUserAge (); int numLaunches = getNumLaunches (); int numSessions = getNumSessions (); Dictionary<string, string> conditions = new Dictionary<string, string> (); //required conditions.Add ("userAge", userAge.ToString()); conditions.Add ("numSessions", numSessions.ToString()); conditions.Add ("numLaunches", numLaunches.ToString()); conditions.Add ("isTablet", isTablet); //standardized conditions.Add ("orientation", "portrait"); conditions.Add ("daysSinceFirstPayment", "-1"); conditions.Add ("daysSinceLastPayment", "-1"); conditions.Add ("language", "en"); conditions.Add ("gender", "female"); conditions.Add ("age", "16"); //game conditions conditions.Add ("gameVersion", "tapgear v1.1"); #if PROPELLER_SDK FuelDynamics.SetUserConditions (conditions); #endif Debug.Log ( "*** conditions ***" + "\n" + "userAge = " + userAge.ToString() + "\n" + "numSessions = " + numSessions.ToString() + "\n" + "numLaunches = " + numLaunches.ToString() + "\n" + "isTablet = " + isTablet + "\n" + "orientation = " + "portrait" + "\n" + "daysSinceFirstPayment = " + "-1" + "\n" + "daysSinceLastPayment = " + "-1" + "\n" + "language = " + "en" + "\n" + "gender = " + "female" + "\n" + "age = " + "16" + "\n" + "gameVersion = " + "tapgear v1.1" ); } public void syncUserValues() { #if PROPELLER_SDK FuelDynamics.SyncUserValues(); #endif } public void OnPropellerSDKUserValues (Dictionary<string, object> userValuesInfo) { //Game Values - defined in the CSV String _friction = "friction"; String _geartype = "geartype"; String _gametime = "gametime"; String _split1name = "split1name"; //Dictionary<string, string> analyticResult = new Dictionary<string, string> (); object value; if (userValuesInfo.TryGetValue (_friction, out value)) { GearFriction = float.Parse (value.ToString ()); } else { Debug.Log("friction not found in userValueInfo"); } if (userValuesInfo.TryGetValue (_geartype, out value)) { GearShapeType = int.Parse(value.ToString()); } else { Debug.Log("geartype not found in userValueInfo"); } if (userValuesInfo.TryGetValue (_gametime, out value)) { GameTime = int.Parse(value.ToString()); } else { Debug.Log("gametime not found in userValueInfo"); } if (userValuesInfo.TryGetValue (_split1name, out value)) { Split1Name = value.ToString(); } else { Debug.Log("split1name not found in userValueInfo"); } Debug.Log ("TryGetValue:: friction = " + GearFriction + ", geartype = " + GearShapeType + ", gametime = " + GameTime); /* foreach(KeyValuePair<string, object> entry in userValuesInfo) { if(_friction.Equals( entry.Key )) { string friction = (string) entry.Value; GearFriction = float.Parse(friction); } else if(_geartype.Equals( entry.Key )) { string geartypeStr = (string) entry.Value; GearShapeType = int.Parse(geartypeStr); } else if(_gametime.Equals( entry.Key )) { string gametimeStr = (string) entry.Value; GameTime = int.Parse(gametimeStr); } else if(_split1name.Equals( entry.Key )) { string split1nameStr = (string) entry.Value; Split1Name = split1nameStr; } analyticResult.Add (entry.Key, (string)entry.Value); } Debug.Log ("friction = " + GearFriction + ", geartype = " + GearShapeType + ", gametime = " + GameTime); */ //store values if (PlayerPrefs.HasKey ("gearfriction")) { PlayerPrefs.SetFloat("gearfriction", GearFriction); } if (PlayerPrefs.HasKey ("geartype")) { PlayerPrefs.SetInt("geartype", GearShapeType); } if (PlayerPrefs.HasKey ("gametime")) { PlayerPrefs.SetInt("gametime", GameTime); } if (PlayerPrefs.HasKey ("splitgroup")) { PlayerPrefs.SetString("splitgroup", Split1Name); } NotificationCenter.DefaultCenter.PostNotification(getMainMenuClass(), "RefreshDebugText"); } }
using System.Threading.Tasks; using EmsApi.Dto.V2; namespace EmsApi.Client.V2.Access { /// <summary> /// Provides access to the EMS API Analytic Set routes. /// These routes replace the Parameter Set routes. /// </summary> public class AnalyticSetAccess : RouteAccess { #region AnalyticSetGroup /// <summary> /// Returns the root analytic group. /// </summary> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticSetGroup> GetAnalyticSetGroupsAsync( CallContext context = null ) { return CallApiTask( api => api.GetAnalyticSetGroups( context: context ).ContinueWith( t => t.Result ) ); } /// <summary> /// Returns the root analytic group. /// </summary> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticSetGroup GetAnalyticSetGroups( CallContext context = null ) { return AccessTaskResult( GetAnalyticSetGroupsAsync( context ) ); } /// <summary> /// Returns the specified analytic group. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group to retrieve. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticSetGroup> GetAnalyticSetGroupAsync( string analyticGroupId, CallContext context = null ) { return CallApiTask( api => api.GetAnalyticSetGroup( analyticGroupId, context: context ).ContinueWith( t => t.Result ) ); } /// <summary> /// Returns the specified analytic group. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group to retrieve. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticSetGroup GetAnalyticSetGroup( string analyticGroupId, CallContext context = null ) { return AccessTaskResult( GetAnalyticSetGroupAsync( analyticGroupId, context ) ); } /// <summary> /// Creates an analytic set group. /// </summary> /// <param name="newAnalyticSetGroup"> /// The information to create a new analytic set group. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticSetGroupCreated> CreateAnalyticSetGroupAsync( NewAnalyticSetGroup newAnalyticSetGroup, CallContext context = null ) { return CallApiTask( api => api.CreateAnalyticSetGroup( newAnalyticSetGroup, context ) ); } /// <summary> /// Creates an analytic set group. /// </summary> /// <param name="newAnalyticSetGroup"> /// The information to create a new analytic set group. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticSetGroupCreated CreateAnalyticSetGroup( NewAnalyticSetGroup newAnalyticSetGroup, CallContext context = null ) { return AccessTaskResult( CreateAnalyticSetGroupAsync( newAnalyticSetGroup, context ) ); } /// <summary> /// Updates an analytic set group. /// </summary> /// <param name="analyticGroupId"> /// The group to update. /// </param> /// <param name="updateAnalyticSetGroup"> /// The information to update the group with. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticSetGroupUpdated> UpdateAnalyticSetGroupAsync( string analyticGroupId, UpdateAnalyticSetGroup updateAnalyticSetGroup, CallContext context = null ) { return CallApiTask( api => api.UpdateAnalyticSetGroup( analyticGroupId, updateAnalyticSetGroup, context ) ); } /// <summary> /// Updates an analytic set group. /// </summary> /// <param name="analyticGroupId"> /// The group to update. /// </param> /// <param name="updateAnalyticSetGroup"> /// The information to update the group with. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticSetGroupUpdated UpdateAnalyticSetGroup( string analyticGroupId, UpdateAnalyticSetGroup updateAnalyticSetGroup, CallContext context = null ) { return AccessTaskResult( UpdateAnalyticSetGroupAsync( analyticGroupId, updateAnalyticSetGroup, context ) ); } /// <summary> /// Deletes an analytic set group. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group to delete. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<object> DeleteAnalyticSetGroupAsync( string analyticGroupId, CallContext context = null ) { return CallApiTask( api => api.DeleteAnalyticSetGroup( analyticGroupId, context ) ); } /// <summary> /// Deletes an analytic set group. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group to delete. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual void DeleteAnalyticSetGroup( string analyticGroupId, CallContext context = null ) { AccessTaskResult<object>( DeleteAnalyticSetGroupAsync( analyticGroupId, context ) ); } #endregion #region AnalyticSet /// <summary> /// Gets a specific analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the analytic set's parent group. /// </param> /// <param name="analyticSetName"> /// The name of the analytic set. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticSet> GetAnalyticSetAsync( string analyticGroupId, string analyticSetName, CallContext context = null ) { return CallApiTask( api => api.GetAnalyticSet( analyticGroupId, analyticSetName, context ) ); } /// <summary> /// Gets a specific analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the analytic set's parent group. /// </param> /// <param name="analyticSetName"> /// The name of the analytic set. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticSet GetAnalyticSet( string analyticGroupId, string analyticSetName, CallContext context = null ) { return AccessTaskResult( GetAnalyticSetAsync( analyticGroupId, analyticSetName, context ) ); } /// <summary> /// Creates an analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group where the new set will be created. /// </param> /// <param name="newAnalyticSet"> /// The information to create the new set. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticSetCreated> CreateAnalyticSetAsync(string analyticGroupId, NewAnalyticSet newAnalyticSet, CallContext context = null ) { return CallApiTask( api => api.CreateAnalyticSet( analyticGroupId, newAnalyticSet, context ) ); } /// <summary> /// Creates an analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group where the new set will be created. /// </param> /// <param name="newAnalyticSet"> /// The information to create the new set. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticSetCreated CreateAnalyticSet( string analyticGroupId, NewAnalyticSet newAnalyticSet, CallContext context = null ) { return AccessTaskResult( CreateAnalyticSetAsync( analyticGroupId, newAnalyticSet, context ) ); } /// <summary> /// Updates an analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the analytic set to update. /// </param> /// <param name="analyticSetName"> /// The name of the analytic set to update. /// </param> /// <param name="updateAnalyticSet"> /// The information to update the analytic set with. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<object> UpdateAnalyticSetAsync( string analyticGroupId, string analyticSetName, UpdateAnalyticSet updateAnalyticSet, CallContext context = null ) { return CallApiTask( api => api.UpdateAnalyticSet( analyticGroupId, analyticSetName, updateAnalyticSet, context ) ); } /// <summary> /// Updates an analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the analytic set to update. /// </param> /// <param name="analyticSetName"> /// The name of the analytic set to update. /// </param> /// <param name="updateAnalyticSet"> /// The information to update the analytic set with. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual void UpdateAnalyticSet( string analyticGroupId, string analyticSetName, UpdateAnalyticSet updateAnalyticSet, CallContext context = null ) { AccessTaskResult<object>( UpdateAnalyticSetAsync( analyticGroupId, analyticSetName, updateAnalyticSet, context ) ); } /// <summary> /// Deletes an analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the analytic set to delete. /// </param> /// <param name="analyticSetName"> /// The name of the analytic set to delete. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<object> DeleteAnalyticSetAsync( string analyticGroupId, string analyticSetName, CallContext context = null ) { return CallApiTask( api => api.DeleteAnalyticSet( analyticGroupId, analyticSetName, context ) ); } /// <summary> /// Deletes an analytic set. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the analytic set to delete. /// </param> /// <param name="analyticSetName"> /// The name of the analytic set to delete. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual void DeleteAnalyticSet( string analyticGroupId, string analyticSetName, CallContext context = null ) { AccessTaskResult<object>( DeleteAnalyticSetAsync( analyticGroupId, analyticSetName, context ) ); } #endregion #region AnalyticCollection /// <summary> /// Gets an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the collection. /// </param> /// <param name="analyticCollectionName"> /// The name of the analytic collection. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticCollection> GetAnalyticCollectionAsync( string analyticGroupId, string analyticCollectionName, CallContext context = null ) { return CallApiTask( api => api.GetAnalyticCollection( analyticGroupId, analyticCollectionName, context ) ); } /// <summary> /// Gets an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the collection. /// </param> /// <param name="analyticCollectionName"> /// The name of the analytic collection.</param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticCollection GetAnalyticCollection( string analyticGroupId, string analyticCollectionName, CallContext context = null ) { return AccessTaskResult( GetAnalyticCollectionAsync( analyticGroupId, analyticCollectionName, context ) ); } /// <summary> /// Creates an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group where the new collection will be created. /// </param> /// <param name="newAnalyticCollection"> /// The information needed to create the new collection. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<AnalyticCollectionCreated> CreateAnalyticCollectionAsync( string analyticGroupId, NewAnalyticCollection newAnalyticCollection, CallContext context = null ) { return CallApiTask( api => api.CreateAnalyticCollection( analyticGroupId, newAnalyticCollection, context ) ); } /// <summary> /// Creates an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the group where the new collection will be created. /// </param> /// <param name="newAnalyticCollection"> /// The information needed to create the new collection. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual AnalyticCollectionCreated CreateAnalyticCollection( string analyticGroupId, NewAnalyticCollection newAnalyticCollection, CallContext context = null ) { return AccessTaskResult( CreateAnalyticCollectionAsync( analyticGroupId, newAnalyticCollection, context ) ); } /// <summary> /// Updates an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the collection to update. /// </param> /// <param name="analyticCollectionName"> /// The name of the collection to update. /// </param> /// <param name="updateAnalyticCollection"> /// The information to update the collection with. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<object> UpdateAnalyticCollectionAsync( string analyticGroupId, string analyticCollectionName, UpdateAnalyticCollection updateAnalyticCollection, CallContext context = null ) { return CallApiTask( api => api.UpdateAnalyticCollection( analyticGroupId, analyticCollectionName, updateAnalyticCollection, context ) ); } /// <summary> /// Updates an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the collection to update. /// </param> /// <param name="analyticCollectionName"> /// The name of the collection to update. /// </param> /// <param name="updateAnalyticCollection"> /// The information to update the collection with. /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual void UpdateAnalyticCollection( string analyticGroupId, string analyticCollectionName, UpdateAnalyticCollection updateAnalyticCollection, CallContext context = null ) { AccessTaskResult<object>( UpdateAnalyticCollectionAsync( analyticGroupId, analyticCollectionName, updateAnalyticCollection, context ) ); } /// <summary> /// Deletes an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the collection to delete. /// </param> /// <param name="analyticCollectionName"> /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual Task<object> DeleteAnalyticCollectionAsync( string analyticGroupId, string analyticCollectionName, CallContext context = null ) { return CallApiTask( api => api.DeleteAnalyticCollection( analyticGroupId, analyticCollectionName, context ) ); } /// <summary> /// Deletes an analytic collection. /// </summary> /// <param name="analyticGroupId"> /// The ID of the parent group of the collection to delete. /// </param> /// <param name="analyticCollectionName"> /// </param> /// <param name="context"> /// The optional call context to include. /// </param> public virtual void DeleteAnalyticCollection( string analyticGroupId, string analyticCollectionName, CallContext context = null ) { AccessTaskResult<object>( DeleteAnalyticCollectionAsync( analyticGroupId, analyticCollectionName, context ) ); } #endregion } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class UnpackStatement : Statement { protected DeclarationCollection _declarations; protected Expression _expression; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public UnpackStatement CloneNode() { return (UnpackStatement)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public UnpackStatement CleanClone() { return (UnpackStatement)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.UnpackStatement; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnUnpackStatement(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( UnpackStatement)node; if (!Node.Matches(_modifier, other._modifier)) return NoMatch("UnpackStatement._modifier"); if (!Node.AllMatch(_declarations, other._declarations)) return NoMatch("UnpackStatement._declarations"); if (!Node.Matches(_expression, other._expression)) return NoMatch("UnpackStatement._expression"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_modifier == existing) { this.Modifier = (StatementModifier)newNode; return true; } if (_declarations != null) { Declaration item = existing as Declaration; if (null != item) { Declaration newItem = (Declaration)newNode; if (_declarations.Replace(item, newItem)) { return true; } } } if (_expression == existing) { this.Expression = (Expression)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { UnpackStatement clone = (UnpackStatement)FormatterServices.GetUninitializedObject(typeof(UnpackStatement)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _declarations) { clone._declarations = _declarations.Clone() as DeclarationCollection; clone._declarations.InitializeParent(clone); } if (null != _expression) { clone._expression = _expression.Clone() as Expression; clone._expression.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _modifier) { _modifier.ClearTypeSystemBindings(); } if (null != _declarations) { _declarations.ClearTypeSystemBindings(); } if (null != _expression) { _expression.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Declaration))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public DeclarationCollection Declarations { get { return _declarations ?? (_declarations = new DeclarationCollection(this)); } set { if (_declarations != value) { _declarations = value; if (null != _declarations) { _declarations.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Expression { get { return _expression; } set { if (_expression != value) { _expression = value; if (null != _expression) { _expression.InitializeParent(this); } } } } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Threading.Tasks; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Completion of a streaming response call if not null. TaskCompletionSource<object> streamingResponseCallFinishedTcs; // TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers). // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { var profiler = Profilers.ForCurrentThread(); using (profiler.NewScope("AsyncCall.UnaryCall")) using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync()) { byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) using (var ctx = BatchContextSafeHandle.Create()) { call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch")) { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); } } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(HandleUnaryResponse, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(HandleUnaryResponse, metadataArray, details.Options.Flags); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); halfcloseRequested = true; byte[] payload = UnsafeSerialize(msg); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(HandleFinished, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { GrpcPreconditions.CheckState(!started); started = true; Initialize(details.Channel.CompletionQueue); streamingResponseCallFinishedTcs = new TaskCompletionSource<object>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(HandleFinished, metadataArray, details.Options.Flags); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// </summary> public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags) { return SendMessageInternalAsync(msg, writeFlags); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// </summary> public Task<TResponse> ReadMessageAsync() { return ReadMessageInternalAsync(); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// </summary> public Task SendCloseFromClientAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (disposed || finished) { // In case the call has already been finished by the serverside, // the halfclose has already been done implicitly, so just return // completed task here. halfcloseRequested = true; return TaskUtils.CompletedTask; } call.StartSendCloseFromClient(HandleSendFinished); halfcloseRequested = true; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingResponseCallFinishedTask { get { return streamingResponseCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResources() { details.Channel.RemoveCallReference(this); } protected override bool IsClient { get { return true; } } protected override Exception GetRpcExceptionClientOnly() { return new RpcException(finishedStatus.Value.Status); } protected override Task CheckSendAllowedOrEarlyResult() { var earlyResult = CheckSendPreconditionsClientSide(); if (earlyResult != null) { return earlyResult; } if (finishedStatus.HasValue) { // throwing RpcException if we already received status on client // side makes the most sense. // Note that this throws even for StatusCode.OK. // Writing after the call has finished is not a programming error because server can close // the call anytime, so don't throw directly, but let the write task finish with an error. var tcs = new TaskCompletionSource<object>(); tcs.SetException(new RpcException(finishedStatus.Value.Status)); return tcs.Task; } return null; } private Task CheckSendPreconditionsClientSide() { GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed."); GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time."); if (cancelRequested) { // Return a cancelled task. var tcs = new TaskCompletionSource<object>(); tcs.SetCanceled(); return tcs.Task; } return null; } private void Initialize(CompletionQueueSafeHandle cq) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); InitializeInternal(call); RegisterCancellationCallback(); } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance; var credentials = details.Options.Credentials; using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null) { var result = details.Channel.Handle.CreateCall( parentCall, ContextPropagationToken.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials); return result; } } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { var token = details.Options.CancellationToken; if (token.CanBeCanceled) { token.Register(() => this.Cancel()); } } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { // TODO(jtattermusch): handle success==false responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; TResponse msg = default(TResponse); var deserializeException = TryDeserialize(receivedMessage, out msg); lock (myLock) { finished = true; if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK) { receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers); } finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } ReleaseResourcesIfPossible(); } responseHeadersTcs.SetResult(responseHeaders); if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status)); return; } unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { // NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT, // success will be always set to true. TaskCompletionSource<object> delayedStreamingWriteTcs = null; lock (myLock) { finished = true; finishedStatus = receivedStatus; if (isStreamingWriteCompletionDelayed) { delayedStreamingWriteTcs = streamingWriteTcs; streamingWriteTcs = null; } ReleaseResourcesIfPossible(); } if (delayedStreamingWriteTcs != null) { delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly()); } var status = receivedStatus.Status; if (status.StatusCode != StatusCode.OK) { streamingResponseCallFinishedTcs.SetException(new RpcException(status)); return; } streamingResponseCallFinishedTcs.SetResult(null); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace OptionsApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using bv.common.Configuration; using bv.common.Core; using bv.common.db; using bv.common.db.Core; using DevExpress.Data.Filtering; using DevExpress.Data.PivotGrid; using DevExpress.Utils; using DevExpress.XtraPivotGrid; using eidss.avr.db.Complexity; using eidss.avr.db.DBService.DataSource; using eidss.model.Avr.Pivot; using eidss.model.Avr.View; using eidss.model.AVR.DataBase; using eidss.model.AVR.SourceData; using eidss.model.Enums; using eidss.model.Resources; using EIDSS; using EIDSS.Enums; namespace eidss.avr.db.Common { public static class AvrPivotGridHelper { private const string IdColumnName = "Id"; private const string AliasColumnName = "Alias"; private const string CaptionColumnName = "Caption"; private const string OrderColumnName = "Order"; private const string AgeGroupFieldName = "sflHCAG_AgeGroup"; private const string PatientSexFieldName = "sflHC_PatientSex"; private static Dictionary<string, Type> m_FieldDataTypes; public static string GetCorrectFilter(CriteriaOperator criteria) { if (Utils.IsEmpty(criteria)) { return null; } string filter = criteria.LegacyToString(); if (!Utils.IsEmpty(filter)) { int ind = filter.IndexOf(" ?", StringComparison.InvariantCulture); while (ind >= 0) { string substrFilter = filter.Substring(0, ind); if (substrFilter.EndsWith("] =") || substrFilter.EndsWith("] <=") || substrFilter.EndsWith("] >=") || substrFilter.EndsWith("] <>") || substrFilter.EndsWith("] >") || substrFilter.EndsWith("] <")) { int bracketInd = substrFilter.LastIndexOf("[", StringComparison.InvariantCulture); if (bracketInd >= 0) { substrFilter = substrFilter.Substring(0, bracketInd) + "1 = 1"; } } if (filter.Length > ind + 2) { filter = substrFilter + filter.Substring(ind + 2); ind = filter.IndexOf(" ?", substrFilter.Length, StringComparison.InvariantCulture); } else { filter = substrFilter; ind = -1; } } } return filter; } #region Create search fields public static List<T> CreateFields<T>(AvrDataTable data) where T : IAvrPivotGridField, new() { var list = new List<T>(); foreach (AvrDataColumn column in data.Columns) { bool isCopy = column.ExtendedProperties.ContainsKey(QueryHelper.CopySuffix); var field = new T { Name = "field" + column.ColumnName, FieldName = column.ColumnName, Caption = column.Caption, Ordinal = column.Ordinal, IsHiddenFilterField = isCopy, Visible = isCopy }; field.SearchFieldDataType = GetSearchFieldType(field.OriginalFieldName); field.UpdateImageIndex(); field.UseNativeFormat = DefaultBoolean.False; list.Add(field); } return list; } internal static Dictionary<string, Type> GetSearchFieldDataTypes(DataTable lookupTable) { var result = new Dictionary<string, Type>(); foreach (KeyValuePair<string, SearchFieldType> pair in QueryLookupHelper.GetFieldTypes(lookupTable)) { Type value; switch (pair.Value) { case SearchFieldType.Bit: value = typeof (bool); break; case SearchFieldType.Date: value = typeof (DateTime); break; case SearchFieldType.Float: value = typeof (float); break; case SearchFieldType.ID: case SearchFieldType.Integer: value = typeof (long); break; default: value = typeof (string); break; } result.Add(pair.Key, value); result.Add(pair.Key + QueryHelper.CopySuffix, value); result.Add(pair.Key + QueryHelper.GisSuffix, value); result.Add(pair.Key + QueryHelper.GisSuffix + QueryHelper.CopySuffix, value); } return result; } internal static Type GetSearchFieldType(string fieldName) { if ((m_FieldDataTypes == null) || (!m_FieldDataTypes.ContainsKey(fieldName))) { DataTable lookupTable = QueryLookupHelper.GetQuerySearchFieldLookupTable(); m_FieldDataTypes = GetSearchFieldDataTypes(lookupTable); } if (!m_FieldDataTypes.ContainsKey(fieldName)) { throw new AvrException("Cannot load type for field " + fieldName); } return m_FieldDataTypes[fieldName]; } #endregion #region Load Search Fields from DB public static IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> GetSortedLayoutSearchFieldRows (LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldDataTable) { List<LayoutDetailDataSet.LayoutSearchFieldRow> rowList = searchFieldDataTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); rowList.Sort((firstRow, secondRow) => { int firstIndex = 10000 * firstRow.intPivotGridAreaType + firstRow.intFieldPivotGridAreaIndex; int secondIndex = 10000 * secondRow.intPivotGridAreaType + secondRow.intFieldPivotGridAreaIndex; return firstIndex.CompareTo(secondIndex); }); return rowList; } public static void LoadSearchFieldsVersionSixFromDB (IList<IAvrPivotGridField> avrFields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldDataTable, long defaultGroupIntervalId) { IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> rowList = GetSortedLayoutSearchFieldRows(searchFieldDataTable); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in rowList) { IAvrPivotGridField field = avrFields.FirstOrDefault(f => f.FieldId == row.idfLayoutSearchField); if (field != null) { field.DefaultGroupInterval = GroupIntervalHelper.GetGroupInterval(defaultGroupIntervalId); field.LoadSearchFieldFromRow(row); } } } public static void LoadExstraSearchFieldsProperties (IList<IAvrPivotGridField> avrFields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldDataTable) { IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> rowList = GetSortedLayoutSearchFieldRows(searchFieldDataTable); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in rowList) { IAvrPivotGridField field = avrFields.FirstOrDefault(f => f.FieldId == row.idfLayoutSearchField); if (field != null) { field.LoadSearchFieldExstraFromRow(row); field.AllPivotFields = avrFields.ToList(); field.FieldNamesDictionary = GetFieldNamesDictionary(field.AllPivotFields); PivotSummaryType summaryType = field.CustomSummaryType == CustomSummaryType.Count ? PivotSummaryType.Count : PivotSummaryType.Custom; field.SummaryType = summaryType; // todo[ivan] uncomment and implement if custom sorting need to be implemented, delete otherwise // if (field.OriginalFieldName == AgeGroupFieldName) // { // field.SortMode = PivotSortMode.Custom; // } } } } public static Dictionary<string, List<IAvrPivotGridField>> GetFieldNamesDictionary(List<IAvrPivotGridField> allPivotFields) { var fieldsDictionary = new Dictionary<string, List<IAvrPivotGridField>>(); foreach (IAvrPivotGridField field in allPivotFields) { string name = field.OriginalFieldName; if (!fieldsDictionary.ContainsKey(name)) { fieldsDictionary.Add(name, new List<IAvrPivotGridField>()); } fieldsDictionary[name].Add(field); } return fieldsDictionary; } public static void SwapOriginalAndCopiedFieldsIfReversed(IEnumerable<IAvrPivotGridField> avrFields) { Dictionary<IAvrPivotGridField, IAvrPivotGridField> fieldsAndCopies = GetFieldsAndCopiesConsideringArea(avrFields); // in case original and copied fields have been swapped in the migration process from v4 foreach (KeyValuePair<IAvrPivotGridField, IAvrPivotGridField> pair in fieldsAndCopies) { IAvrPivotGridField origin = pair.Key; IAvrPivotGridField copy = pair.Value; PivotArea newArea = origin.Area; bool newVisible = origin.Visible; int newIndex = origin.AreaIndex; bool isSwap = false; if (origin.Area == PivotArea.FilterArea) { if (copy.Area == PivotArea.FilterArea) { isSwap = (copy.AllowedAreas != (copy.AllowedAreas & PivotGridAllowedAreas.FilterArea)); newVisible = false; } else { isSwap = true; newArea = copy.Area; newVisible = copy.Visible; newIndex = copy.AreaIndex; } } IAvrPivotGridField originToProcess = isSwap ? copy : origin; IAvrPivotGridField copyToProcess = isSwap ? origin : copy; originToProcess.IsHiddenFilterField = false; originToProcess.Area = (newArea == PivotArea.FilterArea) ? PivotArea.RowArea : newArea; originToProcess.AreaIndex = newIndex; originToProcess.Visible = newVisible; copyToProcess.Visible = true; copyToProcess.IsHiddenFilterField = true; copyToProcess.GroupInterval = PivotGroupInterval.Default; } } public static Dictionary<IAvrPivotGridField, IAvrPivotGridField> GetFieldsAndCopiesConsideringArea (IEnumerable<IAvrPivotGridField> avrFields) { var fieldsAndCopies = new Dictionary<IAvrPivotGridField, IAvrPivotGridField>(); IEnumerable<IGrouping<string, IAvrPivotGridField>> grouppedField = avrFields.GroupBy(f => f.OriginalFieldName); foreach (IGrouping<string, IAvrPivotGridField> fields in grouppedField) { IAvrPivotGridField fieldCopy; fieldCopy = fields.FirstOrDefault(f => f.Area == PivotArea.FilterArea && f.AllowedAreas == (f.AllowedAreas & PivotGridAllowedAreas.FilterArea)) ?? (fields.FirstOrDefault(f => f.Area == PivotArea.FilterArea) ?? (fields.FirstOrDefault(f => !f.Visible) ?? fields.FirstOrDefault(f => f.IsHiddenFilterField))); if (fieldCopy != null) { foreach (IAvrPivotGridField field in fields) { if (field != fieldCopy) { fieldsAndCopies.Add(field, fieldCopy); } } } } return fieldsAndCopies; } #endregion #region Save Search Fields to DB public static void PrepareLayoutSearchFieldsBeforePost (IList<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable, long idflQuery, long idflLayout) { RemoveNonExistingLayoutSearchFieldRows(fields, searchFieldTable); // just in case when no LayoutSearchFieldRow exists for some field AddMissingLayoutSearchFieldRows(fields, searchFieldTable, idflQuery, idflLayout); UpdateLayoutSearchFieldRows(fields, searchFieldTable); } private static void RemoveNonExistingLayoutSearchFieldRows (IEnumerable<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable) { List<string> originalFieldNames = fields.Select(field => field.OriginalFieldName).ToList(); IEnumerable<LayoutDetailDataSet.LayoutSearchFieldRow> allRows = searchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>(); List<LayoutDetailDataSet.LayoutSearchFieldRow> rowsToRemove = allRows.Where(r => !originalFieldNames.Contains(r.strSearchFieldAlias)).ToList(); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in rowsToRemove) { searchFieldTable.RemoveLayoutSearchFieldRow(row); } } private static void AddMissingLayoutSearchFieldRows (IList<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable, long idflQuery, long idflLayout) { int length = 0; foreach (IAvrPivotGridField field in fields) { string filter = String.Format("{0}='{1}'", searchFieldTable.strSearchFieldAliasColumn.ColumnName, field.OriginalFieldName); if (searchFieldTable.Select(filter).Length == 0) { length++; } } List<long> ids = BaseDbService.NewListIntID(length); int count = 0; foreach (IAvrPivotGridField field in fields) { string filter = String.Format("{0}='{1}'", searchFieldTable.strSearchFieldAliasColumn.ColumnName, field.OriginalFieldName); if (searchFieldTable.Select(filter).Length == 0) { AddNewLayoutSearchFieldRow(searchFieldTable, idflQuery, idflLayout, field.OriginalFieldName, (long) field.CustomSummaryType, ids[count]); count++; } } } private static void UpdateLayoutSearchFieldRows (IEnumerable<IAvrPivotGridField> fields, LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable) { searchFieldTable.BeginLoadData(); foreach (IAvrPivotGridField field in fields) { field.SaveSearchFieldToTable(searchFieldTable); } searchFieldTable.EndLoadData(); } #endregion #region Get Search Fields by condition public static List<IAvrPivotGridField> GetFieldCollectionFromArea (IEnumerable<IAvrPivotGridField> allFields, PivotArea pivotArea) { var dataField = new SortedDictionary<int, IAvrPivotGridField>(); foreach (IAvrPivotGridField field in allFields) { if ((field.Visible) && (field.Area == pivotArea)) { dataField.Add(field.AreaIndex, field); } } var fields = new List<IAvrPivotGridField>(dataField.Values); fields.Sort((f1, f2) => f1.AreaIndex.CompareTo(f2.AreaIndex)); return fields; } public static IAvrPivotGridField GetGenderField(IEnumerable<IAvrPivotGridField> fields) { return GetField(fields, PatientSexFieldName); } public static IAvrPivotGridField GetAgeGroupField(IEnumerable<IAvrPivotGridField> fields) { return GetField(fields, AgeGroupFieldName); } private static IAvrPivotGridField GetField(IEnumerable<IAvrPivotGridField> fields, string fieldAlias) { IAvrPivotGridField foundField = fields.ToList().SingleOrDefault( field => field.Visible && (field.Area == PivotArea.ColumnArea || field.Area == PivotArea.RowArea) && field.FieldName.Contains(fieldAlias)); return foundField; } #endregion #region Process Search Field Summary public static bool TryGetDefaultSummaryTypeFor(string name, out CustomSummaryType result) { DataView searchFields = GetSearchFieldRowByName(name); if (searchFields.Count > 0) { object idAggrFunction = searchFields[0]["idfsDefaultAggregateFunction"]; if (idAggrFunction is long) { result = (CustomSummaryType) idAggrFunction; return true; } } result = CustomSummaryType.Undefined; return false; } public static Dictionary<string, CustomSummaryType> GetNameSummaryTypeDictionary (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable) { var dictionary = new Dictionary<string, CustomSummaryType>(); foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in layoutSearchFieldTable.Rows) { string key = AvrPivotGridFieldHelper.CreateFieldName(row.strSearchFieldAlias, row.idfLayoutSearchField); if (!dictionary.ContainsKey(key)) { CustomSummaryType value = ParseSummaryType(row.idfsAggregateFunction); dictionary.Add(key, value); } } return dictionary; } public static CustomSummaryType ParseSummaryType(long value) { IEnumerable<CustomSummaryType> allEnumValues = Enum.GetValues(typeof (CustomSummaryType)).Cast<CustomSummaryType>(); CustomSummaryType result = allEnumValues.Any(current => current == (CustomSummaryType) value) ? (CustomSummaryType) value : CustomSummaryType.Max; return result; } #endregion #region Prepare Pivot Data Source public static AvrDataTable GetPreparedDataSource (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, long queryId, long layoutId, AvrDataTable queryResult, bool isNewObject) { if (queryResult == null) { return null; } FillNewLayoutSearchFields(layoutSearchFieldTable, queryId, layoutId, queryResult, isNewObject); DeleteColumnsMissingInLayoutSearchFieldTable(layoutSearchFieldTable, queryResult, isNewObject); CreateCopiedColumnsAndAjustColumnNames(layoutSearchFieldTable, queryResult); return queryResult; } /// <summary> /// method generates LayoutSearchFieldRow for each column in the Data Source that hasn't aggregate information /// </summary> /// <param name="layoutSearchFieldTable"></param> /// <param name="queryId"></param> /// <param name="layoutId"></param> /// <param name="newDataSource"></param> /// <param name="isNewObject"></param> public static void FillNewLayoutSearchFields (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, long queryId, long layoutId, AvrDataTable newDataSource, bool isNewObject) { List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutSearchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>() .OrderBy(row => row.idfLayoutSearchField) .ToList(); // If LayoutSearchFieldTable doesn't contain row with Search Field that corresponds to one of QueryResult column, // we should create corresponding LayoutSearchField row List<long> idList = null; if (isNewObject) { idList = BaseDbService.NewListIntID(newDataSource.Columns.Count); } int count = 0; foreach (AvrDataColumn column in newDataSource.Columns) { string columnName = column.ColumnName; // process original fields, not copied fields in filter // we think than each column has a copy if (AvrPivotGridFieldHelper.GetIsCopyForFilter(columnName)) { continue; } List<LayoutDetailDataSet.LayoutSearchFieldRow> foundRows = rows.FindAll(row => (row.strSearchFieldAlias == columnName)); if (foundRows.Count < 2) { CustomSummaryType summaryType = (foundRows.Count == 0) ? Configuration.GetDefaultSummaryTypeFor(columnName, column.DataType) : (CustomSummaryType) foundRows[0].idfsAggregateFunction; string copyColumnName = columnName + QueryHelper.CopySuffix; if (isNewObject && idList != null) { if (foundRows.Count == 0) { AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, columnName, (long) summaryType, idList[count]); count++; } LayoutDetailDataSet.LayoutSearchFieldRow copyRow = AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, copyColumnName, (long) summaryType, idList[count]); copyRow.blnHiddenFilterField = true; count++; } else { if (foundRows.Count == 0) { AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, columnName, (long) summaryType); } LayoutDetailDataSet.LayoutSearchFieldRow copyRow = AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, copyColumnName, (long) summaryType); copyRow.blnHiddenFilterField = true; } } else { // second row corresponding to the copied column, so we should change strSearchFieldAlias according to copied column name foundRows[1].strSearchFieldAlias = columnName + QueryHelper.CopySuffix; foundRows[0].blnHiddenFilterField = false; foundRows[1].blnHiddenFilterField = true; } } } /// <summary> /// If Current object is NOT new, Method deletes all columns in the Data Source that hasn't corresponding rows in /// AggregateTable /// </summary> /// <param name="layoutSearchFieldTable"> </param> /// <param name="newDataSource"> </param> /// <param name="isNewObject"> </param> private static void DeleteColumnsMissingInLayoutSearchFieldTable (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, AvrDataTable newDataSource, bool isNewObject) { if (!isNewObject) { List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutSearchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); List<AvrDataColumn> dataColumns = newDataSource.Columns.ToList(); foreach (AvrDataColumn column in dataColumns) { string columnName = column.ExtendedProperties.ContainsKey(QueryHelper.CopySuffix) ? AvrPivotGridFieldHelper.GetOriginalNameFromCopyForFilterName(column.ColumnName) : column.ColumnName; LayoutDetailDataSet.LayoutSearchFieldRow foundRow = rows.Find(row => (row.strSearchFieldAlias == columnName)); if (foundRow == null) { newDataSource.Columns.Remove(column); } } } } /// <summary> /// If LayoutSearchFieldTable contains multiple rows with the same strSearchFieldAlias, method creates corresponding /// columns. /// Also /// method appends Column Name with corresponding idfLayoutSearchField for each column /// </summary> /// <param name="layoutSearchFieldTable"> </param> /// <param name="newDataSource"> </param> private static void CreateCopiedColumnsAndAjustColumnNames (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, AvrDataTable newDataSource) { List<AvrDataColumn> dataColumns = newDataSource.Columns.ToList(); List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutSearchFieldTable.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); foreach (AvrDataColumn column in dataColumns) { string originalName = column.ColumnName; List<LayoutDetailDataSet.LayoutSearchFieldRow> foundRows = rows.FindAll(row => (row.strSearchFieldAlias == originalName)); int rowCounter = 0; foreach (LayoutDetailDataSet.LayoutSearchFieldRow row in foundRows) { CheckLayoutSearchFieldRowTranslations(row); if (column.ExtendedProperties.ContainsKey(QueryHelper.CopySuffix)) { row.strSearchFieldAlias = AvrPivotGridFieldHelper.GetOriginalNameFromCopyForFilterName(originalName); } string caption = row.IsstrNewFieldCaptionNull() || Utils.IsEmpty(row.strNewFieldCaption) ? row.strOriginalFieldCaption : row.strNewFieldCaption; if (rowCounter == 0) { // change name so it shall contain idfLayoutSearchField column.ColumnName = AvrPivotGridFieldHelper.CreateFieldName(row.strSearchFieldAlias, row.idfLayoutSearchField); column.Caption = caption; } else { // create copy of column with new idfLayoutSearchField // name of new column shall contain new id string copyColumnName = AvrPivotGridFieldHelper.CreateFieldName(row.strSearchFieldAlias, row.idfLayoutSearchField); var copyColumn = newDataSource.AddCopyColumn(column.ColumnName, copyColumnName); copyColumn.Caption = caption; } rowCounter++; } } } private static void CheckLayoutSearchFieldRowTranslations(LayoutDetailDataSet.LayoutSearchFieldRow row) { string msg = EidssMessages.Get("msgEmptyRow", "One of rows has empty translation {0}"); if (row.IsstrOriginalFieldENCaptionNull() || row.IsstrOriginalFieldCaptionNull()) { throw new AvrDbException(String.Format(msg, row.strSearchFieldAlias)); } } #endregion #region Administrative Unit & Statistic date field processing public static DataView GetStatisticDateView(IEnumerable<IAvrPivotGridField> avrFields) { DataTable dataTable = CreateListDataTable("DateFieldList"); dataTable.BeginLoadData(); IEnumerable<IAvrPivotGridField> dateFields = avrFields.Where(f => f.Visible && (f.Area == PivotArea.ColumnArea || f.Area == PivotArea.RowArea) && f.IsDateTimeField); foreach (IAvrPivotGridField field in dateFields) { DataRow dr = dataTable.NewRow(); dr[IdColumnName] = AvrPivotGridFieldHelper.GetIdFromFieldName(field.FieldName); dr[AliasColumnName] = field.FieldName; dr[CaptionColumnName] = field.Caption; dr[OrderColumnName] = field.AreaIndex - 1000 * (int) field.Area; dataTable.Rows.Add(dr); } dataTable.EndLoadData(); dataTable.AcceptChanges(); return new DataView(dataTable, "", OrderColumnName, DataViewRowState.CurrentRows); } public static DataView GetAdministrativeUnitView(long queryId, List<IAvrPivotGridField> allFields) { DataView dvMapFieldList = GetMapFiledView(queryId); DataTable dataTable = CreateListDataTable("AdmUnitList"); dataTable.BeginLoadData(); foreach (DataRowView r in dvMapFieldList) { IEnumerable<IAvrPivotGridField> rowFields = GetFieldsInRow(allFields, Utils.Str(r["FieldAlias"])); foreach (IAvrPivotGridField field in rowFields) { DataRow dr = dataTable.NewRow(); dr[IdColumnName] = AvrPivotGridFieldHelper.GetIdFromFieldName(field.FieldName); dr[AliasColumnName] = field.FieldName; dr[CaptionColumnName] = field.Caption; dr[OrderColumnName] = r["intIncidenceDisplayOrder"]; dataTable.Rows.Add(dr); } } DataRow countryRow = dataTable.NewRow(); countryRow[IdColumnName] = -1; countryRow[AliasColumnName] = AvrPivotGridFieldHelper.VirtualCountryFieldName; countryRow[CaptionColumnName] = EidssMessages.Get("strCountry", "Country"); countryRow[OrderColumnName] = 100; dataTable.Rows.Add(countryRow); dataTable.EndLoadData(); dataTable.AcceptChanges(); return new DataView(dataTable, "", String.Format("{0}, {1}, {2}", OrderColumnName, CaptionColumnName, AliasColumnName), DataViewRowState.CurrentRows); } public static DataView GetMapFiledView(long queryId, bool isMap = false) { string key = LookupTables.QuerySearchField.ToString(); DataTable dtMapFieldList = LookupCache.Fill(LookupCache.LookupTables[key]); string field = isMap ? "intMapDisplayOrder" : "intIncidenceDisplayOrder"; string filter = String.Format("idflQuery = {0} and {1} is not null", queryId, field); string sort = String.Format("{0}, FieldCaption", field); var dvMapFieldList = new DataView(dtMapFieldList, filter, sort, DataViewRowState.CurrentRows); return dvMapFieldList; } public static DataTable CreateListDataTable(string tableName) { var dataTable = new DataTable(tableName); dataTable.BeginInit(); var colId = new DataColumn(IdColumnName, typeof (long)); dataTable.Columns.Add(colId); var colAlias = new DataColumn(AliasColumnName, typeof (string)); dataTable.Columns.Add(colAlias); var colCaption = new DataColumn(CaptionColumnName, typeof (string)); dataTable.Columns.Add(colCaption); var colOrder = new DataColumn(OrderColumnName, typeof (int)); dataTable.Columns.Add(colOrder); dataTable.PrimaryKey = new[] {colAlias}; dataTable.EndInit(); return dataTable; } public static IEnumerable<IAvrPivotGridField> GetFieldsInRow(List<IAvrPivotGridField> fields, string originalFieldName) { Utils.CheckNotNullOrEmpty(originalFieldName, "originalFieldName"); List<IAvrPivotGridField> found = fields.FindAll(field => (field.Visible) && (field.AreaIndex >= 0) && (field.Area == PivotArea.RowArea) && (field.OriginalFieldName == originalFieldName)); return found; } #endregion #region Add Search Field Row public static LayoutDetailDataSet.LayoutSearchFieldRow AddNewLayoutSearchFieldRow (LayoutDetailDataSet.LayoutSearchFieldDataTable layoutSearchFieldTable, long queryId, long layoutId, string originalFieldName, long aggregateFunctionId) { return AddNewLayoutSearchFieldRow(layoutSearchFieldTable, queryId, layoutId, originalFieldName, aggregateFunctionId, BaseDbService.NewIntID()); } public static LayoutDetailDataSet.LayoutSearchFieldRow AddNewLayoutSearchFieldRow (LayoutDetailDataSet.LayoutSearchFieldDataTable searchFieldTable, long queryId, long layoutId, string originalFieldName, long aggregateFunctionId, long idfLayoutSearchField) { LayoutDetailDataSet.LayoutSearchFieldRow newRow = searchFieldTable.NewLayoutSearchFieldRow(); newRow.idflLayout = layoutId; newRow.strSearchFieldAlias = originalFieldName; newRow.idfsAggregateFunction = aggregateFunctionId; newRow.idfsBasicCountFunction = (long) CustomSummaryType.DistinctCount; newRow.idfLayoutSearchField = idfLayoutSearchField; newRow.SetidfsGroupDateNull(); newRow.blnShowMissedValue = false; newRow.SetdatDiapasonStartDateNull(); newRow.SetdatDiapasonEndDateNull(); FillMissedReferenceAttribues(newRow, originalFieldName); newRow.SetintPrecisionNull(); newRow.intFieldColumnWidth = AvrView.DefaultFieldWidth; newRow.intFieldCollectionIndex = 0; newRow.intPivotGridAreaType = 0; newRow.intFieldPivotGridAreaIndex = -1; newRow.blnVisible = false; newRow.blnHiddenFilterField = false; newRow.intFieldColumnWidth = AvrView.DefaultFieldWidth; newRow.blnSortAcsending = true; KeyValuePair<string, string> translations = QueryProcessor.GetTranslations(queryId, originalFieldName); newRow.strOriginalFieldENCaption = translations.Key; newRow.strOriginalFieldCaption = translations.Value; searchFieldTable.AddLayoutSearchFieldRow(newRow); return newRow; } private static void FillMissedReferenceAttribues(LayoutDetailDataSet.LayoutSearchFieldRow newRow, string name) { newRow.blnAllowMissedReferenceValues = false; newRow.strLookupTable = String.Empty; newRow.strLookupAttribute = String.Empty; DataView searchFields = GetSearchFieldRowByName(name); if (searchFields.Count > 0) { DataRowView row = searchFields[0]; object flag = row["blnAllowMissedReferenceValues"]; if (flag is bool) { newRow.blnAllowMissedReferenceValues = (bool) flag; } newRow.strLookupTable = Utils.Str(row["strLookupTable"]); if (row["idfsReferenceType"] is long) { newRow.idfsReferenceType = (long) row["idfsReferenceType"]; } if (row["idfsGISReferenceType"] is long) { newRow.idfsGISReferenceType = (long) row["idfsGISReferenceType"]; } newRow.strLookupAttribute = Utils.Str(row["strLookupAttribute"]); if (row["intHACode"] is int) { newRow.intHACode = (int) row["intHACode"]; } } } private static DataView GetSearchFieldRowByName(string name) { Utils.CheckNotNullOrEmpty(name, "name"); string originalName = AvrPivotGridFieldHelper.GetOriginalNameFromCopyForFilterName(name); DataTable searchFieldsTable = QueryLookupHelper.GetSearchFieldLookupTable(); DataView searchFields = searchFieldsTable.DefaultView; searchFields.RowFilter = String.Format("strSearchFieldAlias = '{0}'", originalName); return searchFields; } #endregion #region Add Missed Values public static LayoutValidateResult AddMissedValuesAndValidateComplexity (AvrPivotGridData dataSource, IList<IAvrPivotGridField> allFields, LayoutBaseValidator validator) { if (dataSource == null) { return new LayoutValidateResult(); } List<IAvrPivotGridField> visibleFields = GetFieldCollectionFromArea(allFields, PivotArea.RowArea); visibleFields.AddRange(GetFieldCollectionFromArea(allFields, PivotArea.ColumnArea)); List<IAvrPivotGridField> cortegeFields = AddRelatedFields(visibleFields); Dictionary<IAvrPivotGridField, List<IAvrPivotGridField>> fieldsAndFieldCopy = GetFieldCopyDictionary(allFields, cortegeFields); var cortege = new AvrFieldValueCollection(fieldsAndFieldCopy); if (cortege.AddMissedValues) { Dictionary<IAvrPivotGridField, AvrDataColumn> columns = GetColumnDictionary(dataSource, allFields); List<int> allRowIndexes; List<AvrDataRowBase> allDataRows = GetRowsDictionary(dataSource, out allRowIndexes); int dataFieldCount = GetFieldCollectionFromArea(allFields, PivotArea.DataArea).Count; return AddMissedValuesForFields(dataSource, cortege, columns, allDataRows, allRowIndexes, validator, dataFieldCount); } return new LayoutValidateResult(); } public static IEnumerable<AvrFieldValueCollection> GetMissingValuesForFields (AvrPivotGridData dataSource, AvrFieldValueCollection fieldValuesCortege, Dictionary<IAvrPivotGridField, AvrDataColumn> columns, IList<AvrDataRowBase> rows, IList<int> rowIndexes, int fieldIndex) { if (fieldIndex < fieldValuesCortege.Count) { AvrFieldValuePair fieldValuePair = fieldValuesCortege[fieldIndex]; IAvrPivotGridField field = fieldValuePair.Field; IDictionary<object, AvrMissedValue> valuesDictionary = GetExistingValuesDictionary(fieldValuePair, columns, rows, rowIndexes); bool isNonCountryFieldRelated = (field.GisReferenceTypeId != (long) GisReferenceType.Country && fieldValuePair.IsRelated); if (field.AddMissedValues || isNonCountryFieldRelated /* || field.IsHiddenFilterField && field.IsDateTimeField*/) { IList<AvrMissedValue> missedValues; try { missedValues = field.IsDateTimeField ? AddMissedDates(fieldValuePair) : field.AddMissedReferencies(fieldValuesCortege); } catch (Exception ex) { throw new AvrException(field.GetMissedValuesErrorMessage(), ex); } foreach (AvrMissedValue missedValue in missedValues) { if (valuesDictionary.ContainsKey(missedValue.FieldValue)) { if (missedValue.LinkedFieldValues.Count > 0 && valuesDictionary[missedValue.FieldValue].LinkedFieldValues.Count == 0) { valuesDictionary[missedValue.FieldValue].LinkedFieldValues = missedValue.LinkedFieldValues; } } else { if (!missedValue.IsHistorical) { valuesDictionary.Add(missedValue.FieldValue, missedValue); } } } } if (valuesDictionary.Count == 0) { for (int i = fieldIndex; i < fieldValuesCortege.Count; i++) { fieldValuesCortege[i].Value = null; } foreach (AvrFieldValueCollection val in GetMissingValuesForFields(dataSource, fieldValuesCortege, columns, new List<AvrDataRowBase>(), new List<int>(), fieldValuesCortege.Count)) { yield return val; } } foreach (AvrMissedValue missedValue in valuesDictionary.Values) { fieldValuePair.Value = missedValue.FieldValue; fieldValuePair.LinkedFieldValues.Clear(); foreach (KeyValuePair<string, object> pair in missedValue.LinkedFieldValues) { if (field.FieldNamesDictionary.ContainsKey(pair.Key)) { foreach (IAvrPivotGridField linkedField in field.FieldNamesDictionary[pair.Key]) { fieldValuePair.LinkedFieldValues.Add(linkedField, pair.Value); } } } foreach (AvrFieldValueCollection val in GetMissingValuesForFields(dataSource, fieldValuesCortege, columns, missedValue.FilteredRows, missedValue.FilteredIndexes, fieldIndex + 1)) { yield return val; } } } else { yield return fieldValuesCortege; } } private static LayoutValidateResult AddMissedValuesForFields (AvrPivotGridData dataSource, AvrFieldValueCollection fieldValuesCortege, Dictionary<IAvrPivotGridField, AvrDataColumn> columns, IList<AvrDataRowBase> rows, IList<int> rowIndexes, LayoutBaseValidator validator, int dataFieldCount) { dataFieldCount = Math.Max(1, dataFieldCount); int step = BaseSettings.AvrWarningCellCountLimit / (10 * dataFieldCount); int counter = 0; var complexity = new LayoutMissedValuesComplexity(); foreach (AvrFieldValueCollection collection in GetMissingValuesForFields(dataSource, fieldValuesCortege, columns, rows, rowIndexes, 0)) { counter++; complexity.SetCelllCount(counter * dataFieldCount); if (counter % step == 0) { LayoutValidateResult result = validator.Validate(complexity); if (!result.IsOk()) { if (!result.IsUserDialogOk()) { return result; } validator.IgnoreValidationWarnings = true; } } AvrDataRow row = dataSource.NewRow(); foreach (AvrFieldValuePair pair in collection) { row.SetValue(pair.Field.Ordinal, pair.Value ?? AvrDataRowBase.DbNullValue); foreach (KeyValuePair<IAvrPivotGridField, object> linkedPair in pair.LinkedFieldValues) { row.SetValue(linkedPair.Key.Ordinal, linkedPair.Value ?? AvrDataRowBase.DbNullValue); } } dataSource.ThreadSafeAddRow(row); } return validator.Validate(complexity); } private static IDictionary<object, AvrMissedValue> GetExistingValuesDictionary (AvrFieldValuePair fieldValuePair, IDictionary<IAvrPivotGridField, AvrDataColumn> columns, IList<AvrDataRowBase> rows, IList<int> rowIndexes) { PivotGroupInterval minInterval = GetMinPivotGroupInterval(fieldValuePair); bool isDateTimeField = fieldValuePair.Field.IsDateTimeField; var valuesDictionary = new Dictionary<object, AvrMissedValue>(); AvrDataColumn column = columns[fieldValuePair.Field]; for (int i = 0; i < rows.Count; i++) { AvrDataRowBase row = rows[i]; object fieldValue = row[column.Ordinal]; if (isDateTimeField && fieldValue is DateTime) { fieldValue = TruncateDateValue(minInterval, (DateTime) fieldValue); } AvrMissedValue foundMissedValue; if (!valuesDictionary.TryGetValue(fieldValue, out foundMissedValue)) { foundMissedValue = new AvrMissedValue(fieldValue); valuesDictionary.Add(fieldValue, foundMissedValue); } foundMissedValue.FilteredRows.Add(row); foundMissedValue.FilteredIndexes.Add(rowIndexes[i]); } return valuesDictionary; } public static List<IAvrPivotGridField> AddRelatedFields(IList<IAvrPivotGridField> visibleFields) { List<IAvrPivotGridField> fields = visibleFields.ToList(); //for fields with missing value remove all their copies without missing values var removeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in fields.Where(f => f.AddMissedValues)) //foreach (IAvrPivotGridField field in fields.Where(f => f.AddMissedValues && !f.IsDateTimeField)) { IAvrPivotGridField originalField = field; removeFields.AddRange( fields.Where(f => !f.AddMissedValues && f != originalField && f.OriginalFieldName == originalField.OriginalFieldName)); } foreach (IAvrPivotGridField field in removeFields) { fields.Remove(field); } //remove all linked fields removeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in fields) { removeFields.AddRange(field.LinkedFields); } foreach (IAvrPivotGridField field in removeFields) { fields.Remove(field); } //for fields remove all their copies except first one fields = GetDistinctFields(fields); // remove all field copies that can be found in related chains removeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in fields) { removeFields.AddRange(field.GetRelatedFieldChain().Where(fields.Contains)); } foreach (IAvrPivotGridField field in removeFields) { fields.Remove(field); } var cortegeFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in fields) { cortegeFields.AddRange(field.GetRelatedFieldChain()); cortegeFields.Add(field); } return cortegeFields; } private static List<IAvrPivotGridField> GetDistinctFields(IEnumerable<IAvrPivotGridField> fields) { var distinctFields = new List<IAvrPivotGridField>(); foreach (IAvrPivotGridField field in fields) { IAvrPivotGridField originalField = field; if (distinctFields.All(f => f.OriginalFieldName != originalField.OriginalFieldName)) { distinctFields.Add(originalField); } } return distinctFields; } private static Dictionary<IAvrPivotGridField, List<IAvrPivotGridField>> GetFieldCopyDictionary (IList<IAvrPivotGridField> allFields, IEnumerable<IAvrPivotGridField> cortegeFields) { var fieldsAndFieldCopy = new Dictionary<IAvrPivotGridField, List<IAvrPivotGridField>>(); foreach (IAvrPivotGridField field in cortegeFields) { IAvrPivotGridField originalField = field; List<IAvrPivotGridField> fieldCopy = allFields.Where( f => f.OriginalFieldName == originalField.OriginalFieldName && f != originalField).ToList(); fieldsAndFieldCopy.Add(field, fieldCopy); } return fieldsAndFieldCopy; } private static IList<AvrMissedValue> AddMissedDates(AvrFieldValuePair pair) { List<AvrMissedValue> values = pair.Field.AddMissedDates(); var fieldGroupping = new Dictionary<PivotGroupInterval, IAvrPivotGridField>(); foreach (IAvrPivotGridField copy in pair.FieldCopy) { if (!fieldGroupping.ContainsKey(copy.GroupInterval)) { fieldGroupping.Add(copy.GroupInterval, copy); } } foreach (IAvrPivotGridField copy in fieldGroupping.Values) { values.AddRange(copy.AddMissedDates()); } values = values.Distinct(AvrMissedValue.FieldValueComparer).ToList(); return values; } public static DateTime TruncateDateValue(PivotGroupInterval minInterval, DateTime value) { //todo: [ivan] modify to support other date interval (it needs for proper layout complexity calculations) DateTime result = minInterval == PivotGroupInterval.DateYear || minInterval == PivotGroupInterval.DateQuarter || minInterval == PivotGroupInterval.DateMonth ? value.TruncateToFirstDateInInterval(minInterval) : value.Date; return result; } private static PivotGroupInterval GetMinPivotGroupInterval(AvrFieldValuePair pair) { PivotGroupInterval minInterval = pair.Field.GroupInterval; foreach (IAvrPivotGridField copy in pair.FieldCopy) { if (!copy.IsHiddenFilterField && minInterval > copy.GroupInterval) { minInterval = copy.GroupInterval; } } return minInterval; } #endregion #region Fill Empty Values public static LayoutValidateResult FillEmptyValuesAndValidateComplexity (AvrPivotGridData dataSource, IList<IAvrPivotGridField> allFields, LayoutBaseValidator validator) { if (dataSource == null) { return new LayoutValidateResult(); } List<int> allRowIndexes; List<AvrDataRowBase> allDataRows = GetRowsDictionary(dataSource, out allRowIndexes); if (allDataRows.Count == 0) { return new LayoutValidateResult(); } AvrFieldValueCollection rowCortege = GetCortegeFromArea(allFields, PivotArea.RowArea); AvrFieldValueCollection colCortege = GetCortegeFromArea(allFields, PivotArea.ColumnArea); int dataCount = GetFieldCollectionFromArea(allFields, PivotArea.DataArea).Count; var complexity = new LayoutEmptyValuesComplexity(dataSource.RowsCount, rowCortege.Count, colCortege.Count, dataCount); Dictionary<IAvrPivotGridField, AvrDataColumn> columns = GetColumnDictionary(dataSource, allFields); if (rowCortege.Count == 0) { complexity.ColCount = GetExistingValuesForFields(dataSource, columns, colCortege, allDataRows, allRowIndexes, 0).Count(); complexity.RowCount = 1; return validator.Validate(complexity); } if (colCortege.Count == 0) { complexity.ColCount = 1; complexity.RowCount = GetExistingValuesForFields(dataSource, columns, rowCortege, allDataRows, allRowIndexes, 0).Count(); return validator.Validate(complexity); } var colFieldValuesList = new List<AvrFieldValueCollectionWithRowsWrapper>(); foreach (AvrFieldValueCollectionWithRowsWrapper colValues in GetExistingValuesForFields(dataSource, columns, colCortege, allDataRows, allRowIndexes, 0)) { var newCollection = new AvrFieldValueCollection(colValues.Collection, true); var newCollectionWrapper = new AvrFieldValueCollectionWithRowsWrapper(newCollection, colValues.RowList, colValues.RowIndexesList); colFieldValuesList.Add(newCollectionWrapper); } complexity.ColCount = colFieldValuesList.Count; int step = Math.Max(1, BaseSettings.AvrWarningCellCountLimit / (10 * Math.Max(1, complexity.ColCount))); AvrColumnRowIntersectionFinder intersectionFinder = new AvrColumnRowIntersectionFinder(dataSource); foreach (AvrFieldValueCollectionWithRowsWrapper rowValues in GetExistingValuesForFields(dataSource, columns, rowCortege, allDataRows, allRowIndexes, 0)) { complexity.RowCount++; if (complexity.RowCount % step == 0) { LayoutValidateResult result = validator.Validate(complexity); if (!result.IsOk()) { if (!result.IsUserDialogOk()) { intersectionFinder.KillAll(); return result; } validator.IgnoreValidationWarnings = true; } } var rowValuesCollection = new AvrFieldValueCollection(rowValues.Collection, true); var rowValuesCopy = new AvrFieldValueCollectionWithRowsWrapper(rowValuesCollection, rowValues.RowList, rowValues.RowIndexesList); intersectionFinder.Enqueue(new AvrColumnRowIntersectionPair(colFieldValuesList, rowValuesCopy)); } intersectionFinder.WaitAll(); return validator.Validate(complexity); } private static AvrFieldValueCollection GetCortegeFromArea(IList<IAvrPivotGridField> allFields, PivotArea area) { List<IAvrPivotGridField> fieldsFromArea = GetFieldCollectionFromArea(allFields, area); fieldsFromArea = GetDistinctFields(fieldsFromArea); Dictionary<IAvrPivotGridField, List<IAvrPivotGridField>> fieldsDict = GetFieldCopyDictionary(allFields, fieldsFromArea); var cortege = new AvrFieldValueCollection(fieldsDict); return cortege; } public static IEnumerable<AvrFieldValueCollectionWithRowsWrapper> GetExistingValuesForFields (AvrPivotGridData dataSource, Dictionary<IAvrPivotGridField, AvrDataColumn> columns, AvrFieldValueCollection fieldValuesCortege, IList<AvrDataRowBase> rows, IList<int> rowIndexes, int fieldIndex) { if (fieldIndex < fieldValuesCortege.Count) { AvrFieldValuePair fieldValuePair = fieldValuesCortege[fieldIndex]; IDictionary<object, AvrMissedValue> valuesDictionary = GetExistingValuesDictionary(fieldValuePair, columns, rows, rowIndexes); if (valuesDictionary.Count == 0) { for (int i = fieldIndex; i < fieldValuesCortege.Count; i++) { fieldValuesCortege[i].Value = null; } IEnumerable<AvrFieldValueCollectionWithRowsWrapper> recoursiveValues = GetExistingValuesForFields(dataSource, columns, fieldValuesCortege, new List<AvrDataRowBase>(), new List<int>(), fieldValuesCortege.Count); foreach (AvrFieldValueCollectionWithRowsWrapper recoursiveValue in recoursiveValues) { yield return recoursiveValue; } } foreach (AvrMissedValue existingValue in valuesDictionary.Values) { fieldValuePair.Value = existingValue.FieldValue; IEnumerable<AvrFieldValueCollectionWithRowsWrapper> recoursiveValues = GetExistingValuesForFields(dataSource, columns, fieldValuesCortege, existingValue.FilteredRows, existingValue.FilteredIndexes, fieldIndex + 1); foreach (AvrFieldValueCollectionWithRowsWrapper recoursiveValue in recoursiveValues) { yield return recoursiveValue; } } } else { yield return new AvrFieldValueCollectionWithRowsWrapper(fieldValuesCortege, rows, rowIndexes); } } private static Dictionary<IAvrPivotGridField, AvrDataColumn> GetColumnDictionary (AvrPivotGridData dataSource, IEnumerable<IAvrPivotGridField> allFields) { var columnDictionary = new Dictionary<IAvrPivotGridField, AvrDataColumn>(); foreach (IAvrPivotGridField field in allFields) { AvrDataColumn column = dataSource.Columns.First(c => c.ColumnName == field.FieldName); columnDictionary.Add(field, column); } return columnDictionary; } public static List<AvrDataRowBase> GetRowsDictionary(AvrPivotGridData dataSource, out List<int> rowIndexes) { List<AvrDataRowBase> allDataRows = dataSource.Rows.ToList(); rowIndexes = new List<int>(allDataRows.Count); for (int i = 0; i < allDataRows.Count; i++) { rowIndexes.Add(i); } return allDataRows; } /// <summary> /// Remove Function Operators from Clause. /// </summary> /// <param name="criteria"> </param> public static void RemoveFunctionOperators(GroupOperator criteria) { var toRemove = new List<CriteriaOperator>(); foreach (CriteriaOperator operand in criteria.Operands) { if (operand is FunctionOperator) { toRemove.Add(operand); } else { var groupOperator = operand as GroupOperator; if (!ReferenceEquals(groupOperator, null)) { RemoveFunctionOperators(groupOperator); } } } foreach (CriteriaOperator operand in toRemove) { criteria.Operands.Remove(operand); } } #endregion #region Create/delete Field Copy public static T CreateFieldCopy<T> (IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset, AvrPivotGridData pivotData, long queryId, long layoutId) where T : IAvrPivotGridField, new() { Utils.CheckNotNull(sourceField, "sourceField"); LayoutDetailDataSet.LayoutSearchFieldRow destRow = CreateLayoutSearchFieldInformationCopy(sourceField, layoutDataset, queryId, layoutId); string copyColumnName = AvrPivotGridFieldHelper.CreateFieldName(sourceField.OriginalFieldName, destRow.idfLayoutSearchField); pivotData.RealPivotData.AddCopyColumn(sourceField.FieldName, copyColumnName); pivotData.ClonedPivotData.AddCopyColumn(sourceField.FieldName, copyColumnName); var copy = new T(); sourceField.CreatePivotGridFieldCopy(copy, copyColumnName); var allFields = new List<IAvrPivotGridField>(); allFields.AddRange(sourceField.AllPivotFields); allFields.Add(copy); foreach (IAvrPivotGridField field in allFields) { field.AllPivotFields.Add(copy); } return copy; } private static LayoutDetailDataSet.LayoutSearchFieldRow CreateLayoutSearchFieldInformationCopy (IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset, long queryId, long layoutId) { LayoutDetailDataSet.LayoutSearchFieldRow sourceRow = GetLayoutSearchFieldRowByField(sourceField, layoutDataset); LayoutDetailDataSet.LayoutSearchFieldRow destRow = AddNewLayoutSearchFieldRow(layoutDataset.LayoutSearchField, queryId, layoutId, sourceRow.strSearchFieldAlias, (long) sourceField.GetDefaultSummaryType()); destRow.strNewFieldCaption = sourceRow.strNewFieldCaption; destRow.strNewFieldENCaption = sourceRow.strNewFieldENCaption; if (!sourceRow.IsidfUnitLayoutSearchFieldNull() && !sourceRow.IsstrUnitSearchFieldAliasNull()) { destRow.strUnitSearchFieldAlias = sourceRow.strUnitSearchFieldAlias; destRow.idfUnitLayoutSearchField = sourceRow.idfUnitLayoutSearchField; } if (!sourceRow.IsidfDateLayoutSearchFieldNull() && !sourceRow.IsstrDateSearchFieldAliasNull()) { destRow.strDateSearchFieldAlias = sourceRow.strDateSearchFieldAlias; destRow.idfDateLayoutSearchField = sourceRow.idfDateLayoutSearchField; } destRow.strLookupAttribute = sourceRow.strLookupAttribute; destRow.strLookupTable = sourceRow.strLookupTable; destRow.intHACode = sourceRow.intHACode; if (!sourceRow.IsidfsReferenceTypeNull()) { destRow.idfsReferenceType = sourceRow.idfsReferenceType; } if (!sourceRow.IsidfsGISReferenceTypeNull()) { destRow.idfsGISReferenceType = sourceRow.idfsGISReferenceType; } if (sourceRow.IsblnAllowMissedReferenceValuesNull()) { destRow.blnAllowMissedReferenceValues = sourceRow.blnAllowMissedReferenceValues; } return destRow; } public static LayoutDetailDataSet.LayoutSearchFieldRow GetLayoutSearchFieldRowByField (IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset) { Utils.CheckNotNull(sourceField, "sourceField"); if (sourceField.FieldId < 0) { throw new AvrException(String.Format("Field {0} doesn't has Id", sourceField.FieldName)); } LayoutDetailDataSet.LayoutSearchFieldRow sourceRow = layoutDataset.LayoutSearchField.FindByidfLayoutSearchField(sourceField.FieldId); if (sourceRow == null) { throw new AvrException(String.Format("LayoutSearchField information not found for field {0} with ID {1}", sourceField.FieldName, sourceField.FieldId)); } return sourceRow; } public static void DeleteFieldCopy(IAvrPivotGridField sourceField, LayoutDetailDataSet layoutDataset, AvrPivotGridData pivotData) { AvrDataColumn sourceColumn = pivotData.RealPivotData.Columns[sourceField.FieldName]; pivotData.RealPivotData.Columns.Remove(sourceColumn); AvrDataColumn sourceClonedColumn = pivotData.ClonedPivotData.Columns[sourceField.FieldName]; pivotData.ClonedPivotData.Columns.Remove(sourceClonedColumn); // clear Unit, Denoninator, Date and other fields here string originalName = sourceField.OriginalFieldName; List<LayoutDetailDataSet.LayoutSearchFieldRow> rows = layoutDataset.LayoutSearchField.Rows.Cast<LayoutDetailDataSet.LayoutSearchFieldRow>().ToList(); List<LayoutDetailDataSet.LayoutSearchFieldRow> unitRows = rows.FindAll(uRow => (!uRow.IsstrUnitSearchFieldAliasNull() && uRow.strUnitSearchFieldAlias == originalName)); foreach (LayoutDetailDataSet.LayoutSearchFieldRow uRow in unitRows) { uRow.SetstrUnitSearchFieldAliasNull(); uRow.SetidfUnitLayoutSearchFieldNull(); } List<LayoutDetailDataSet.LayoutSearchFieldRow> dateRows = rows.FindAll(dateRow => (!dateRow.IsstrDateSearchFieldAliasNull() && dateRow.strDateSearchFieldAlias == originalName)); foreach (LayoutDetailDataSet.LayoutSearchFieldRow dateRow in dateRows) { dateRow.SetstrDateSearchFieldAliasNull(); dateRow.SetidfDateLayoutSearchFieldNull(); } // remove corresponding aggregate row LayoutDetailDataSet.LayoutSearchFieldRow row = layoutDataset.LayoutSearchField.FindByidfLayoutSearchField(sourceField.FieldId); layoutDataset.LayoutSearchField.RemoveLayoutSearchFieldRow(row); //remove field in fieldlist for each field var allFields = new List<IAvrPivotGridField>(); allFields.AddRange(sourceField.AllPivotFields); foreach (IAvrPivotGridField field in allFields) { field.AllPivotFields.Remove(sourceField); } } public static bool EnableDeleteField(IAvrPivotGridField field, IEnumerable<IAvrPivotGridField> avrFields) { if (field == null) { return false; } int count = avrFields.Count(f => f.OriginalFieldName == field.OriginalFieldName); return count > 2; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace AzureGuidance.API.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System.Xml; namespace XmlDocumentTests.XmlNodeTests { public class LastChildTests { [Fact] public static void ElementWithNoChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void ElementWithNoChildTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<top attr1='test1' attr2='test2' />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void DeleteOnlyChildInsertNewNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var old = node.FirstChild; node.RemoveChild(old); var newNode = xmlDocument.CreateTextNode("textNode"); node.AppendChild(newNode); Assert.Equal("textNode", node.LastChild.Value); Assert.Equal(XmlNodeType.Text, node.LastChild.NodeType); Assert.Equal(node.ChildNodes.Count, 1); } [Fact] public static void DeleteOnlyChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); Assert.Null(node.LastChild); Assert.Equal(0, node.ChildNodes.Count); } [Fact] public static void DeleteOnlyChildAddTwoChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); var element1 = xmlDocument.CreateElement("elem1"); var element2 = xmlDocument.CreateElement("elem2"); node.AppendChild(element1); node.AppendChild(element2); Assert.Equal(2, node.ChildNodes.Count); Assert.Equal(element2, node.LastChild); } [Fact] public static void DeleteOnlyChildAddTwoChildrenDeleteBoth() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<elem att1='foo'><a /></elem>"); var node = xmlDocument.DocumentElement; var oldNode = node.FirstChild; node.RemoveChild(oldNode); var element1 = xmlDocument.CreateElement("elem1"); var element2 = xmlDocument.CreateElement("elem2"); node.AppendChild(element1); node.AppendChild(element2); node.RemoveChild(element1); node.RemoveChild(element2); Assert.Null(node.LastChild); Assert.Equal(0, node.ChildNodes.Count); } [Fact] public static void AttributeWithOnlyText() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<element attrib='helloworld' />"); var node = xmlDocument.DocumentElement.GetAttributeNode("attrib"); Assert.Equal("helloworld", node.LastChild.Value); Assert.Equal(1, node.ChildNodes.Count); } [Fact] public static void ElementWithTwoAttributes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(" <element attrib1='hello' attrib2='world' />"); Assert.Null(xmlDocument.DocumentElement.LastChild); } [Fact] public static void ElementWithOneChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/></root>"); Assert.Equal(XmlNodeType.Element, xmlDocument.DocumentElement.LastChild.NodeType); Assert.Equal("child1", xmlDocument.DocumentElement.LastChild.Name); } [Fact] public static void ElementWithMoreThanOneChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2>Some Text</child2><!-- comment --><?PI pi comments?></root>"); Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count); Assert.NotNull(xmlDocument.DocumentElement.LastChild); Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.DocumentElement.LastChild.NodeType); } [Fact] public static void ElementNodeWithOneChildAndOneElement() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<element attrib1='value'>content</element>"); Assert.Equal(XmlNodeType.Text, xmlDocument.DocumentElement.LastChild.NodeType); Assert.Equal("content", xmlDocument.DocumentElement.LastChild.Value); } [Fact] public static void NewlyCreatedElement() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateElement("element"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedAttribute() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateAttribute("attribute"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedTextNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateTextNode("textnode"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedCDataNode() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateCDataSection("cdata section"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedProcessingInstruction() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateProcessingInstruction("PI", "data"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedComment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateComment("comment"); Assert.Null(node.LastChild); } [Fact] public static void NewlyCreatedDocumentFragment() { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateDocumentFragment(); Assert.Null(node.LastChild); } [Fact] public static void InsertChildAtLengthMinus1() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>"); var child3 = xmlDocument.DocumentElement.LastChild; Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal("child3", child3.Name); var newNode = xmlDocument.CreateElement("elem1"); xmlDocument.DocumentElement.InsertBefore(newNode, child3); Assert.Equal(4, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(child3, xmlDocument.DocumentElement.LastChild); } [Fact] public static void InsertChildToElementWithNoNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root/>"); Assert.False(xmlDocument.DocumentElement.HasChildNodes); var newNode = xmlDocument.CreateElement("elem1"); xmlDocument.DocumentElement.AppendChild(newNode); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } [Fact] public static void ReplaceOnlyChildOfNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child/></root>"); var oldNode = xmlDocument.DocumentElement.LastChild; var newNode = xmlDocument.CreateElement("elem1"); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild); xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } [Fact] public static void ReplaceChild() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root><child1/><child2/><child3/></root>"); var oldNode = xmlDocument.DocumentElement.LastChild; var newNode = xmlDocument.CreateElement("elem1"); Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(oldNode, xmlDocument.DocumentElement.LastChild); xmlDocument.DocumentElement.ReplaceChild(newNode, oldNode); Assert.Equal(3, xmlDocument.DocumentElement.ChildNodes.Count); Assert.Equal(newNode, xmlDocument.DocumentElement.LastChild); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Web; using System.Web.Mvc; using HyperSlackers.Bootstrap.Controls; using System.Diagnostics.Contracts; using HyperSlackers.Bootstrap.Extensions; namespace HyperSlackers.Bootstrap.Controls { public class FormGroup<TModel> { internal readonly HtmlHelper<TModel> html; internal FormType formType = FormType.Default; internal readonly IDictionary<string, object> labelHtmlAttributes = new Dictionary<string, object>(); internal readonly IDictionary<string, object> controlHtmlAttributes = new Dictionary<string, object>(); internal readonly IDictionary<string, object> formGroupHtmlAttributes = new Dictionary<string, object>(); internal int? labelWidthLg; internal int? labelWidthMd; internal int? labelWidthSm; internal int? labelWidthXs; internal int? controlWidthLg; internal int? controlWidthMd; internal int? controlWidthSm; internal int? controlWidthXs; internal FormGroupValidationState validationState = FormGroupValidationState.Default; internal Icon feedbackIcon; internal bool useDefaultFeedbackIcon; internal InputSize size = InputSize.Default; [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(labelHtmlAttributes != null); Contract.Invariant(controlHtmlAttributes != null); Contract.Invariant(formGroupHtmlAttributes != null); } internal FormGroup(HtmlHelper<TModel> html) { Contract.Requires<ArgumentNullException>(html != null, "html"); this.html = html; } internal FormGroup(HtmlHelper<TModel> html, Form form) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentNullException>(form != null, "form"); this.html = html; formType = form.formType; labelWidthXs = form.labelWidthXs; labelWidthSm = form.labelWidthSm; labelWidthMd = form.labelWidthMd; labelWidthLg = form.labelWidthLg; controlWidthXs = form.controlWidthXs; controlWidthSm = form.controlWidthSm; controlWidthMd = form.controlWidthMd; controlWidthLg = form.controlWidthLg; LabelHtmlAttributes(form.labelHtmlAttributes); ControlHtmlAttributes(form.controlHtmlAttributes); } internal FormGroup(AjaxHelper<TModel> ajax, AjaxForm form) { Contract.Requires<ArgumentNullException>(ajax != null, "ajax"); Contract.Requires<ArgumentNullException>(form != null, "form"); html = new HtmlHelper<TModel>(ajax.ViewContext, ajax.ViewDataContainer, ajax.RouteCollection); formType = form.formType; labelWidthXs = form.labelWidthXs; labelWidthSm = form.labelWidthSm; labelWidthMd = form.labelWidthMd; labelWidthLg = form.labelWidthLg; controlWidthXs = form.controlWidthXs; controlWidthSm = form.controlWidthSm; controlWidthMd = form.controlWidthMd; controlWidthLg = form.controlWidthLg; LabelHtmlAttributes(form.labelHtmlAttributes); ControlHtmlAttributes(form.controlHtmlAttributes); } internal FormGroup(HtmlHelper<TModel> html, NavBarForm form) { Contract.Requires<ArgumentNullException>(html != null, "html"); Contract.Requires<ArgumentNullException>(form != null, "form"); this.html = html; formType = form.formType; labelWidthXs = form.labelWidthXs; labelWidthSm = form.labelWidthSm; labelWidthMd = form.labelWidthMd; labelWidthLg = form.labelWidthLg; controlWidthXs = form.controlWidthXs; controlWidthSm = form.controlWidthSm; controlWidthMd = form.controlWidthMd; controlWidthLg = form.controlWidthLg; LabelHtmlAttributes(form.labelHtmlAttributes); ControlHtmlAttributes(form.controlHtmlAttributes); } public FormGroup<TModel> ValidationState(FormGroupValidationState state) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); validationState = state; SetDefaultFeedbackIcon(); return (FormGroup<TModel>)this; } public FormGroup<TModel> FeedbackIcon(bool useDefault = true) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); useDefaultFeedbackIcon = useDefault; SetDefaultFeedbackIcon(); return (FormGroup<TModel>)this; } public FormGroup<TModel> FeedbackIcon(GlyphIcon icon) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); feedbackIcon = icon.Class("form-control-feedback"); return (FormGroup<TModel>)this; } public FormGroup<TModel> FeedbackIcon(FontAwesomeIcon icon) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); feedbackIcon = icon.Class("form-control-feedback"); return (FormGroup<TModel>)this; } public FormGroup<TModel> FeedbackIcon(GlyphIconType icon) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); feedbackIcon = new GlyphIcon(icon).Class("form-control-feedback"); return (FormGroup<TModel>)this; } public FormGroup<TModel> FeedbackIcon(FontAwesomeIconType icon) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); feedbackIcon = new FontAwesomeIcon(icon).Class("form-control-feedback"); return (FormGroup<TModel>)this; } public FormGroup<TModel> Size(InputSize inputSize) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); size = inputSize; return this; } public FormGroup<TModel> Type(FormType type) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); formType = type; return (FormGroup<TModel>)this; } public FormGroup<TModel> FormGroupClass(string cssClass) { Contract.Requires<ArgumentException>(!cssClass.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); formGroupHtmlAttributes.AddIfNotExistsCssClass(cssClass); return this; } public FormGroup<TModel> FormGroupDataAttributes(object htmlAttributes) { Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); formGroupHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes.ToHtmlDataAttributes()); return this; } public FormGroup<TModel> FormGroupHtmlAttributes(object htmlAttributes) { Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); formGroupHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes.ToDictionary()); return this; } public FormGroup<TModel> FormGroupHtmlAttributes(IDictionary<string, object> htmlAttributes) { //x Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); formGroupHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes); return (FormGroup<TModel>)this; } public FormGroup<TModel> LabelHtmlAttributes(object htmlAttributes) // TODO: add overrides for controls and labels attributes/cssclass/etc ALSO add to form so multiple formgroups can share attrs { Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes.ToDictionary()); return this; } public FormGroup<TModel> LabelHtmlAttributes(IDictionary<string, object> htmlAttributes) { //x Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes); return this; } public FormGroup<TModel> ControlHtmlAttributes(object htmlAttributes) // TODO: add overrides for controls and labels attributes/cssclass/etc ALSO add to form so multiple formgroups can share attrs { Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes.ToDictionary()); return this; } public FormGroup<TModel> ControlHtmlAttributes(IDictionary<string, object> htmlAttributes) { //x Contract.Requires<ArgumentNullException>(htmlAttributes != null, "htmlAttributes"); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlHtmlAttributes.AddOrReplaceHtmlAttributes(htmlAttributes); return this; } public FormGroup<TModel> ControlWidthLg(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlWidthLg = width; return this; } public FormGroup<TModel> ControlWidthMd(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlWidthMd = width; return this; } public FormGroup<TModel> ControlWidthSm(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlWidthSm = width; return this; } public FormGroup<TModel> ControlWidthXs(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlWidthXs = width; return this; } public FormGroup<TModel> ControlWidth(int? widthLg, int? widthMd, int? widthSm, int? widthXs) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); controlWidthLg = widthLg; controlWidthMd = widthMd; controlWidthSm = widthSm; controlWidthXs = widthXs; return this; } public FormGroup<TModel> LabelWidthLg(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelWidthLg = width; formType = FormType.Horizontal; return this; } public FormGroup<TModel> LabelWidthMd(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelWidthMd = width; formType = FormType.Horizontal; return this; } public FormGroup<TModel> LabelWidthSm(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelWidthSm = width; formType = FormType.Horizontal; return this; } public FormGroup<TModel> LabelWidthXs(int? width) { Contract.Requires<ArgumentOutOfRangeException>(width == null || (width > 0 && width <= 12)); Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelWidthXs = width; formType = FormType.Horizontal; return this; } public FormGroup<TModel> LabelWidth(int? widthLg, int? widthMd, int? widthSm, int? widthXs) { Contract.Ensures(Contract.Result<FormGroup<TModel>>() != null); labelWidthLg = widthLg; labelWidthMd = widthMd; labelWidthSm = widthSm; labelWidthXs = widthXs; return this; } public CheckBoxControl<TModel> CheckBox(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<CheckBoxControl<TModel>>() != null); return new CheckBoxControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public CheckBoxControl<TModel> CheckBoxFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<CheckBoxControl<TModel>>() != null); return new CheckBoxControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public CheckBoxListFromEnumControl<TModel, TValue> CheckBoxesFromEnum<TValue>(string htmlFieldName) where TValue : struct, IConvertible { Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<CheckBoxListFromEnumControl<TModel, TValue>>() != null); return new CheckBoxListFromEnumControl<TModel, TValue>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public CheckBoxListFromEnumControl<TModel, TValue> CheckBoxesFromEnumFor<TValue>(Expression<Func<TModel, TValue>> expression) where TValue : struct, IConvertible { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<CheckBoxListFromEnumControl<TModel, TValue>>() != null); return new CheckBoxListFromEnumControl<TModel, TValue>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public CheckBoxListControl<TModel, TSource, SValue, SText> CheckBoxList<TSource, SValue, SText>(string htmlFieldName, Expression<Func<TModel, IEnumerable<TSource>>> sourceDataExpression, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(sourceDataExpression != null, "sourceDataExpression"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<CheckBoxListControl<TModel, TSource, SValue, SText>>() != null); return new CheckBoxListControl<TModel, TSource, SValue, SText>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData), sourceDataExpression, valueExpression, textExpression).FormGroup(this); } public CheckBoxListControl<TModel, TSource, SValue, SText> CheckBoxList<TSource, SValue, SText>(string htmlFieldName, IEnumerable<TSource> sourceData, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(sourceData != null, "sourceData"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<CheckBoxListControl<TModel, TSource, SValue, SText>>() != null); return new CheckBoxListControl<TModel, TSource, SValue, SText>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData), sourceData, valueExpression, textExpression).FormGroup(this); } public CheckBoxListControl<TModel, TSource, SValue, SText> CheckBoxListFor<TValue, TSource, SValue, SText>(Expression<Func<TModel, TValue>> expression, Expression<Func<TModel, IEnumerable<TSource>>> sourceDataExpression, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentNullException>(sourceDataExpression != null, "sourceDataExpression"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<CheckBoxListControl<TModel, TSource, SValue, SText>>() != null); return new CheckBoxListControl<TModel, TSource, SValue, SText>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), sourceDataExpression, valueExpression, textExpression).FormGroup(this); } public CheckBoxListControl<TModel, TSource, SValue, SText> CheckBoxListFor<TValue, TSource, SValue, SText>(Expression<Func<TModel, TValue>> expression, IEnumerable<TSource> sourceData, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentNullException>(sourceData != null, "sourceData"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<CheckBoxListControl<TModel, TSource, SValue, SText>>() != null); return new CheckBoxListControl<TModel, TSource, SValue, SText>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), sourceData, valueExpression, textExpression).FormGroup(this); } public ControlGroupControl<TModel> CustomControls(string controls) { Contract.Requires<ArgumentException>(!controls.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ControlGroupControl<TModel>>() != null); IHtmlString[] htmlStrings = new IHtmlString[] { MvcHtmlString.Create(controls) }; return CustomControls(htmlStrings); } public ControlGroupControl<TModel> CustomControls(params IHtmlString[] controls) { Contract.Requires<ArgumentNullException>(controls != null, "controls"); Contract.Ensures(Contract.Result<ControlGroupControl<TModel>>() != null); List<IHtmlString> controlList = new List<IHtmlString>(); foreach (var item in controls) { controlList.Add(item); } return new ControlGroupControl<TModel>(html, controlList).FormGroup(this); } public DisplayControl<TModel> Display(string expression) { Contract.Requires<ArgumentException>(!expression.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<DisplayControl<TModel>>() != null); return new DisplayControl<TModel>(html, expression, ModelMetadata.FromStringExpression(expression, html.ViewData)).FormGroup(this); } public DisplayControl<TModel> DisplayFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<DisplayControl<TModel>>() != null); return new DisplayControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public ControlGroupControl<TModel> StaticText(string html) { Contract.Requires<ArgumentException>(!html.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<ControlGroupControl<TModel>>() != null); var p = new TagBuilder("p"); p.AddCssClass("form-control-static"); p.InnerHtml = html; return CustomControls(p.ToString()); } public DisplayTextControl<TModel> DisplayText(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<DisplayTextControl<TModel>>() != null); return new DisplayTextControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public DisplayTextControl<TModel> DisplayTextFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<DisplayTextControl<TModel>>() != null); return new DisplayTextControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public DropDownListControl<TModel> DropDownList(string htmlFieldName, IEnumerable<SelectListItem> selectList) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(selectList != null, "selectList"); Contract.Ensures(Contract.Result<DropDownListControl<TModel>>() != null); return new DropDownListControl<TModel>(html, htmlFieldName, selectList, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public DropDownListControl<TModel> DropDownList(string htmlFieldName, string optionLabel) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(optionLabel != null, "optionLabel"); Contract.Requires<ArgumentException>(!optionLabel.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<DropDownListControl<TModel>>() != null); return new DropDownListControl<TModel>(html, htmlFieldName, optionLabel, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public DropDownListControl<TModel> DropDownListFor<TValue>(Expression<Func<TModel, TValue>> expression, IEnumerable<SelectListItem> selectList) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentNullException>(selectList != null, "selectList"); Contract.Ensures(Contract.Result<DropDownListControl<TModel>>() != null); return new DropDownListControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), selectList, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public DropDownListFromEnumControl<TModel, TValue> DropDownListFromEnum<TValue>(string htmlFieldName) where TValue : struct, IConvertible { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<DropDownListFromEnumControl<TModel, TValue>>() != null); return new DropDownListFromEnumControl<TModel, TValue>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public DropDownListFromEnumControl<TModel, TValue> DropDownListFromEnumFor<TValue>(Expression<Func<TModel, TValue>> expression) where TValue : struct, IConvertible { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<DropDownListFromEnumControl<TModel, TValue>>() != null); return new DropDownListFromEnumControl<TModel, TValue>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public EditorControl<TModel> Editor(string expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentException>(!expression.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<EditorControl<TModel>>() != null); return new EditorControl<TModel>(html, expression, ModelMetadata.FromStringExpression(expression, html.ViewData)).FormGroup(this); } public EditorControl<TModel> EditorFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<EditorControl<TModel>>() != null); return new EditorControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public FileControl<TModel> File(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<FileControl<TModel>>() != null); return new FileControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public FileControl<TModel> FileFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<FileControl<TModel>>() != null); return new FileControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public ListBoxControl<TModel> ListBox(string htmlFieldName, IEnumerable<SelectListItem> selectList) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(selectList != null, "selectList"); Contract.Ensures(Contract.Result<ListBoxControl<TModel>>() != null); return new ListBoxControl<TModel>(html, htmlFieldName, selectList, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public ListBoxControl<TModel> ListBoxFor<TValue>(Expression<Func<TModel, TValue>> expression, IEnumerable<SelectListItem> selectList) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentNullException>(selectList != null, "selectList"); return new ListBoxControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), selectList, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public PasswordControl<TModel> Password(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<PasswordControl<TModel>>() != null); return new PasswordControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public PasswordControl<TModel> PasswordFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<PasswordControl<TModel>>() != null); return new PasswordControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public RadioButtonControl<TModel> RadioButton(string htmlFieldName, object value) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<RadioButtonControl<TModel>>() != null); return new RadioButtonControl<TModel>(html, htmlFieldName, value, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public RadioButtonControl<TModel> RadioButtonFor<TValue>(Expression<Func<TModel, TValue>> expression, object value) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<RadioButtonControl<TModel>>() != null); return new RadioButtonControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), value, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public RadioButtonListControl<TModel, TSource, SValue, SText> RadioButtonList<TSource, SValue, SText>(string htmlFieldName, Expression<Func<TModel, IEnumerable<TSource>>> sourceDataExpression, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(sourceDataExpression != null, "sourceDataExpression"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<RadioButtonListControl<TModel, TSource, SValue, SText>>() != null); return new RadioButtonListControl<TModel, TSource, SValue, SText>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData), sourceDataExpression, valueExpression, textExpression).FormGroup(this); } public RadioButtonListControl<TModel, TSource, SValue, SText> RadioButtonList<TSource, SValue, SText>(string htmlFieldName, IEnumerable<TSource> sourceData, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Requires<ArgumentNullException>(sourceData != null, "sourceData"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<RadioButtonListControl<TModel, TSource, SValue, SText>>() != null); return new RadioButtonListControl<TModel, TSource, SValue, SText>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData), sourceData, valueExpression, textExpression).FormGroup(this); } public RadioButtonListControl<TModel, TSource, SValue, SText> RadioButtonListFor<TValue, TSource, SValue, SText>(Expression<Func<TModel, TValue>> expression, Expression<Func<TModel, IEnumerable<TSource>>> sourceDataExpression, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentNullException>(sourceDataExpression != null, "sourceDataExpression"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<RadioButtonListControl<TModel, TSource, SValue, SText>>() != null); return new RadioButtonListControl<TModel, TSource, SValue, SText>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), sourceDataExpression, valueExpression, textExpression).FormGroup(this); } public RadioButtonListControl<TModel, TSource, SValue, SText> RadioButtonListFor<TValue, TSource, SValue, SText>(Expression<Func<TModel, TValue>> expression, IEnumerable<TSource> sourceData, Expression<Func<TSource, SValue>> valueExpression, Expression<Func<TSource, SText>> textExpression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Requires<ArgumentNullException>(sourceData != null, "sourceData"); Contract.Requires<ArgumentNullException>(valueExpression != null, "valueExpression"); Contract.Requires<ArgumentNullException>(textExpression != null, "textExpression"); Contract.Ensures(Contract.Result<RadioButtonListControl<TModel, TSource, SValue, SText>>() != null); return new RadioButtonListControl<TModel, TSource, SValue, SText>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), sourceData, valueExpression, textExpression).FormGroup(this); } public RadioButtonListFromEnumControl<TModel> RadioButtonsFromEnum<TValue>(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Ensures(Contract.Result<RadioButtonListFromEnumControl<TModel>>() != null); return new RadioButtonListFromEnumControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public RadioButtonListFromEnumControl<TModel> RadioButtonsFromEnumFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<RadioButtonListFromEnumControl<TModel>>() != null); return new RadioButtonListFromEnumControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public RadioButtonTrueFalseControl<TModel> RadioButtonTrueFalse(string htmlFieldName) { Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null); return new RadioButtonTrueFalseControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public RadioButtonTrueFalseControl<TModel> RadioButtonTrueFalseFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<RadioButtonTrueFalseControl<TModel>>() != null); return new RadioButtonTrueFalseControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } //public StaticTextControl<TModel> Static(string text) //{ // //x Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(text)); // Contract.Ensures(Contract.Result<TextAreaControl<TModel>>() != null); // return new StaticTextControl<TModel>(this.html, text).FormGroup(this); //} public TextAreaControl<TModel> TextArea(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<TextAreaControl<TModel>>() != null); return new TextAreaControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public TextAreaControl<TModel> TextAreaFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<TextAreaControl<TModel>>() != null); return new TextAreaControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public TextBoxControl<TModel> TextBox(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<TextBoxControl<TModel>>() != null); return new TextBoxControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public TextBoxControl<TModel> TextBoxFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<TextBoxControl<TModel>>() != null); return new TextBoxControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public DatePickerControl<TModel> DatePicker(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<DatePickerControl<TModel>>() != null); return new DatePickerControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public DatePickerControl<TModel> DatePickerFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<DatePickerControl<TModel>>() != null); return new DatePickerControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } public CkEditorControl<TModel> CkEditor(string htmlFieldName) { Contract.Requires<ArgumentNullException>(htmlFieldName != null, "htmlFieldName"); Contract.Requires<ArgumentException>(!htmlFieldName.IsNullOrWhiteSpace()); Contract.Ensures(Contract.Result<CkEditorControl<TModel>>() != null); return new CkEditorControl<TModel>(html, htmlFieldName, ModelMetadata.FromStringExpression(htmlFieldName, html.ViewData)).FormGroup(this); } public CkEditorControl<TModel> CkEditorFor<TValue>(Expression<Func<TModel, TValue>> expression) { Contract.Requires<ArgumentNullException>(expression != null, "expression"); Contract.Ensures(Contract.Result<CkEditorControl<TModel>>() != null); return new CkEditorControl<TModel>(html, ExpressionHelper.GetExpressionText(expression), ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData)).FormGroup(this); } private void SetDefaultFeedbackIcon() { if (useDefaultFeedbackIcon) { switch (validationState) { case FormGroupValidationState.Success: FeedbackIcon(GlyphIconType.Ok); break; case FormGroupValidationState.Warning: FeedbackIcon(GlyphIconType.WarningSign); break; case FormGroupValidationState.Error: FeedbackIcon(GlyphIconType.Remove); break; default: feedbackIcon = null; break; } } } [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return base.ToString(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { return base.Equals(obj); } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } [EditorBrowsable(EditorBrowsableState.Never)] public new Type GetType() { return base.GetType(); } } }
// 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.Reflection.Metadata.Ecma335; using Xunit; namespace System.Reflection.Metadata.Tests { public class HandleTests { [Fact] public void HandleKindsMatchSpecAndDoNotChange() { // These are chosen to match their encoding in metadata tokens as specified by the CLI spec Assert.Equal(0x00, (int)HandleKind.ModuleDefinition); Assert.Equal(0x01, (int)HandleKind.TypeReference); Assert.Equal(0x02, (int)HandleKind.TypeDefinition); Assert.Equal(0x04, (int)HandleKind.FieldDefinition); Assert.Equal(0x06, (int)HandleKind.MethodDefinition); Assert.Equal(0x08, (int)HandleKind.Parameter); Assert.Equal(0x09, (int)HandleKind.InterfaceImplementation); Assert.Equal(0x0A, (int)HandleKind.MemberReference); Assert.Equal(0x0B, (int)HandleKind.Constant); Assert.Equal(0x0C, (int)HandleKind.CustomAttribute); Assert.Equal(0x0E, (int)HandleKind.DeclarativeSecurityAttribute); Assert.Equal(0x11, (int)HandleKind.StandaloneSignature); Assert.Equal(0x14, (int)HandleKind.EventDefinition); Assert.Equal(0x17, (int)HandleKind.PropertyDefinition); Assert.Equal(0x19, (int)HandleKind.MethodImplementation); Assert.Equal(0x1A, (int)HandleKind.ModuleReference); Assert.Equal(0x1B, (int)HandleKind.TypeSpecification); Assert.Equal(0x20, (int)HandleKind.AssemblyDefinition); Assert.Equal(0x26, (int)HandleKind.AssemblyFile); Assert.Equal(0x23, (int)HandleKind.AssemblyReference); Assert.Equal(0x27, (int)HandleKind.ExportedType); Assert.Equal(0x2A, (int)HandleKind.GenericParameter); Assert.Equal(0x2B, (int)HandleKind.MethodSpecification); Assert.Equal(0x2C, (int)HandleKind.GenericParameterConstraint); Assert.Equal(0x28, (int)HandleKind.ManifestResource); Assert.Equal(0x70, (int)HandleKind.UserString); // These values were chosen arbitrarily, but must still never change Assert.Equal(0x71, (int)HandleKind.Blob); Assert.Equal(0x72, (int)HandleKind.Guid); Assert.Equal(0x78, (int)HandleKind.String); Assert.Equal(0x7c, (int)HandleKind.NamespaceDefinition); } [Fact] public void HandleConversionGivesCorrectKind() { var expectedKinds = new SortedSet<HandleKind>((HandleKind[])Enum.GetValues(typeof(HandleKind))); Action<Handle, HandleKind> assert = (handle, expectedKind) => { Assert.False(expectedKinds.Count == 0, "Repeat handle in tests below."); Assert.Equal(expectedKind, handle.Kind); expectedKinds.Remove(expectedKind); }; assert(default(ModuleDefinitionHandle), HandleKind.ModuleDefinition); assert(default(AssemblyDefinitionHandle), HandleKind.AssemblyDefinition); assert(default(InterfaceImplementationHandle), HandleKind.InterfaceImplementation); assert(default(MethodDefinitionHandle), HandleKind.MethodDefinition); assert(default(MethodSpecificationHandle), HandleKind.MethodSpecification); assert(default(TypeDefinitionHandle), HandleKind.TypeDefinition); assert(default(ExportedTypeHandle), HandleKind.ExportedType); assert(default(TypeReferenceHandle), HandleKind.TypeReference); assert(default(TypeSpecificationHandle), HandleKind.TypeSpecification); assert(default(MemberReferenceHandle), HandleKind.MemberReference); assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition); assert(default(EventDefinitionHandle), HandleKind.EventDefinition); assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition); assert(default(StandaloneSignatureHandle), HandleKind.StandaloneSignature); assert(default(MemberReferenceHandle), HandleKind.MemberReference); assert(default(FieldDefinitionHandle), HandleKind.FieldDefinition); assert(default(EventDefinitionHandle), HandleKind.EventDefinition); assert(default(PropertyDefinitionHandle), HandleKind.PropertyDefinition); assert(default(ParameterHandle), HandleKind.Parameter); assert(default(GenericParameterHandle), HandleKind.GenericParameter); assert(default(GenericParameterConstraintHandle), HandleKind.GenericParameterConstraint); assert(default(ModuleReferenceHandle), HandleKind.ModuleReference); assert(default(CustomAttributeHandle), HandleKind.CustomAttribute); assert(default(DeclarativeSecurityAttributeHandle), HandleKind.DeclarativeSecurityAttribute); assert(default(ManifestResourceHandle), HandleKind.ManifestResource); assert(default(ConstantHandle), HandleKind.Constant); assert(default(ManifestResourceHandle), HandleKind.ManifestResource); assert(default(MethodImplementationHandle), HandleKind.MethodImplementation); assert(default(AssemblyFileHandle), HandleKind.AssemblyFile); assert(default(StringHandle), HandleKind.String); assert(default(AssemblyReferenceHandle), HandleKind.AssemblyReference); assert(default(UserStringHandle), HandleKind.UserString); assert(default(GuidHandle), HandleKind.Guid); assert(default(BlobHandle), HandleKind.Blob); assert(default(NamespaceDefinitionHandle), HandleKind.NamespaceDefinition); assert(default(DocumentHandle), HandleKind.Document); assert(default(MethodDebugInformationHandle), HandleKind.MethodDebugInformation); assert(default(LocalScopeHandle), HandleKind.LocalScope); assert(default(LocalConstantHandle), HandleKind.LocalConstant); assert(default(LocalVariableHandle), HandleKind.LocalVariable); assert(default(ImportScopeHandle), HandleKind.ImportScope); assert(default(CustomDebugInformationHandle), HandleKind.CustomDebugInformation); Assert.True(expectedKinds.Count == 0, "Some handles are missing from this test: " + string.Join("," + Environment.NewLine, expectedKinds)); } [Fact] public void Conversions_Handles() { Assert.Equal(1, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new Handle((byte)HandleType.Module, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new Handle((byte)HandleType.Assembly, 0x00ffffff)).RowId); Assert.Equal(1, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 1)).RowId); Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new Handle((byte)HandleType.InterfaceImpl, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new Handle((byte)HandleType.MethodDef, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new Handle((byte)HandleType.MethodSpec, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new Handle((byte)HandleType.TypeDef, 0x00ffffff)).RowId); Assert.Equal(1, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 1)).RowId); Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new Handle((byte)HandleType.ExportedType, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new Handle((byte)HandleType.TypeRef, 0x00ffffff)).RowId); Assert.Equal(1, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 1)).RowId); Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new Handle((byte)HandleType.TypeSpec, 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId); Assert.Equal(1, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 1)).RowId); Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new Handle((byte)HandleType.Signature, 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new Handle((byte)HandleType.MemberRef, 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new Handle((byte)HandleType.FieldDef, 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new Handle((byte)HandleType.Event, 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new Handle((byte)HandleType.Property, 0x00ffffff)).RowId); Assert.Equal(1, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 1)).RowId); Assert.Equal(0x00ffffff, ((ParameterHandle)new Handle((byte)HandleType.ParamDef, 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterHandle)new Handle((byte)HandleType.GenericParam, 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new Handle((byte)HandleType.GenericParamConstraint, 0x00ffffff)).RowId); Assert.Equal(1, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new Handle((byte)HandleType.ModuleRef, 0x00ffffff)).RowId); Assert.Equal(1, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 1)).RowId); Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new Handle((byte)HandleType.CustomAttribute, 0x00ffffff)).RowId); Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 1)).RowId); Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new Handle((byte)HandleType.DeclSecurity, 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId); Assert.Equal(1, ((ConstantHandle)new Handle((byte)HandleType.Constant, 1)).RowId); Assert.Equal(0x00ffffff, ((ConstantHandle)new Handle((byte)HandleType.Constant, 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new Handle((byte)HandleType.ManifestResource, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new Handle((byte)HandleType.File, 0x00ffffff)).RowId); Assert.Equal(1, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 1)).RowId); Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new Handle((byte)HandleType.MethodImpl, 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new Handle((byte)HandleType.AssemblyRef, 0x00ffffff)).RowId); Assert.Equal(1, ((UserStringHandle)new Handle((byte)HandleType.UserString, 1)).GetHeapOffset()); Assert.Equal(0x00ffffff, ((UserStringHandle)new Handle((byte)HandleType.UserString, 0x00ffffff)).GetHeapOffset()); Assert.Equal(1, ((GuidHandle)new Handle((byte)HandleType.Guid, 1)).Index); Assert.Equal(0x1fffffff, ((GuidHandle)new Handle((byte)HandleType.Guid, 0x1fffffff)).Index); Assert.Equal(1, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((NamespaceDefinitionHandle)new Handle((byte)HandleType.Namespace, 0x1fffffff)).GetHeapOffset()); Assert.Equal(1, ((StringHandle)new Handle((byte)HandleType.String, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((StringHandle)new Handle((byte)HandleType.String, 0x1fffffff)).GetHeapOffset()); Assert.Equal(1, ((BlobHandle)new Handle((byte)HandleType.Blob, 1)).GetHeapOffset()); Assert.Equal(0x1fffffff, ((BlobHandle)new Handle((byte)HandleType.Blob, 0x1fffffff)).GetHeapOffset()); } [Fact] public void Conversions_EntityHandles() { Assert.Equal(1, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.Module | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.Assembly | 0x00ffffff)).RowId); Assert.Equal(1, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 1)).RowId); Assert.Equal(0x00ffffff, ((InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.InterfaceImpl | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodDefinitionHandle)new EntityHandle(TokenTypeIds.MethodDef | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodSpecificationHandle)new EntityHandle(TokenTypeIds.MethodSpec | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeDefinitionHandle)new EntityHandle(TokenTypeIds.TypeDef | 0x00ffffff)).RowId); Assert.Equal(1, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 1)).RowId); Assert.Equal(0x00ffffff, ((ExportedTypeHandle)new EntityHandle(TokenTypeIds.ExportedType | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeReferenceHandle)new EntityHandle(TokenTypeIds.TypeRef | 0x00ffffff)).RowId); Assert.Equal(1, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 1)).RowId); Assert.Equal(0x00ffffff, ((TypeSpecificationHandle)new EntityHandle(TokenTypeIds.TypeSpec | 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId); Assert.Equal(1, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 1)).RowId); Assert.Equal(0x00ffffff, ((StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.Signature | 0x00ffffff)).RowId); Assert.Equal(1, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 1)).RowId); Assert.Equal(0x00ffffff, ((MemberReferenceHandle)new EntityHandle(TokenTypeIds.MemberRef | 0x00ffffff)).RowId); Assert.Equal(1, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 1)).RowId); Assert.Equal(0x00ffffff, ((FieldDefinitionHandle)new EntityHandle(TokenTypeIds.FieldDef | 0x00ffffff)).RowId); Assert.Equal(1, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 1)).RowId); Assert.Equal(0x00ffffff, ((EventDefinitionHandle)new EntityHandle(TokenTypeIds.Event | 0x00ffffff)).RowId); Assert.Equal(1, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 1)).RowId); Assert.Equal(0x00ffffff, ((PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.Property | 0x00ffffff)).RowId); Assert.Equal(1, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 1)).RowId); Assert.Equal(0x00ffffff, ((ParameterHandle)new EntityHandle(TokenTypeIds.ParamDef | 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterHandle)new EntityHandle(TokenTypeIds.GenericParam | 0x00ffffff)).RowId); Assert.Equal(1, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 1)).RowId); Assert.Equal(0x00ffffff, ((GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.GenericParamConstraint | 0x00ffffff)).RowId); Assert.Equal(1, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 1)).RowId); Assert.Equal(0x00ffffff, ((ModuleReferenceHandle)new EntityHandle(TokenTypeIds.ModuleRef | 0x00ffffff)).RowId); Assert.Equal(1, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 1)).RowId); Assert.Equal(0x00ffffff, ((CustomAttributeHandle)new EntityHandle(TokenTypeIds.CustomAttribute | 0x00ffffff)).RowId); Assert.Equal(1, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 1)).RowId); Assert.Equal(0x00ffffff, ((DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.DeclSecurity | 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId); Assert.Equal(1, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 1)).RowId); Assert.Equal(0x00ffffff, ((ConstantHandle)new EntityHandle(TokenTypeIds.Constant | 0x00ffffff)).RowId); Assert.Equal(1, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 1)).RowId); Assert.Equal(0x00ffffff, ((ManifestResourceHandle)new EntityHandle(TokenTypeIds.ManifestResource | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyFileHandle)new EntityHandle(TokenTypeIds.File | 0x00ffffff)).RowId); Assert.Equal(1, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 1)).RowId); Assert.Equal(0x00ffffff, ((MethodImplementationHandle)new EntityHandle(TokenTypeIds.MethodImpl | 0x00ffffff)).RowId); Assert.Equal(1, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 1)).RowId); Assert.Equal(0x00ffffff, ((AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.AssemblyRef | 0x00ffffff)).RowId); } [Fact] public void Conversions_VirtualHandles() { Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Module ), 1)); Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Assembly ), 1)); Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.InterfaceImpl), 1)); Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodDef ), 1)); Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodSpec), 1)); Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeDef ), 1)); Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ExportedType), 1)); Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeRef), 1)); Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.TypeSpec), 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1)); Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Signature), 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MemberRef), 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.FieldDef ), 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Event ), 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Property ), 1)); Assert.Throws<InvalidCastException>(() => (ParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ParamDef), 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParam), 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.GenericParamConstraint), 1)); Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ModuleRef), 1)); Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.CustomAttribute), 1)); Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.DeclSecurity), 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1)); Assert.Throws<InvalidCastException>(() => (ConstantHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.Constant), 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.ManifestResource), 1)); Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.File), 1)); Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle) new Handle((byte)(HandleType.VirtualBit | HandleType.MethodImpl), 1)); Assert.Throws<InvalidCastException>(() => (UserStringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.UserString), 1)); Assert.Throws<InvalidCastException>(() => (GuidHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Guid), 1)); var x1 = (AssemblyReferenceHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.AssemblyRef), 1); var x2 = (StringHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.String), 1); var x3 = (BlobHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Blob), 1); var x4 = (NamespaceDefinitionHandle)new Handle((byte)(HandleType.VirtualBit | HandleType.Namespace), 1); } [Fact] public void Conversions_VirtualEntityHandles() { Assert.Throws<InvalidCastException>(() => (ModuleDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Module | 1)); Assert.Throws<InvalidCastException>(() => (AssemblyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Assembly | 1)); Assert.Throws<InvalidCastException>(() => (InterfaceImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.InterfaceImpl | 1)); Assert.Throws<InvalidCastException>(() => (MethodDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodDef | 1)); Assert.Throws<InvalidCastException>(() => (MethodSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodSpec | 1)); Assert.Throws<InvalidCastException>(() => (TypeDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeDef | 1)); Assert.Throws<InvalidCastException>(() => (ExportedTypeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ExportedType | 1)); Assert.Throws<InvalidCastException>(() => (TypeReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeRef | 1)); Assert.Throws<InvalidCastException>(() => (TypeSpecificationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.TypeSpec | 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1)); Assert.Throws<InvalidCastException>(() => (StandaloneSignatureHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Signature | 1)); Assert.Throws<InvalidCastException>(() => (MemberReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MemberRef | 1)); Assert.Throws<InvalidCastException>(() => (FieldDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.FieldDef | 1)); Assert.Throws<InvalidCastException>(() => (EventDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Event | 1)); Assert.Throws<InvalidCastException>(() => (PropertyDefinitionHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Property | 1)); Assert.Throws<InvalidCastException>(() => (ParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ParamDef | 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParam | 1)); Assert.Throws<InvalidCastException>(() => (GenericParameterConstraintHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.GenericParamConstraint | 1)); Assert.Throws<InvalidCastException>(() => (ModuleReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ModuleRef | 1)); Assert.Throws<InvalidCastException>(() => (CustomAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.CustomAttribute | 1)); Assert.Throws<InvalidCastException>(() => (DeclarativeSecurityAttributeHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.DeclSecurity | 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1)); Assert.Throws<InvalidCastException>(() => (ConstantHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.Constant | 1)); Assert.Throws<InvalidCastException>(() => (ManifestResourceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.ManifestResource | 1)); Assert.Throws<InvalidCastException>(() => (AssemblyFileHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.File | 1)); Assert.Throws<InvalidCastException>(() => (MethodImplementationHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.MethodImpl | 1)); var x1 = (AssemblyReferenceHandle)new EntityHandle(TokenTypeIds.VirtualBit | TokenTypeIds.AssemblyRef | 1); } [Fact] public void IsNil() { Assert.False(ModuleDefinitionHandle.FromRowId(1).IsNil); Assert.False(AssemblyDefinitionHandle.FromRowId(1).IsNil); Assert.False(InterfaceImplementationHandle.FromRowId(1).IsNil); Assert.False(MethodDefinitionHandle.FromRowId(1).IsNil); Assert.False(MethodSpecificationHandle.FromRowId(1).IsNil); Assert.False(TypeDefinitionHandle.FromRowId(1).IsNil); Assert.False(ExportedTypeHandle.FromRowId(1).IsNil); Assert.False(TypeReferenceHandle.FromRowId(1).IsNil); Assert.False(TypeSpecificationHandle.FromRowId(1).IsNil); Assert.False(MemberReferenceHandle.FromRowId(1).IsNil); Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil); Assert.False(EventDefinitionHandle.FromRowId(1).IsNil); Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil); Assert.False(StandaloneSignatureHandle.FromRowId(1).IsNil); Assert.False(MemberReferenceHandle.FromRowId(1).IsNil); Assert.False(FieldDefinitionHandle.FromRowId(1).IsNil); Assert.False(EventDefinitionHandle.FromRowId(1).IsNil); Assert.False(PropertyDefinitionHandle.FromRowId(1).IsNil); Assert.False(ParameterHandle.FromRowId(1).IsNil); Assert.False(GenericParameterHandle.FromRowId(1).IsNil); Assert.False(GenericParameterConstraintHandle.FromRowId(1).IsNil); Assert.False(ModuleReferenceHandle.FromRowId(1).IsNil); Assert.False(CustomAttributeHandle.FromRowId(1).IsNil); Assert.False(DeclarativeSecurityAttributeHandle.FromRowId(1).IsNil); Assert.False(ManifestResourceHandle.FromRowId(1).IsNil); Assert.False(ConstantHandle.FromRowId(1).IsNil); Assert.False(ManifestResourceHandle.FromRowId(1).IsNil); Assert.False(AssemblyFileHandle.FromRowId(1).IsNil); Assert.False(MethodImplementationHandle.FromRowId(1).IsNil); Assert.False(AssemblyReferenceHandle.FromRowId(1).IsNil); Assert.False(((EntityHandle)ModuleDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)InterfaceImplementationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodSpecificationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ExportedTypeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)TypeSpecificationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)StandaloneSignatureHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MemberReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)FieldDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)EventDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)PropertyDefinitionHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ParameterHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)GenericParameterHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)GenericParameterConstraintHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ModuleReferenceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)CustomAttributeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ConstantHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)ManifestResourceHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyFileHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)MethodImplementationHandle.FromRowId(1)).IsNil); Assert.False(((EntityHandle)AssemblyReferenceHandle.FromRowId(1)).IsNil); Assert.False(StringHandle.FromOffset(1).IsNil); Assert.False(BlobHandle.FromOffset(1).IsNil); Assert.False(UserStringHandle.FromOffset(1).IsNil); Assert.False(GuidHandle.FromIndex(1).IsNil); Assert.False(DocumentNameBlobHandle.FromOffset(1).IsNil); Assert.False(((Handle)StringHandle.FromOffset(1)).IsNil); Assert.False(((Handle)BlobHandle.FromOffset(1)).IsNil); Assert.False(((Handle)UserStringHandle.FromOffset(1)).IsNil); Assert.False(((Handle)GuidHandle.FromIndex(1)).IsNil); Assert.False(((BlobHandle)DocumentNameBlobHandle.FromOffset(1)).IsNil); Assert.True(ModuleDefinitionHandle.FromRowId(0).IsNil); Assert.True(AssemblyDefinitionHandle.FromRowId(0).IsNil); Assert.True(InterfaceImplementationHandle.FromRowId(0).IsNil); Assert.True(MethodDefinitionHandle.FromRowId(0).IsNil); Assert.True(MethodSpecificationHandle.FromRowId(0).IsNil); Assert.True(TypeDefinitionHandle.FromRowId(0).IsNil); Assert.True(ExportedTypeHandle.FromRowId(0).IsNil); Assert.True(TypeReferenceHandle.FromRowId(0).IsNil); Assert.True(TypeSpecificationHandle.FromRowId(0).IsNil); Assert.True(MemberReferenceHandle.FromRowId(0).IsNil); Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil); Assert.True(EventDefinitionHandle.FromRowId(0).IsNil); Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil); Assert.True(StandaloneSignatureHandle.FromRowId(0).IsNil); Assert.True(MemberReferenceHandle.FromRowId(0).IsNil); Assert.True(FieldDefinitionHandle.FromRowId(0).IsNil); Assert.True(EventDefinitionHandle.FromRowId(0).IsNil); Assert.True(PropertyDefinitionHandle.FromRowId(0).IsNil); Assert.True(ParameterHandle.FromRowId(0).IsNil); Assert.True(GenericParameterHandle.FromRowId(0).IsNil); Assert.True(GenericParameterConstraintHandle.FromRowId(0).IsNil); Assert.True(ModuleReferenceHandle.FromRowId(0).IsNil); Assert.True(CustomAttributeHandle.FromRowId(0).IsNil); Assert.True(DeclarativeSecurityAttributeHandle.FromRowId(0).IsNil); Assert.True(ManifestResourceHandle.FromRowId(0).IsNil); Assert.True(ConstantHandle.FromRowId(0).IsNil); Assert.True(ManifestResourceHandle.FromRowId(0).IsNil); Assert.True(AssemblyFileHandle.FromRowId(0).IsNil); Assert.True(MethodImplementationHandle.FromRowId(0).IsNil); Assert.True(AssemblyReferenceHandle.FromRowId(0).IsNil); Assert.True(((EntityHandle)ModuleDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)InterfaceImplementationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodSpecificationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ExportedTypeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)TypeSpecificationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)StandaloneSignatureHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MemberReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)FieldDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)EventDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)PropertyDefinitionHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ParameterHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)GenericParameterHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)GenericParameterConstraintHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ModuleReferenceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)CustomAttributeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)DeclarativeSecurityAttributeHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ConstantHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)ManifestResourceHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyFileHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)MethodImplementationHandle.FromRowId(0)).IsNil); Assert.True(((EntityHandle)AssemblyReferenceHandle.FromRowId(0)).IsNil); // heaps: Assert.True(StringHandle.FromOffset(0).IsNil); Assert.True(BlobHandle.FromOffset(0).IsNil); Assert.True(UserStringHandle.FromOffset(0).IsNil); Assert.True(GuidHandle.FromIndex(0).IsNil); Assert.True(DocumentNameBlobHandle.FromOffset(0).IsNil); Assert.True(((Handle)StringHandle.FromOffset(0)).IsNil); Assert.True(((Handle)BlobHandle.FromOffset(0)).IsNil); Assert.True(((Handle)UserStringHandle.FromOffset(0)).IsNil); Assert.True(((Handle)GuidHandle.FromIndex(0)).IsNil); Assert.True(((BlobHandle)DocumentNameBlobHandle.FromOffset(0)).IsNil); // virtual: Assert.False(AssemblyReferenceHandle.FromVirtualIndex(0).IsNil); Assert.False(StringHandle.FromVirtualIndex(0).IsNil); Assert.False(BlobHandle.FromVirtualIndex(0, 0).IsNil); Assert.False(((Handle)AssemblyReferenceHandle.FromVirtualIndex(0)).IsNil); Assert.False(((Handle)StringHandle.FromVirtualIndex(0)).IsNil); Assert.False(((Handle)BlobHandle.FromVirtualIndex(0, 0)).IsNil); } [Fact] public void IsVirtual() { Assert.False(AssemblyReferenceHandle.FromRowId(1).IsVirtual); Assert.False(StringHandle.FromOffset(1).IsVirtual); Assert.False(BlobHandle.FromOffset(1).IsVirtual); Assert.True(AssemblyReferenceHandle.FromVirtualIndex(0).IsVirtual); Assert.True(StringHandle.FromVirtualIndex(0).IsVirtual); Assert.True(BlobHandle.FromVirtualIndex(0, 0).IsVirtual); } [Fact] public void StringKinds() { var str = StringHandle.FromOffset(123); Assert.Equal(StringKind.Plain, str.StringKind); Assert.False(str.IsVirtual); Assert.Equal(123, str.GetHeapOffset()); Assert.Equal(str, (Handle)str); Assert.Equal(str, (StringHandle)(Handle)str); Assert.Equal(0x78, ((Handle)str).VType); Assert.Equal(123, ((Handle)str).Offset); var vstr = StringHandle.FromVirtualIndex(StringHandle.VirtualIndex.AttributeTargets); Assert.Equal(StringKind.Virtual, vstr.StringKind); Assert.True(vstr.IsVirtual); Assert.Equal(StringHandle.VirtualIndex.AttributeTargets, vstr.GetVirtualIndex()); Assert.Equal(vstr, (Handle)vstr); Assert.Equal(vstr, (StringHandle)(Handle)vstr); Assert.Equal(0xF8, ((Handle)vstr).VType); Assert.Equal((int)StringHandle.VirtualIndex.AttributeTargets, ((Handle)vstr).Offset); var dot = StringHandle.FromOffset(123).WithDotTermination(); Assert.Equal(StringKind.DotTerminated, dot.StringKind); Assert.False(dot.IsVirtual); Assert.Equal(123, dot.GetHeapOffset()); Assert.Equal(dot, (Handle)dot); Assert.Equal(dot, (StringHandle)(Handle)dot); Assert.Equal(0x79, ((Handle)dot).VType); Assert.Equal(123, ((Handle)dot).Offset); var winrtPrefix = StringHandle.FromOffset(123).WithWinRTPrefix(); Assert.Equal(StringKind.WinRTPrefixed, winrtPrefix.StringKind); Assert.True(winrtPrefix.IsVirtual); Assert.Equal(123, winrtPrefix.GetHeapOffset()); Assert.Equal(winrtPrefix, (Handle)winrtPrefix); Assert.Equal(winrtPrefix, (StringHandle)(Handle)winrtPrefix); Assert.Equal(0xF9, ((Handle)winrtPrefix).VType); Assert.Equal(123, ((Handle)winrtPrefix).Offset); } [Fact] public void NamespaceKinds() { var full = NamespaceDefinitionHandle.FromFullNameOffset(123); Assert.False(full.IsVirtual); Assert.Equal(123, full.GetHeapOffset()); Assert.Equal(full, (Handle)full); Assert.Equal(full, (NamespaceDefinitionHandle)(Handle)full); Assert.Equal(0x7C, ((Handle)full).VType); Assert.Equal(123, ((Handle)full).Offset); var virtual1 = NamespaceDefinitionHandle.FromVirtualIndex(123); Assert.True(virtual1.IsVirtual); Assert.Equal(virtual1, (Handle)virtual1); Assert.Equal(virtual1, (NamespaceDefinitionHandle)(Handle)virtual1); Assert.Equal(0xFC, ((Handle)virtual1).VType); Assert.Equal(123, ((Handle)virtual1).Offset); var virtual2 = NamespaceDefinitionHandle.FromVirtualIndex(uint.MaxValue >> 3); Assert.True(virtual2.IsVirtual); Assert.Equal(virtual2, (Handle)virtual2); Assert.Equal(virtual2, (NamespaceDefinitionHandle)(Handle)virtual2); Assert.Equal(0xFC, ((Handle)virtual2).VType); Assert.Equal((int)(uint.MaxValue >> 3), ((Handle)virtual2).Offset); Assert.Throws<BadImageFormatException>(() => NamespaceDefinitionHandle.FromVirtualIndex((uint.MaxValue >> 3) + 1)); } [Fact] public void HandleKindHidesSpecialStringAndNamespaces() { foreach (int virtualBit in new[] { 0, (int)HandleType.VirtualBit }) { for (int i = 0; i <= sbyte.MaxValue; i++) { Handle handle = new Handle((byte)(virtualBit | i), 0); Assert.True(handle.IsNil ^ handle.IsVirtual); Assert.Equal(virtualBit != 0, handle.IsVirtual); Assert.Equal(handle.EntityHandleType, (uint)i << TokenTypeIds.RowIdBitCount); switch (i) { // String has two extra bits to represent its kind that are hidden from the handle type case (int)HandleKind.String: case (int)HandleKind.String + 1: case (int)HandleKind.String + 2: case (int)HandleKind.String + 3: Assert.Equal(HandleKind.String, handle.Kind); break; // all other types surface token type directly. default: Assert.Equal((int)handle.Kind, i); break; } } } } [Fact] public void MethodDefToDebugInfo() { Assert.Equal( MethodDefinitionHandle.FromRowId(123).ToDebugInformationHandle(), MethodDebugInformationHandle.FromRowId(123)); Assert.Equal( MethodDebugInformationHandle.FromRowId(123).ToDefinitionHandle(), MethodDefinitionHandle.FromRowId(123)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Avalonia.Controls; using Avalonia.Controls.Platform.Surfaces; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Media.Imaging; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Threading; using Avalonia.Utilities; namespace Avalonia.Headless { class HeadlessWindowImpl : IWindowImpl, IPopupImpl, IFramebufferPlatformSurface, IHeadlessWindow { private IKeyboardDevice _keyboard; private Stopwatch _st = Stopwatch.StartNew(); private Pointer _mousePointer; private WriteableBitmap _lastRenderedFrame; private object _sync = new object(); public bool IsPopup { get; } public HeadlessWindowImpl(bool isPopup) { IsPopup = isPopup; Surfaces = new object[] { this }; _keyboard = AvaloniaLocator.Current.GetService<IKeyboardDevice>(); _mousePointer = new Pointer(Pointer.GetNextFreeId(), PointerType.Mouse, true); MouseDevice = new MouseDevice(_mousePointer); ClientSize = new Size(1024, 768); } public void Dispose() { Closed?.Invoke(); _lastRenderedFrame?.Dispose(); _lastRenderedFrame = null; } public Size ClientSize { get; set; } public Size? FrameSize => null; public double RenderScaling { get; } = 1; public double DesktopScaling => RenderScaling; public IEnumerable<object> Surfaces { get; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size, PlatformResizeReason> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public IRenderer CreateRenderer(IRenderRoot root) => new DeferredRenderer(root, AvaloniaLocator.Current.GetService<IRenderLoop>()); public void Invalidate(Rect rect) { } public void SetInputRoot(IInputRoot inputRoot) { InputRoot = inputRoot; } public IInputRoot InputRoot { get; set; } public Point PointToClient(PixelPoint point) => point.ToPoint(RenderScaling); public PixelPoint PointToScreen(Point point) => PixelPoint.FromPoint(point, RenderScaling); public void SetCursor(ICursorImpl cursor) { } public Action Closed { get; set; } public IMouseDevice MouseDevice { get; } public void Show(bool activate, bool isDialog) { if (activate) Dispatcher.UIThread.Post(() => Activated?.Invoke(), DispatcherPriority.Input); } public void Hide() { Dispatcher.UIThread.Post(() => Deactivated?.Invoke(), DispatcherPriority.Input); } public void BeginMoveDrag() { } public void BeginResizeDrag(WindowEdge edge) { } public PixelPoint Position { get; set; } public Action<PixelPoint> PositionChanged { get; set; } public void Activate() { Dispatcher.UIThread.Post(() => Activated?.Invoke(), DispatcherPriority.Input); } public Action Deactivated { get; set; } public Action Activated { get; set; } public IPlatformHandle Handle { get; } = new PlatformHandle(IntPtr.Zero, "STUB"); public Size MaxClientSize { get; } = new Size(1920, 1280); public void Resize(Size clientSize, PlatformResizeReason reason) { // Emulate X11 behavior here if (IsPopup) DoResize(clientSize); else Dispatcher.UIThread.Post(() => { DoResize(clientSize); }); } void DoResize(Size clientSize) { // Uncomment this check and experience a weird bug in layout engine if (ClientSize != clientSize) { ClientSize = clientSize; Resized?.Invoke(clientSize, PlatformResizeReason.Unspecified); } } public void SetMinMaxSize(Size minSize, Size maxSize) { } public void SetTopmost(bool value) { } public IScreenImpl Screen { get; } = new HeadlessScreensStub(); public WindowState WindowState { get; set; } public Action<WindowState> WindowStateChanged { get; set; } public void SetTitle(string title) { } public void SetSystemDecorations(bool enabled) { } public void SetIcon(IWindowIconImpl icon) { } public void ShowTaskbarIcon(bool value) { } public void CanResize(bool value) { } public Func<bool> Closing { get; set; } class FramebufferProxy : ILockedFramebuffer { private readonly ILockedFramebuffer _fb; private readonly Action _onDispose; private bool _disposed; public FramebufferProxy(ILockedFramebuffer fb, Action onDispose) { _fb = fb; _onDispose = onDispose; } public void Dispose() { if (_disposed) return; _disposed = true; _fb.Dispose(); _onDispose(); } public IntPtr Address => _fb.Address; public PixelSize Size => _fb.Size; public int RowBytes => _fb.RowBytes; public Vector Dpi => _fb.Dpi; public PixelFormat Format => _fb.Format; } public ILockedFramebuffer Lock() { var bmp = new WriteableBitmap(PixelSize.FromSize(ClientSize, RenderScaling), new Vector(96, 96) * RenderScaling, PixelFormat.Rgba8888, AlphaFormat.Premul); var fb = bmp.Lock(); return new FramebufferProxy(fb, () => { lock (_sync) { _lastRenderedFrame?.Dispose(); _lastRenderedFrame = bmp; } }); } public IRef<IWriteableBitmapImpl> GetLastRenderedFrame() { lock (_sync) return _lastRenderedFrame?.PlatformImpl?.CloneAs<IWriteableBitmapImpl>(); } private ulong Timestamp => (ulong)_st.ElapsedMilliseconds; // TODO: Hook recent Popup changes. IPopupPositioner IPopupImpl.PopupPositioner => null; public Size MaxAutoSizeHint => new Size(1920, 1080); public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; } public WindowTransparencyLevel TransparencyLevel => WindowTransparencyLevel.None; public Action GotInputWhenDisabled { get; set; } public bool IsClientAreaExtendedToDecorations => false; public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; } public bool NeedsManagedDecorations => false; public Thickness ExtendedMargins => new Thickness(); public Thickness OffScreenMargin => new Thickness(); public Action LostFocus { get; set; } public AcrylicPlatformCompensationLevels AcrylicCompensationLevels => new AcrylicPlatformCompensationLevels(1, 1, 1); void IHeadlessWindow.KeyPress(Key key, RawInputModifiers modifiers) { Input?.Invoke(new RawKeyEventArgs(_keyboard, Timestamp, InputRoot, RawKeyEventType.KeyDown, key, modifiers)); } void IHeadlessWindow.KeyRelease(Key key, RawInputModifiers modifiers) { Input?.Invoke(new RawKeyEventArgs(_keyboard, Timestamp, InputRoot, RawKeyEventType.KeyUp, key, modifiers)); } void IHeadlessWindow.MouseDown(Point point, int button, RawInputModifiers modifiers) { Input?.Invoke(new RawPointerEventArgs(MouseDevice, Timestamp, InputRoot, button == 0 ? RawPointerEventType.LeftButtonDown : button == 1 ? RawPointerEventType.MiddleButtonDown : RawPointerEventType.RightButtonDown, point, modifiers)); } void IHeadlessWindow.MouseMove(Point point, RawInputModifiers modifiers) { Input?.Invoke(new RawPointerEventArgs(MouseDevice, Timestamp, InputRoot, RawPointerEventType.Move, point, modifiers)); } void IHeadlessWindow.MouseUp(Point point, int button, RawInputModifiers modifiers) { Input?.Invoke(new RawPointerEventArgs(MouseDevice, Timestamp, InputRoot, button == 0 ? RawPointerEventType.LeftButtonUp : button == 1 ? RawPointerEventType.MiddleButtonUp : RawPointerEventType.RightButtonUp, point, modifiers)); } void IWindowImpl.Move(PixelPoint point) { } public IPopupImpl CreatePopup() { // TODO: Hook recent Popup changes. return null; } public void SetWindowManagerAddShadowHint(bool enabled) { } public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel) { } public void SetParent(IWindowImpl parent) { } public void SetEnabled(bool enable) { } public void SetSystemDecorations(SystemDecorations enabled) { } public void BeginMoveDrag(PointerPressedEventArgs e) { } public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e) { } public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint) { } public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints) { } public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight) { } } }
/* Copyright Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache 2 License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.Security.Principal; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.WebPages; using Microsoft.Practices.ServiceLocation; using Microsoft.Practices.Unity; using MileageStats.Web.Capabilities; using MileageStats.Web.ClientProfile; using MileageStats.Web.Models; using MileageStats.Web.Authentication; using MileageStats.Web.UnityExtensions; using System.Linq; using System.Collections.Generic; using System.Web.Configuration; using MileageStats.Domain.Handlers; using MileageStats.Web.Infrastructure; using System.Net; using MileageStats.Domain.Contracts; namespace MileageStats.Web { public class MvcApplication : HttpApplication { private static IUnityContainer container; public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new CustomHandleErrorFilter(new Dictionary<Type, HttpStatusCode>() { { typeof(UnauthorizedException), HttpStatusCode.Forbidden } }) { View = "_Error" }); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" }); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "JsonMakesForYearRoute", // Route name "Vehicle/MakesForYear", // URL with parameters new { action = "MakesForYear", controller = "ModelAndMake" } // Parameter defaults ); routes.MapRoute( "JsonModelsForMakeRoute", // Route name "Vehicle/ModelsForMake", // URL with parameters new { action = "ModelsForMake", controller = "ModelAndMake" } // Parameter defaults ); routes.MapRoute( "VehiclePhotoRoute", // Route name "Vehicle/Photo/{vehiclePhotoId}", // URL with parameters new { controller = "VehiclePhoto", action = "GetVehiclePhoto", vehiclePhotoId = UrlParameter.Optional } // Parameter defaults ); routes.MapRoute( "VehicleFuelEfficiencyChartRoute", "Vehicle/FuelEfficiencyChart/{userId}/{vehicleId}", new { controller = "VehicleChart", action = "FuelEfficiencyChart" } ); routes.MapRoute( "JsonGetVehicleStatisticSeriesRoute", "Vehicle/JsonGetVehicleStatisticSeries/{id}", new { controller = "VehicleChart", action = "JsonGetVehicleStatisticSeries", id = UrlParameter.Optional } ); routes.MapRoute( "VehicleTotalDistanceChartRoute", "Vehicle/TotalDistanceChart/{userId}/{vehicleId}", new { controller = "VehicleChart", action = "TotalDistanceChart" } ); routes.MapRoute( "VehicleTotalCostChartRoute", "Vehicle/TotalCostChart/{userId}/{vehicleId}", new { controller = "VehicleChart", action = "TotalCostChart" } ); routes.MapRoute( "ListRoute", // Route name "Vehicle/{vehicleId}/{controller}/List", // URL with parameters new { action = "List", vehicleId = UrlParameter.Optional } // Parameter defaults ); ); routes.MapRoute( "ListPartialRoute", // Route name "Vehicle/{vehicleId}/{controller}/ListPartial", // URL with parameters new { action = "ListPartial", vehicleId = UrlParameter.Optional } // Parameter defaults ); routes.MapRoute( "JsonListRoute", // Route name "{controller}/JsonList/{vehicleId}", // URL with parameters new { action = "JsonList" } // Parameter defaults ); routes.MapRoute( "FulfillRoute", // Route name "Vehicle/{vehicleId}/Reminder/{id}/Fulfill", new { action = "Fulfill", controller = "Reminder" } ); routes.MapRoute( "AddRoute", // Route name "Vehicle/{vehicleId}/{controller}/Add", new {action = "Add"} ); routes.MapRoute( "VehicleDetailsRoute", "Vehicle/{vehicleId}/Details", new { controller = "Vehicle", action = "Details" } ); routes.MapRoute( "VehicleEditRoute", "Vehicle/{vehicleId}/Edit", new { controller = "Vehicle", action = "Edit" } ); routes.MapRoute( "DetailsRoute", "Vehicle/{vehicleId}/{controller}/{id}/Details", new { action = "Details" } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new {controller = "Dashboard", action = "Index", id = UrlParameter.Optional} // Parameter defaults ); } public override void Init() { PostAuthenticateRequest += PostAuthenticateRequestHandler; EndRequest += EndRequestHandler; base.Init(); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); InitializeDependencyInjectionContainer(); // Sets a custom controller factory for overriding the default settings like the TempDataProvider. ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory()); // Injects the custom BrowserCapabilitiesProvider into the ASP.NET pipeline. HttpCapabilitiesBase.BrowserCapabilitiesProvider = container.Resolve<MobileCapabilitiesProvider>(); // Injects the custom metadata provider. ModelMetadataProviders.Current = new CustomMetadataProvider(); // When the user decides to explicitly switch to the desktop view, we // want to display a placeholder page rather than the actual desktop. // We can identify that this is the case when the actual user agent // doesn't match the overriden user agent. DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("PlaceholderDesktop") { ContextCondition = context => context.GetOverriddenUserAgent() != context.Request.UserAgent }); } private void EndRequestHandler(object sender, EventArgs e) { // This is a workaround since subscribing to HttpContext.Current.ApplicationInstance.EndRequest // from HttpContext.Current.ApplicationInstance.BeginRequest does not work. IEnumerable<UnityHttpContextPerRequestLifetimeManager> perRequestManagers = container.Registrations .Select(r => r.LifetimeManager) .OfType<UnityHttpContextPerRequestLifetimeManager>() .ToArray(); foreach (var manager in perRequestManagers) { manager.Dispose(); } } private void PostAuthenticateRequestHandler(object sender, EventArgs e) { var formsAuthentication = ServiceLocator.Current.GetInstance<IFormsAuthentication>(); var ticket = formsAuthentication.GetAuthenticationTicket(new HttpContextWrapper(HttpContext.Current)); if (ticket != null) { var mileageStatsIdentity = new MileageStatsIdentity(ticket); //Implemented workaround for the scenario where the user is not found in the repository // but the cookie exists. var getUser = ServiceLocator.Current.GetInstance<GetUserByClaimId>(); if (getUser.Execute(mileageStatsIdentity.Name) == null) { formsAuthentication.Signout(); if (Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; Context.Response.End(); } else { Context.Response.Redirect("~/Auth/Index", true); } } else { Context.User = new GenericPrincipal(mileageStatsIdentity, null); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This should survive the lifetime of the application.")] private static void InitializeDependencyInjectionContainer() { container = new UnityContainerFactory().CreateConfiguredContainer(); var serviceLocator = new UnityServiceLocator(container); ServiceLocator.SetLocatorProvider(() => serviceLocator); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); container.RegisterInstance<IProfileManifestRepository>( new XmlProfileManifestRepository("~/ClientProfile/", (path) => HttpContext.Current.Server.MapPath(path))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Semver; using Umbraco.Core.Configuration; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Services; namespace Umbraco.Core.Persistence.Migrations.Initial { public class DatabaseSchemaResult { public DatabaseSchemaResult() { Errors = new List<Tuple<string, string>>(); TableDefinitions = new List<TableDefinition>(); ValidTables = new List<string>(); ValidColumns = new List<string>(); ValidConstraints = new List<string>(); ValidIndexes = new List<string>(); } public List<Tuple<string, string>> Errors { get; set; } public List<TableDefinition> TableDefinitions { get; set; } public List<string> ValidTables { get; set; } public List<string> ValidColumns { get; set; } public List<string> ValidConstraints { get; set; } public List<string> ValidIndexes { get; set; } internal IEnumerable<DbIndexDefinition> DbIndexDefinitions { get; set; } /// <summary> /// Checks in the db which version is installed based on the migrations that have been run /// </summary> /// <param name="migrationEntryService"></param> /// <returns></returns> public SemVersion DetermineInstalledVersionByMigrations(IMigrationEntryService migrationEntryService) { SemVersion mostrecent = null; if (ValidTables.Any(x => x.InvariantEquals("umbracoMigration"))) { var allMigrations = migrationEntryService.GetAll(Constants.System.UmbracoMigrationName); mostrecent = allMigrations.OrderByDescending(x => x.Version).Select(x => x.Version).FirstOrDefault(); } return mostrecent ?? new SemVersion(new Version(0, 0, 0)); } /// <summary> /// Determines the version of the currently installed database by detecting the current database structure /// </summary> /// <returns> /// A <see cref="Version"/> with Major and Minor values for /// non-empty database, otherwise "0.0.0" for empty databases. /// </returns> public Version DetermineInstalledVersion() { //If (ValidTables.Count == 0) database is empty and we return -> new Version(0, 0, 0); if (ValidTables.Count == 0) return new Version(0, 0, 0); //If Errors is empty or if TableDefinitions tables + columns correspond to valid tables + columns then we're at current version if (Errors.Any() == false || (TableDefinitions.All(x => ValidTables.Contains(x.Name)) && TableDefinitions.SelectMany(definition => definition.Columns).All(x => ValidColumns.Contains(x.Name)))) return UmbracoVersion.Current; //If Errors contains umbracoApp or umbracoAppTree its pre-6.0.0 -> new Version(4, 10, 0); if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoApp") || x.Item2.InvariantEquals("umbracoAppTree")))) { //If Errors contains umbracoUser2app or umbracoAppTree foreignkey to umbracoApp exists its pre-4.8.0 -> new Version(4, 7, 0); if (Errors.Any(x => x.Item1.Equals("Constraint") && (x.Item2.InvariantContains("umbracoUser2app_umbracoApp") || x.Item2.InvariantContains("umbracoAppTree_umbracoApp")))) { return new Version(4, 7, 0); } return new Version(4, 8, 0); } //if the error is for umbracoServer if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoServer")))) { return new Version(6, 0, 0); } //if the error indicates a problem with the column cmsMacroProperty.macroPropertyType then it is not version 7 // since these columns get removed in v7 if (Errors.Any(x => x.Item1.Equals("Column") && (x.Item2.InvariantEquals("cmsMacroProperty,macroPropertyType")))) { //if the error is for this IX_umbracoNodeTrashed which is added in 6.2 AND in 7.1 but we do not have the above columns // then it must mean that we aren't on 6.2 so must be 6.1 if (Errors.Any(x => x.Item1.Equals("Index") && (x.Item2.InvariantEquals("IX_umbracoNodeTrashed")))) { return new Version(6, 1, 0); } else { //if there are no errors for that index, then the person must have 6.2 installed return new Version(6, 2, 0); } } //if the error indicates a problem with the constraint FK_cmsContent_cmsContentType_nodeId then it is not version 7.2 // since this gets added in 7.2.0 so it must be the previous version if (Errors.Any(x => x.Item1.Equals("Constraint") && (x.Item2.InvariantEquals("FK_cmsContent_cmsContentType_nodeId")))) { return new Version(7, 0, 0); } //if the error is for umbracoAccess it must be the previous version to 7.3 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoAccess")))) { return new Version(7, 2, 0); } //if the error is for umbracoDeployChecksum it must be the previous version to 7.4 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoDeployChecksum")))) { return new Version(7, 3, 0); } //if the error is for umbracoRedirectUrl it must be the previous version to 7.5 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoRedirectUrl")))) { return new Version(7, 4, 0); } //if the error indicates a problem with the column cmsMacroProperty.uniquePropertyId then it is not version 7.6 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Column") && (x.Item2.InvariantEquals("cmsMacroProperty,uniquePropertyId")))) { return new Version(7, 5, 0); } //if the error is for umbracoUserGroup it must be the previous version to 7.7 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("umbracoUserStartNode")))) { return new Version(7, 6, 0); } //if the error is for cmsMedia it must be the previous version to 7.8 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Table") && (x.Item2.InvariantEquals("cmsMedia")))) { return new Version(7, 7, 0); } //if the error is for isSensitive column it must be the previous version to 7.9 since that is when it is added if (Errors.Any(x => x.Item1.Equals("Column") && (x.Item2.InvariantEquals("cmsMemberType,isSensitive")))) { return new Version(7, 8, 0); } return UmbracoVersion.Current; } /// <summary> /// Gets a summary of the schema validation result /// </summary> /// <returns>A string containing a human readable string with a summary message</returns> public string GetSummary() { var sb = new StringBuilder(); if (Errors.Any() == false) { sb.AppendLine("The database schema validation didn't find any errors."); return sb.ToString(); } //Table error summary if (Errors.Any(x => x.Item1.Equals("Table"))) { sb.AppendLine("The following tables were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Table")).Select(x => x.Item2))); sb.AppendLine(" "); } //Column error summary if (Errors.Any(x => x.Item1.Equals("Column"))) { sb.AppendLine("The following columns were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Column")).Select(x => x.Item2))); sb.AppendLine(" "); } //Constraint error summary if (Errors.Any(x => x.Item1.Equals("Constraint"))) { sb.AppendLine("The following constraints (Primary Keys, Foreign Keys and Indexes) were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Constraint")).Select(x => x.Item2))); sb.AppendLine(" "); } //Index error summary if (Errors.Any(x => x.Item1.Equals("Index"))) { sb.AppendLine("The following indexes were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Index")).Select(x => x.Item2))); sb.AppendLine(" "); } //Unknown constraint error summary if (Errors.Any(x => x.Item1.Equals("Unknown"))) { sb.AppendLine("The following unknown constraints (Primary Keys, Foreign Keys and Indexes) were found in the database, but are not in the current schema:"); sb.AppendLine(string.Join(",", Errors.Where(x => x.Item1.Equals("Unknown")).Select(x => x.Item2))); sb.AppendLine(" "); } if (SqlSyntaxContext.SqlSyntaxProvider is MySqlSyntaxProvider) { sb.AppendLine("Please note that the constraints could not be validated because the current dataprovider is MySql."); } return sb.ToString(); } } }
using UnityEngine; using System.Collections; public class MenuPage : FPage { private static Starfield background; private static Starfield background2; public static FSprite menuBackground; public static FSprite menuAnims; private static FButton btnInstructions; private static FButton btnCredits; private static FButton btnPlay; private bool playingTransition = false; private bool playReverse = false; private bool transitionIn = false; private int frameCount = 0; private int animationCounter = 0; // Use this for initialization override public void Start () { transitionIn = InitScript.shouldPlayMenuTransition; InitScript.inGame = false; background = new Starfield(InitScript.bg1Pos,false); Futile.stage.AddChild(background); background2 = new Starfield(InitScript.bg2Pos, false); Futile.stage.AddChild(background2); menuBackground = new FSprite("MenuStatic.png"); menuBackground.scale = 2.0f; menuBackground.x = 0; if (InitScript.shouldPlayMenuTransition == true) menuBackground.isVisible = false; Futile.stage.AddChild(menuBackground); menuAnims = new FSprite("Menutoplay6.png"); if (InitScript.shouldPlayMenuTransition == false) menuAnims.SetElementByName("MenuAnim0.png"); menuAnims.scale = 2.0f; menuAnims.x = 0; //menuAnims.isVisible = false; Futile.stage.AddChild(menuAnims); btnInstructions = new FButton("InfoButton.png"); btnInstructions.x -= 1; btnInstructions.y -= 126; btnInstructions.scale = 2.0f; if (InitScript.shouldPlayMenuTransition == true) btnInstructions.isVisible = false; Futile.stage.AddChild(btnInstructions); btnCredits = new FButton("CreditsButton.png"); btnCredits.x -= 1; btnCredits.y -= 166; btnCredits.scale = 2.0f; if (InitScript.shouldPlayMenuTransition == true) btnCredits.isVisible = false; Futile.stage.AddChild(btnCredits); btnPlay = new FButton("PlayButton.png"); btnPlay.x = 0; btnPlay.y = 0; btnPlay.scale = 2.0f; Futile.stage.AddChild(btnPlay); InitScript.blackBar1.MoveToTop(); InitScript.blackBar2.MoveToTop(); btnInstructions.SignalRelease += HandleInfoButtonRelease; btnCredits.SignalRelease += HandleCreditButtonRelease; btnPlay.SignalRelease += HandlePlayButtonRelease; Futile.instance.SignalUpdate += HandleUpdate; } override public void HandleAddedToStage() { base.HandleAddedToStage(); } override public void HandleRemovedFromStage() { Destroy(); Futile.instance.SignalUpdate -= HandleUpdate; base.HandleRemovedFromStage(); } public static void Destroy() { Futile.stage.RemoveChild(background); Futile.stage.RemoveChild(background2); Futile.stage.RemoveChild(menuAnims); Futile.stage.RemoveChild(btnCredits); Futile.stage.RemoveChild(btnInstructions); } private void HandlePlayButtonRelease(FButton button) { playAnimation(); } // Update is called once per frame private void HandleCreditButtonRelease (FButton button) { if (InitScript.inGame == false) InitScript.gotoCredits(); } private void HandleInfoButtonRelease (FButton button) { if (InitScript.inGame == false) InitScript.gotoInstructions(); } private void playAnimation() { Futile.stage.RemoveChild(menuBackground); btnInstructions.isVisible = false; btnCredits.isVisible = false; playingTransition = true; } protected void HandleUpdate () { background.Update(); InitScript.bg1Pos = background.x; background2.Update(); InitScript.bg2Pos = background2.x; //if (Input.GetMouseButtonDown(0)) //{ // playAnimation(); //} frameCount++; if (transitionIn == true) { if (frameCount % 3 == 0) { animationCounter++; if (animationCounter >= 8) animationCounter = 0; if (animationCounter == 0) menuAnims.SetElementByName("Menutoplay6.png"); else if (animationCounter == 1) menuAnims.SetElementByName("Menutoplay5.png"); else if (animationCounter == 2) menuAnims.SetElementByName("Menutoplay4.png"); else if (animationCounter == 3) menuAnims.SetElementByName("Menutoplay3.png"); else if (animationCounter == 4) menuAnims.SetElementByName("Menutoplay2.png"); else if (animationCounter == 5) menuAnims.SetElementByName("Menutoplay1.png"); else if (animationCounter == 6) menuAnims.SetElementByName("Menutoplay0.png"); else if (animationCounter == 7) { //menuAnims.isVisible = true; menuBackground.isVisible = true; btnInstructions.isVisible = true; btnCredits.isVisible = true; transitionIn = false; } } } if (playingTransition == false && transitionIn == false) { if (frameCount % 5 == 0) { animationCounter++; if (animationCounter >= 4) animationCounter = 0; if (animationCounter == 0) menuAnims.SetElementByName("MenuAnim0.png"); else if (animationCounter == 1) menuAnims.SetElementByName("MenuAnim1.png"); else if (animationCounter == 2) menuAnims.SetElementByName("MenuAnim2.png"); else if (animationCounter == 3) menuAnims.SetElementByName("MenuAnim3.png"); } } else if (playingTransition == true) { if (frameCount % 3 == 0) { animationCounter++; if (animationCounter >= 8) animationCounter = 0; if (animationCounter == 0) menuAnims.SetElementByName("Menutoplay0.png"); else if (animationCounter == 1) menuAnims.SetElementByName("Menutoplay1.png"); else if (animationCounter == 2) menuAnims.SetElementByName("Menutoplay2.png"); else if (animationCounter == 3) menuAnims.SetElementByName("Menutoplay3.png"); else if (animationCounter == 4) menuAnims.SetElementByName("Menutoplay4.png"); else if (animationCounter == 5) menuAnims.SetElementByName("Menutoplay5.png"); else if (animationCounter == 6) menuAnims.SetElementByName("Menutoplay6.png"); else if (animationCounter == 7) InitScript.goToGame(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters { public class InputFormatterTest { private class CatchAllFormatter : TestFormatter { public CatchAllFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("*/*")); } } [Theory] [InlineData("application/mathml-content+xml")] [InlineData("application/mathml-presentation+xml")] [InlineData("application/mathml+xml; undefined=ignored")] [InlineData("application/octet-stream; padding=3")] [InlineData("application/xml")] [InlineData("application/xml-dtd; undefined=ignored")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p; undefined=ignored")] [InlineData("text/html")] public void CatchAll_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType) { // Arrange var formatter = new CatchAllFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.True(result); } private class MultipartFormatter : TestFormatter { public MultipartFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("multipart/*")); } } [Theory] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p; undefined=ignored")] public void MultipartFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType) { // Arrange var formatter = new MultipartFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.True(result); } [Theory] [InlineData("application/mathml-content+xml")] [InlineData("application/mathml-presentation+xml")] [InlineData("application/mathml+xml; undefined=ignored")] [InlineData("application/octet-stream; padding=3")] [InlineData("application/xml")] [InlineData("application/xml-dtd; undefined=ignored")] [InlineData("text/html")] public void MultipartFormatter_CanRead_ReturnsFalseForUnsupportedMediaTypes(string requestContentType) { // Arrange var formatter = new MultipartFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.False(result); } private class MultipartMixedFormatter : TestFormatter { public MultipartMixedFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("multipart/mixed")); } } [Theory] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p; undefined=ignored")] public void MultipartMixedFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType) { // Arrange var formatter = new MultipartMixedFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.True(result); } [Theory] [InlineData("application/mathml-content+xml")] [InlineData("application/mathml-presentation+xml")] [InlineData("application/mathml+xml; undefined=ignored")] [InlineData("application/octet-stream; padding=3")] [InlineData("application/xml")] [InlineData("application/xml-dtd; undefined=ignored")] [InlineData("text/html")] public void MultipartMixedFormatter_CanRead_ReturnsFalseForUnsupportedMediaTypes(string requestContentType) { // Arrange var formatter = new MultipartMixedFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.False(result); } private class MathMLFormatter : TestFormatter { public MathMLFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/mathml-content+xml")); SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/mathml-presentation+xml")); SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/mathml+xml")); } } [Theory] [InlineData("application/mathml-content+xml")] [InlineData("application/mathml-presentation+xml")] [InlineData("application/mathml+xml; undefined=ignored")] public void MathMLFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType) { // Arrange var formatter = new MathMLFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.True(result); } [Theory] [InlineData("application/octet-stream; padding=3")] [InlineData("application/xml")] [InlineData("application/xml-dtd; undefined=ignored")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p; undefined=ignored")] [InlineData("text/html")] public void MathMLFormatter_CanRead_ReturnsFalseForUnsupportedMediaTypes(string requestContentType) { // Arrange var formatter = new MathMLFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.False(result); } // IsSubsetOf does not follow XML media type conventions. This formatter does not support "application/*+xml". private class XmlFormatter : TestFormatter { public XmlFormatter() { SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml")); SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml")); } } [Theory] [InlineData("application/xml")] [InlineData("application/mathml-content+xml")] [InlineData("application/mathml-presentation+xml")] [InlineData("application/mathml+xml; test=value")] public void XMLFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType) { // Arrange var formatter = new XmlFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.True(result); } [Theory] [InlineData("application/octet-stream; padding=3")] [InlineData("application/xml-dtd; undefined=ignored")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p")] [InlineData("multipart/mixed; boundary=gc0p4Jq0M2Yt08j34c0p; undefined=ignored")] [InlineData("text/html")] public void XMLFormatter_CanRead_ReturnsFalseForUnsupportedMediaTypes(string requestContentType) { // Arrange var formatter = new XmlFormatter(); var httpContext = new DefaultHttpContext(); httpContext.Request.ContentType = requestContentType; var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(void)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(context); // Assert Assert.False(result); } [Fact] public void GetSupportedContentTypes_UnsupportedObjectType_ReturnsNull() { // Arrange var formatter = new TestFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml")); formatter.SupportedTypes.Add(typeof(string)); // Act var results = formatter.GetSupportedContentTypes(contentType: null, objectType: typeof(int)); // Assert Assert.Null(results); } [Fact] public void GetSupportedContentTypes_SupportedObjectType_ReturnsContentTypes() { // Arrange var formatter = new TestFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml")); formatter.SupportedTypes.Add(typeof(string)); // Act var results = formatter.GetSupportedContentTypes(contentType: null, objectType: typeof(string)); // Assert Assert.Collection(results, c => Assert.Equal("text/xml", c)); } [Fact] public void GetSupportedContentTypes_NullContentType_ReturnsAllContentTypes() { // Arrange var formatter = new TestFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml")); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml")); // Act var results = formatter.GetSupportedContentTypes(contentType: null, objectType: typeof(string)); // Assert Assert.Collection( results.OrderBy(c => c.ToString()), c => Assert.Equal("application/xml", c), c => Assert.Equal("text/xml", c)); } [Fact] public void GetSupportedContentTypes_NonNullContentType_FiltersContentTypes() { // Arrange var formatter = new TestFormatter(); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/xml")); formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/xml")); // Act var results = formatter.GetSupportedContentTypes("text/*", typeof(string)); // Assert Assert.Collection(results, c => Assert.Equal("text/xml", c)); } [Fact] public void CanRead_ThrowsInvalidOperationException_IfMediaTypesListIsEmpty() { // Arrange var formatter = new BadConfigurationFormatter(); var context = new InputFormatterContext( new DefaultHttpContext(), string.Empty, new ModelStateDictionary(), new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)), (s, e) => new StreamReader(s, e)); // Act & Assert Assert.Throws<InvalidOperationException>(() => formatter.CanRead(context)); } [Fact] public void GetSupportedContentTypes_ThrowsInvalidOperationException_IfMediaTypesListIsEmpty() { // Arrange var formatter = new BadConfigurationFormatter(); // Act & Assert Assert.Throws<InvalidOperationException>( () => formatter.GetSupportedContentTypes("application/json", typeof(object))); } [Theory] [InlineData(true, true)] [InlineData(false, false)] public async Task ReadAsync_WithEmptyRequest_ReturnsNoValueResultWhenExpected(bool allowEmptyInputValue, bool expectedIsModelSet) { // Arrange var formatter = new TestFormatter(); var context = new InputFormatterContext( new DefaultHttpContext(), string.Empty, new ModelStateDictionary(), new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)), (s, e) => new StreamReader(s, e), allowEmptyInputValue); context.HttpContext.Request.ContentLength = 0; // Act var result = await formatter.ReadAsync(context); // Assert Assert.False(result.HasError); Assert.Null(result.Model); Assert.Equal(expectedIsModelSet, result.IsModelSet); } private class BadConfigurationFormatter : InputFormatter { public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { throw new NotImplementedException(); } } private class TestFormatter : InputFormatter { public IList<Type> SupportedTypes { get; } = new List<Type>(); protected override bool CanReadType(Type type) { return SupportedTypes.Count == 0 ? true : SupportedTypes.Contains(type); } public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { throw new NotImplementedException(); } } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityServer4.Events; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Extensions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace IdentityServer4.Quickstart.UI { /// <summary> /// This controller processes the consent UI /// </summary> [SecurityHeaders] [Authorize] public class ConsentController : Controller { private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IResourceStore _resourceStore; private readonly IEventService _events; private readonly ILogger<ConsentController> _logger; public ConsentController( IIdentityServerInteractionService interaction, IClientStore clientStore, IResourceStore resourceStore, IEventService events, ILogger<ConsentController> logger) { _interaction = interaction; _clientStore = clientStore; _resourceStore = resourceStore; _events = events; _logger = logger; } /// <summary> /// Shows the consent screen /// </summary> /// <param name="returnUrl"></param> /// <returns></returns> [HttpGet] public async Task<IActionResult> Index(string returnUrl) { var vm = await BuildViewModelAsync(returnUrl); if (vm != null) { return View("Index", vm); } return View("Error"); } /// <summary> /// Handles the consent screen postback /// </summary> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(ConsentInputModel model) { var result = await ProcessConsent(model); if (result.IsRedirect) { if (await _clientStore.IsPkceClientAsync(result.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = result.RedirectUri }); } return Redirect(result.RedirectUri); } if (result.HasValidationError) { ModelState.AddModelError(string.Empty, result.ValidationError); } if (result.ShowView) { return View("Index", result.ViewModel); } return View("Error"); } /*****************************************/ /* helper APIs for the ConsentController */ /*****************************************/ private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model) { var result = new ProcessConsentResult(); // validate return url is still valid var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); if (request == null) return result; ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model?.Button == "no") { grantedConsent = ConsentResponse.Denied; // emit event await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested)); } // user clicked 'yes' - validate the data else if (model?.Button == "yes") { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { var scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = scopes.ToArray() }; // emit event await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.ClientId, request.ScopesRequested, grantedConsent.ScopesConsented, grantedConsent.RememberConsent)); } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // communicate outcome of consent back to identityserver await _interaction.GrantConsentAsync(request, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; result.ClientId = request.ClientId; } else { // we need to redisplay the consent UI result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model); } return result; } private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(returnUrl); if (request != null) { var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId); if (client != null) { var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested); if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any())) { return CreateConsentViewModel(model, returnUrl, request, client, resources); } else { _logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y)); } } else { _logger.LogError("Invalid client id: {0}", request.ClientId); } } else { _logger.LogError("No consent request matching request: {0}", returnUrl); } return null; } private ConsentViewModel CreateConsentViewModel( ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, Resources resources) { var vm = new ConsentViewModel { RememberConsent = model?.RememberConsent ?? true, ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(), ReturnUrl = returnUrl, ClientName = client.ClientName ?? client.ClientId, ClientUrl = client.ClientUri, ClientLogoUrl = client.LogoUri, AllowRememberConsent = client.AllowRememberConsent }; vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess) { vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] { GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null) }); } return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, DisplayName = identity.DisplayName, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(Scope scope, bool check) { return new ScopeViewModel { Name = scope.Name, DisplayName = scope.DisplayName, Description = scope.Description, Emphasize = scope.Emphasize, Required = scope.Required, Checked = check || scope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Name = IdentityServer4.IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } } }
// ********************************* // Message from Original Author: // // 2008 Jose Menendez Poo // Please give me credit if you use this code. It's all I ask. // Contact me for more info: menendezpoo@gmail.com // ********************************* // // Original project from http://ribbon.codeplex.com/ // Continue to support and maintain by http://officeribbon.codeplex.com/ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Design; using System.ComponentModel; using System.Drawing.Drawing2D; using System.Windows.Forms.RibbonHelpers; namespace System.Windows.Forms { [ToolboxItemAttribute(false)] public class RibbonPopup : Control { #region Fields private RibbonWrappedDropDown _toolStripDropDown; private int _borderRoundness; #endregion #region Events public event EventHandler Showed; /// <summary> /// Raised when the popup is closed /// </summary> public event EventHandler Closed; /// <summary> /// Raised when the popup is about to be closed /// </summary> public event ToolStripDropDownClosingEventHandler Closing; /// <summary> /// Raised when the Popup is about to be opened /// </summary> public event CancelEventHandler Opening; #endregion #region Ctor public RibbonPopup() { SetStyle(ControlStyles.Opaque, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.Selectable, false); BorderRoundness = 3; } #endregion #region Props /// <summary> /// Gets or sets the roundness of the border /// </summary> [Browsable(false)] public int BorderRoundness { get { return _borderRoundness; } set { _borderRoundness = value; } } /// <summary> /// Gets the related ToolStripDropDown /// </summary> internal RibbonWrappedDropDown WrappedDropDown { get { return _toolStripDropDown; } set { _toolStripDropDown = value; } } #endregion #region Methods /// <summary> /// Shows this Popup on the specified location of the screen /// </summary> /// <param name="screenLocation"></param> public void Show(Point screenLocation) { if (WrappedDropDown == null) { ToolStripControlHost host = new ToolStripControlHost(this); WrappedDropDown = new RibbonWrappedDropDown(); WrappedDropDown.AutoClose = RibbonDesigner.Current != null; WrappedDropDown.Items.Add(host); WrappedDropDown.Padding = Padding.Empty; WrappedDropDown.Margin = Padding.Empty; host.Padding = Padding.Empty; host.Margin = Padding.Empty; WrappedDropDown.Opening += new CancelEventHandler(ToolStripDropDown_Opening); WrappedDropDown.Closing += new ToolStripDropDownClosingEventHandler(ToolStripDropDown_Closing); WrappedDropDown.Closed += new ToolStripDropDownClosedEventHandler(ToolStripDropDown_Closed); WrappedDropDown.Size = Size; } WrappedDropDown.Show(screenLocation); RibbonPopupManager.Register(this); OnShowed(EventArgs.Empty); } /// <summary> /// Handles the Opening event of the ToolStripDropDown /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ToolStripDropDown_Opening(object sender, CancelEventArgs e) { OnOpening(e); } /// <summary> /// Called when pop-up is being opened /// </summary> /// <param name="e"></param> protected virtual void OnOpening(CancelEventArgs e) { if (Opening != null) { Opening(this, e); } } /// <summary> /// Handles the Closing event of the ToolStripDropDown /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ToolStripDropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e) { OnClosing(e); } /// <summary> /// Handles the closed event of the ToolStripDropDown /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ToolStripDropDown_Closed(object sender, ToolStripDropDownClosedEventArgs e) { OnClosed(EventArgs.Empty); } /// <summary> /// Closes this popup. /// </summary> public void Close() { if (WrappedDropDown != null) { WrappedDropDown.Close(); } } /// <summary> /// Raises the <see cref="Closing"/> event /// </summary> /// <param name="e"></param> protected virtual void OnClosing(ToolStripDropDownClosingEventArgs e) { if (Closing != null) { Closing(this, e); } } /// <summary> /// Raises the <see cref="Closed"/> event. /// <remarks>If you override this event don't forget to call base! Otherwise the popup will not be unregistered and hook will not work!</remarks> /// </summary> /// <param name="e"></param> protected virtual void OnClosed(EventArgs e) { RibbonPopupManager.Unregister(this); if (Closed != null) { Closed(this, e); } //if (NextPopup != null) //{ // NextPopup.CloseForward(); // NextPopup = null; //} //if (PreviousPopup != null && PreviousPopup.NextPopup.Equals(this)) //{ // PreviousPopup.NextPopup = null; //} } /// <summary> /// Raises the Showed event /// </summary> /// <param name="e"></param> protected virtual void OnShowed(EventArgs e) { if (Showed != null) { Showed(this, e); } } /// <summary> /// Raises the <see cref="Paint"/> event /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); using (GraphicsPath p = RibbonProfessionalRenderer.RoundRectangle(new Rectangle(Point.Empty, Size), BorderRoundness)) { using (Region r = new Region(p)) { WrappedDropDown.Region = r; } } } /// <summary> /// Overriden. Used to drop a shadow on the popup /// </summary> protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; if (WinApi.IsXP) { cp.ClassStyle |= WinApi.CS_DROPSHADOW; } return cp; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using SIL.Keyboarding; using SIL.Reporting; namespace SIL.Windows.Forms.WritingSystems { public partial class WSSortControl : UserControl { private WritingSystemSetupModel _model; private readonly Hashtable _sortUsingValueMap; private Hashtable _languageOptionMap; private bool _changingModel; private IKeyboardDefinition _defaultKeyboard; private string _defaultFontName; private float _defaultFontSize; public event EventHandler UserWantsHelpWithCustomSorting; public WSSortControl() { InitializeComponent(); _sortUsingValueMap = new Hashtable(); foreach (KeyValuePair<string, string> sortUsingOption in WritingSystemSetupModel.SortUsingOptions) { int index = _sortUsingComboBox.Items.Add(sortUsingOption.Value); _sortUsingValueMap[sortUsingOption.Key] = index; _sortUsingValueMap[index] = sortUsingOption.Key; } _defaultFontName = _sortRulesTextBox.Font.Name; _defaultFontSize = _sortRulesTextBox.Font.SizeInPoints; // default text for testing the sort rules _testSortText.Text = string.Join(Environment.NewLine, "pear", "apple", "orange", "mango", "peach"); } public void BindToModel(WritingSystemSetupModel model) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } _model = model; if (_model != null) { UpdateFromModel(); _model.SelectionChanged += ModelSelectionChanged; _model.CurrentItemUpdated += ModelCurrentItemUpdated; } this.Disposed += OnDisposed; } void OnDisposed(object sender, EventArgs e) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } } private void ModelSelectionChanged(object sender, EventArgs e) { UpdateFromModel(); } private void ModelCurrentItemUpdated(object sender, EventArgs e) { if (_changingModel) { return; } UpdateFromModel(); } private void UpdateFromModel() { _rulesValidationTimer.Enabled = false; if (!_model.HasCurrentSelection) { _sortrules_panel.Visible = false; _languagecombo_panel.Visible = false; Enabled = false; return; } Enabled = true; LoadLanguageChoicesFromModel(); if (_sortUsingValueMap.ContainsKey(_model.CurrentCollationRulesType)) { _sortUsingComboBox.SelectedIndex = (int)_sortUsingValueMap[_model.CurrentCollationRulesType]; } else { _sortUsingComboBox.SelectedIndex = -1; } SetControlFonts(); } private void LoadLanguageChoicesFromModel() { _languageComboBox.Items.Clear(); _languageOptionMap = new Hashtable(); foreach (KeyValuePair<string, string> languageOption in _model.SortLanguageOptions) { int index = _languageComboBox.Items.Add(languageOption.Value); _languageOptionMap[index] = languageOption.Key; _languageOptionMap[languageOption.Key] = index; } _sortUsingComboBox.SelectedIndex = -1; } private void _sortRulesTextBox_TextChanged(object sender, EventArgs e) { _changingModel = true; try { _model.CurrentCollationRules = _sortRulesTextBox.Text; _rulesValidationTimer.Stop(); _rulesValidationTimer.Start(); } finally { _changingModel = false; } } private void _sortUsingComboBox_SelectedIndexChanged(object sender, EventArgs e) { _sortrules_panel.Visible = false; _languagecombo_panel.Visible = false; if (_sortUsingComboBox.SelectedIndex == -1) { return; } string newValue = (string)_sortUsingValueMap[_sortUsingComboBox.SelectedIndex]; _changingModel = true; try { _model.CurrentCollationRulesType = newValue; } finally { _changingModel = false; } if (newValue == "OtherLanguage") { _sortrules_panel.Visible = true; _languagecombo_panel.Visible = true; _rulesValidationTimer.Enabled = false; if (_languageOptionMap.ContainsKey(_model.CurrentCollationRules)) { _languageComboBox.SelectedIndex = (int)_languageOptionMap[_model.CurrentCollationRules]; } } else if (newValue == "CustomSimple" || newValue == "CustomIcu") { _sortrules_panel.Visible = true; _sortRulesTextBox.Text = _model.CurrentCollationRules; } } private void _languageComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (_languageComboBox.SelectedIndex == -1) { return; } string newValue = (string) _languageOptionMap[_languageComboBox.SelectedIndex]; _changingModel = true; try { _model.CurrentCollationRules = newValue; } finally { _changingModel = false; } } private void _testSortButton_Click(object sender, EventArgs e) { try { if (ValidateSortRules()) { _testSortResult.Text = _model.TestSort(_testSortText.Text); } } catch (ApplicationException ex) { ErrorReport.NotifyUserOfProblem("Unable to sort test text: {0}", ex.Message); } } private void SetControlFonts() { float fontSize = _model.CurrentDefaultFontSize; if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize)) { fontSize = _defaultFontSize; } string fontName = _model.CurrentDefaultFontName; if (string.IsNullOrEmpty(fontName)) { fontName = _defaultFontName; } Font customFont = new Font(fontName, fontSize); _sortRulesTextBox.Font = customFont; // We are not setting the RightToLeft propert for the sort rules because the ICU syntax is inherently left to right. _testSortText.Font = customFont; _testSortText.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; _testSortResult.Font = customFont; _testSortResult.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; } private void TextControl_Enter(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard = Keyboard.Controller.ActiveKeyboard; _model.ActivateCurrentKeyboard(); } private void TextControl_Leave(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard.Activate(); if (_rulesValidationTimer.Enabled) { _rulesValidationTimer.Enabled = false; ValidateSortRules(); } } private void _rulesValidationTimer_Tick(object sender, EventArgs e) { _rulesValidationTimer.Enabled = false; ValidateSortRules(); } private bool ValidateSortRules() { string message; const string prefixToMessage = "SORT RULES WILL NOT BE SAVED\r\n"; if (!_model.ValidateCurrentSortRules(out message)) { _testSortResult.Text = prefixToMessage + (message ?? String.Empty); _testSortResult.ForeColor = Color.Red; return false; } if (_testSortResult.Text.StartsWith(prefixToMessage)) { _testSortResult.Text = String.Empty; _testSortResult.ForeColor = Color.Black; } return true; } private void OnHelpLabelClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (UserWantsHelpWithCustomSorting != null) UserWantsHelpWithCustomSorting(sender, e); } } }
// // ImageReader.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using Mono.Cecil.Metadata; using RVA = System.UInt32; namespace Mono.Cecil.PE { sealed class ImageReader : BinaryStreamReader { readonly Image image; DataDirectory cli; DataDirectory metadata; public ImageReader(Stream stream) : base(stream) { image = new Image(); image.FileName = Mixin.GetFullyQualifiedName(stream); } void MoveTo(DataDirectory directory) { BaseStream.Position = image.ResolveVirtualAddress(directory.VirtualAddress); } void MoveTo(uint position) { BaseStream.Position = position; } void ReadImage() { if (BaseStream.Length < 128) throw new BadImageFormatException(); // - DOSHeader // PE 2 // Start 58 // Lfanew 4 // End 64 if (ReadUInt16() != 0x5a4d) throw new BadImageFormatException(); Advance(58); MoveTo(ReadUInt32()); if (ReadUInt32() != 0x00004550) throw new BadImageFormatException(); // - PEFileHeader // Machine 2 image.Architecture = ReadArchitecture(); // NumberOfSections 2 ushort sections = ReadUInt16(); // TimeDateStamp 4 // PointerToSymbolTable 4 // NumberOfSymbols 4 // OptionalHeaderSize 2 Advance(14); // Characteristics 2 ushort characteristics = ReadUInt16(); ushort subsystem, dll_characteristics; ReadOptionalHeaders(out subsystem, out dll_characteristics); ReadSections(sections); ReadCLIHeader(); ReadMetadata(); image.Kind = GetModuleKind(characteristics, subsystem); image.Characteristics = (ModuleCharacteristics)dll_characteristics; } TargetArchitecture ReadArchitecture() { var machine = ReadUInt16(); switch (machine) { case 0x014c: return TargetArchitecture.I386; case 0x8664: return TargetArchitecture.AMD64; case 0x0200: return TargetArchitecture.IA64; case 0x01c4: return TargetArchitecture.ARMv7; } throw new NotSupportedException(); } static ModuleKind GetModuleKind(ushort characteristics, ushort subsystem) { if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll return ModuleKind.Dll; if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui return ModuleKind.Windows; return ModuleKind.Console; } void ReadOptionalHeaders(out ushort subsystem, out ushort dll_characteristics) { // - PEOptionalHeader // - StandardFieldsHeader // Magic 2 bool pe64 = ReadUInt16() == 0x20b; // pe32 || pe64 // LMajor 1 // LMinor 1 // CodeSize 4 // InitializedDataSize 4 // UninitializedDataSize4 // EntryPointRVA 4 // BaseOfCode 4 // BaseOfData 4 || 0 // - NTSpecificFieldsHeader // ImageBase 4 || 8 // SectionAlignment 4 // FileAlignement 4 // OSMajor 2 // OSMinor 2 // UserMajor 2 // UserMinor 2 // SubSysMajor 2 // SubSysMinor 2 // Reserved 4 // ImageSize 4 // HeaderSize 4 // FileChecksum 4 Advance(66); // SubSystem 2 subsystem = ReadUInt16(); // DLLFlags 2 dll_characteristics = ReadUInt16(); // StackReserveSize 4 || 8 // StackCommitSize 4 || 8 // HeapReserveSize 4 || 8 // HeapCommitSize 4 || 8 // LoaderFlags 4 // NumberOfDataDir 4 // - DataDirectoriesHeader // ExportTable 8 // ImportTable 8 // ResourceTable 8 // ExceptionTable 8 // CertificateTable 8 // BaseRelocationTable 8 Advance(pe64 ? 88 : 72); // Debug 8 image.Debug = ReadDataDirectory(); // Copyright 8 // GlobalPtr 8 // TLSTable 8 // LoadConfigTable 8 // BoundImport 8 // IAT 8 // DelayImportDescriptor8 Advance(56); // CLIHeader 8 cli = ReadDataDirectory(); if (cli.IsZero) throw new BadImageFormatException(); // Reserved 8 Advance(8); } string ReadAlignedString(int length) { int read = 0; var buffer = new char[length]; while (read < length) { var current = ReadByte(); if (current == 0) break; buffer[read++] = (char)current; } Advance(-1 + ((read + 4) & ~3) - read); return new string(buffer, 0, read); } string ReadZeroTerminatedString(int length) { int read = 0; var buffer = new char[length]; var bytes = ReadBytes(length); while (read < length) { var current = bytes[read]; if (current == 0) break; buffer[read++] = (char)current; } return new string(buffer, 0, read); } void ReadSections(ushort count) { var sections = new Section[count]; for (int i = 0; i < count; i++) { var section = new Section(); // Name section.Name = ReadZeroTerminatedString(8); // VirtualSize 4 Advance(4); // VirtualAddress 4 section.VirtualAddress = ReadUInt32(); // SizeOfRawData 4 section.SizeOfRawData = ReadUInt32(); // PointerToRawData 4 section.PointerToRawData = ReadUInt32(); // PointerToRelocations 4 // PointerToLineNumbers 4 // NumberOfRelocations 2 // NumberOfLineNumbers 2 // Characteristics 4 Advance(16); sections[i] = section; ReadSectionData(section); } image.Sections = sections; } void ReadSectionData(Section section) { var position = BaseStream.Position; MoveTo(section.PointerToRawData); var length = (int)section.SizeOfRawData; var data = new byte[length]; int offset = 0, read; while ((read = Read(data, offset, length - offset)) > 0) offset += read; section.Data = data; BaseStream.Position = position; } void ReadCLIHeader() { MoveTo(cli); // - CLIHeader // Cb 4 // MajorRuntimeVersion 2 // MinorRuntimeVersion 2 Advance(8); // Metadata 8 metadata = ReadDataDirectory(); // Flags 4 image.Attributes = (ModuleAttributes)ReadUInt32(); // EntryPointToken 4 image.EntryPointToken = ReadUInt32(); // Resources 8 image.Resources = ReadDataDirectory(); // StrongNameSignature 8 image.StrongName = ReadDataDirectory(); // CodeManagerTable 8 // VTableFixups 8 // ExportAddressTableJumps 8 // ManagedNativeHeader 8 } void ReadMetadata() { MoveTo(metadata); if (ReadUInt32() != 0x424a5342) throw new BadImageFormatException(); // MajorVersion 2 // MinorVersion 2 // Reserved 4 Advance(8); var version = ReadZeroTerminatedString(ReadInt32()); image.Runtime = Mixin.ParseRuntime(version); // Flags 2 Advance(2); var streams = ReadUInt16(); var section = image.GetSectionAtVirtualAddress(metadata.VirtualAddress); if (section == null) throw new BadImageFormatException(); image.MetadataSection = section; for (int i = 0; i < streams; i++) ReadMetadataStream(section); if (image.TableHeap != null) ReadTableHeap(); } void ReadMetadataStream(Section section) { // Offset 4 uint start = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32(); // relative to the section start // Size 4 uint size = ReadUInt32(); var name = ReadAlignedString(16); switch (name) { case "#~": case "#-": image.TableHeap = new TableHeap(section, start, size); break; case "#Strings": image.StringHeap = new StringHeap(section, start, size); break; case "#Blob": image.BlobHeap = new BlobHeap(section, start, size); break; case "#GUID": image.GuidHeap = new GuidHeap(section, start, size); break; case "#US": image.UserStringHeap = new UserStringHeap(section, start, size); break; } } void ReadTableHeap() { var heap = image.TableHeap; uint start = heap.Section.PointerToRawData; MoveTo(heap.Offset + start); // Reserved 4 // MajorVersion 1 // MinorVersion 1 Advance(6); // HeapSizes 1 var sizes = ReadByte(); // Reserved2 1 Advance(1); // Valid 8 heap.Valid = ReadInt64(); // Sorted 8 heap.Sorted = ReadInt64(); for (int i = 0; i < TableHeap.TableCount; i++) { if (!heap.HasTable((Table)i)) continue; heap.Tables[i].Length = ReadUInt32(); } SetIndexSize(image.StringHeap, sizes, 0x1); SetIndexSize(image.GuidHeap, sizes, 0x2); SetIndexSize(image.BlobHeap, sizes, 0x4); ComputeTableInformations(); } static void SetIndexSize(Heap heap, uint sizes, byte flag) { if (heap == null) return; heap.IndexSize = (sizes & flag) > 0 ? 4 : 2; } int GetTableIndexSize(Table table) { return image.GetTableIndexSize(table); } int GetCodedIndexSize(CodedIndex index) { return image.GetCodedIndexSize(index); } void ComputeTableInformations() { uint offset = (uint)BaseStream.Position - image.MetadataSection.PointerToRawData; // header int stridx_size = image.StringHeap.IndexSize; int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2; var heap = image.TableHeap; var tables = heap.Tables; for (int i = 0; i < TableHeap.TableCount; i++) { var table = (Table)i; if (!heap.HasTable(table)) continue; int size; switch (table) { case Table.Module: size = 2 // Generation + stridx_size // Name + (image.GuidHeap.IndexSize * 3); // Mvid, EncId, EncBaseId break; case Table.TypeRef: size = GetCodedIndexSize(CodedIndex.ResolutionScope) // ResolutionScope + (stridx_size * 2); // Name, Namespace break; case Table.TypeDef: size = 4 // Flags + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize(CodedIndex.TypeDefOrRef) // BaseType + GetTableIndexSize(Table.Field) // FieldList + GetTableIndexSize(Table.Method); // MethodList break; case Table.FieldPtr: size = GetTableIndexSize(Table.Field); // Field break; case Table.Field: size = 2 // Flags + stridx_size // Name + blobidx_size; // Signature break; case Table.MethodPtr: size = GetTableIndexSize(Table.Method); // Method break; case Table.Method: size = 8 // Rva 4, ImplFlags 2, Flags 2 + stridx_size // Name + blobidx_size // Signature + GetTableIndexSize(Table.Param); // ParamList break; case Table.ParamPtr: size = GetTableIndexSize(Table.Param); // Param break; case Table.Param: size = 4 // Flags 2, Sequence 2 + stridx_size; // Name break; case Table.InterfaceImpl: size = GetTableIndexSize(Table.TypeDef) // Class + GetCodedIndexSize(CodedIndex.TypeDefOrRef); // Interface break; case Table.MemberRef: size = GetCodedIndexSize(CodedIndex.MemberRefParent) // Class + stridx_size // Name + blobidx_size; // Signature break; case Table.Constant: size = 2 // Type + GetCodedIndexSize(CodedIndex.HasConstant) // Parent + blobidx_size; // Value break; case Table.CustomAttribute: size = GetCodedIndexSize(CodedIndex.HasCustomAttribute) // Parent + GetCodedIndexSize(CodedIndex.CustomAttributeType) // Type + blobidx_size; // Value break; case Table.FieldMarshal: size = GetCodedIndexSize(CodedIndex.HasFieldMarshal) // Parent + blobidx_size; // NativeType break; case Table.DeclSecurity: size = 2 // Action + GetCodedIndexSize(CodedIndex.HasDeclSecurity) // Parent + blobidx_size; // PermissionSet break; case Table.ClassLayout: size = 6 // PackingSize 2, ClassSize 4 + GetTableIndexSize(Table.TypeDef); // Parent break; case Table.FieldLayout: size = 4 // Offset + GetTableIndexSize(Table.Field); // Field break; case Table.StandAloneSig: size = blobidx_size; // Signature break; case Table.EventMap: size = GetTableIndexSize(Table.TypeDef) // Parent + GetTableIndexSize(Table.Event); // EventList break; case Table.EventPtr: size = GetTableIndexSize(Table.Event); // Event break; case Table.Event: size = 2 // Flags + stridx_size // Name + GetCodedIndexSize(CodedIndex.TypeDefOrRef); // EventType break; case Table.PropertyMap: size = GetTableIndexSize(Table.TypeDef) // Parent + GetTableIndexSize(Table.Property); // PropertyList break; case Table.PropertyPtr: size = GetTableIndexSize(Table.Property); // Property break; case Table.Property: size = 2 // Flags + stridx_size // Name + blobidx_size; // Type break; case Table.MethodSemantics: size = 2 // Semantics + GetTableIndexSize(Table.Method) // Method + GetCodedIndexSize(CodedIndex.HasSemantics); // Association break; case Table.MethodImpl: size = GetTableIndexSize(Table.TypeDef) // Class + GetCodedIndexSize(CodedIndex.MethodDefOrRef) // MethodBody + GetCodedIndexSize(CodedIndex.MethodDefOrRef); // MethodDeclaration break; case Table.ModuleRef: size = stridx_size; // Name break; case Table.TypeSpec: size = blobidx_size; // Signature break; case Table.ImplMap: size = 2 // MappingFlags + GetCodedIndexSize(CodedIndex.MemberForwarded) // MemberForwarded + stridx_size // ImportName + GetTableIndexSize(Table.ModuleRef); // ImportScope break; case Table.FieldRVA: size = 4 // RVA + GetTableIndexSize(Table.Field); // Field break; case Table.EncLog: case Table.EncMap: size = 4; break; case Table.Assembly: size = 16 // HashAlgId 4, Version 4 * 2, Flags 4 + blobidx_size // PublicKey + (stridx_size * 2); // Name, Culture break; case Table.AssemblyProcessor: size = 4; // Processor break; case Table.AssemblyOS: size = 12; // Platform 4, Version 2 * 4 break; case Table.AssemblyRef: size = 12 // Version 2 * 4 + Flags 4 + (blobidx_size * 2) // PublicKeyOrToken, HashValue + (stridx_size * 2); // Name, Culture break; case Table.AssemblyRefProcessor: size = 4 // Processor + GetTableIndexSize(Table.AssemblyRef); // AssemblyRef break; case Table.AssemblyRefOS: size = 12 // Platform 4, Version 2 * 4 + GetTableIndexSize(Table.AssemblyRef); // AssemblyRef break; case Table.File: size = 4 // Flags + stridx_size // Name + blobidx_size; // HashValue break; case Table.ExportedType: size = 8 // Flags 4, TypeDefId 4 + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize(CodedIndex.Implementation); // Implementation break; case Table.ManifestResource: size = 8 // Offset, Flags + stridx_size // Name + GetCodedIndexSize(CodedIndex.Implementation); // Implementation break; case Table.NestedClass: size = GetTableIndexSize(Table.TypeDef) // NestedClass + GetTableIndexSize(Table.TypeDef); // EnclosingClass break; case Table.GenericParam: size = 4 // Number, Flags + GetCodedIndexSize(CodedIndex.TypeOrMethodDef) // Owner + stridx_size; // Name break; case Table.MethodSpec: size = GetCodedIndexSize(CodedIndex.MethodDefOrRef) // Method + blobidx_size; // Instantiation break; case Table.GenericParamConstraint: size = GetTableIndexSize(Table.GenericParam) // Owner + GetCodedIndexSize(CodedIndex.TypeDefOrRef); // Constraint break; default: throw new NotSupportedException(); } tables[i].RowSize = (uint)size; tables[i].Offset = offset; offset += (uint)size * tables[i].Length; } } public static Image ReadImageFrom(Stream stream) { try { var reader = new ImageReader(stream); reader.ReadImage(); return reader.image; } catch (EndOfStreamException e) { throw new BadImageFormatException(Mixin.GetFullyQualifiedName(stream), 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 System.Collections.Generic; using System.Collections.Immutable; using Xunit; namespace System.Linq.Parallel.Tests { public static class AggregateTests { private const int ResultFuncModifier = 17; [Theory] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Sum(int count) { // The operation will overflow for long-running sizes, but that's okay: // The helper is overflowing too! Assert.Equal(Functions.SumRange(0, count), UnorderedSources.Default(count).Aggregate((x, y) => unchecked(x + y))); } [Fact] [OuterLoop] public static void Aggregate_Sum_Longrunning() { Aggregate_Sum(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Sum_Seed(int count) { Assert.Equal(Functions.SumRange(0, count), UnorderedSources.Default(count).Aggregate(0, (x, y) => unchecked(x + y))); } [Fact] [OuterLoop] public static void Aggregate_Sum_Seed_Longrunning() { Aggregate_Sum_Seed(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Product_Seed(int count) { // The operation will overflow for long-running sizes, but that's okay: // The helper is overflowing too! Assert.Equal(Functions.ProductRange(1, count), ParallelEnumerable.Range(1, count).Aggregate(1L, (x, y) => unchecked(x * y))); } [Fact] [OuterLoop] public static void Aggregate_Product_Seed_Longrunning() { Aggregate_Product_Seed(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Collection_Seed(int count) { Assert.Equal(Enumerable.Range(0, count), UnorderedSources.Default(count).Aggregate(ImmutableList<int>.Empty, (l, x) => l.Add(x)).OrderBy(x => x)); } [Fact] [OuterLoop] public static void Aggregate_Collection_Seed_Longrunning() { // Given the cost of using an object, reduce count. Aggregate_Collection_Seed(Sources.OuterLoopCount / 2); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Sum_Result(int count) { Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, UnorderedSources.Default(count).Aggregate(0, (x, y) => unchecked(x + y), result => result + ResultFuncModifier)); } [Fact] [OuterLoop] public static void Aggregate_Sum_Result_Longrunning() { Aggregate_Sum_Result(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Product_Result(int count) { Assert.Equal(Functions.ProductRange(1, count) + ResultFuncModifier, ParallelEnumerable.Range(1, count).Aggregate(1L, (x, y) => unchecked(x * y), result => result + ResultFuncModifier)); } [Fact] [OuterLoop] public static void Aggregate_Product_Results_Longrunning() { Aggregate_Product_Result(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Collection_Results(int count) { Assert.Equal(Enumerable.Range(0, count), UnorderedSources.Default(count).Aggregate(ImmutableList<int>.Empty, (l, x) => l.Add(x), l => l.OrderBy(x => x))); } [Fact] [OuterLoop] public static void Aggregate_Collection_Results_Longrunning() { Aggregate_Collection_Results(Sources.OuterLoopCount / 2); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Sum_Accumulator(int count) { ParallelQuery<int> query = UnorderedSources.Default(count); int actual = query.Aggregate( 0, (accumulator, x) => accumulator + x, (left, right) => unchecked(left + right), result => result + ResultFuncModifier); Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual); } [Fact] [OuterLoop] public static void Aggregate_Sum_Accumulator_Longrunning() { Aggregate_Sum_Accumulator(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Product_Accumulator(int count) { ParallelQuery<int> query = ParallelEnumerable.Range(1, count); long actual = query.Aggregate( 1L, (accumulator, x) => unchecked(accumulator * x), (left, right) => left * right, result => result + ResultFuncModifier); Assert.Equal(Functions.ProductRange(1, count) + ResultFuncModifier, actual); } [Fact] [OuterLoop] public static void Aggregate_Product_Accumulator_Longrunning() { Aggregate_Product_Accumulator(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Collection_Accumulator(int count) { ParallelQuery<int> query = UnorderedSources.Default(count); IList<int> actual = query.Aggregate( ImmutableList<int>.Empty, (accumulator, x) => accumulator.Add(x), (left, right) => left.AddRange(right), result => result.OrderBy(x => x).ToList()); Assert.Equal(Enumerable.Range(0, count), actual); } [Fact] [OuterLoop] public static void Aggregate_Collection_Accumulator_Longrunning() { Aggregate_Collection_Accumulator(Sources.OuterLoopCount / 2); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Sum_SeedFunction(int count) { ParallelQuery<int> query = UnorderedSources.Default(count); int actual = query.Aggregate( () => 0, (accumulator, x) => accumulator + x, (left, right) => unchecked(left + right), result => result + ResultFuncModifier); Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual); } [Fact] [OuterLoop] public static void Aggregate_Sum_SeedFunction_Longrunning() { Aggregate_Sum_SeedFunction(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Product_SeedFunction(int count) { ParallelQuery<int> query = ParallelEnumerable.Range(1, count); long actual = query.Aggregate( () => 1L, (accumulator, x) => unchecked(accumulator * x), (left, right) => left * right, result => result + ResultFuncModifier); Assert.Equal(Functions.ProductRange(1, count) + ResultFuncModifier, actual); } [Fact] [OuterLoop] public static void Aggregate_Product_SeedFunction_Longrunning() { Aggregate_Product_SeedFunction(Sources.OuterLoopCount); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(16)] public static void Aggregate_Collection_SeedFunction(int count) { ParallelQuery<int> query = UnorderedSources.Default(count); IList<int> actual = query.Aggregate( () => ImmutableList<int>.Empty, (accumulator, x) => accumulator.Add(x), (left, right) => left.AddRange(right), result => result.OrderBy(x => x).ToList()); Assert.Equal(Enumerable.Range(0, count), actual); } [Fact] [OuterLoop] public static void Aggregate_Collection_SeedFunction_Longrunning() { Aggregate_Collection_SeedFunction(Sources.OuterLoopCount / 2); } [Fact] public static void Aggregate_InvalidOperationException() { Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Aggregate((i, j) => i)); // All other invocations return the seed value. Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j)); Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, i => i)); Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, (i, j) => i + j, i => i)); Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(() => -1, (i, j) => i + j, (i, j) => i + j, i => i)); } [Fact] public static void Aggregate_OperationCanceledException() { AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate((i, j) => { canceler(); return j; })); AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; })); AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, i => i)); AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, (i, j) => i, i => i)); AssertThrows.EventuallyCanceled((source, canceler) => source.Aggregate(() => 0, (i, j) => { canceler(); ; return j; }, (i, j) => i, i => i)); } [Fact] public static void Aggregate_AggregateException_Wraps_OperationCanceledException() { AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate((i, j) => { canceler(); return j; })); AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; })); AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, i => i)); AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, (i, j) => i, i => i)); AssertThrows.OtherTokenCanceled((source, canceler) => source.Aggregate(() => 0, (i, j) => { canceler(); ; return j; }, (i, j) => i, i => i)); AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate((i, j) => { canceler(); return j; })); AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; })); AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, i => i)); AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(0, (i, j) => { canceler(); return j; }, (i, j) => i, i => i)); AssertThrows.SameTokenNotCanceled((source, canceler) => source.Aggregate(() => 0, (i, j) => { canceler(); ; return j; }, (i, j) => i, i => i)); } [Fact] public static void Aggregate_OperationCanceledException_PreCanceled() { AssertThrows.AlreadyCanceled(source => source.Aggregate((i, j) => i)); AssertThrows.AlreadyCanceled(source => source.Aggregate(0, (i, j) => i)); AssertThrows.AlreadyCanceled(source => source.Aggregate(0, (i, j) => i, i => i)); AssertThrows.AlreadyCanceled(source => source.Aggregate(0, (i, j) => i, (i, j) => i, i => i)); AssertThrows.AlreadyCanceled(source => source.Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i)); } [Fact] public static void Aggregate_AggregateException() { AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate((i, j) => { throw new DeliberateTestException(); })); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => { throw new DeliberateTestException(); })); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, i => i)); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(0, (i, j) => i, i => { throw new DeliberateTestException(); })); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i)); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); })); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(() => { throw new DeliberateTestException(); }, (i, j) => i, (i, j) => i, i => i)); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(() => 0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i)); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); })); if (Environment.ProcessorCount >= 2) { AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i)); AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(2).Aggregate(() => 0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i)); } } [Fact] public static void Aggregate_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate((i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("func", () => UnorderedSources.Default(1).Aggregate(null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i)); AssertExtensions.Throws<ArgumentNullException>("func", () => UnorderedSources.Default(1).Aggregate(0, null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, i => i)); AssertExtensions.Throws<ArgumentNullException>("func", () => UnorderedSources.Default(1).Aggregate(0, null, i => i)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => UnorderedSources.Default(1).Aggregate<int, int, int>(0, (i, j) => i, null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, (i, j) => i, i => i)); AssertExtensions.Throws<ArgumentNullException>("updateAccumulatorFunc", () => UnorderedSources.Default(1).Aggregate(0, null, (i, j) => i, i => i)); AssertExtensions.Throws<ArgumentNullException>("combineAccumulatorsFunc", () => UnorderedSources.Default(1).Aggregate(0, (i, j) => i, null, i => i)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => UnorderedSources.Default(1).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, null)); AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i)); AssertExtensions.Throws<ArgumentNullException>("seedFactory", () => UnorderedSources.Default(1).Aggregate<int, int, int>(null, (i, j) => i, (i, j) => i, i => i)); AssertExtensions.Throws<ArgumentNullException>("updateAccumulatorFunc", () => UnorderedSources.Default(1).Aggregate(() => 0, null, (i, j) => i, i => i)); AssertExtensions.Throws<ArgumentNullException>("combineAccumulatorsFunc", () => UnorderedSources.Default(1).Aggregate(() => 0, (i, j) => i, null, i => i)); AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => UnorderedSources.Default(1).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, null)); } } }
using System; using System.IO; using NUnit.Framework; namespace FileHelpers.Tests.CommonTests { [TestFixture] public class IgnoreFirsts { private readonly string mExpectedLongHeaderText = "you can get this lines" + Environment.NewLine + "with the FileHelperEngine.HeaderText property" + Environment.NewLine; private readonly string mExpectedShortHeaderText = "This is a new header...." + Environment.NewLine; [Test] public void DiscardFirst1() { var res = FileTest.Good.DiscardFirst0.ReadWithEngine<DiscardType0>(); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); } [Test] public void DiscardFirst2() { var engine = new FileHelperEngine<DiscardType1>(); var res = engine.ReadFile(FileTest.Good.DiscardFirst1.Path); Assert.AreEqual(engine.TotalRecords, res.Length); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); } [Test] public void DiscardFirst3() { var res = FileTest.Good.DiscardFirst1.ReadWithEngine<DiscardType11>(); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); } [Test] public void DiscardFirst4() { var engine = new FileHelperEngine<DiscardType2>(); var res = engine.ReadFile(FileTest.Good.DiscardFirst2.Path); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual(mExpectedLongHeaderText, engine.HeaderText); } [Test] public void DiscardFirst5() { var res = FileTest.Good.DiscardFirst3 .ReadWithEngine<DiscardType2>(); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); } [Test] public void DiscardFirst6() { var engine = FileTest.Good.DiscardFirst2 .BeginRead<DiscardType2>(); Assert.AreEqual(mExpectedLongHeaderText, engine.HeaderText); var res = engine.ReadNext(); Assert.AreEqual(new DateTime(1314, 12, 11), res.Field1); } [Test] public void DiscardFirst7() { var engine = FileTest.Good.DiscardFirst2 .BeginRead<DiscardType3>(); var res = engine.ReadNext(); Assert.AreEqual(null, res); } [Test] public void DiscardFirst8() { var res = FileTest.Good.DiscardFirst2 .ReadWithEngine<DiscardType3>(); Assert.AreEqual(0, res.Length); } [Test] public void DiscardFirst9() { var engine = FileTest.Good.DiscardFirst2 .BeginRead<DiscardType4>(); var res = engine.ReadNext(); Assert.AreEqual(null, res); } [Test] public void DiscardFirstA() { var res = FileTest.Good.DiscardFirst2 .ReadWithEngine<DiscardType4>(); Assert.AreEqual(0, res.Length); } [Test] public void DiscardFirstReport() { var engine = new FileHelperEngine<DiscardReportType>(); var res = engine.ReadFile(FileTest.Good.DiscardFirstReport.Path); Assert.AreEqual(2, res.Length); Assert.AreEqual(123, res[0].FirstColumn); Assert.AreEqual(456, res[1].FirstColumn); Assert.AreEqual("HEADER TEXT", engine.HeaderText.Trim()); } [DelimitedRecord(";"), IgnoreFirst] public class DiscardReportType { public int FirstColumn; } [Test] public void DiscardWriteRead() { var engine = new FileHelperEngine<DiscardType1>(); DiscardType1[] res = engine.ReadFile(FileTest.Good.DiscardFirst1.Path); engine.HeaderText = "This is a new header...."; engine.WriteFile("tempo.txt", res); engine.HeaderText = "none none"; var res2 = (DiscardType1[]) engine.ReadFile(@"tempo.txt"); Assert.AreEqual(res.Length, res2.Length); Assert.AreEqual(mExpectedShortHeaderText, engine.HeaderText); if (File.Exists("tempo.txt")) File.Delete("tempo.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); } [Test] public void DiscardWriteRead2() { var engine = new FileHelperEngine<DiscardType1>(); DiscardType1[] res = engine.ReadFile(FileTest.Good.DiscardFirst1.Path); var asyncEngine = new FileHelperAsyncEngine<DiscardType1>(); asyncEngine.HeaderText = "This is a new header...."; asyncEngine.BeginWriteFile("tempo.txt"); asyncEngine.WriteNexts(res); asyncEngine.Close(); asyncEngine.HeaderText = "none none\r\n"; asyncEngine.BeginReadFile(@"tempo.txt"); while (asyncEngine.ReadNext() != null) {} Assert.AreEqual(res.Length, asyncEngine.TotalRecords); Assert.AreEqual(mExpectedShortHeaderText, asyncEngine.HeaderText); asyncEngine.Close(); Assert.AreEqual(res.Length, asyncEngine.TotalRecords); Assert.AreEqual(mExpectedShortHeaderText, asyncEngine.HeaderText); if (File.Exists("tempo.txt")) File.Delete("tempo.txt"); } [Test] public void DiscardFirstAndQuoted() { var engine = new FileHelperEngine<Account>(); var res = TestCommon.ReadTest(engine, "Good", "Accounts.txt"); Assert.AreEqual(2, res.Length); Assert.AreEqual ("def", res [1].Extra); } } [FixedLengthRecord] [IgnoreFirst(0)] public class DiscardType0 { [FieldFixedLength(8)] [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime Field1; [FieldFixedLength(3)] public string Field2; [FieldFixedLength(3)] [FieldConverter(ConverterKind.Int32)] public int Field3; } [FixedLengthRecord] [IgnoreFirst] public class DiscardType1 { [FieldFixedLength(8)] [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime Field1; [FieldFixedLength(3)] public string Field2; [FieldFixedLength(3)] [FieldConverter(ConverterKind.Int32)] public int Field3; } [FixedLengthRecord] [IgnoreFirst(1)] public class DiscardType11 { [FieldFixedLength(8)] [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime Field1; [FieldFixedLength(3)] public string Field2; [FieldFixedLength(3)] [FieldConverter(ConverterKind.Int32)] public int Field3; } [FixedLengthRecord] [IgnoreFirst(2)] public class DiscardType2 { [FieldFixedLength(8)] [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime Field1; [FieldFixedLength(3)] public string Field2; [FieldFixedLength(3)] [FieldConverter(ConverterKind.Int32)] public int Field3; } [FixedLengthRecord] [IgnoreFirst(800000)] [IgnoreLast] public class DiscardType3 { [FieldFixedLength(8)] [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime Field1; [FieldFixedLength(3)] public string Field2; [FieldFixedLength(3)] [FieldConverter(ConverterKind.Int32)] public int Field3; } [FixedLengthRecord] [IgnoreLast(38000)] public class DiscardType4 { [FieldFixedLength(8)] [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime Field1; [FieldFixedLength(3)] public string Field2; [FieldFixedLength(3)] [FieldConverter(ConverterKind.Int32)] public int Field3; } [IgnoreFirst(1)] [DelimitedRecord(",")] [IgnoreEmptyLines()] public class Account { [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)] public string AccountName; [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)] public string Extra; } }
using Kitware.VTK; using System; /// <summary> /// Class Containing Main Method /// </summary> public class StreamlinesWithLineWidgetClass { /// <summary> /// Entry Point /// </summary> /// <param name="argv"></param> public static void Main(String[] argv) { // This example demonstrates how to use the vtkLineWidget to seed // and manipulate streamlines. Two line widgets are created. One is // invoked by pressing 'W', the other by pressing 'L'. Both can exist // together. // Start by loading some data. pl3d = vtkPLOT3DReader.New(); pl3d.SetXYZFileName("../../../combxyz.bin"); pl3d.SetQFileName("../../../combq.bin"); pl3d.SetScalarFunctionNumber(100); pl3d.SetVectorFunctionNumber(202); pl3d.Update(); // The line widget is used seed the streamlines. lineWidget = vtkLineWidget.New(); seeds = vtkPolyData.New(); lineWidget.SetInput(pl3d.GetOutput()); lineWidget.SetAlignToYAxis(); lineWidget.PlaceWidget(); lineWidget.GetPolyData(seeds); lineWidget.ClampToBoundsOn(); rk4 = vtkRungeKutta4.New(); streamer = vtkStreamLine.New(); streamer.SetInputConnection(pl3d.GetOutputPort()); streamer.SetSource(seeds); streamer.SetMaximumPropagationTime(100); streamer.SetIntegrationStepLength(.2); streamer.SetStepLength(.001); streamer.SetNumberOfThreads(1); streamer.SetIntegrationDirectionToForward(); streamer.VorticityOn(); streamer.SetIntegrator(rk4); rf = vtkRibbonFilter.New(); rf.SetInputConnection(streamer.GetOutputPort()); rf.SetWidth(0.1); rf.SetWidthFactor(5); streamMapper = vtkPolyDataMapper.New(); streamMapper.SetInputConnection(rf.GetOutputPort()); streamMapper.SetScalarRange(pl3d.GetOutput().GetScalarRange()[0], pl3d.GetOutput().GetScalarRange()[1]); streamline = vtkActor.New(); streamline.SetMapper(streamMapper); streamline.VisibilityOff(); // The second line widget is used seed more streamlines. lineWidget2 = vtkLineWidget.New(); seeds2 = vtkPolyData.New(); lineWidget2.SetInput(pl3d.GetOutput()); lineWidget2.PlaceWidget(); lineWidget2.GetPolyData(seeds2); lineWidget2.SetKeyPressActivationValue((sbyte)108); streamer2 = vtkStreamLine.New(); streamer2.SetInputConnection(pl3d.GetOutputPort()); streamer2.SetSource(seeds2); streamer2.SetMaximumPropagationTime(100); streamer2.SetIntegrationStepLength(.2); streamer2.SetStepLength(.001); streamer2.SetNumberOfThreads(1); streamer2.SetIntegrationDirectionToForward(); streamer2.VorticityOn(); streamer2.SetIntegrator(rk4); rf2 = vtkRibbonFilter.New(); rf2.SetInputConnection(streamer2.GetOutputPort()); rf2.SetWidth(0.1); rf2.SetWidthFactor(5); streamMapper2 = vtkPolyDataMapper.New(); streamMapper2.SetInputConnection(rf2.GetOutputPort()); streamMapper2.SetScalarRange(pl3d.GetOutput().GetScalarRange()[0], pl3d.GetOutput().GetScalarRange()[1]); streamline2 = vtkActor.New(); streamline2.SetMapper(streamMapper2); streamline2.VisibilityOff(); outline = vtkStructuredGridOutlineFilter.New(); outline.SetInputConnection(pl3d.GetOutputPort()); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection(outline.GetOutputPort()); outlineActor = vtkActor.New(); outlineActor.SetMapper(outlineMapper); // Create the RenderWindow, Renderer and both Actors ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer(ren1); iren = vtkRenderWindowInteractor.New(); iren.SetRenderWindow(renWin); // Associate the line widget with the interactor lineWidget.SetInteractor(iren); lineWidget.StartInteractionEvt += new vtkObject.vtkObjectEventHandler(BeginInteraction); lineWidget.InteractionEvt += new vtkObject.vtkObjectEventHandler(GenerateStreamlines); lineWidget2.SetInteractor(iren); lineWidget2.StartInteractionEvt += new vtkObject.vtkObjectEventHandler(BeginInteraction2); lineWidget2.EndInteractionEvt += new vtkObject.vtkObjectEventHandler(GenerateStreamlines2); // Add the actors to the renderer, set the background and size ren1.AddActor(outlineActor); ren1.AddActor(streamline); ren1.AddActor(streamline2); ren1.SetBackground(1, 1, 1); renWin.SetSize(300, 300); ren1.SetBackground(0.1, 0.2, 0.4); cam1 = ren1.GetActiveCamera(); cam1.SetClippingRange(3.95297, 50); cam1.SetFocalPoint(9.71821, 0.458166, 29.3999); cam1.SetPosition(2.7439, -37.3196, 38.7167); cam1.SetViewUp(-0.16123, 0.264271, 0.950876); // render the image renWin.Render(); lineWidget2.On(); iren.Initialize(); iren.Start(); //Clean Up deleteAllVTKObjects(); } static vtkPLOT3DReader pl3d; static vtkLineWidget lineWidget; static vtkPolyData seeds; static vtkRungeKutta4 rk4; static vtkStreamLine streamer; static vtkRibbonFilter rf; static vtkPolyDataMapper streamMapper; static vtkActor streamline; static vtkLineWidget lineWidget2; static vtkPolyData seeds2; static vtkStreamLine streamer2; static vtkRibbonFilter rf2; static vtkPolyDataMapper streamMapper2; static vtkActor streamline2; static vtkStructuredGridOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkCamera cam1; /// <summary> /// Callback function for lineWidget.StartInteractionEvt /// </summary> public static void BeginInteraction(vtkObject sender, vtkObjectEventArgs e) { streamline.VisibilityOn(); } /// <summary> /// Callback function for lineWidget.InteractionEvt /// </summary> public static void GenerateStreamlines(vtkObject sender, vtkObjectEventArgs e) { lineWidget.GetPolyData(seeds); } /// <summary> /// Callback function for lineWidget2.StartInteractionEvt /// </summary> public static void BeginInteraction2(vtkObject sender, vtkObjectEventArgs e) { streamline2.VisibilityOn(); } /// <summary> /// Callback function for lineWidget2.InteractionEvt /// </summary> public static void GenerateStreamlines2(vtkObject sender, vtkObjectEventArgs e) { lineWidget2.GetPolyData(seeds2); renWin.Render(); } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if (pl3d != null) { pl3d.Dispose(); } if (lineWidget != null) { lineWidget.Dispose(); } if (seeds != null) { seeds.Dispose(); } if (rk4 != null) { rk4.Dispose(); } if (streamer != null) { streamer.Dispose(); } if (rf != null) { rf.Dispose(); } if (streamMapper != null) { streamMapper.Dispose(); } if (streamline != null) { streamline.Dispose(); } if (lineWidget2 != null) { lineWidget2.Dispose(); } if (seeds2 != null) { seeds2.Dispose(); } if (streamer2 != null) { streamer2.Dispose(); } if (rf2 != null) { rf2.Dispose(); } if (streamMapper2 != null) { streamMapper2.Dispose(); } if (streamline2 != null) { streamline2.Dispose(); } if (outline != null) { outline.Dispose(); } if (outlineMapper != null) { outlineMapper.Dispose(); } if (outlineActor != null) { outlineActor.Dispose(); } if (ren1 != null) { ren1.Dispose(); } if (renWin != null) { renWin.Dispose(); } if (iren != null) { iren.Dispose(); } if (cam1 != null) { cam1.Dispose(); } } } //--- end of script --//
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; using System.Collections.Generic; namespace OpenSim.Region.Physics.BasicPhysicsPlugin { /// <summary> /// This is an incomplete extremely basic physics implementation /// </summary> /// <remarks> /// Not useful for anything at the moment apart from some regression testing in other components where some form /// of physics plugin is needed. /// </remarks> public class BasicScene : PhysicsScene { private List<BasicActor> _actors = new List<BasicActor>(); private float[] _heightMap; private List<BasicPhysicsPrim> _prims = new List<BasicPhysicsPrim>(); //protected internal string sceneIdentifier; public BasicScene(string engineType, string _sceneIdentifier) { EngineType = engineType; Name = EngineType + "/" + _sceneIdentifier; //sceneIdentifier = _sceneIdentifier; } public override bool IsThreaded { get { return (false); // for now we won't be multithreaded } } public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying) { BasicActor act = new BasicActor(size); act.Position = position; act.Flying = isFlying; _actors.Add(act); return act; } public override void AddPhysicsActorTaint(PhysicsActor prim) { } public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, uint localid) { BasicPhysicsPrim prim = new BasicPhysicsPrim(primName, localid, position, size, rotation, pbs); prim.IsPhysical = isPhysical; _prims.Add(prim); return prim; } public override void DeleteTerrain() { } public override void Dispose() { } public override void GetResults() { } public override Dictionary<uint, float> GetTopColliders() { Dictionary<uint, float> returncolliders = new Dictionary<uint, float>(); return returncolliders; } public override void Initialise(IMesher meshmerizer, IConfigSource config) { } public override void RemoveAvatar(PhysicsActor actor) { BasicActor act = (BasicActor)actor; if (_actors.Contains(act)) _actors.Remove(act); } public override void RemovePrim(PhysicsActor actor) { BasicPhysicsPrim prim = (BasicPhysicsPrim)actor; if (_prims.Contains(prim)) _prims.Remove(prim); } public override void SetTerrain(float[] heightMap) { _heightMap = heightMap; } public override void SetWaterLevel(float baseheight) { } public override float Simulate(float timeStep) { // Console.WriteLine("Simulating"); float fps = 0; for (int i = 0; i < _actors.Count; ++i) { BasicActor actor = _actors[i]; Vector3 actorPosition = actor.Position; Vector3 actorVelocity = actor.Velocity; // Console.WriteLine( // "Processing actor {0}, starting pos {1}, starting vel {2}", i, actorPosition, actorVelocity); actorPosition.X += actor.Velocity.X * timeStep; actorPosition.Y += actor.Velocity.Y * timeStep; if (actor.Position.Y < 0) { actorPosition.Y = 0.1F; } else if (actor.Position.Y >= Constants.RegionSize) { actorPosition.Y = ((int)Constants.RegionSize - 0.1f); } if (actor.Position.X < 0) { actorPosition.X = 0.1F; } else if (actor.Position.X >= Constants.RegionSize) { actorPosition.X = ((int)Constants.RegionSize - 0.1f); } float terrainHeight = 0; if (_heightMap != null) terrainHeight = _heightMap[(int)actor.Position.Y * Constants.RegionSize + (int)actor.Position.X]; float height = terrainHeight + actor.Size.Z; if (actor.Flying) { if (actor.Position.Z + (actor.Velocity.Z * timeStep) < terrainHeight + 2) { actorPosition.Z = height; actorVelocity.Z = 0; actor.IsColliding = true; } else { actorPosition.Z += actor.Velocity.Z * timeStep; actor.IsColliding = false; } } else { actorPosition.Z = height; actorVelocity.Z = 0; actor.IsColliding = true; } actor.Position = actorPosition; actor.Velocity = actorVelocity; } return fps; } } }
using JeffFerguson.Gepsio.IoC; using JeffFerguson.Gepsio.Xml.Interfaces; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace JeffFerguson.Gepsio { /// <summary> /// An XML document containing one or more XBRL fragments. /// </summary> /// <remarks> /// <para> /// An XBRL fragment is a fragment of XBRL data having an xbrl tag as its root. In the generic case, /// an XBRL document will have an xbrl tag as the root tag of the XML document, and, in this case, /// the entire XBRL document is one large XBRL fragment. However, section 4.1 of the XBRL 2.1 Specification /// makes provisions for multiple XBRL fragments to be stored in a single document: /// </para> /// <para> /// "If multiple 'data islands' of XBRL mark-up are included in a larger document, the xbrl element is /// the container for each [fragment]." /// </para> /// <para> /// Gepsio supports this notion by defining an XBRL document containing a collection of one or more /// XBRL fragments, as in the following code sample: /// </para> /// <code> /// var myDocument = new XbrlDocument(); /// myDocument.Load("myxbrldoc.xml"); /// foreach(var currentFragment in myDocument.XbrlFragments) /// { /// // XBRL data is available from the "currentFragment" variable /// } /// </code> /// <para> /// In the vast majority of cases, an XBRL document will be an XML document with the xbrl tag at its /// root, and, as a result, the <see cref="XbrlDocument"/> uses to load the XBRL document will have /// a single <see cref="XbrlFragment"/> in the document's fragments container. Consider, however, the /// possibility of having more than one fragment in a document, in accordance of the text in section /// 4.1 of the XBRL 2.1 Specification. /// </para> /// </remarks> public class XbrlDocument { // namespace URIs internal static string XbrlNamespaceUri = "http://www.xbrl.org/2003/instance"; internal static string XbrlLinkbaseNamespaceUri = "http://www.xbrl.org/2003/linkbase"; internal static string XbrlDimensionsNamespaceUri = "http://xbrl.org/2005/xbrldt"; internal static string XbrlEssenceAliasArcroleNamespaceUri = "http://www.xbrl.org/2003/arcrole/essence-alias"; internal static string XbrlGeneralSpecialArcroleNamespaceUri = "http://www.xbrl.org/2003/arcrole/general-special"; internal static string XbrlSimilarTuplesArcroleNamespaceUri = "http://www.xbrl.org/2003/arcrole/similar-tuples"; internal static string XbrlRequiresElementArcroleNamespaceUri = "http://www.xbrl.org/2003/arcrole/requires-element"; internal static string XbrlFactFootnoteArcroleNamespaceUri = "http://www.xbrl.org/2003/arcrole/fact-footnote"; internal static string XbrlIso4217NamespaceUri = "http://www.xbrl.org/2003/iso4217"; internal static string XmlNamespaceUri1998 = "http://www.w3.org/XML/1998/namespace"; internal static string XmlNamespaceUri2000 = "http://www.w3.org/2000/xmlns/"; internal static string XmlSchemaInstanceUri = "http://www.w3.org/2001/XMLSchema-instance"; // role URIs internal static string XbrlLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/label"; internal static string XbrlTerseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/terseLabel"; internal static string XbrlVerboseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/verboseLabel"; internal static string XbrlPositiveLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/positiveLabel"; internal static string XbrlPositiveTerseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/positiveTerseLabel"; internal static string XbrlPositiveVerboseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/positiveVerboseLabel"; internal static string XbrlNegativeLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/negativeLabel"; internal static string XbrlNegativeTerseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/negativeTerseLabel"; internal static string XbrlNegativeVerboseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/negativeVerboseLabel"; internal static string XbrlZeroLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/zeroLabel"; internal static string XbrlZeroTerseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/zeroTerseLabel"; internal static string XbrlZeroVerboseLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/zeroVerboseLabel"; internal static string XbrlTotalLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/totalLabel"; internal static string XbrlPeriodStartLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/periodStartLabel"; internal static string XbrlPeriodEndLabelRoleNamespaceUri = "http://www.xbrl.org/2003/role/periodEndLabel"; internal static string XbrlDocumentationRoleNamespaceUri = "http://www.xbrl.org/2003/role/documentation"; internal static string XbrlDocumentationGuidanceRoleNamespaceUri = "http://www.xbrl.org/2003/role/definitionGuidance"; internal static string XbrlDisclosureGuidanceRoleNamespaceUri = "http://www.xbrl.org/2003/role/disclosureGuidance"; internal static string XbrlPresentationGuidanceRoleNamespaceUri = "http://www.xbrl.org/2003/role/presentationGuidance"; internal static string XbrlMeasurementGuidanceRoleNamespaceUri = "http://www.xbrl.org/2003/role/measurementGuidance"; internal static string XbrlCommentaryGuidanceRoleNamespaceUri = "http://www.xbrl.org/2003/role/commentaryGuidance"; internal static string XbrlExampleGuidanceRoleNamespaceUri = "http://www.xbrl.org/2003/role/exampleGuidance"; internal static string XbrlLinkbaseReferenceRoleNamespaceUri = "http://www.xbrl.org/2003/role/linkbaseRef"; internal static string XbrlCalculationLinkbaseReferenceRoleNamespaceUri = "http://www.xbrl.org/2003/role/calculationLinkbaseRef"; internal static string XbrlDefinitionLinkbaseReferenceRoleNamespaceUri = "http://www.xbrl.org/2003/role/definitionLinkbaseRef"; internal static string XbrlLabelLinkbaseReferenceRoleNamespaceUri = "http://www.xbrl.org/2003/role/labelLinkbaseRef"; internal static string XbrlPresentationLinkbaseReferenceRoleNamespaceUri = "http://www.xbrl.org/2003/role/presentationLinkbaseRef"; internal static string XbrlReferenceLinkbaseReferenceRoleNamespaceUri = "http://www.xbrl.org/2003/role/referenceLinkbaseRef"; /// <summary> /// The name of the XML document used to contain the XBRL data. /// </summary> public string Filename { get; private set; } /// <summary> /// The path to the XML document used to contain the XBRL data. /// </summary> public string Path { get; private set; } /// <summary> /// A collection of <see cref="XbrlFragment"/> objects that contain the document's /// XBRL data. /// </summary> public List<XbrlFragment> XbrlFragments { get; private set; } /// <summary> /// Evaluates to true if the document contains no XBRL validation errors. Evaluates to /// false if the document contains at least one XBRL validation error. /// </summary> public bool IsValid { get { if (this.XbrlFragments == null) return true; if (this.XbrlFragments.Count == 0) return true; foreach (var currentFragment in this.XbrlFragments) { if (currentFragment.IsValid == false) return false; } return true; } } /// <summary> /// A collection of all validation errors found while validating the fragment. /// </summary> public List<ValidationError> ValidationErrors { get { if (this.XbrlFragments == null) return null; if (this.XbrlFragments.Count == 0) return null; if (this.XbrlFragments.Count == 1) return this.XbrlFragments[0].ValidationErrors; var aggregatedValidationErrors = new List<ValidationError>(); foreach (var currentFragment in this.XbrlFragments) { aggregatedValidationErrors.AddRange(currentFragment.ValidationErrors); } return aggregatedValidationErrors; } } /// <summary> /// The constructor for the XbrlDocument class. /// </summary> public XbrlDocument() { this.XbrlFragments = new List<XbrlFragment>(); } /// <summary> /// Synchronously loads a local filesystem or Internet-accessible XBRL document containing /// XBRL data. /// </summary> /// <remarks> /// This method supports documents located on the local file system, and also /// documents specified through a URL, as shown in the following example: /// <code> /// var localDoc = new XbrlDocument(); /// localDoc.Load(@"..\..\..\JeffFerguson.Test.Gepsio\InferPrecisionTestDocuments\Example13Row7.xbrl"); /// var internetDoc = new XbrlDocument(); /// internetDoc.Load("http://www.xbrl.org/taxonomy/int/fr/ias/ci/pfs/2002-11-15/SampleCompany-2002-11-15.xml"); /// </code> /// </remarks> /// <param name="Filename"> /// The filename of the XML document to load. /// </param> public void Load(string Filename) { var SchemaValidXbrl = Container.Resolve<IDocument>(); SchemaValidXbrl.Load(Filename); this.Filename = Filename; this.Path = System.IO.Path.GetDirectoryName(this.Filename); Parse(SchemaValidXbrl); } /// <summary> /// Asynchronously loads a local filesystem or Internet-accessible XBRL document containing /// XBRL data. /// </summary> /// <remarks> /// This method supports documents located on the local file system, and also /// documents specified through a URL, as shown in the following example: /// <code> /// var localDoc = new XbrlDocument(); /// localDoc.Load(@"..\..\..\JeffFerguson.Test.Gepsio\InferPrecisionTestDocuments\Example13Row7.xbrl"); /// var internetDoc = new XbrlDocument(); /// await internetDoc.LoadAsync("http://www.xbrl.org/taxonomy/int/fr/ias/ci/pfs/2002-11-15/SampleCompany-2002-11-15.xml"); /// </code> /// </remarks> /// <param name="Filename"> /// The filename of the XML document to load. /// </param> public async Task LoadAsync(string Filename) { var SchemaValidXbrl = Container.Resolve<IDocument>(); await SchemaValidXbrl.LoadAsync(Filename); this.Filename = Filename; this.Path = System.IO.Path.GetDirectoryName(this.Filename); Parse(SchemaValidXbrl); } /// <summary> /// Synchronously loads an XBRL document containing XBRL data from a stream. /// </summary> /// <remarks> /// <para> /// Gepsio supports streams using the .NET Stream base class, which means that any type of stream /// supported by .NET and having the Stream class as a base class will be supported by Gepsio. /// This means that code like this will work: /// </para> /// <code> /// var webClient = new WebClient(); /// string readXml = webClient.DownloadString("http://www.xbrl.org/taxonomy/int/fr/ias/ci/pfs/2002-11-15/SampleCompany-2002-11-15.xml"); /// byte[] byteArray = Encoding.ASCII.GetBytes(readXml); /// MemoryStream memStream = new MemoryStream(byteArray); /// var newDoc = new XbrlDocument(); /// newDoc.Load(memStream); /// </code> /// <para> /// Schema references found in streamed XBRL instances must specify an absolute location, and not /// a relative location. For example, this schema reference is fine: /// </para> /// <code> /// xsi:schemaLocation=http://www.xbrlsolutions.com/taxonomies/iso4217/2002-06-30/iso4217.xsd /// </code> /// <para> /// However, this one is not: /// </para> /// <code> /// &lt;xbrll:schemaRef xlink:href="msft-20141231.xsd" ... /&gt; /// </code> /// <para> /// The reason behind this restriction is that Gepsio must load schema references using an absolute /// location, and uses the location of the XBRL document instance as the reference path when /// resolving schema relative paths to an absolute location. A schema reference without a path, for /// example, says "find this schema in the same location as the XBRL document instance referencing /// the schema". When the XBRL document instance is located through a file path or URL, then the /// location is known, and the schema reference can be found. When the XBRL document instance is /// passed in as a stream, however, the instance has no location, per se. Since it has no location, /// there is no "location starting point" for resolving schema locations using relative paths. /// </para> /// <para> /// If you try to load an XBRL document instance through a stream, and that stream references a schema /// through a relative path, then the document will be marked as invalid when the Load() method /// returns. This code, for example, will load an invalid document instance, since the XBRL document /// instance references a schema through a relative path: /// </para> /// <code> /// var webClient = new WebClient(); /// string readXml = webClient.DownloadString("http://www.sec.gov/Archives/edgar/data/789019/000119312515020351/msft-20141231.xml"); /// byte[] byteArray = Encoding.ASCII.GetBytes(readXml); /// MemoryStream memStream = new MemoryStream(byteArray); /// var newDoc = new XbrlDocument(); /// newDoc.Load(memStream); /// // newDoc.IsValid property will be FALSE here. Sad face. /// </code> /// <para> /// The document's ValidationErrors collection will contain a SchemaValidationError object, which will /// contain a message similar to the following: /// </para> /// <code> /// "The XBRL schema at msft-20141231.xsd could not be read because the file could not be found. Because /// the schema cannot be loaded, some validations will not be able to be performed. Other validation errors /// reported against this instance may stem from the fact that the schema cannot be loaded. More information /// on the "file not found" condition is available from the validation error object's inner exception /// property." /// </code> /// <para> /// XBRL document instances loaded through a stream which use absolute paths for schema references will be /// valid (assuming that all of the other XBRL semantics in the instance are correct). /// </para> /// </remarks> /// <param name="dataStream"> /// A stream of data containing the XML document to load. /// </param> public void Load(Stream dataStream) { var SchemaValidXbrl = Container.Resolve<IDocument>(); SchemaValidXbrl.Load(dataStream); this.Filename = string.Empty; this.Path = string.Empty; Parse(SchemaValidXbrl); } /// <summary> /// Asynchronously loads an XBRL document containing XBRL data from a stream. /// </summary> /// <remarks> /// <para> /// Gepsio supports streams using the .NET Stream base class, which means that any type of stream /// supported by .NET and having the Stream class as a base class will be supported by Gepsio. /// This means that code like this will work: /// </para> /// <code> /// var webClient = new WebClient(); /// string readXml = webClient.DownloadString("http://www.xbrl.org/taxonomy/int/fr/ias/ci/pfs/2002-11-15/SampleCompany-2002-11-15.xml"); /// byte[] byteArray = Encoding.ASCII.GetBytes(readXml); /// MemoryStream memStream = new MemoryStream(byteArray); /// var newDoc = new XbrlDocument(); /// await newDoc.LoadAsync(memStream); /// </code> /// <para> /// Schema references found in streamed XBRL instances must specify an absolute location, and not /// a relative location. For example, this schema reference is fine: /// </para> /// <code> /// xsi:schemaLocation=http://www.xbrlsolutions.com/taxonomies/iso4217/2002-06-30/iso4217.xsd /// </code> /// <para> /// However, this one is not: /// </para> /// <code> /// &lt;xbrll:schemaRef xlink:href="msft-20141231.xsd" ... /&gt; /// </code> /// <para> /// The reason behind this restriction is that Gepsio must load schema references using an absolute /// location, and uses the location of the XBRL document instance as the reference path when /// resolving schema relative paths to an absolute location. A schema reference without a path, for /// example, says "find this schema in the same location as the XBRL document instance referencing /// the schema". When the XBRL document instance is located through a file path or URL, then the /// location is known, and the schema reference can be found. When the XBRL document instance is /// passed in as a stream, however, the instance has no location, per se. Since it has no location, /// there is no "location starting point" for resolving schema locations using relative paths. /// </para> /// <para> /// If you try to load an XBRL document instance through a stream, and that stream references a schema /// through a relative path, then the document will be marked as invalid when the Load() method /// returns. This code, for example, will load an invalid document instance, since the XBRL document /// instance references a schema through a relative path: /// </para> /// <code> /// var webClient = new WebClient(); /// string readXml = webClient.DownloadString("http://www.sec.gov/Archives/edgar/data/789019/000119312515020351/msft-20141231.xml"); /// byte[] byteArray = Encoding.ASCII.GetBytes(readXml); /// MemoryStream memStream = new MemoryStream(byteArray); /// var newDoc = new XbrlDocument(); /// await newDoc.LoadAsync(memStream); /// // newDoc.IsValid property will be FALSE here. Sad face. /// </code> /// <para> /// The document's ValidationErrors collection will contain a SchemaValidationError object, which will /// contain a message similar to the following: /// </para> /// <code> /// "The XBRL schema at msft-20141231.xsd could not be read because the file could not be found. Because /// the schema cannot be loaded, some validations will not be able to be performed. Other validation errors /// reported against this instance may stem from the fact that the schema cannot be loaded. More information /// on the "file not found" condition is available from the validation error object's inner exception /// property." /// </code> /// <para> /// XBRL document instances loaded through a stream which use absolute paths for schema references will be /// valid (assuming that all of the other XBRL semantics in the instance are correct). /// </para> /// </remarks> /// <param name="dataStream"> /// A stream of data containing the XML document to load. /// </param> public async Task LoadAsync(Stream dataStream) { var SchemaValidXbrl = Container.Resolve<IDocument>(); await SchemaValidXbrl.LoadAsync(dataStream); this.Filename = string.Empty; this.Path = string.Empty; Parse(SchemaValidXbrl); } /// <summary> /// Parse the document, looking for fragments that can be processed. /// </summary> private void Parse(IDocument doc) { var NewNamespaceManager = Container.Resolve<INamespaceManager>(); NewNamespaceManager.Document = doc; NewNamespaceManager.AddNamespace("instance", XbrlNamespaceUri); INodeList XbrlNodes = doc.SelectNodes("//instance:xbrl", NewNamespaceManager); foreach (INode XbrlNode in XbrlNodes) this.XbrlFragments.Add(new XbrlFragment(this, NewNamespaceManager, XbrlNode)); } /// <summary> /// Finds the <see cref="RoleType"/> object having the given ID. /// </summary> /// <param name="RoleTypeId"> /// The ID of the role type to find. /// </param> /// <returns> /// The <see cref="RoleType"/> object having the given ID, or null if no /// object can be found. /// </returns> public RoleType GetRoleType(string RoleTypeId) { foreach (var currentFragment in XbrlFragments) { var roleTypeCandidate = currentFragment.GetRoleType(RoleTypeId); if (roleTypeCandidate != null) return roleTypeCandidate; } return null; } /// <summary> /// Finds the <see cref="CalculationLink"/> object having the given role. /// </summary> /// <param name="CalculationLinkRole"> /// The role type to find. /// </param> /// <returns> /// The <see cref="CalculationLink"/> object having the given role, or /// null if no object can be found. /// </returns> public CalculationLink GetCalculationLink(RoleType CalculationLinkRole) { foreach (var currentFragment in XbrlFragments) { var calculationLinkCandidate = currentFragment.GetCalculationLink(CalculationLinkRole); if (calculationLinkCandidate != null) return calculationLinkCandidate; } return null; } } }
// Copyright (c) 2012, Event Store LLP // 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 Event Store LLP 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.Collections.Generic; using System.Linq; using System.Threading; using EventStore.ClientAPI; using EventStore.ClientAPI.SystemData; using EventStore.Common.Log; using EventStore.Core.Services; using EventStore.Core.Tests.ClientAPI.Helpers; using EventStore.Core.Tests.Helpers; using NUnit.Framework; using ILogger = EventStore.Common.Log.ILogger; namespace EventStore.Core.Tests.ClientAPI { [TestFixture, Category("LongRunning")] public class subscribe_to_all_catching_up_should : SpecificationWithDirectory { private static readonly ILogger Log = LogManager.GetLoggerFor<subscribe_to_all_catching_up_should>(); private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(60); private MiniNode _node; private IEventStoreConnection _conn; [SetUp] public override void SetUp() { base.SetUp(); _node = new MiniNode(PathName, skipInitializeStandardUsersCheck: false); _node.Start(); _conn = TestConnection.Create(_node.TcpEndPoint); _conn.Connect(); _conn.SetStreamMetadata("$all", -1, StreamMetadata.Build().SetReadRole(SystemRoles.All), new UserCredentials(SystemUsers.Admin, SystemUsers.DefaultAdminPassword)); } [TearDown] public override void TearDown() { _conn.Close(); _node.Shutdown(); base.TearDown(); } [Test, Category("LongRunning")] public void call_dropped_callback_after_stop_method_call() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.Connect(); var dropped = new CountdownEvent(1); var subscription = store.SubscribeToAllFrom(null, false, (x, y) => { }, _ => Log.Info("Live processing started."), (x, y, z) => dropped.Signal()); Assert.IsFalse(dropped.Wait(0)); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } } [Test, Category("LongRunning")] public void be_able_to_subscribe_to_empty_db() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.Connect(); var appeared = new ManualResetEventSlim(false); var dropped = new CountdownEvent(1); var subscription = store.SubscribeToAllFrom(null, false, (_, x) => { if (!SystemStreams.IsSystemStream(x.OriginalEvent.EventStreamId)) appeared.Set(); }, _ => Log.Info("Live processing started."), (_, __, ___) => dropped.Signal()); Thread.Sleep(100); // give time for first pull phase store.SubscribeToAll(false, (s, x) => { }, (s, r, e) => { }); Thread.Sleep(100); Assert.IsFalse(appeared.Wait(0), "Some event appeared!"); Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } } [Test, Category("LongRunning")] public void read_all_existing_events_and_keep_listening_to_new_ones() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.Connect(); var events = new List<ResolvedEvent>(); var appeared = new CountdownEvent(20); var dropped = new CountdownEvent(1); for (int i = 0; i < 10; ++i) { store.AppendToStream("stream-" + i.ToString(), -1, new EventData(Guid.NewGuid(), "et-" + i.ToString(), false, new byte[3], null)); } var subscription = store.SubscribeToAllFrom(null, false, (x, y) => { if (!SystemStreams.IsSystemStream(y.OriginalEvent.EventStreamId)) { events.Add(y); appeared.Signal(); } }, _ => Log.Info("Live processing started."), (x, y, z) => dropped.Signal()); for (int i = 10; i < 20; ++i) { store.AppendToStream("stream-" + i.ToString(), -1, new EventData(Guid.NewGuid(), "et-" + i.ToString(), false, new byte[3], null)); } if (!appeared.Wait(Timeout)) { Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); Assert.Fail("Couldn't wait for all events."); } Assert.AreEqual(20, events.Count); for (int i = 0; i < 20; ++i) { Assert.AreEqual("et-" + i.ToString(), events[i].OriginalEvent.EventType); } Assert.IsFalse(dropped.Wait(0)); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } } [Test, Category("LongRunning")] public void filter_events_and_keep_listening_to_new_ones() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.Connect(); var events = new List<ResolvedEvent>(); var appeared = new CountdownEvent(10); var dropped = new CountdownEvent(1); for (int i = 0; i < 10; ++i) { store.AppendToStream("stream-" + i.ToString(), -1, new EventData(Guid.NewGuid(), "et-" + i.ToString(), false, new byte[3], null)); } var allSlice = store.ReadAllEventsForward(Position.Start, 100, false); var lastEvent = allSlice.Events.Last(); var subscription = store.SubscribeToAllFrom(lastEvent.OriginalPosition, false, (x, y) => { events.Add(y); appeared.Signal(); }, _ => Log.Info("Live processing started."), (x, y, z) => { Log.Info("Subscription dropped: {0}, {1}.", y, z); dropped.Signal(); }); for (int i = 10; i < 20; ++i) { store.AppendToStream("stream-" + i.ToString(), -1, new EventData(Guid.NewGuid(), "et-" + i.ToString(), false, new byte[3], null)); } Log.Info("Waiting for events..."); if (!appeared.Wait(Timeout)) { Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); Assert.Fail("Couldn't wait for all events."); } Log.Info("Events appeared..."); Assert.AreEqual(10, events.Count); for (int i = 0; i < 10; ++i) { Assert.AreEqual("et-" + (10 + i).ToString(), events[i].OriginalEvent.EventType); } Assert.IsFalse(dropped.Wait(0)); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); Assert.AreEqual(events.Last().OriginalPosition, subscription.LastProcessedPosition); } } [Test, Category("LongRunning")] public void filter_events_and_work_if_nothing_was_written_after_subscription() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.Connect(); var events = new List<ResolvedEvent>(); var appeared = new CountdownEvent(1); var dropped = new CountdownEvent(1); for (int i = 0; i < 10; ++i) { store.AppendToStream("stream-" + i.ToString(), -1, new EventData(Guid.NewGuid(), "et-" + i.ToString(), false, new byte[3], null)); } var allSlice = store.ReadAllEventsForward(Position.Start, 100, false); var lastEvent = allSlice.Events[allSlice.Events.Length - 2]; var subscription = store.SubscribeToAllFrom(lastEvent.OriginalPosition, false, (x, y) => { events.Add(y); appeared.Signal(); }, _ => Log.Info("Live processing started."), (x, y, z) => { Log.Info("Subscription dropped: {0}, {1}.", y, z); dropped.Signal(); }); Log.Info("Waiting for events..."); if (!appeared.Wait(Timeout)) { Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); Assert.Fail("Couldn't wait for all events."); } Log.Info("Events appeared..."); Assert.AreEqual(1, events.Count); Assert.AreEqual("et-9", events[0].OriginalEvent.EventType); Assert.IsFalse(dropped.Wait(0)); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); Assert.AreEqual(events.Last().OriginalPosition, subscription.LastProcessedPosition); } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Diagnostics; using Axiom.Animating; using Axiom.Core; using Axiom.Graphics; using Axiom.MathLib; using Axiom.Configuration; using Axiom.Utility; using Axiom.SceneManagers.Multiverse; using Multiverse.Lib.LogUtil; using Multiverse.AssetRepository; namespace Multiverse.Tools.AxiomTester { public partial class Form1 : Form { protected readonly float oneMeter = 1000.0f; protected Root engine; protected Camera camera; protected Viewport viewport; protected Axiom.Core.SceneManager scene; protected RenderWindow window; protected int inhibit = 0; protected bool quit = false; protected float time = 0; protected bool displayWireFrame = false; protected bool displayTerrain = false; protected bool displayOcean = false; protected bool spinCamera = false; protected int objectCount = 0; protected int totalVertexCount = 0; protected int numObjectsSharingMaterial = 0; protected bool randomSizes = false; protected bool randomScales = false; protected bool randomOrientations = false; protected Mesh unitBox; protected Mesh unitSphere; protected Mesh unitCylinder; protected Mesh zombieModel; protected Mesh humanFemaleModel; private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Form1)); private static string MyDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); private static string ClientAppDataFolder = Path.Combine(MyDocumentsFolder, "AxiomTester"); private static string ConfigFolder = Path.Combine(ClientAppDataFolder, "Config"); private static string LogFolder = Path.Combine(ClientAppDataFolder, "Logs"); private static string FallbackLogfile = Path.Combine(LogFolder, "AxiomTester.log"); private static string MeterEventsFile = Path.Combine(LogFolder, "MeterEvents.log"); private static string MeterLogFile = Path.Combine(LogFolder, "MeterLog.log"); protected enum WhichObjectsEnum { woBoxes = 0, woEllipsoids = 1, woCylinders = 2, woPlane = 3, woRandom = 4, woZombie = 5, woHumanFemale = 6 } protected Mesh[] meshes; protected string[] animationNames; protected string[][] visibleSubMeshes; protected WhichObjectsEnum whichObjects = WhichObjectsEnum.woBoxes; protected bool animatedObjects; protected Random rand = new Random(); protected List<SceneNode> sceneNodeList = new List<SceneNode>(); protected List<Entity> entityList = new List<Entity>(); protected List<Material> materialList = new List<Material>(); protected List<Texture> textureList = new List<Texture>(); protected Material prototypeMaterial; protected bool useTextures = false; protected bool uniqueTextures = false; protected int lastFrameRenderCalls = 0; protected long lastTotalRenderCalls = 0; protected int lastFrameSetPassCalls = 0; protected long lastTotalSetPassCalls = 0; protected long lastFrameTime = 0; protected float animationSpeed = 1.0f; protected float animationTime; protected float currentAnimationTime; protected float currentAnimationLength; protected bool animationInitialized = false; protected long timerFreq = Stopwatch.Frequency; Multiverse.Generator.FractalTerrainGenerator terrainGenerator; private List<AnimationState> animStateList; public Form1() { InitializeComponent(); // Set up log configuration folders if (!Directory.Exists(ConfigFolder)) Directory.CreateDirectory(ConfigFolder); // Note that the DisplaySettings.xml should also show up in this folder. if (!Directory.Exists(LogFolder)) Directory.CreateDirectory(LogFolder); bool interactive = System.Windows.Forms.SystemInformation.UserInteractive; LogUtil.InitializeLogging(Path.Combine(ConfigFolder, "LogConfig.xml"), "DefaultLogConfig.xml", FallbackLogfile, interactive); whichObjectsComboBox.SelectedIndex = 0; runDemosRadioButton_Click(null, null); terrainGenerator = new Multiverse.Generator.FractalTerrainGenerator(); axiomPictureBox.Height = this.ClientSize.Height - 60; MeterManager.MeterLogFile = MeterLogFile; MeterManager.MeterEventsFile = MeterEventsFile; } #region Axiom Initialization Code protected bool Setup() { // get a reference to the engine singleton engine = new Root("EngineConfig.xml", null); // add event handlers for frame events engine.FrameStarted += new FrameEvent(OnFrameStarted); engine.FrameEnded += new FrameEvent(OnFrameEnded); // allow for setting up resource gathering SetupResources(); //show the config dialog and collect options if (!ConfigureAxiom()) { // shutting right back down engine.Shutdown(); return false; } ChooseSceneManager(); CreateCamera(); CreateViewports(); // set default mipmap level TextureManager.Instance.DefaultNumMipMaps = 5; // call the overridden CreateScene method CreateScene(); return true; } protected bool SetupResources() { RepositoryClass.Instance.InitializeRepositoryPath(); if (!RepositoryClass.Instance.RepositoryDirectoryListSet()) { return false; } foreach (string s in RepositoryClass.AxiomDirectories) { List<string> repositoryDirectoryList = RepositoryClass.Instance.RepositoryDirectoryList; List<string> l = new List<string>(); foreach (string repository in repositoryDirectoryList) l.Add(Path.Combine(repository, s)); ResourceManager.AddCommonArchive(l, "Folder"); } return true; } protected bool ConfigureAxiom() { // HACK: Temporary RenderSystem renderSystem = Root.Instance.RenderSystems[0]; Root.Instance.RenderSystem = renderSystem; Root.Instance.Initialize(false); window = Root.Instance.CreateRenderWindow("Main Window", axiomPictureBox.Width, axiomPictureBox.Height, false, "externalWindow", axiomPictureBox, "useNVPerfHUD", true); Root.Instance.Initialize(false); return true; } protected void ChooseSceneManager() { scene = Root.Instance.SceneManagers.GetSceneManager(SceneType.ExteriorClose); DisplayTerrain = false; } protected void CreateCamera() { camera = scene.CreateCamera("PlayerCam"); float scale = 100f; camera.Position = new Vector3(64 * oneMeter, 0 * oneMeter, 64 * oneMeter); camera.LookAt(new Vector3(0, 0, 0)); camera.Near = 1 * oneMeter; camera.Far = 10000 * oneMeter; } protected virtual void CreateViewports() { Debug.Assert(window != null, "Attempting to use a null RenderWindow."); // create a new viewport and set it's background color viewport = window.AddViewport(camera, 0, 0, 1.0f, 1.0f, 100); viewport.BackgroundColor = ColorEx.Black; viewport.OverlaysEnabled = false; } #endregion Axiom Initialization Code #region Application Startup Code public bool Start() { if (!Setup()) { return false; } // start the engines rendering loop engine.StartRendering(); return true; } #endregion Application Startup Code #region Scene Setup protected void GenerateScene() { ((Axiom.SceneManagers.Multiverse.SceneManager)scene).SetWorldParams(terrainGenerator, new DefaultLODSpec()); scene.LoadWorldGeometry(""); Axiom.SceneManagers.Multiverse.TerrainManager.Instance.ShowOcean = displayOcean; scene.AmbientLight = new ColorEx(0.8f, 0.8f, 0.8f); Light light = scene.CreateLight("MainLight"); light.Type = LightType.Directional; Vector3 lightDir = new Vector3(-80 * oneMeter, -70 * oneMeter, -80 * oneMeter); lightDir.Normalize(); light.Direction = lightDir; light.Position = -lightDir; light.Diffuse = ColorEx.White; light.SetAttenuation(1000 * oneMeter, 1, 0, 0); return; } protected void CreateRibbons() { viewport.BackgroundColor = ColorEx.Black; float scale = 100f; scene.AmbientLight = new ColorEx(0.5f, 0.5f, 0.5f); //scene.SetSkyBox(true, "Examples/SpaceSkyBox", 20f * oneMeter); Vector3 dir = new Vector3(-1f, -1f, 0.5f); dir.Normalize(); Light light1 = scene.CreateLight("light1"); light1.Type = LightType.Directional; light1.Direction = dir; // Create a barrel for the ribbons to fly through Entity barrel = scene.CreateEntity("barrel", "barrel.mesh"); SceneNode barrelNode = scene.RootSceneNode.CreateChildSceneNode(); barrelNode.ScaleFactor = 5f * Vector3.UnitScale; barrelNode.AttachObject(barrel); RibbonTrail trail = new RibbonTrail("DemoTrail", "numberOfChains", 2, "maxElementsPerChain", 80); trail.MaterialName = "Examples/LightRibbonTrail"; trail.TrailLength = scale * 400f; scene.RootSceneNode.CreateChildSceneNode().AttachObject(trail); // Create 3 nodes for trail to follow SceneNode animNode = scene.RootSceneNode.CreateChildSceneNode(); animNode.Position = scale * new Vector3(50f, 30f, 0); Animation anim = scene.CreateAnimation("an1", 14); anim.InterpolationMode = InterpolationMode.Spline; NodeAnimationTrack track = anim.CreateNodeTrack(1, animNode); TransformKeyFrame kf = track.CreateNodeKeyFrame(0); kf.Translate = scale * new Vector3(50f,30f,0f); kf = track.CreateNodeKeyFrame(2); kf.Translate = scale * new Vector3(100f, -30f, 0f); kf = track.CreateNodeKeyFrame(4); kf.Translate = scale * new Vector3(120f, -100f, 150f); kf = track.CreateNodeKeyFrame(6); kf.Translate = scale * new Vector3(30f, -100f, 50f); kf = track.CreateNodeKeyFrame(8); kf.Translate = scale * new Vector3(-50f, 30f, -50f); kf = track.CreateNodeKeyFrame(10); kf.Translate = scale * new Vector3(-150f, -20f, -100f); kf = track.CreateNodeKeyFrame(12); kf.Translate = scale * new Vector3(-50f, -30f, 0f); kf = track.CreateNodeKeyFrame(14); kf.Translate = scale * new Vector3(50f, 30f, 0f); AnimationState animState = scene.CreateAnimationState("an1"); //animState.Enabled = true; animStateList = new List<AnimationState>(); animStateList.Add(animState); trail.SetInitialColor(0, 1.0f, 0.8f, 0f, 1.0f); trail.SetColorChange(0, 0.5f, 0.5f, 0.5f, 0.5f); trail.SetInitialWidth(0, scale * 5f); trail.AddNode(animNode); // Add light Light light2 = scene.CreateLight("light2"); light2.Diffuse = trail.GetInitialColor(0); animNode.AttachObject(light2); // Add billboard BillboardSet bbs = scene.CreateBillboardSet("bb", 1); bbs.CreateBillboard(Vector3.Zero, trail.GetInitialColor(0)); bbs.MaterialName = "flare"; animNode.AttachObject(bbs); animNode = scene.RootSceneNode.CreateChildSceneNode(); animNode.Position = scale * new Vector3(-50f, 100f, 0f); anim = scene.CreateAnimation("an2", 10); anim.InterpolationMode = InterpolationMode.Spline; track = anim.CreateNodeTrack(1, animNode); kf = track.CreateNodeKeyFrame(0); kf.Translate = scale * new Vector3(-50f,100f,0f); kf = track.CreateNodeKeyFrame(2); kf.Translate = scale * new Vector3(-100f, 150f, -30f); kf = track.CreateNodeKeyFrame(4); kf.Translate = scale * new Vector3(-200f, 0f, 40f); kf = track.CreateNodeKeyFrame(6); kf.Translate = scale * new Vector3(0f, -150f, 70f); kf = track.CreateNodeKeyFrame(8); kf.Translate = scale * new Vector3(50f, 0f, 30f); kf = track.CreateNodeKeyFrame(10); kf.Translate = scale * new Vector3(-50f,100f,0f); animState = scene.CreateAnimationState("an2"); //animState.setEnabled(true); animStateList.Add(animState); trail.SetInitialColor(1, 0.0f, 1.0f, 0.4f, 1.0f); trail.SetColorChange(1, 0.5f, 0.5f, 0.5f, 0.5f); trail.SetInitialWidth(1, scale * 5f); trail.AddNode(animNode); // Add light Light light3 = scene.CreateLight("l3"); light3.Diffuse = trail.GetInitialColor(1); animNode.AttachObject(light3); // Add billboard bbs = scene.CreateBillboardSet("bb2", 1); bbs.CreateBillboard(Vector3.Zero, trail.GetInitialColor(1)); bbs.MaterialName = "flare"; animNode.AttachObject(bbs); } protected void CreateScene() { viewport.BackgroundColor = ColorEx.White; viewport.OverlaysEnabled = false; GenerateScene(); scene.SetFog(FogMode.Linear, ColorEx.White, .008f, 0, 1000 * oneMeter); unitBox = MeshManager.Instance.Load("unit_box.mesh"); unitSphere = MeshManager.Instance.Load("unit_sphere.mesh"); unitCylinder = MeshManager.Instance.Load("unit_cylinder.mesh"); zombieModel = MeshManager.Instance.Load("zombie.mesh"); humanFemaleModel = MeshManager.Instance.Load("hmn_f_01_base.mesh"); meshes = new Mesh[7] { unitBox, unitSphere, unitCylinder, null, null, zombieModel, humanFemaleModel }; string[] zombieSubMeshes = new string[] { "Zombie_Body2-obj.0", "Zombie_Clothes2-obj.0" }; string[] hmSubMeshes = new string[] { "feet_heels_tokyopop_a_01-mesh.0", "legs_ntrl_tokyopop_a_01-mesh.0", "torso_ntrl_tokyopop_a_01-mesh.0", "face_asia_01-mesh.0", "hair_bob_01-mesh.0" }; visibleSubMeshes = new string[][] { zombieSubMeshes, hmSubMeshes }; animationNames = new string[2] { "run", "ntrl_walk_loop"}; return; } protected void ClearCreatedObjects() { for (int i=0; i<sceneNodeList.Count; i++) { SceneNode node = sceneNodeList[i]; Entity entity = entityList[i]; node.DetachObject(entity); scene.RemoveEntity(entity); node.RemoveFromParent(); } sceneNodeList.Clear(); entityList.Clear(); foreach (Material material in materialList) { material.Dispose(); MaterialManager.Instance.Unload(material); } materialList.Clear(); foreach (Texture texture in textureList) { texture.Dispose(); TextureManager.Instance.Unload(texture); } textureList.Clear(); totalVertexCount = 0; } protected string GetAnimationName() { return animationNames[(int)whichObjects - (int)WhichObjectsEnum.woZombie]; } protected void EnsureObjectsCreated() { ClearCreatedObjects(); Texture prototypeTexture = null; if (useTextures) { prototypeMaterial = MaterialManager.Instance.Load("barrel.barrel"); if (uniqueTextures) prototypeTexture = TextureManager.Instance.Load("blank.dds"); } else prototypeMaterial = MaterialManager.Instance.Load("unit_box.unit_box"); prototypeMaterial.Compile(); if (objectCount == 0) return; int materialCount = (animatedObjects ? 0 : (numObjectsSharingMaterial == 0 ? objectCount : (numObjectsSharingMaterial >= objectCount ? 1 : (objectCount + numObjectsSharingMaterial - 1) / numObjectsSharingMaterial))); materialCountLabel.Text = "Material Count: " + materialCount; if (whichObjects == WhichObjectsEnum.woPlane || whichObjects == WhichObjectsEnum.woRandom) { Mesh plane = meshes[(int)WhichObjectsEnum.woPlane]; if (plane != null) plane.Unload(); // Create the plane float planeSide = 1000f; int planeUnits = Int32.Parse(planeUnitsTextBox.Text); plane = MeshManager.Instance.CreatePlane("testerPlane", new Plane(Vector3.UnitZ, Vector3.Zero), planeSide, planeSide, planeUnits, planeUnits, true, 1, planeSide / planeUnits, planeSide / planeUnits, Vector3.UnitY); meshes[(int)WhichObjectsEnum.woPlane] = plane; } // Create the new materials for (int i = 0; i < materialCount; i++) { Material mat = prototypeMaterial.Clone("mat" + i); Pass p = mat.GetTechnique(0).GetPass(0); if (!animatedObjects && uniqueTextures) { Texture t = prototypeTexture; Texture texture = TextureManager.Instance.CreateManual("texture" + i, t.TextureType, t.Width, t.Height, t.NumMipMaps, t.Format, t.Usage); textureList.Add(texture); p.CreateTextureUnitState(texture.Name); } // Make the materials lovely shades of blue p.Ambient = new ColorEx(1f, .2f, .2f, (1f / materialCount) * i); p.Diffuse = new ColorEx(p.Ambient); p.Specular = new ColorEx(1f, 0f, 0f, 0f); materialList.Add(mat); } // Create the entities and scene nodes for (int i=0; i<objectCount; i++) { Mesh mesh = selectMesh(); Material mat = null; if (materialCount > 0) mat = materialList[i % materialCount]; Entity entity = scene.CreateEntity("entity" + i, mesh); if (animatedObjects) { string[] visibleSubs = visibleSubMeshes[(int)whichObjects - (int) WhichObjectsEnum.woZombie]; for (int j = 0; j < entity.SubEntityCount; ++j) { SubEntity sub = entity.GetSubEntity(j); bool visible = false; foreach (string s in visibleSubs) { if (s == sub.SubMesh.Name) { visible = true; break; } } sub.IsVisible = visible; if (visible) totalVertexCount += sub.SubMesh.VertexData.vertexCount; } } else { if (mesh.SharedVertexData != null) totalVertexCount += mesh.SharedVertexData.vertexCount; else { for (int j=0; j<mesh.SubMeshCount; j++) { SubMesh subMesh = mesh.GetSubMesh(j); totalVertexCount += subMesh.VertexData.vertexCount; } } } if (animatedObjects && animateCheckBox.Checked) { AnimationState currentAnimation = entity.GetAnimationState(GetAnimationName()); currentAnimation.IsEnabled = true; if (!animationInitialized) { currentAnimationLength = entity.GetAnimationState(GetAnimationName()).Length; animationInitialized = true; } } if (mat != null) entity.MaterialName = mat.Name; entityList.Add(entity); SceneNode node = scene.RootSceneNode.CreateChildSceneNode(); sceneNodeList.Add(node); node.AttachObject(entity); node.Position = new Vector3(randomCoord(), randomCoord(), randomCoord()); if (randomSizes) node.ScaleFactor = Vector3.UnitScale * randomScale(); else if (randomScales) node.ScaleFactor = new Vector3(randomScale(), randomScale(), randomScale()); else node.ScaleFactor = Vector3.UnitScale * 1f; if (randomOrientations) { Vector3 axis = new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble()); node.Orientation = Vector3.UnitY.GetRotationTo(axis.ToNormalized()); } else node.Orientation = Quaternion.Identity; } } protected Mesh selectMesh() { if (whichObjects == WhichObjectsEnum.woRandom) { int r = (int)(rand.NextDouble() * 4.0); if (r >= 4) r = 3; return meshes[r]; } else return meshes[(int)whichObjects]; } protected float randomCoord() { return (float)((rand.NextDouble() - 0.5) * 50 * oneMeter); } protected float randomScale() { return (float)(.25 + (2.0 * (rand.NextDouble() - .15)));; } #endregion Scene Setup #region Axiom Frame Event Handlers public void meterOneFrame() { if (Root.Instance != null) Root.Instance.ToggleMetering(1); } protected void OnFrameEnded(object source, FrameEventArgs e) { return; } protected void runAnimations() { if (!animationInitialized) return; long curTimer = Stopwatch.GetTimestamp(); float frameTime = (float)(curTimer - lastFrameTime) / (float)timerFreq; lastFrameTime = curTimer; float advanceTime = frameTime * animationSpeed; float time = currentAnimationTime + advanceTime; // Loop the animation while (time >= currentAnimationLength) time -= currentAnimationLength; foreach (Entity entity in entityList) { AnimationState currentAnimation = entity.GetAnimationState(GetAnimationName()); currentAnimation.Time = time; } currentAnimationTime = time; } protected void OnFrameStarted(object source, FrameEventArgs e) { if (quit) { Root.Instance.QueueEndRendering(); return; } // Calculate the number of render calls since the last frame lastFrameRenderCalls = (int)(RenderSystem.TotalRenderCalls - lastTotalRenderCalls); // Remember the current count for next frame lastTotalRenderCalls = RenderSystem.TotalRenderCalls; int fps = Root.Instance.CurrentFPS; FPSLabel.Text = "FPS: " + fps.ToString(); rendersPerFrameLabel.Text = "Renders Per Frame: " + lastFrameRenderCalls; renderCallsLabel.Text = "Renders Per Second: " + fps * lastFrameRenderCalls; // Calculate the number of set pass calls since the last frame lastFrameSetPassCalls = (int)(scene.TotalSetPassCalls - lastTotalSetPassCalls); // Remember the current count for next frame lastTotalSetPassCalls = scene.TotalSetPassCalls; setPassCallsLabel.Text = "Set Pass Calls Per Frame: " + lastFrameSetPassCalls; // Display the number of vertices vertexCountLabel.Text = "Verts/Obj: " + (objectCount == 0 ? 0 : totalVertexCount / objectCount) + " Total Verts: " + totalVertexCount; float scaleMove = 100 * e.TimeSinceLastFrame * oneMeter; time += e.TimeSinceLastFrame; //Axiom.SceneManagers.Multiverse.WorldManager.Instance.Time = time; if (spinCamera) { float rot = 20 * e.TimeSinceLastFrame; camera.Yaw(rot); } if (animatedObjects && animateCheckBox.Checked) { runAnimations(); } //// reset acceleration zero //camAccel = Vector3.Zero; //// set the scaling of camera motion //cameraScale = 100 * e.TimeSinceLastFrame; //if (moveForward) //{ // camAccel.z = -1.0f; //} //if (moveBack) //{ // camAccel.z = 1.0f; //} //if (moveLeft) //{ // camAccel.x = -0.5f; //} //if (moveRight) //{ // camAccel.x = 0.5f; //} //// handle rotation of the camera with the mouse //if (mouseRotate) //{ // float deltaX = mouseX - lastMouseX; // float deltaY = mouseY - lastMouseY; // camera.Yaw(-deltaX * mouseRotationScale); // camera.Pitch(-deltaY * mouseRotationScale); //} //// update last mouse position //lastMouseX = mouseX; //lastMouseY = mouseY; //if (humanSpeed) //{ // camVelocity = camAccel * 7.0f * oneMeter; // camera.MoveRelative(camVelocity * e.TimeSinceLastFrame); //} //else //{ // camVelocity += (camAccel * scaleMove * camSpeed); // // move the camera based on the accumulated movement vector // camera.MoveRelative(camVelocity * e.TimeSinceLastFrame); // // Now dampen the Velocity - only if user is not accelerating // if (camAccel == Vector3.Zero) // { // float decel = 1 - (6 * e.TimeSinceLastFrame); // if (decel < 0) // { // decel = 0; // } // camVelocity *= decel; // } //} //if (followTerrain || (result.worldFragment.SingleIntersection.y + (2.0f * oneMeter)) > camera.Position.y) //{ // // adjust new camera position to be a fixed distance above the ground // camera.Position = new Vector3(camera.Position.x, result.worldFragment.SingleIntersection.y + (2.0f * oneMeter), camera.Position.z); //} } #endregion Axiom Frame Event Handlers private bool DisplayTerrain { get { return displayTerrain; } set { displayTerrain = value; Axiom.SceneManagers.Multiverse.TerrainManager.Instance.DrawTerrain = displayTerrain; } } private bool DisplayWireFrame { get { return displayWireFrame; } set { displayWireFrame = value; if (displayWireFrame) { camera.SceneDetail = SceneDetailLevel.Wireframe; } else { camera.SceneDetail = SceneDetailLevel.Solid; } } } private bool DisplayOcean { get { return displayOcean; } set { displayOcean = value; Axiom.SceneManagers.Multiverse.TerrainManager.Instance.ShowOcean = displayOcean; } } private bool SpinCamera { get { return spinCamera; } set { spinCamera = value; } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { quit = true; } private void wireFrameToolStripMenuItem_Click(object sender, EventArgs e) { DisplayWireFrame = !DisplayWireFrame; } private void viewToolStripMenuItem1_DropDownOpening(object sender, EventArgs e) { wireFrameToolStripMenuItem.Checked = DisplayWireFrame; displayOceanToolStripMenuItem.Checked = DisplayOcean; displayTerrainToolStripMenuItem.Checked = DisplayTerrain; spinCameraToolStripMenuItem.Checked = SpinCamera; } private void displayOceanToolStripMenuItem_Click(object sender, EventArgs e) { DisplayOcean = !DisplayOcean; } private void displayTerrainToolStripMenuItem_Click(object sender, EventArgs e) { DisplayTerrain = !DisplayTerrain; } private void spinCameraToolStripMenuItem_Click(object sender, EventArgs e) { SpinCamera = !SpinCamera; } private void toolStripButton1_Click(object sender, EventArgs e) { SpinCamera = !SpinCamera; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { quit = true; e.Cancel = true; } private void numObjectsTrackBar_ValueChanged(object sender, EventArgs e) { objectCount = numObjectsTrackBar.Value; numObjectsLabel.Text = "Number of Objects: " + objectCount; } private void numSharingMaterialTrackBar_ValueChanged(object sender, EventArgs e) { numObjectsSharingMaterial = numSharingMaterialTrackBar.Value; numSharingMaterialLabel.Text = "Number of Object Sharing Each Material: " + numObjectsSharingMaterial; } private void generateObjectsButton_Click(object sender, EventArgs e) { EnsureObjectsCreated(); } private void randomOrientationsCheckBox_CheckedChanged(object sender, EventArgs e) { randomOrientations = randomOrientationsCheckBox.Checked; } private void randomSizesRadioButton_CheckedChanged(object sender, EventArgs e) { randomSizes = randomSizesRadioButton.Checked; } private void randomScalesRadioButton_CheckedChanged(object sender, EventArgs e) { randomScales = randomScalesRadioButton.Checked; } private void unitSizeRadioButton_CheckedChanged(object sender, EventArgs e) { randomSizes = false; randomScales = false; } private void whichObjectsComboBox_SelectedIndexChanged(object sender, EventArgs e) { whichObjects = (WhichObjectsEnum)whichObjectsComboBox.SelectedIndex; animatedObjects = whichObjects == WhichObjectsEnum.woZombie || whichObjects == WhichObjectsEnum.woHumanFemale; animateCheckBox.Visible = animatedObjects; animationInitialized = false; planeUnitsPanel.Visible = whichObjects == WhichObjectsEnum.woPlane || whichObjects == WhichObjectsEnum.woRandom; } private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.N && e.Alt && e.Shift && e.Control) { commentLabel.Text = "Metering one frame"; meterOneFrame(); } } private void useTextureCheckBox_CheckedChanged(object sender, EventArgs e) { useTextures = useTextureCheckBox.Checked; uniqueTexturesCheckBox.Enabled = useTextures; if (!useTextures) uniqueTexturesCheckBox.Checked = false; } private void uniqueTexturesCheckBox_CheckedChanged(object sender, EventArgs e) { uniqueTextures = uniqueTexturesCheckBox.Checked; } private void meterButton_Click(object sender, EventArgs e) { if (engine != null) engine.ToggleMetering(1); } private void panelSelectionChanged(bool runDemos) { inhibit++; renderObjectsRadioButton.Checked = !runDemos; runDemosRadioButton.Checked = runDemos; inhibit--; renderObjectsPanel.Visible = !runDemos; runDemosPanel.Visible = runDemos; } private void renderObjectsRadioButton_Click(object sender, EventArgs e) { if (inhibit == 0) panelSelectionChanged(!renderObjectsRadioButton.Checked); } private void runDemosRadioButton_Click(object sender, EventArgs e) { if (inhibit == 0) panelSelectionChanged(runDemosRadioButton.Checked); } private void OnRibbonFrameStarted(object source, FrameEventArgs e) { // For RibbbonTrail display foreach (AnimationState animi in animStateList) animi.AddTime(e.TimeSinceLastFrame); } private void runRibbonsDemoButton_Click(object sender, EventArgs e) { CreateRibbons(); engine.FrameStarted += new FrameEvent(OnRibbonFrameStarted); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E11Level111111Child (editable child object).<br/> /// This is a generated base class of <see cref="E11Level111111Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="E10Level11111"/> collection. /// </remarks> [Serializable] public partial class E11Level111111Child : BusinessBase<E11Level111111Child> { #region State Fields [NotUndoable] [NonSerialized] internal int cQarentID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E11Level111111Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="E11Level111111Child"/> object.</returns> internal static E11Level111111Child NewE11Level111111Child() { return DataPortal.CreateChild<E11Level111111Child>(); } /// <summary> /// Factory method. Loads a <see cref="E11Level111111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E11Level111111Child"/> object.</returns> internal static E11Level111111Child GetE11Level111111Child(SafeDataReader dr) { E11Level111111Child obj = new E11Level111111Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E11Level111111Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private E11Level111111Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E11Level111111Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E11Level111111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Child_Name")); cQarentID1 = dr.GetInt32("CQarentID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="E11Level111111Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddE11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="E11Level111111Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(E10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateE11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="E11Level111111Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(E10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteE11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; namespace Free.Database.Dao.Net { public enum CollatingOrder { dbSortUndefined = -1, dbSortNeutral = 1024, dbSortArabic = 1025, dbSortChineseTraditional = 1028, dbSortCzech = 1029, dbSortNorwdan = 1030, dbSortGreek = 1032, dbSortGeneral = 1033, dbSortSpanish = 1034, dbSortHebrew = 1037, dbSortHungarian = 1038, dbSortIcelandic = 1039, dbSortJapanese = 1041, dbSortKorean = 1042, dbSortDutch = 1043, dbSortPolish = 1045, dbSortCyrillic = 1049, dbSortSwedFin = 1053, dbSortThai = 1054, dbSortTurkish = 1055, dbSortSlovenian = 1060, dbSortChineseSimplified = 2052, dbSortPDXNor = 1030, dbSortPDXIntl = 1033, dbSortPDXSwe = 1053 } public enum CommitTransOptions { dbForceOSFlush = 1 } public enum CursorDriver { dbUseDefaultCursor = -1, dbUseODBCCursor = 1, dbUseServerCursor = 2, dbUseClientBatchCursor = 3, dbUseNoCursor = 4 } public enum DatabaseType { dbVersion10 = 1, dbEncrypt = 2, dbDecrypt = 4, dbVersion11 = 8, dbVersion20 = 16, dbVersion30 = 32 } public enum DataType { dbBoolean = 1, dbByte = 2, dbInteger = 3, dbLong = 4, dbCurrency = 5, dbSingle = 6, dbDouble = 7, dbDate = 8, dbBinary = 9, dbText = 10, dbLongBinary = 11, dbMemo = 12, dbGUID = 15, dbBigInt = 16, dbVarBinary = 17, dbChar = 18, dbNumeric = 19, dbDezimal = 20, dbFloat = 21, dbTime = 22, dbTimeStamp = 23 } /* public enum _DAOSuppHelp { KeepLocal = 0, LogMessages = 0, Replicable = 0, ReplicableBool = 0, V1xNullBehavior = 0 }*/ public enum DriverPrompt { dbDriverComplete = 0, dbDriverNoPrompt = 1, dbDriverPrompt = 2, dbDriverCompleteRequired = 3, dbRunAsync = 1024 } public enum EditMode { dbEditNone = 0, dbEditInProgress = 1, dbEditAdd = 2, dbEditChanged = 4, dbEditDeleted = 8, dbEditNew = 16 } public enum FieldAttribute { dbDescending = 1, dbFixedField = 1, dbVariableField = 2, dbAutoIncrField = 16, dbUpdatableField = 32, dbSystemField = 8192, dbHyperlinkField = 32768 } public enum Idle { dbFreeLocks = 1, dbRefreshCache = 8 } public enum LockType { dbOptimisticValue = 1, dbPessimistic = 2, dbOptimistic = 3, dbReadOnly = 4, dbOptimisticBatch = 5 } public enum ParameterDirection { dbParamInput = 1, dbParamOutput = 2, dbParamInputOutput = 3, dbParamReturnValue = 4 } public enum Permission { dbSecNoAccess = 0, dbSecCreate = 1, dbSecDBCreate = 1, dbSecDBOpen = 2, dbSecReadDef = 4, dbSecDBExclusive = 4, dbSecDBAdmin = 8, dbSecRetrieveData = 20, // 0x00014 dbSecInsertData = 32, // 0x00020 dbSecReplaceData = 64, // 0x00040 dbSecDeleteData = 128, // 0x00080 dbSecDelete = 65536, // 0x10000 dbSecWriteDef = 65548, // 0x1000C dbSecReadSec = 131072, // 0x20000 dbSecWriteSec = 262144, // 0x40000 dbSecWriteOwner = 524288, // 0x80000 dbSecFullAccess = 1048575 // 0xFFFFF } public enum QueryDefState { dbQPrepare = 1, dbQUnprepare = 2 } public enum QueryDefType { dbQSelect = 0, dbQCrosstab = 16, dbQDelete = 32, dbQUpdate = 48, dbQAppend = 64, dbQMakeTable = 80, dbQDDL = 96, dbQSQLPassThrough = 112, dbQSetOperation = 128, dbQSPTBulk = 144, dbQCompound = 160, dbQProcedure = 224, dbQAction = 240 } public enum RecordsetOption { dbDenyWrite = 1, dbDenyRead = 2, dbReadOnly = 4, dbAppendOnly = 8, dbInconsistent = 16, dbConsistent = 32, dbSQLPassThrough = 64, dbFailOnError = 128, dbForwardOnly = 256, dbSeeChanges = 512, dbRunAsync = 1024, dbExecDirect = 2048 } public enum RecordsetType { dbOpenTable = 1, dbOpenDynaset = 2, dbOpenSnapshot = 4, dbOpenForwardOnly = 8, dbOpenDynamic = 16 } public enum RecordStatus { dbRecordUnmodified = 0, dbRecordModified = 1, dbRecordNew = 2, dbRecordDeleted = 3, dbRecordDBDeleted = 4 } public enum RelationAttribute { dbRelationUnique = 1, dbRelationDontEnforce = 2, dbRelationInherited = 4, dbRelationUpdateCascade = 256, dbRelationDeleteCascade = 4096, dbRelationLeft = 16777216, dbRelationRight = 33554432 } public enum ReplicaType { dbRepMakePartial = 1, dbRepMakeReadOnly = 2 } public enum SetOption { dbPageTimeout = 6, dbMaxBufferSize = 8, dbLockRetry = 57, dbUserCommitSync = 58, dbImplicitCommitSync = 59, dbExclusiveAsyncDelay = 60, dbSharedAsyncDelay = 61, dbMaxLocksPerFile = 62, dbLockDelay = 63, dbRecycleLVs = 65, dbFlushTransactionTimeout = 66 } public enum SynchronizeType { dbRepExportChanges = 1, dbRepImportChanges = 2, dbRepImpExpChanges = 4, dbRepSyncInternet = 16 } public enum TableDefAttribute { dbSystemObject = -2147483646, dbHiddenObject = 1, dbAttachExclusive = 65536, dbAttachSavePWD = 131072, dbAttachedODBC = 536870912, dbAttachedTable = 1073741824, } public enum UpdateCriteria { dbCriteriaKey = 1, dbCriteriaModValues = 2, dbCriteriaAllCols = 4, dbCriteriaTimestamp = 8, dbCriteriaDeleteInsert = 16, dbCriteriaUpdate = 32 } public enum UpdateType { dbUpdateRegular = 1, dbUpdateCurrentRecord = 2, dbUpdateBatch = 4 } public enum WorkspaceType { dbUseODBC = 1, dbUseJet = 2 } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Web; using System.Xml.Linq; using System.Xml.XPath; using Examine; using Examine.LuceneEngine; using Examine.LuceneEngine.Providers; using Lucene.Net.Analysis.Standard; using Lucene.Net.Store; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.UmbracoExamine; using Umbraco.Web; using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.XmlPublishedCache; using UmbracoExamine; using UmbracoExamine.DataServices; using umbraco.BusinessLogic; using System.Linq; namespace Umbraco.Tests.PublishedContent { /// <summary> /// Tests the typed extension methods on IPublishedContent using the DefaultPublishedMediaStore /// </summary> [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class PublishedMediaTests : PublishedContentTestBase { public override void Initialize() { base.Initialize(); UmbracoExamineSearcher.DisableInitializationCheck = true; BaseUmbracoIndexer.DisableInitializationCheck = true; } public override void TearDown() { base.TearDown(); UmbracoExamineSearcher.DisableInitializationCheck = null; BaseUmbracoIndexer.DisableInitializationCheck = null; } /// <summary> /// Shared with PublishMediaStoreTests /// </summary> /// <param name="id"></param> /// <param name="umbracoContext"></param> /// <returns></returns> internal static IPublishedContent GetNode(int id, UmbracoContext umbracoContext) { var ctx = umbracoContext; var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application), ctx); var doc = cache.GetById(id); Assert.IsNotNull(doc); return doc; } private IPublishedContent GetNode(int id) { return GetNode(id, GetUmbracoContext("/test", 1234)); } [Test] public void Get_Property_Value_Uses_Converter() { var mType = MockedContentTypes.CreateImageMediaType("image2"); //lets add an RTE to this mType.PropertyGroups.First().PropertyTypes.Add( new PropertyType("test", DataTypeDatabaseType.Nvarchar, "content") { Name = "Rich Text", DataTypeDefinitionId = -87 //tiny mce }); ServiceContext.ContentTypeService.Save(mType); var media = MockedMedia.CreateMediaImage(mType, -1); media.Properties["content"].Value = "<div>This is some content</div>"; ServiceContext.MediaService.Save(media); var publishedMedia = GetNode(media.Id); var propVal = publishedMedia.GetPropertyValue("content"); Assert.IsInstanceOf<IHtmlString>(propVal); Assert.AreEqual("<div>This is some content</div>", propVal.ToString()); var propVal2 = publishedMedia.GetPropertyValue<IHtmlString>("content"); Assert.IsInstanceOf<IHtmlString>(propVal2); Assert.AreEqual("<div>This is some content</div>", propVal2.ToString()); var propVal3 = publishedMedia.GetPropertyValue("Content"); Assert.IsInstanceOf<IHtmlString>(propVal3); Assert.AreEqual("<div>This is some content</div>", propVal3.ToString()); } [Test] public void Ensure_Children_Sorted_With_Examine() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var ctx = GetUmbracoContext("/test", 1234); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); var rootChildren = publishedMedia.Children().ToArray(); var currSort = 0; for (var i = 0; i < rootChildren.Count(); i++) { Assert.GreaterOrEqual(rootChildren[i].SortOrder, currSort); currSort = rootChildren[i].SortOrder; } } } [Test] public void Do_Not_Find_In_Recycle_Bin() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var ctx = GetUmbracoContext("/test", 1234); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //ensure it is found var publishedMedia = cache.GetById(3113); Assert.IsNotNull(publishedMedia); //move item to recycle bin var newXml = XElement.Parse(@"<node id='3113' version='5b3e46ab-3e37-4cfa-ab70-014234b5bd33' parentID='-21' level='1' writerID='0' nodeType='1032' template='0' sortOrder='2' createDate='2010-05-19T17:32:46' updateDate='2010-05-19T17:32:46' nodeName='Another Umbraco Image' urlName='acnestressscrub' writerName='Administrator' nodeTypeAlias='Image' path='-1,-21,3113'> <data alias='umbracoFile'><![CDATA[/media/1234/blah.pdf]]></data> <data alias='umbracoWidth'>115</data> <data alias='umbracoHeight'>268</data> <data alias='umbracoBytes'>10726</data> <data alias='umbracoExtension'>jpg</data> </node>"); indexer.ReIndexNode(newXml, "media"); //ensure it still exists in the index (raw examine search) var criteria = searcher.CreateSearchCriteria(); var filter = criteria.Id(3113); var found = searcher.Search(filter.Compile()); Assert.IsNotNull(found); Assert.AreEqual(1, found.TotalItemCount); //ensure it does not show up in the published media store var recycledMedia = cache.GetById(3113); Assert.IsNull(recycledMedia); } } [Test] public void Children_With_Examine() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var ctx = GetUmbracoContext("/test", 1234); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); var rootChildren = publishedMedia.Children(); Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { 2222, 1113, 1114, 1115, 1116 })); var publishedChild1 = cache.GetById(2222); var subChildren = publishedChild1.Children(); Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { 2112 })); } } [Test] public void Descendants_With_Examine() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var ctx = GetUmbracoContext("/test", 1234); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); var rootDescendants = publishedMedia.Descendants(); Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1113, 1114, 1115, 1116 })); var publishedChild1 = cache.GetById(2222); var subDescendants = publishedChild1.Descendants(); Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2112, 3113 })); } } [Test] public void DescendantsOrSelf_With_Examine() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var ctx = GetUmbracoContext("/test", 1234); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(1111); var rootDescendants = publishedMedia.DescendantsOrSelf(); Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { 1111, 2112, 2222, 1113, 1114, 1115, 1116 })); var publishedChild1 = cache.GetById(2222); var subDescendants = publishedChild1.DescendantsOrSelf(); Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { 2222, 2112, 3113 })); } } [Test] public void Ancestors_With_Examine() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var ctx = GetUmbracoContext("/test", 1234); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); var ancestors = publishedMedia.Ancestors(); Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 2112, 2222, 1111 })); } } [Test] public void AncestorsOrSelf_With_Examine() { using (var luceneDir = new RAMDirectory()) { var indexer = IndexInitializer.GetUmbracoIndexer(luceneDir); indexer.RebuildIndex(); var ctx = GetUmbracoContext("/test", 1234); var searcher = IndexInitializer.GetUmbracoSearcher(luceneDir); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application, searcher, indexer), ctx); //we are using the media.xml media to test the examine results implementation, see the media.xml file in the ExamineHelpers namespace var publishedMedia = cache.GetById(3113); var ancestors = publishedMedia.AncestorsOrSelf(); Assert.IsTrue(ancestors.Select(x => x.Id).ContainsAll(new[] { 3113, 2112, 2222, 1111 })); } } [Test] public void Children_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); var publishedMedia = GetNode(mRoot.Id); var rootChildren = publishedMedia.Children(); Assert.IsTrue(rootChildren.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id })); var publishedChild1 = GetNode(mChild1.Id); var subChildren = publishedChild1.Children(); Assert.IsTrue(subChildren.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); } [Test] public void Descendants_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); var publishedMedia = GetNode(mRoot.Id); var rootDescendants = publishedMedia.Descendants(); Assert.IsTrue(rootDescendants.Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); var publishedChild1 = GetNode(mChild1.Id); var subDescendants = publishedChild1.Descendants(); Assert.IsTrue(subDescendants.Select(x => x.Id).ContainsAll(new[] { mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); } [Test] public void DescendantsOrSelf_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); var publishedMedia = GetNode(mRoot.Id); var rootDescendantsOrSelf = publishedMedia.DescendantsOrSelf(); Assert.IsTrue(rootDescendantsOrSelf.Select(x => x.Id).ContainsAll( new[] { mRoot.Id, mChild1.Id, mChild2.Id, mChild3.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); var publishedChild1 = GetNode(mChild1.Id); var subDescendantsOrSelf = publishedChild1.DescendantsOrSelf(); Assert.IsTrue(subDescendantsOrSelf.Select(x => x.Id).ContainsAll( new[] { mChild1.Id, mSubChild1.Id, mSubChild2.Id, mSubChild3.Id })); } [Test] public void Parent_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); var publishedRoot = GetNode(mRoot.Id); Assert.AreEqual(null, publishedRoot.Parent); var publishedChild1 = GetNode(mChild1.Id); Assert.AreEqual(mRoot.Id, publishedChild1.Parent.Id); var publishedSubChild1 = GetNode(mSubChild1.Id); Assert.AreEqual(mChild1.Id, publishedSubChild1.Parent.Id); } [Test] public void Ancestors_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); var publishedSubChild1 = GetNode(mSubChild1.Id); Assert.IsTrue(publishedSubChild1.Ancestors().Select(x => x.Id).ContainsAll(new[] { mChild1.Id, mRoot.Id })); } [Test] public void AncestorsOrSelf_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot.Id); var mChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child3", mType, user, mRoot.Id); var mSubChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild1", mType, user, mChild1.Id); var mSubChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild2", mType, user, mChild1.Id); var mSubChild3 = global::umbraco.cms.businesslogic.media.Media.MakeNew("SubChild3", mType, user, mChild1.Id); var publishedSubChild1 = GetNode(mSubChild1.Id); Assert.IsTrue(publishedSubChild1.AncestorsOrSelf().Select(x => x.Id).ContainsAll( new[] { mSubChild1.Id, mChild1.Id, mRoot.Id })); } [Test] public void Convert_From_Legacy_Xml() { var config = SettingsForTests.GenerateMockSettings(); var contentMock = Mock.Get(config.Content); contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(true); SettingsForTests.ConfigureSettings(config); var nodeId = 2112; var xml = XElement.Parse(@"<node id=""2112"" version=""5b3e46ab-3e37-4cfa-ab70-014234b5bd39"" parentID=""2222"" level=""3"" writerID=""0"" nodeType=""1032"" template=""0"" sortOrder=""1"" createDate=""2010-05-19T17:32:46"" updateDate=""2010-05-19T17:32:46"" nodeName=""Sam's Umbraco Image"" urlName=""acnestressscrub"" writerName=""Administrator"" nodeTypeAlias=""Image"" path=""-1,1111,2222,2112""> <data alias=""umbracoFile""><![CDATA[/media/1234/blah.pdf]]></data> <data alias=""umbracoWidth"">115</data> <data alias=""umbracoHeight"">268</data> <data alias=""umbracoBytes"">10726</data> <data alias=""umbracoExtension"">jpg</data> <node id=""3113"" version=""5b3e46ab-3e37-4cfa-ab70-014234b5bd33"" parentID=""2112"" level=""4"" writerID=""0"" nodeType=""1032"" template=""0"" sortOrder=""2"" createDate=""2010-05-19T17:32:46"" updateDate=""2010-05-19T17:32:46"" nodeName=""Another Umbraco Image"" urlName=""acnestressscrub"" writerName=""Administrator"" nodeTypeAlias=""Image"" path=""-1,1111,2222,2112,3113""> <data alias=""umbracoFile""><![CDATA[/media/1234/blah.pdf]]></data> <data alias=""umbracoWidth"">115</data> <data alias=""umbracoHeight"">268</data> <data alias=""umbracoBytes"">10726</data> <data alias=""umbracoExtension"">jpg</data> </node> </node>"); var node = xml.DescendantsAndSelf("node").Single(x => (int) x.Attribute("id") == nodeId); var publishedMedia = new PublishedMediaCache(ApplicationContext); var nav = node.CreateNavigator(); var converted = publishedMedia.CreateFromCacheValues( publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/node"), nodeId)); Assert.AreEqual(nodeId, converted.Id); Assert.AreEqual(3, converted.Level); Assert.AreEqual(1, converted.SortOrder); Assert.AreEqual("Sam's Umbraco Image", converted.Name); Assert.AreEqual("-1,1111,2222,2112", converted.Path); } [Test] public void Convert_From_Standard_Xml() { var config = SettingsForTests.GenerateMockSettings(); var contentMock = Mock.Get(config.Content); contentMock.Setup(x => x.UseLegacyXmlSchema).Returns(true); SettingsForTests.ConfigureSettings(config); var nodeId = 2112; var xml = XElement.Parse(@"<Image id=""2112"" version=""5b3e46ab-3e37-4cfa-ab70-014234b5bd39"" parentID=""2222"" level=""3"" writerID=""0"" nodeType=""1032"" template=""0"" sortOrder=""1"" createDate=""2010-05-19T17:32:46"" updateDate=""2010-05-19T17:32:46"" nodeName=""Sam's Umbraco Image"" urlName=""acnestressscrub"" writerName=""Administrator"" nodeTypeAlias=""Image"" path=""-1,1111,2222,2112"" isDoc=""""> <umbracoFile><![CDATA[/media/1234/blah.pdf]]></umbracoFile> <umbracoWidth>115</umbracoWidth> <umbracoHeight>268</umbracoHeight> <umbracoBytes>10726</umbracoBytes> <umbracoExtension>jpg</umbracoExtension> <Image id=""3113"" version=""5b3e46ab-3e37-4cfa-ab70-014234b5bd33"" parentID=""2112"" level=""4"" writerID=""0"" nodeType=""1032"" template=""0"" sortOrder=""2"" createDate=""2010-05-19T17:32:46"" updateDate=""2010-05-19T17:32:46"" nodeName=""Another Umbraco Image"" urlName=""acnestressscrub"" writerName=""Administrator"" nodeTypeAlias=""Image"" path=""-1,1111,2222,2112,3113"" isDoc=""""> <umbracoFile><![CDATA[/media/1234/blah.pdf]]></umbracoFile> <umbracoWidth>115</umbracoWidth> <umbracoHeight>268</umbracoHeight> <umbracoBytes>10726</umbracoBytes> <umbracoExtension>jpg</umbracoExtension> </Image> </Image>"); var node = xml.DescendantsAndSelf("Image").Single(x => (int)x.Attribute("id") == nodeId); var publishedMedia = new PublishedMediaCache(ApplicationContext); var nav = node.CreateNavigator(); var converted = publishedMedia.CreateFromCacheValues( publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/Image"), nodeId)); Assert.AreEqual(nodeId, converted.Id); Assert.AreEqual(3, converted.Level); Assert.AreEqual(1, converted.SortOrder); Assert.AreEqual("Sam's Umbraco Image", converted.Name); Assert.AreEqual("-1,1111,2222,2112", converted.Path); } [Test] public void Detects_Error_In_Xml() { var errorXml = new XElement("error", string.Format("No media is maching '{0}'", 1234)); var nav = errorXml.CreateNavigator(); var publishedMedia = new PublishedMediaCache(ApplicationContext); var converted = publishedMedia.ConvertFromXPathNodeIterator(nav.Select("/"), 1234); Assert.IsNull(converted); } } }
//WordSlide //Copyright (C) 2008-2012 Jonathan Ray <asky314159@gmail.com> //WordSlide is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. //A copy of the GNU General Public License should be in the //Installer directory of this source tree. If not, see //<http://www.gnu.org/licenses/>. namespace WordSlide { partial class SetupForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.allSlides = new System.Windows.Forms.ListBox(); this.selectedSlides = new System.Windows.Forms.ListBox(); this.addSlides = new System.Windows.Forms.Button(); this.removeSlides = new System.Windows.Forms.Button(); this.reorderUp = new System.Windows.Forms.Button(); this.reorderDown = new System.Windows.Forms.Button(); this.acceptButton = new System.Windows.Forms.Button(); this.closeButton = new System.Windows.Forms.Button(); this.addblankButton = new System.Windows.Forms.Button(); this.clearButton = new System.Windows.Forms.Button(); this.searchBox = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // allSlides // this.allSlides.FormattingEnabled = true; this.allSlides.Location = new System.Drawing.Point(12, 38); this.allSlides.Name = "allSlides"; this.allSlides.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.allSlides.Size = new System.Drawing.Size(184, 134); this.allSlides.TabIndex = 11; this.allSlides.KeyDown += new System.Windows.Forms.KeyEventHandler(this.allSlides_KeyDown); this.allSlides.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.allSlides_DoubleClick); this.allSlides.MouseDown += new System.Windows.Forms.MouseEventHandler(this.allSlides_MouseDown); // // selectedSlides // this.selectedSlides.AllowDrop = true; this.selectedSlides.FormattingEnabled = true; this.selectedSlides.Location = new System.Drawing.Point(268, 12); this.selectedSlides.Name = "selectedSlides"; this.selectedSlides.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended; this.selectedSlides.Size = new System.Drawing.Size(184, 160); this.selectedSlides.TabIndex = 1; this.selectedSlides.DragDrop += new System.Windows.Forms.DragEventHandler(this.selectedSlides_DragDrop); this.selectedSlides.DragEnter += new System.Windows.Forms.DragEventHandler(this.selectedSlides_DragEnter); this.selectedSlides.MouseDown += new System.Windows.Forms.MouseEventHandler(this.selectedSlides_MouseDown); // // addSlides // this.addSlides.Location = new System.Drawing.Point(212, 12); this.addSlides.Name = "addSlides"; this.addSlides.Size = new System.Drawing.Size(38, 23); this.addSlides.TabIndex = 2; this.addSlides.Text = "->"; this.addSlides.UseVisualStyleBackColor = true; this.addSlides.Click += new System.EventHandler(this.addSlides_Click); // // removeSlides // this.removeSlides.Location = new System.Drawing.Point(212, 41); this.removeSlides.Name = "removeSlides"; this.removeSlides.Size = new System.Drawing.Size(38, 23); this.removeSlides.TabIndex = 3; this.removeSlides.Text = "<-"; this.removeSlides.UseVisualStyleBackColor = true; this.removeSlides.Click += new System.EventHandler(this.removeSlides_Click); // // reorderUp // this.reorderUp.Location = new System.Drawing.Point(458, 41); this.reorderUp.Name = "reorderUp"; this.reorderUp.Size = new System.Drawing.Size(42, 23); this.reorderUp.TabIndex = 4; this.reorderUp.Text = "/\\"; this.reorderUp.UseVisualStyleBackColor = true; this.reorderUp.Click += new System.EventHandler(this.reorderUp_Click); // // reorderDown // this.reorderDown.Location = new System.Drawing.Point(458, 70); this.reorderDown.Name = "reorderDown"; this.reorderDown.Size = new System.Drawing.Size(42, 23); this.reorderDown.TabIndex = 5; this.reorderDown.Text = "\\/"; this.reorderDown.UseVisualStyleBackColor = true; this.reorderDown.Click += new System.EventHandler(this.reorderDown_Click); // // acceptButton // this.acceptButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.acceptButton.Location = new System.Drawing.Point(295, 178); this.acceptButton.Name = "acceptButton"; this.acceptButton.Size = new System.Drawing.Size(75, 23); this.acceptButton.TabIndex = 6; this.acceptButton.Text = "OK"; this.acceptButton.UseVisualStyleBackColor = true; this.acceptButton.Click += new System.EventHandler(this.acceptButton_Click); // // closeButton // this.closeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.closeButton.Location = new System.Drawing.Point(377, 178); this.closeButton.Name = "closeButton"; this.closeButton.Size = new System.Drawing.Size(75, 23); this.closeButton.TabIndex = 7; this.closeButton.Text = "Close"; this.closeButton.UseVisualStyleBackColor = true; this.closeButton.Click += new System.EventHandler(this.closeButton_Click); // // addblankButton // this.addblankButton.Location = new System.Drawing.Point(183, 178); this.addblankButton.Name = "addblankButton"; this.addblankButton.Size = new System.Drawing.Size(106, 23); this.addblankButton.TabIndex = 8; this.addblankButton.Text = "Add Blank Slide"; this.addblankButton.UseVisualStyleBackColor = true; this.addblankButton.Click += new System.EventHandler(this.addblankButton_Click); // // clearButton // this.clearButton.Location = new System.Drawing.Point(458, 138); this.clearButton.Name = "clearButton"; this.clearButton.Size = new System.Drawing.Size(42, 34); this.clearButton.TabIndex = 10; this.clearButton.Text = "Clear"; this.clearButton.UseVisualStyleBackColor = true; this.clearButton.Click += new System.EventHandler(this.clearButton_Click); // // searchBox // this.searchBox.Location = new System.Drawing.Point(12, 12); this.searchBox.Name = "searchBox"; this.searchBox.Size = new System.Drawing.Size(184, 20); this.searchBox.TabIndex = 0; this.searchBox.TextChanged += new System.EventHandler(this.searchBox_TextChanged); this.searchBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.searchBox_KeyDown); // // SetupForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(507, 211); this.Controls.Add(this.searchBox); this.Controls.Add(this.clearButton); this.Controls.Add(this.addblankButton); this.Controls.Add(this.closeButton); this.Controls.Add(this.acceptButton); this.Controls.Add(this.reorderDown); this.Controls.Add(this.reorderUp); this.Controls.Add(this.removeSlides); this.Controls.Add(this.addSlides); this.Controls.Add(this.selectedSlides); this.Controls.Add(this.allSlides); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SetupForm"; this.Text = "Set Up Slides"; this.Load += new System.EventHandler(this.SetupForm_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListBox allSlides; private System.Windows.Forms.ListBox selectedSlides; private System.Windows.Forms.Button addSlides; private System.Windows.Forms.Button removeSlides; private System.Windows.Forms.Button reorderUp; private System.Windows.Forms.Button reorderDown; private System.Windows.Forms.Button acceptButton; private System.Windows.Forms.Button closeButton; private System.Windows.Forms.Button addblankButton; private System.Windows.Forms.Button clearButton; private System.Windows.Forms.TextBox searchBox; } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for LinksOperations. /// </summary> public static partial class LinksOperationsExtensions { /// <summary> /// Creates a link or updates an existing link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate Link operation. /// </param> public static LinkResourceFormat CreateOrUpdate(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName, LinkResourceFormat parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, hubName, linkName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a link or updates an existing link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate Link operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LinkResourceFormat> CreateOrUpdateAsync(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName, LinkResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, linkName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> public static LinkResourceFormat Get(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName) { return operations.GetAsync(resourceGroupName, hubName, linkName).GetAwaiter().GetResult(); } /// <summary> /// Gets a link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LinkResourceFormat> GetAsync(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, hubName, linkName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> public static void Delete(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName) { operations.DeleteAsync(resourceGroupName, hubName, linkName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, hubName, linkName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the links in the specified hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> public static IPage<LinkResourceFormat> ListByHub(this ILinksOperations operations, string resourceGroupName, string hubName) { return operations.ListByHubAsync(resourceGroupName, hubName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the links in the specified hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<LinkResourceFormat>> ListByHubAsync(this ILinksOperations operations, string resourceGroupName, string hubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByHubWithHttpMessagesAsync(resourceGroupName, hubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a link or updates an existing link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate Link operation. /// </param> public static LinkResourceFormat BeginCreateOrUpdate(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName, LinkResourceFormat parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, hubName, linkName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a link or updates an existing link in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='linkName'> /// The name of the link. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate Link operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LinkResourceFormat> BeginCreateOrUpdateAsync(this ILinksOperations operations, string resourceGroupName, string hubName, string linkName, LinkResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, linkName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the links in the specified hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<LinkResourceFormat> ListByHubNext(this ILinksOperations operations, string nextPageLink) { return operations.ListByHubNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the links in the specified hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<LinkResourceFormat>> ListByHubNextAsync(this ILinksOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByHubNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Data; using System.Windows.Forms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// /// </summary> public class CooccurrenceChartTable : DataTable { private CooccurrenceChartSearch m_Search; private DataColumn m_DataColumn; private DataRow m_DataRow; private DataSet m_DataSet; private string m_Key; private string m_ID; public CooccurrenceChartTable(CooccurrenceChartSearch search) { m_Search = search; // Key column m_Key = "Key"; m_DataColumn = new DataColumn(); m_DataColumn.DataType = System.Type.GetType("System.String"); m_DataColumn.ColumnName = m_Key; m_DataColumn.Caption = m_Key; m_DataColumn.AutoIncrement = false; m_DataColumn.ReadOnly = false; m_DataColumn.Unique = true; this.Columns.Add(m_DataColumn); // ID column m_ID = "ID"; m_DataColumn = new DataColumn(); m_DataColumn.DataType = System.Type.GetType("System.String"); m_DataColumn.ColumnName = m_ID; m_DataColumn.Caption = m_ID; m_DataColumn.AutoIncrement = false; m_DataColumn.ReadOnly = false; m_DataColumn.Unique = false; this.Columns.Add(m_DataColumn); // Columns if (search.IsConsonantCol()) { Consonant cns = null; for (int i = 0; i < search.GI.ConsonantCount(); i++) { cns = search.GI.GetConsonant(i); if (cns.MatchesFeatures(search.CFeatures2)) this.AddColumn(cns.Symbol); } } if (search.IsVowelCol()) { Vowel vwl = null; for (int i = 0; i < search.GI.VowelCount(); i++) { vwl = search.GI.GetVowel(i); if (vwl.MatchesFeatures(search.VFeatures2)) this.AddColumn(vwl.Symbol); } } if (search.IsSyllographCol()) { Syllograph syllograph = null; for (int i = 0; i < search.GI.SyllographCount(); i++) { syllograph = search.GI.GetSyllograph(i); if (syllograph.MatchesFeatures(search.SFeatures2)) this.AddColumn(syllograph.Symbol); } } //Rows if (search.IsConsonantRow()) { Consonant cns = null; for (int i = 0; i < search.GI.ConsonantCount(); i++) { cns = search.GI.GetConsonant(i); if (cns.MatchesFeatures(search.CFeatures1)) { m_DataRow = this.NewRow(); m_DataRow[m_Key] = cns.GetKey(); m_DataRow[m_ID] = cns.Symbol; try { this.Rows.Add(m_DataRow); } catch (System.Exception ex) { string msg = cns.Symbol + " row not processed due to exception: " + ex.GetType().ToString(); MessageBox.Show(msg); } } } } if (search.IsVowelRow()) { Vowel vwl = null; for (int i = 0; i < search.GI.VowelCount(); i++) { vwl = search.GI.GetVowel(i); if (vwl.MatchesFeatures(search.VFeatures1)) { m_DataRow = this.NewRow(); m_DataRow[m_Key] = vwl.GetKey(); m_DataRow[m_ID] = vwl.Symbol; try { this.Rows.Add(m_DataRow); } catch (System.Exception ex) { string msg = vwl.Symbol + " row not processed due to exception: " + ex.GetType().ToString(); MessageBox.Show(msg); } } } } if (search.IsSyllographRow()) { Syllograph syllograph = null; for (int i = 0; i < search.GI.SyllographCount(); i++) { syllograph = search.GI.GetSyllograph(i); if (syllograph.MatchesFeatures(search.SFeatures1)) { m_DataRow = this.NewRow(); m_DataRow[m_Key] = ToUnicodeScalarValue(syllograph.Symbol); m_DataRow[m_ID] = syllograph.Symbol; try { this.Rows.Add(m_DataRow); } catch (System.Exception ex) { string msg = syllograph.Symbol + " row not processed due to exception: " + ex.GetType().ToString(); MessageBox.Show(msg); } } } } // Make the ID column the primary key column. DataColumn[] dcPrimaryKey = new DataColumn[1]; dcPrimaryKey[0] = this.Columns[m_Key]; this.PrimaryKey = dcPrimaryKey; // Add the new DataTable to the DataSet. m_DataSet = new DataSet(); m_DataSet.Tables.Add(this); } public DataSet GetDataSet() { return m_DataSet; } public DataRow GetDataRow(int n) { if (n < this.Rows.Count) return this.Rows[n]; else return null; } public DataColumn GetDataColumn(int n) { if (n < this.Columns.Count) return this.Columns[n]; else return null; } //public string GetID() //{ // return m_ID; //} public int GetRowIndex(string strSym) { int num = -1; DataRow dr = null; string strKey = ""; for (int i = 0; i < this.Rows.Count; i++) { dr = this.GetDataRow(i); strKey = strSym; if (m_Search.IsSyllographRow()) strKey = ToUnicodeScalarValue(strSym); if ((string) dr[m_Key] == strKey) { num = i; break; } } return num; } public int GetColumnIndex(string strSym) { return this.Columns.IndexOf(strSym); } public string GetColumnHeaders() { string strHdrs = ""; string strTab = Constants.Tab; foreach (DataColumn dc in this.Columns) { if ( (dc.ColumnName != m_ID) && (dc.ColumnName != m_Key) ) { strHdrs += strTab + dc.Caption.ToString().PadLeft(5); } } strHdrs = Constants.kHCOn + strHdrs + Constants.kHCOff + Environment.NewLine; return strHdrs; } public string GetRows(string Caption) { string strRow = ""; WordList wl = null; int nSize = 0; int nCnt = 0; FormProgressBar pb = new FormProgressBar(Caption); pb.PB_Init(0, this.Rows.Count); foreach (DataRow dr in this.Rows) { nCnt++; pb.PB_Update(nCnt); nSize = dr.ItemArray.Length; strRow += Constants.kHCOn + dr[m_ID].ToString() + Constants.Tab + Constants.kHCOff; for (int i = 2; i < nSize; i++) { if (dr.ItemArray[i].ToString() != "") { wl = (WordList) dr.ItemArray[i]; strRow += wl.WordCount().ToString().PadLeft(5) + Constants.Tab; } else strRow += Constants.Space.ToString().PadLeft(5) + Constants.Tab; ; } strRow += Environment.NewLine; } pb.Close(); return strRow; } public WordList GetWordList(int row, int col) { WordList wl = null; DataRow dr = this.Rows[row]; if (dr.ItemArray[col].ToString() != "") wl = (WordList) dr.ItemArray[col]; return wl; } public void UpdateChartCell(int row, int col, Word wrd) { int num = 0; object obj = null; WordList wl = null; DataRow dr = null; num = this.Rows.Count; dr = this.Rows[row]; object[] ia = dr.ItemArray; if (ia.GetValue(col).ToString() != "") { obj = ia.GetValue(col); if (obj == null) wl = new WordList(); else wl = (WordList) obj; wl.AddWord(wrd); obj = (object) wl; } else { wl = new WordList(); wl.AddWord(wrd); obj = (object) wl; } ia.SetValue(obj, col); this.AcceptChanges(); this.BeginLoadData(); dr = this.LoadDataRow(ia, false); this.EndLoadData(); } private void AddColumn(string strName) { m_DataColumn = new DataColumn(); m_DataColumn.DataType = typeof(PrimerProObjects.WordList); m_DataColumn.ColumnName = strName; m_DataColumn.Caption = strName; m_DataColumn.AutoIncrement = false; m_DataColumn.ReadOnly = false; m_DataColumn.Unique = false; this.Columns.Add(m_DataColumn); } private string ToUnicodeScalarValue(string str) { string strUnicode = ""; int num = 0; foreach (char c in str) { num = (int)c; strUnicode = strUnicode + num.ToString(); } return strUnicode; } } }
namespace Newq.Tests { using Models; using Xunit; public class SelectStatementTests { [Fact] public void Select1() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Customer>((target, context) => { target.Add(context.Table<Provider>(t => t.Products)); }) .LeftJoin<Provider>((filter, context) => { filter.Add(context.Table<Customer>(t => t.Name).EqualTo(context.Table<Provider>(t => t.Name))); }) .Where((filter, context) => { filter.Add(context.Table<Customer>(t => t.City).Like("New")); }) .GroupBy((target, context) => { target.Add(context.Table<Provider>(t => t.Products)); }) .Having((filter, context) => { filter.Add(context.Table<Provider>(t => t.Name).NotLike("New")); }) .OrderBy((target, context) => { target.Add(context.Table<Customer>(t => t.Name, SortOrder.Desc)); }); queryBuilder.Paginate(new Paginator()); var result = queryBuilder.ToString(); var expected = "SELECT " + "[Provider.Products]" + ",[Customer.Name] " + "FROM (" + "SELECT " + "ROW_NUMBER() OVER(ORDER BY [Customer.Name] DESC) AS [$ROW_NUMBER]" + ",[Provider.Products]" + ",[Customer.Name] " + "FROM (" + "SELECT " + "[Provider].[Products] AS [Provider.Products]" + ",[Customer].[Name] AS [Customer.Name] " + "FROM " + "[Customer] " + "LEFT JOIN " + "[Provider] " + "ON " + "[Customer].[Name] = [Provider].[Name] " + "WHERE " + "[Customer].[City] LIKE '%New%' " + "GROUP BY " + "[Provider].[Products] " + "HAVING " + "[Provider].[Name] NOT LIKE '%New%'" + ") AS [$ORIGINAL_QUERY]" + ") AS [$PAGINATOR] " + "WHERE " + "[$PAGINATOR].[$ROW_NUMBER] BETWEEN 1 AND 10 "; Assert.Equal(expected, result); } [Fact] public void Select2() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Customer>((target, context) => { target += context.Table<Customer>(t => t.Name); target += context.Table<Provider>(t => t.Products); }) .LeftJoin<Provider>((filter, context) => { filter += context.Table<Customer>(t => t.Name) == context.Table<Provider>(t => t.Name); }) .Where((filter, context) => { filter += context.Table<Customer>(t => t.City).Like("New"); }) .GroupBy((target, context) => { target += context.Table<Provider>(t => t.Products); }) .Having((filter, context) => { filter += context.Table<Provider>(t => t.Name).NotLike("New"); }) .OrderBy((target, context) => { target += context.Table<Customer>(t => t.Name, SortOrder.Desc); target += context.Table<Customer>(t => t.Id, SortOrder.Desc); }); queryBuilder.Paginate(new Paginator()); var result = queryBuilder.ToString(); var expected = "SELECT " + "[Customer.Name]" + ",[Provider.Products]" + ",[Customer.Id] " + "FROM (" + "SELECT " + "ROW_NUMBER() OVER(ORDER BY [Customer.Name] DESC,[Customer.Id] DESC) AS [$ROW_NUMBER]" + ",[Customer.Name]" + ",[Provider.Products]" + ",[Customer.Id] " + "FROM (" + "SELECT " + "[Customer].[Name] AS [Customer.Name]" + ",[Provider].[Products] AS [Provider.Products]" + ",[Customer].[Id] AS [Customer.Id] " + "FROM " + "[Customer] " + "LEFT JOIN " + "[Provider] " + "ON " + "[Customer].[Name] = [Provider].[Name] " + "WHERE " + "[Customer].[City] LIKE '%New%' " + "GROUP BY " + "[Provider].[Products] " + "HAVING " + "[Provider].[Name] NOT LIKE '%New%'" + ") AS [$ORIGINAL_QUERY]" + ") AS [$PAGINATOR] " + "WHERE " + "[$PAGINATOR].[$ROW_NUMBER] BETWEEN 1 AND 10 "; Assert.Equal(expected, result); } [Fact] public void Select3() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Customer>((target, context) => { target += context.Table<Provider>(t => t.Products); }) .LeftJoin<Provider>((filter, context) => { filter += context.Table<Customer>(t => t.Name) == context.Table<Provider>(t => t.Name); }) .Where((filter, context) => { filter += context.Table<Customer>(t => t.City).Like("New"); }) .GroupBy((target, context) => { target += context.Table<Provider>(t => t.Products); }) .Having((filter, context) => { filter += context.Table<Provider>(t => t.Name).NotLike("New"); }) .OrderBy((target, context) => { target += context.Table<Customer>(t => t.Name, SortOrder.Desc); target += context.Table<Customer>(t => t.Id, SortOrder.Desc); }); var result = queryBuilder.ToString(); var expected = "SELECT " + "[Provider].[Products] AS [Provider.Products] " + "FROM " + "[Customer] " + "LEFT JOIN " + "[Provider] " + "ON " + "[Customer].[Name] = [Provider].[Name] " + "WHERE " + "[Customer].[City] LIKE '%New%' " + "GROUP BY " + "[Provider].[Products] " + "HAVING " + "[Provider].[Name] NOT LIKE '%New%' " + "ORDER BY " + "[Customer].[Name] DESC" + ",[Customer].[Id] DESC "; Assert.Equal(expected, result); } [Fact] public void Select4() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Customer>() .LeftJoin<Provider>((filter, context) => { filter += context.Table<Customer>(t => t.Name) == context.Table<Provider>(t => t.Name); }) .Where((filter, context) => { filter += context.Table<Customer>(t => t.City).Like("New"); }) .OrderBy((target, context) => { target += context.Table<Customer>(t => t.Name, SortOrder.Desc); target += context.Table<Customer>(t => t.Id, SortOrder.Desc); }); var result = queryBuilder.ToString(); var expected = "SELECT " + "[Customer].[Id] AS [Customer.Id]" + ",[Customer].[Name] AS [Customer.Name]" + ",[Customer].[City] AS [Customer.City]" + ",[Customer].[Remark] AS [Customer.Remark]" + ",[Customer].[Status] AS [Customer.Status]" + ",[Customer].[Flag] AS [Customer.Flag]" + ",[Customer].[Version] AS [Customer.Version]" + ",[Customer].[AuthorId] AS [Customer.AuthorId]" + ",[Customer].[EditorId] AS [Customer.EditorId]" + ",[Customer].[CreatedDate] AS [Customer.CreatedDate]" + ",[Customer].[ModifiedDate] AS [Customer.ModifiedDate] " + "FROM " + "[Customer] " + "LEFT JOIN " + "[Provider] " + "ON " + "[Customer].[Name] = [Provider].[Name] " + "WHERE " + "[Customer].[City] LIKE '%New%' " + "ORDER BY " + "[Customer].[Name] DESC" + ",[Customer].[Id] DESC "; Assert.Equal(expected, result); } [Fact] public void Select5() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Person>(); var result = queryBuilder.ToString(); var expected = "SELECT " + "[PERSION].[ID] AS [PERSION.ID]" + ",[PERSION].[Name] AS [PERSION.Name] " + "FROM " + "[PERSION] "; Assert.Equal(expected, result); } [Fact] public void Select6() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Man>(); var result = queryBuilder.ToString(); var expected = "SELECT " + "[PERSION].[ID] AS [PERSION.ID]" + ",[PERSION].[Name] AS [PERSION.Name] " + "FROM " + "[PERSION] "; Assert.Equal(expected, result); } [Fact] public void Select7() { var queryBuilder = new QueryBuilder(); queryBuilder .Select<Woman>(); var result = queryBuilder.ToString(); var expected = "SELECT " + "[Woman].[ID] AS [Woman.ID]" + ",[Woman].[Name] AS [Woman.Name] " + "FROM " + "[Woman] "; Assert.Equal(expected, result); } } }
using System; using System.Globalization; public class DateTimeParseExact2 { private const int c_MIN_STRING_LEN = 1; private const int c_MAX_STRING_LEN = 2048; private const int c_NUM_LOOPS = 100; private static DateTimeStyles[] c_STYLES = new DateTimeStyles[7] {DateTimeStyles.AdjustToUniversal, DateTimeStyles.AllowInnerWhite, DateTimeStyles.AllowLeadingWhite, DateTimeStyles.AllowTrailingWhite , DateTimeStyles.AllowWhiteSpaces, DateTimeStyles.NoCurrentDateDefault, DateTimeStyles.None }; public static int Main() { DateTimeParseExact2 test = new DateTimeParseExact2(); TestLibrary.TestFramework.BeginTestCase("DateTimeParseExact2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; MyFormater formater = new MyFormater(); string dateBefore = ""; DateTime dateAfter; TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.ParseExact(DateTime.Now)"); try { for(int i=0; i<c_STYLES.Length; i++) { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.ParseExact( dateBefore, new string[] {"G"}, formater, c_STYLES[i] ); if (!TestLibrary.Utilities.IsWindows && (c_STYLES[i]==DateTimeStyles.AdjustToUniversal)) // Mac prints offset { dateAfter = dateAfter.ToLocalTime(); } if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("001", "DateTime.ParseExact(" + dateBefore + ", G, " + c_STYLES[i] + ") did not equal " + dateAfter.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.ParseExact(DateTime.Now, g, formater, <invalid DateTimeStyles>)"); try { for(int i=-1024; i<1024; i++) { try { // skip the valid values if (0 == (i & (int)DateTimeStyles.AdjustToUniversal) && 0 == (i & (int)DateTimeStyles.AssumeUniversal) && 0 == (i & (int)DateTimeStyles.AllowInnerWhite) && 0 == (i & (int)DateTimeStyles.AllowLeadingWhite) && 0 == (i & (int)DateTimeStyles.AllowTrailingWhite) && 0 == (i & (int)DateTimeStyles.AllowWhiteSpaces) && 0 == (i & (int)DateTimeStyles.NoCurrentDateDefault) && i != (int)DateTimeStyles.None ) { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.ParseExact( dateBefore, new string[] {"G"}, formater, (DateTimeStyles)i); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("011", "DateTime.ParseExact(" + dateBefore + ", " + (DateTimeStyles)i + ") did not equal " + dateAfter.ToString()); retVal = false; } } } catch (System.ArgumentException) { // } } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest1() { bool retVal = true; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.ParseExact(null)"); try { try { for(int i=0; i<c_STYLES.Length; i++) { DateTime.ParseExact(null, new string[] {"d"}, formater, c_STYLES[i]); TestLibrary.TestFramework.LogError("029", "DateTime.ParseExact(null, d, " + c_STYLES[i] + ") should have thrown"); retVal = false; } } catch (ArgumentNullException) { // expected } } catch (Exception e) { TestLibrary.TestFramework.LogError("030", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; MyFormater formater = new MyFormater(); TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.ParseExact(String.Empty)"); try { try { for(int i=0; i<c_STYLES.Length; i++) { DateTime.ParseExact(String.Empty, new string[] {"d"}, formater, c_STYLES[i]); TestLibrary.TestFramework.LogError("029", "DateTime.ParseExact(String.Empty, d, " + c_STYLES[i] + ") should have thrown"); retVal = false; } } catch (ArgumentNullException) { // expected } } catch (FormatException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("032", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; MyFormater formater = new MyFormater(); string strDateTime = ""; DateTime dateAfter; string[] formats = new string[17] {"d", "D", "f", "F", "g", "G", "m", "M", "r", "R", "s", "t", "T", "u", "U", "y", "Y"}; string format; int formatIndex; TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.ParseExact(<garbage>)"); try { for (int i=0; i<c_NUM_LOOPS; i++) { for(int j=0; j<c_STYLES.Length; j++) { try { formatIndex = TestLibrary.Generator.GetInt32(-55) % 34; if (0 <= formatIndex && formatIndex < 17) { format = formats[formatIndex]; } else { format = TestLibrary.Generator.GetChar(-55) + ""; } strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); dateAfter = DateTime.ParseExact(strDateTime, new string[] {format}, formater, c_STYLES[j]); TestLibrary.TestFramework.LogError("033", "DateTime.ParseExact(" + strDateTime + ", "+ format + ", " + c_STYLES[j] + ") should have thrown (" + dateAfter + ")"); retVal = false; } catch (FormatException) { // expected } } } } catch (Exception e) { TestLibrary.TestFramework.LogError("034", "Failing date: " + strDateTime); TestLibrary.TestFramework.LogError("034", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; MyFormater formater = new MyFormater(); string dateBefore = ""; DateTime dateAfter; string[] formats = null; TestLibrary.TestFramework.BeginScenario("NegTest4: DateTime.ParseExact(DateTime.Now, null)"); try { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.ParseExact( dateBefore, formats, formater, DateTimeStyles.NoCurrentDateDefault ); TestLibrary.TestFramework.LogError("035", "DateTime.ParseExact(" + dateBefore + ", null, " + DateTimeStyles.NoCurrentDateDefault + ") should have thrown " + dateAfter.ToString()); retVal = false; } catch (System.ArgumentNullException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("036", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("036", "Unexpected exception: " + e); retVal = false; } return retVal; } } public class MyFormater : IFormatProvider { public object GetFormat(Type formatType) { if (typeof(IFormatProvider) == formatType) { return this; } else { return null; } } }
using System; using System.Threading; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; namespace MyDownloader.App.SingleInstancing { /// <summary> /// Represents the method which would be used to retrieve an ISingleInstanceEnforcer object when instantiating a SingleInstanceTracker object. /// If the method returns null, the SingleInstanceTracker's constructor will throw an exception. /// </summary> /// <returns>An ISingleInstanceEnforcer object which would receive messages.</returns> public delegate ISingleInstanceEnforcer SingleInstanceEnforcerRetriever(); /// <summary> /// Represents an object used to check for a previous instance of an application, and sending messages to it. /// </summary> public class SingleInstanceTracker : IDisposable { #region Member Variables private bool disposed; private Mutex singleInstanceMutex; private bool isFirstInstance; private IChannel ipcChannel; private SingleInstanceProxy proxy; #endregion #region Construction / Destruction /// <summary> /// Instantiates a new SingleInstanceTracker object. /// When using this constructor it is assumed that there is no need for sending messages to the first application instance. /// To enable the tracker's ability to send messages to the first instance, use the SingleInstanceTracker(string name, SingleInstanceEnforcerRetriever enforcerRetriever) constructor overload instead. /// </summary> /// <param name="name">The unique name used to identify the application.</param> /// <exception cref="System.ArgumentNullException">name is null or empty.</exception> /// <exception cref="SingleInstancing.SingleInstancingException">A general error occured while trying to instantiate the SingleInstanceInteractor. See InnerException for more details.</exception> public SingleInstanceTracker(string name) : this(name, null) { } /// <summary> /// Instantiates a new SingleInstanceTracker object. /// When using this constructor overload and enforcerRetriever is null, the SingleInstanceTracker object can only be used to determine whether the application is already running. /// </summary> /// <param name="name">The unique name used to identify the application.</param> /// <param name="enforcerRetriever">The method which would be used to retrieve an ISingleInstanceEnforcer object when instantiating the new object.</param> /// <exception cref="System.ArgumentNullException">name is null or empty.</exception> /// <exception cref="SingleInstancing.SingleInstancingException">A general error occured while trying to instantiate the SingleInstanceInteractor. See InnerException for more details.</exception> public SingleInstanceTracker(string name, SingleInstanceEnforcerRetriever enforcerRetriever) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name", "name cannot be null or empty."); try { singleInstanceMutex = new Mutex(true, name, out isFirstInstance); // Do not attempt to construct the IPC channel if there is no need for messages if (enforcerRetriever != null) { string proxyObjectName = "SingleInstanceProxy"; string proxyUri = "ipc://" + name + "/" + proxyObjectName; // If no previous instance was found, create a server channel which will provide the proxy to the first created instance if (isFirstInstance) { // Create an IPC server channel to listen for SingleInstanceProxy object requests ipcChannel = new IpcServerChannel(name); // Register the channel and get it ready for use ChannelServices.RegisterChannel(ipcChannel, false); // Register the service which gets the SingleInstanceProxy object, so it can be accessible by IPC client channels RemotingConfiguration.RegisterWellKnownServiceType(typeof(SingleInstanceProxy), proxyObjectName, WellKnownObjectMode.Singleton); // Attempt to retrieve the enforcer from the delegated method ISingleInstanceEnforcer enforcer = enforcerRetriever(); // Validate that an enforcer object was returned if (enforcer == null) throw new InvalidOperationException("The method delegated by the enforcerRetriever argument returned null. The method must return an ISingleInstanceEnforcer object."); // Create the first proxy object proxy = new SingleInstanceProxy(enforcer); // Publish the first proxy object so IPC clients requesting a proxy would receive a reference to it RemotingServices.Marshal(proxy, proxyObjectName); } else { // Create an IPC client channel to request the existing SingleInstanceProxy object. ipcChannel = new IpcClientChannel(); // Register the channel and get it ready for use ChannelServices.RegisterChannel(ipcChannel, false); // Retreive a reference to the proxy object which will be later used to send messages proxy = (SingleInstanceProxy)Activator.GetObject(typeof(SingleInstanceProxy), proxyUri); // Notify the first instance of the application that a new instance was created // proxy.Enforcer.OnNewInstanceCreated(new EventArgs()); } } } catch (Exception ex) { throw new SingleInstancingException("Failed to instantiate a new SingleInstanceTracker object. See InnerException for more details.", ex); } } /// <summary> /// Releases all unmanaged resources used by the object. /// </summary> ~SingleInstanceTracker() { Dispose(false); } #region IDisposable Members /// <summary> /// Releases all unmanaged resources used by the object, and potentially releases managed resources. /// </summary> /// <param name="disposing">true to dispose of managed resources; otherwise false.</param> protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (singleInstanceMutex != null) { singleInstanceMutex.Close(); singleInstanceMutex = null; } if (ipcChannel != null) { ChannelServices.UnregisterChannel(ipcChannel); ipcChannel = null; } } disposed = true; } } /// <summary> /// Releases all resources used by the object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #endregion #region Member Functions /// <summary> /// Sends a message to the first instance of the application. /// </summary> /// <param name="message">The message to send to the first instance of the application. The message must be serializable.</param> /// <exception cref="System.InvalidOperationException">The object was constructed with the SingleInstanceTracker(string name) constructor overload, or with the SingleInstanceTracker(string name, SingleInstanceEnforcerRetriever enforcerRetriever) cosntructor overload, with enforcerRetriever set to null.</exception> /// <exception cref="SingleInstancing.SingleInstancingException">The SingleInstanceInteractor has failed to send the message to the first application instance. The first instance might have terminated.</exception> public void SendMessageToFirstInstance(object message) { if (disposed) throw new ObjectDisposedException("The SingleInstanceTracker object has already been disposed."); if (ipcChannel == null) throw new InvalidOperationException("The object was constructed with the SingleInstanceTracker(string name) constructor overload, or with the SingleInstanceTracker(string name, SingleInstanceEnforcerRetriever enforcerRetriever) constructor overload, with enforcerRetriever set to null, thus you cannot send messages to the first instance."); try { proxy.Enforcer.OnMessageReceived(new MessageEventArgs(message)); } catch (Exception ex) { throw new SingleInstancingException("Failed to send message to the first instance of the application. The first instance might have terminated.", ex); } } #endregion #region Properties /// <summary> /// Gets a value indicating whether this instance of the application is the first instance. /// </summary> public bool IsFirstInstance { get { if (disposed) throw new ObjectDisposedException("The SingleInstanceTracker object has already been disposed."); return isFirstInstance; } } /// <summary> /// Gets the single instance enforcer (the first instance of the application) which would receive messages. /// </summary> public ISingleInstanceEnforcer Enforcer { get { if (disposed) throw new ObjectDisposedException("The SingleInstanceTracker object has already been disposed."); return proxy.Enforcer; } } #endregion } }
#region File Description //----------------------------------------------------------------------------- // GameplayScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Threading; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace MahjongXNA { /// <summary> /// This screen implements the actual game logic. It is just a /// placeholder to get the idea across: you'll probably want to /// put some more interesting gameplay in here! /// </summary> class GameplayScreen : GameScreen { #region Fields ContentManager content; SpriteFont gameFont; Vector2 playerPosition = new Vector2(100, 100); Vector2 enemyPosition = new Vector2(100, 100); Random random = new Random(); float pauseAlpha; #endregion #region Initialization /// <summary> /// Constructor. /// </summary> public GameplayScreen() { TransitionOnTime = TimeSpan.FromSeconds(1.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } /// <summary> /// Load graphics content for the game. /// </summary> public override void LoadContent() { if (content == null) content = new ContentManager(ScreenManager.Game.Services, "Content"); gameFont = content.Load<SpriteFont>("gamefont"); // A real game would probably have more content than this sample, so // it would take longer to load. We simulate that by delaying for a // while, giving you a chance to admire the beautiful loading screen. Thread.Sleep(1000); // once the load has finished, we use ResetElapsedTime to tell the game's // timing mechanism that we have just finished a very long frame, and that // it should not try to catch up. ScreenManager.Game.ResetElapsedTime(); } /// <summary> /// Unload graphics content used by the game. /// </summary> public override void UnloadContent() { content.Unload(); } #endregion #region Update and Draw /// <summary> /// Updates the state of the game. This method checks the GameScreen.IsActive /// property, so the game will stop updating when the pause menu is active, /// or if you tab away to a different application. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, false); // Gradually fade in or out depending on whether we are covered by the pause screen. if (coveredByOtherScreen) pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1); else pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0); if (IsActive) { // Apply some random jitter to make the enemy move around. const float randomization = 10; enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization; enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization; // Apply a stabilizing force to stop the enemy moving off the screen. Vector2 targetPosition = new Vector2( ScreenManager.GraphicsDevice.Viewport.Width / 2 - gameFont.MeasureString("Insert Gameplay Here").X / 2, 200); enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f); // TODO: this game isn't very fun! You could probably improve // it by inserting something more interesting in this space :-) } } /// <summary> /// Lets the game respond to player input. Unlike the Update method, /// this will only be called when the gameplay screen is active. /// </summary> public override void HandleInput(InputState input) { if (input == null) throw new ArgumentNullException("input"); // Look up inputs for the active player profile. int playerIndex = (int)ControllingPlayer.Value; KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex]; GamePadState gamePadState = input.CurrentGamePadStates[playerIndex]; // The game pauses either if the user presses the pause button, or if // they unplug the active gamepad. This requires us to keep track of // whether a gamepad was ever plugged in, because we don't want to pause // on PC if they are playing with a keyboard and have no gamepad at all! bool gamePadDisconnected = !gamePadState.IsConnected && input.GamePadWasConnected[playerIndex]; if (input.IsPauseGame(ControllingPlayer) || gamePadDisconnected) { ScreenManager.AddScreen(new PauseMenuScreen(), ControllingPlayer); } else { // Otherwise move the player position. Vector2 movement = Vector2.Zero; if (keyboardState.IsKeyDown(Keys.Left)) movement.X--; if (keyboardState.IsKeyDown(Keys.Right)) movement.X++; if (keyboardState.IsKeyDown(Keys.Up)) movement.Y--; if (keyboardState.IsKeyDown(Keys.Down)) movement.Y++; Vector2 thumbstick = gamePadState.ThumbSticks.Left; movement.X += thumbstick.X; movement.Y -= thumbstick.Y; if (movement.Length() > 1) movement.Normalize(); playerPosition += movement * 2; } } /// <summary> /// Draws the gameplay screen. /// </summary> public override void Draw(GameTime gameTime) { // This game has a blue background. Why? Because! ScreenManager.GraphicsDevice.Clear(ClearOptions.Target, Color.CornflowerBlue, 0, 0); // Our player and enemy are both actually just text strings. SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); spriteBatch.DrawString(gameFont, "// TODO", playerPosition, Color.Green); spriteBatch.DrawString(gameFont, "Insert Gameplay Here", enemyPosition, Color.DarkRed); spriteBatch.End(); // If the game is transitioning on or off, fade it out to black. if (TransitionPosition > 0 || pauseAlpha > 0) { float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2); ScreenManager.FadeBackBufferToBlack(alpha); } } #endregion } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.VisualTree; using Xunit; namespace Avalonia.Controls.UnitTests { public class ListBoxTests_Single { [Fact] public void Focusing_Item_With_Tab_Should_Not_Select_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new GotFocusEventArgs { RoutedEvent = InputElement.GotFocusEvent, NavigationMethod = NavigationMethod.Tab, }); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Focusing_Item_With_Arrow_Key_Should_Select_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new GotFocusEventArgs { RoutedEvent = InputElement.GotFocusEvent, NavigationMethod = NavigationMethod.Directional, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Item_Should_Select_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Selected_Item_Should_Not_Deselect_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.SelectedIndex = 0; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Item_Should_Select_It_When_SelectionMode_Toggle() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Single | SelectionMode.Toggle, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Selected_Item_Should_Deselect_It_When_SelectionMode_Toggle() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Toggle, }; ApplyTemplate(target); target.SelectedIndex = 0; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Clicking_Selected_Item_Should_Not_Deselect_It_When_SelectionMode_ToggleAlwaysSelected() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Toggle | SelectionMode.AlwaysSelected, }; ApplyTemplate(target); target.SelectedIndex = 0; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Another_Item_Should_Select_It_When_SelectionMode_Toggle() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Single | SelectionMode.Toggle, }; ApplyTemplate(target); target.SelectedIndex = 1; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Setting_Item_IsSelected_Sets_ListBox_Selection() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); ((ListBoxItem)target.GetLogicalChildren().ElementAt(1)).IsSelected = true; Assert.Equal("Bar", target.SelectedItem); Assert.Equal(1, target.SelectedIndex); } private Control CreateListBoxTemplate(ITemplatedControl parent) { return new ScrollViewer { Template = new FuncControlTemplate(CreateScrollViewerTemplate), Content = new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent.GetObservable(ItemsControl.ItemsProperty).ToBinding(), } }; } private Control CreateScrollViewerTemplate(ITemplatedControl parent) { return new ScrollContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = parent.GetObservable(ContentControl.ContentProperty).ToBinding(), }; } private void ApplyTemplate(ListBox target) { // Apply the template to the ListBox itself. target.ApplyTemplate(); // Then to its inner ScrollViewer. var scrollViewer = (ScrollViewer)target.GetVisualChildren().Single(); scrollViewer.ApplyTemplate(); // Then make the ScrollViewer create its child. ((ContentPresenter)scrollViewer.Presenter).UpdateChild(); // Now the ItemsPresenter should be reigstered, so apply its template. target.Presenter.ApplyTemplate(); } } }
// ------------------------------------- // Domain : IBT / Realtime.co // Author : Nicholas Ventimiglia // Product : Messaging and Storage // Published : 2014 // ------------------------------------- using System.Collections.Generic; namespace Realtime.Storage.Models { // ReSharper disable InconsistentNaming /// <summary> /// Request for a ordered Query of item's from the repository /// </summary> /// <typeparam name="T">The Type of the Item</typeparam> public class ItemQueryRequest<T> where T : class { internal bool _searchForward = true; internal Filter _filter; internal List<string> _properties; internal DataKey _startKey; internal DataKey _datakey; internal int _limit = 0; #region ctor /// <summary> /// creates a new query for the primary key /// </summary> /// <param name="primaryKey"></param> public ItemQueryRequest(object primaryKey) { _datakey = new DataKey(primaryKey); } #endregion #region Filters /// <summary> /// Adds property truncation /// </summary> /// <param name="attribute"></param> /// <returns></returns> public ItemQueryRequest<T> WithProperty(string attribute) { if(_properties == null) _properties = new List<string>(); _properties.Add(attribute); return this; } /// <summary> /// adds property truncation /// </summary> /// <param name="attribute"></param> /// <returns></returns> public ItemQueryRequest<T> WithProperties(IEnumerable<string> attribute) { if (_properties == null) _properties = new List<string>(); _properties.AddRange(attribute); return this; } /// <summary> /// The primary key of the item from which to continue an earlier operation. This value is returned in the stopKey if that operation was interrupted before completion; either because of the result set size or because of the setting for limit. /// </summary> public ItemQueryRequest<T> WithStartKey(object primaryKey) { _startKey = new DataKey(primaryKey); return this; } /// <summary> /// The primary key of the item from which to continue an earlier operation. This value is returned in the stopKey if that operation was interrupted before completion; either because of the result set size or because of the setting for limit. /// </summary> public ItemQueryRequest<T> WithStartKey(object primaryKey, object secondaryKey) { _startKey = new DataKey(primaryKey, secondaryKey); return this; } /// <summary> /// The primary key of the item from which to continue an earlier operation. This value is returned in the stopKey if that operation was interrupted before completion; either because of the result set size or because of the setting for limit. /// </summary> public ItemQueryRequest<T> WithStartKey(DataKey startKey) { _startKey = startKey; return this; } /// <summary> /// The maximum number of items to evaluate (not necessarily the number of matching items). /// </summary> /// <param name="count"></param> /// <returns></returns> public ItemQueryRequest<T> Limit(int count) { _limit = count; return this; } #endregion #region Filters /// <summary> /// Defines if the items will be retrieved in ascending order. /// </summary> /// <returns>This table reference.</returns> public ItemQueryRequest<T> Asc() { _searchForward = true; return this; } /// <summary> /// Defines if the items will be retrieved in descending order. /// </summary> /// <returns>This table reference.</returns> public ItemQueryRequest<T> Desc() { _searchForward = false; return this; } #region Filters /// <summary> /// Applies a filter that, upon retrieval, will have the items that have the selected property with a value other than null. /// </summary> /// <returns>This table reference.</returns> public ItemQueryRequest<T> NotNull(string attributeName) { _filter = new Filter { value = null, op = FilterOperator.notNull }; return this; } /// <summary> /// Applies a filter that, upon retrieval, will have the items that have the selected property with a null value. /// </summary> /// <returns>This table reference.</returns> public ItemQueryRequest<T> IsNull(string attributeName) { _filter = new Filter { value = null, op = FilterOperator.@null }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items that match the filter property value. /// </summary> /// <param name="value">The value of the property to be matched.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> IsEquals(object value) { _filter = new Filter { value = value, op = FilterOperator.equals }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items that do not match the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> NotEquals(object value) { _filter = new Filter { value = value, op = FilterOperator.notEqual }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items greater or equal to filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> GreaterEqual(object value) { _filter = new Filter { value = value, op = FilterOperator.greaterEqual }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items greater than the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> GreaterThan(object value) { _filter = new Filter { value = value, op = FilterOperator.greaterThan }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items lesser or equals to the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> LesserEqual(object value) { _filter = new Filter { value = value, op = FilterOperator.lessEqual }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items lesser than the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> LesserThan(object value) { _filter = new Filter { value = value, op = FilterOperator.lessThan }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items that contains the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> Contains(object value) { _filter = new Filter { value = value, op = FilterOperator.contains }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items that do not contain the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> NotContains(object value) { _filter = new Filter { value = value, op = FilterOperator.notContains }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items that begins with the filter property value. /// </summary> /// <param name="value">The value of the property to filter.</param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> BeginsWith(object value) { _filter = new Filter { value = value, op = FilterOperator.beginsWith }; return this; } /// <summary> /// Applies a filter to the table. When fetched, it will return the items in range of the filter property value. /// </summary> /// <param name="startValue"></param> /// <param name="endValue"></param> /// <returns>This table reference.</returns> public ItemQueryRequest<T> Between(object startValue, object endValue) { _filter = new BetweenFilter { value = startValue, endvalue = endValue, op = FilterOperator.between }; return this; } #endregion #endregion } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Xml; using NUnit.Engine; namespace NUnit.ConsoleRunner { /// <summary> /// TestEventHandler processes events from the running /// test for the console runner. /// </summary> #if NET20 public class TestEventHandler : MarshalByRefObject, ITestEventListener #else public class TestEventHandler : ITestEventListener #endif { private readonly ExtendedTextWriter _outWriter; private readonly bool _displayBeforeTest; private readonly bool _displayAfterTest; private readonly bool _displayBeforeOutput; private string _lastTestOutput; private bool _wantNewLine = false; public TestEventHandler(ExtendedTextWriter outWriter, string labelsOption) { _outWriter = outWriter; labelsOption = labelsOption.ToUpperInvariant(); _displayBeforeTest = labelsOption == "BEFORE" || labelsOption == "BEFOREANDAFTER"; _displayAfterTest = labelsOption == "AFTER" || labelsOption == "BEFOREANDAFTER"; _displayBeforeOutput = _displayBeforeTest || _displayAfterTest || labelsOption == "ONOUTPUTONLY"; } public void OnTestEvent(string report) { var doc = new XmlDocument(); doc.LoadXml(report); var testEvent = doc.FirstChild; switch (testEvent.Name) { case "start-test": TestStarted(testEvent); break; case "test-case": TestFinished(testEvent); break; case "test-suite": SuiteFinished(testEvent); break; case "test-output": TestOutput(testEvent); break; } } private void TestStarted(XmlNode testResult) { var testName = testResult.Attributes["fullname"].Value; if (_displayBeforeTest) WriteLabelLine(testName); } private void TestFinished(XmlNode testResult) { var testName = testResult.Attributes["fullname"].Value; var status = testResult.GetAttribute("label") ?? testResult.GetAttribute("result"); var outputNode = testResult.SelectSingleNode("output"); if (outputNode != null) { if (_displayBeforeOutput) WriteLabelLine(testName); FlushNewLineIfNeeded(); WriteOutputLine(testName, outputNode.InnerText); } if (_displayAfterTest) WriteLabelLineAfterTest(testName, status); } private void SuiteFinished(XmlNode testResult) { var suiteName = testResult.Attributes["fullname"].Value; var outputNode = testResult.SelectSingleNode("output"); if (outputNode != null) { if (_displayBeforeOutput) WriteLabelLine(suiteName); FlushNewLineIfNeeded(); WriteOutputLine(suiteName, outputNode.InnerText); } } private void TestOutput(XmlNode outputNode) { var testName = outputNode.GetAttribute("testname"); var stream = outputNode.GetAttribute("stream"); if (_displayBeforeOutput && testName != null) WriteLabelLine(testName); WriteOutputLine(testName, outputNode.InnerText, stream == "Error" ? ColorStyle.Error : ColorStyle.Output); } private string _currentLabel; private void WriteLabelLine(string label) { if (label != _currentLabel) { FlushNewLineIfNeeded(); _lastTestOutput = label; _outWriter.WriteLine(ColorStyle.SectionHeader, $"=> {label}"); _currentLabel = label; } } private void WriteLabelLineAfterTest(string label, string status) { FlushNewLineIfNeeded(); _lastTestOutput = label; if (status != null) { _outWriter.Write(GetColorForResultStatus(status), $"{status} "); } _outWriter.WriteLine(ColorStyle.SectionHeader, $"=> {label}"); _currentLabel = label; } private void WriteOutputLine(string testName, string text) { WriteOutputLine(testName, text, ColorStyle.Output); } private void WriteOutputLine(string testName, string text, ColorStyle color) { if (_lastTestOutput != testName) { FlushNewLineIfNeeded(); _lastTestOutput = testName; } _outWriter.Write(color, text); // If the text we just wrote did not have a new line, flag that we should eventually emit one. if (!text.EndsWith("\n")) { _wantNewLine = true; } } private void FlushNewLineIfNeeded() { if (_wantNewLine) { _outWriter.WriteLine(); _wantNewLine = false; } } private static ColorStyle GetColorForResultStatus(string status) { switch (status) { case "Passed": return ColorStyle.Pass; case "Failed": return ColorStyle.Failure; case "Error": case "Invalid": case "Cancelled": return ColorStyle.Error; case "Warning": case "Ignored": return ColorStyle.Warning; default: return ColorStyle.Output; } } #if NET20 public override object InitializeLifetimeService() { return null; } #endif } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using log4net; using NetGore.IO; using SFML.Graphics; namespace NetGore.Graphics { /// <summary> /// Base class for a <see cref="GrhData"/>, which is what describes how a <see cref="Grh"/> functions. /// </summary> public abstract class GrhData { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); const string _categorizationValueKey = "Categorization"; const string _indexValueKey = "Index"; readonly GrhIndex _grhIndex; SpriteCategorization _categorization; /// <summary> /// Initializes a new instance of the <see cref="GrhData"/> class. /// </summary> /// <param name="cat">The <see cref="SpriteCategorization"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="cat"/> is null.</exception> protected GrhData(SpriteCategorization cat) { // This is the only way we allow GrhDatas with an invalid GrhIndex. It should only ever be called for // GrhDatas that will NOT persist, such as the AutomaticAnimatedGrhData's frames. _categorization = cat; _grhIndex = GrhIndex.Invalid; } /// <summary> /// Initializes a new instance of the <see cref="GrhData"/> class. /// </summary> /// <param name="grhIndex">The <see cref="GrhIndex"/>.</param> /// <param name="cat">The <see cref="SpriteCategorization"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="cat"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="grhIndex"/> is equal to GrhIndex.Invalid.</exception> protected GrhData(GrhIndex grhIndex, SpriteCategorization cat) { if (cat == null) throw new ArgumentNullException("cat"); if (grhIndex.IsInvalid) { const string errmsg = "Failed to create GrhData with category `{0}`." + " No GrhData may be created with a GrhIndex equal to GrhIndex.Invalid"; var err = string.Format(errmsg, cat); log.Error(err); throw new ArgumentOutOfRangeException("grhIndex", err); } _categorization = cat; _grhIndex = grhIndex; } /// <summary> /// Notifies listeners when the <see cref="GrhData"/>'s categorization has changed. /// </summary> public event TypedEventHandler<GrhData, EventArgs<SpriteCategorization>> CategorizationChanged; /// <summary> /// Gets the <see cref="SpriteCategorization"/> for this <see cref="GrhData"/>. /// </summary> public SpriteCategorization Categorization { get { return _categorization; } } /// <summary> /// When overridden in the derived class, gets the frames in an animated <see cref="GrhData"/>, or an /// IEnumerable containing a reference to its self if stationary. /// </summary> public abstract IEnumerable<StationaryGrhData> Frames { get; } /// <summary> /// When overridden in the derived class, gets the number of frames in this <see cref="GrhData"/>. If this /// is not an animated <see cref="GrhData"/>, this value will always return 0. /// </summary> public abstract int FramesCount { get; } /// <summary> /// Gets the index of the <see cref="GrhData"/>. /// </summary> public GrhIndex GrhIndex { get { return _grhIndex; } } /// <summary> /// When overridden in the derived class, gets the size of the <see cref="GrhData"/>'s sprite in pixels. /// </summary> public abstract Vector2 Size { get; } /// <summary> /// When overridden in the derived class, gets the speed multiplier of the <see cref="GrhData"/> animation where each /// frame lasts 1f/Speed milliseconds. For non-animated <see cref="GrhData"/>s, this value will always be 0. /// </summary> public abstract float Speed { get; } /// <summary> /// When overridden in the derived class, creates a new <see cref="GrhData"/> equal to this <see cref="GrhData"/> /// except for the specified parameters. /// </summary> /// <param name="newCategorization">The <see cref="SpriteCategorization"/> to give to the new /// <see cref="GrhData"/>.</param> /// <param name="newGrhIndex">The <see cref="GrhIndex"/> to give to the new /// <see cref="GrhData"/>.</param> /// <returns>A deep copy of this <see cref="GrhData"/>.</returns> protected abstract GrhData DeepCopy(SpriteCategorization newCategorization, GrhIndex newGrhIndex); /// <summary> /// Creates a deep copy of the <see cref="GrhData"/>. /// </summary> /// <param name="newCategorization">Categorization for the duplicated GrhData. Must be unique.</param> /// <returns>Deep copy of the <see cref="GrhData"/> with the new categorization and its own /// unique <see cref="GrhIndex"/>.</returns> /// <exception cref="ArgumentException"><paramref name="newCategorization"/> is already in use.</exception> public GrhData Duplicate(SpriteCategorization newCategorization) { if (GrhInfo.GetData(newCategorization) != null) throw new ArgumentException("Category already in use.", "newCategorization"); var index = GrhInfo.NextFreeIndex(); Debug.Assert(GrhInfo.GetData(index) == null, "Slot to use is already in use! How the hell did this happen!? GrhInfo.NextFreeIndex() must be broken."); var dc = DeepCopy(newCategorization, index); GrhInfo.AddGrhData(dc); return dc; } /// <summary> /// When overridden in the derived class, gets the frame in an animated <see cref="GrhData"/> with the /// corresponding index, or null if the index is out of range. If stationary, this will always return /// a reference to its self, no matter what the index is. /// </summary> /// <param name="frameIndex">The index of the frame to get.</param> /// <returns>The frame with the given <paramref name="frameIndex"/>, or null if the <paramref name="frameIndex"/> /// is invalid, or a reference to its self if this is not an animated <see cref="GrhData"/>.</returns> public abstract StationaryGrhData GetFrame(int frameIndex); /// <summary> /// Gets the largest size of all the <see cref="GrhData"/>s. /// </summary> /// <param name="grhDatas">The <see cref="GrhData"/>s.</param> /// <returns>The largest size of all the <see cref="GrhData"/>s.</returns> protected static Vector2 GetMaxSize(IEnumerable<GrhData> grhDatas) { if (grhDatas == null || grhDatas.IsEmpty()) return Vector2.Zero; var ret = Vector2.Zero; foreach (var f in grhDatas) { if (f.Size.X > ret.X) ret.X = f.Size.X; if (f.Size.Y > ret.Y) ret.Y = f.Size.Y; } return ret; } protected internal static void ReadHeader(IValueReader r, out GrhIndex grhIndex, out SpriteCategorization cat) { grhIndex = r.ReadGrhIndex(_indexValueKey); cat = r.ReadSpriteCategorization(_categorizationValueKey); } /// <summary> /// Sets the categorization for the <see cref="GrhData"/>. /// </summary> /// <param name="categorization">The new categorization.</param> /// <exception cref="ArgumentNullException"><paramref name="categorization" /> is <c>null</c>.</exception> public void SetCategorization(SpriteCategorization categorization) { if (categorization == null) throw new ArgumentNullException("categorization"); // Check that either of the values are different if (_categorization == categorization) return; var oldCategorization = _categorization; _categorization = categorization; if (CategorizationChanged != null) CategorizationChanged.Raise(this, EventArgsHelper.Create(oldCategorization)); } /// <summary> /// Returns a System.String that represents the <see cref="GrhData"/>. /// </summary> /// <returns>A System.String that represents the <see cref="GrhData"/>.</returns> public override string ToString() { return string.Format("[{0}] {1}", GrhIndex, Categorization); } /// <summary> /// Writes the <see cref="GrhData"/> to an <see cref="IValueWriter"/>. /// </summary> /// <param name="w"><see cref="IValueWriter"/> to write to.</param> /// <exception cref="GrhDataException">The <see cref="GrhIndex"/> invalid.</exception> /// <exception cref="ArgumentNullException"><paramref name="w" /> is <c>null</c>.</exception> public void Write(IValueWriter w) { // Check for valid data if (GrhIndex.IsInvalid) throw new GrhDataException("The GrhIndex invalid."); if (w == null) throw new ArgumentNullException("w"); Debug.Assert(Categorization != null); // Write the index and category w.Write(_indexValueKey, GrhIndex); w.Write(_categorizationValueKey, Categorization); // Write the custom values WriteCustomValues(w); } /// <summary> /// When overridden in the derived class, writes the values unique to this derived type to the /// <paramref name="writer"/>. /// </summary> /// <param name="writer">The <see cref="IValueWriter"/> to write to.</param> protected abstract void WriteCustomValues(IValueWriter writer); public enum BoundWallType : byte { NoWall = 0, Solid = 1, Platform = 2, } /// <summary> /// The tags for a GrhData file. Defines certain attributes, like if the Grh should be covered by a wall, animation speed, /// default layer to be placed on, etc. /// </summary> public class FileTags { static readonly Regex _tagRegex = new Regex("\\[(?<tag>\\w)(?<value>[^\\]]+)\\]"); static readonly Regex _tagWallDefinitionRegex = new Regex("(?<wallType>\\d+)x(?<x>.+)y(?<y>.+)w(?<w>.+)h(?<h>.+)"); /// <summary> /// Gets the categorization title of the sprite. /// </summary> public string Title { get; private set; } /// <summary> /// Gets the animation speed, if specified. /// </summary> public ushort? AnimationSpeed { get; private set; } /// <summary> /// Gets the list of bound walls. Can be null. If non-null, the rectangle defines the position and size of the wall. /// </summary> public List<Tuple<BoundWallType, Rectangle?>> Walls { get; private set; } /// <summary> /// Gets the default layer to use, if specified. /// </summary> public MapRenderLayer? Layer { get; private set; } /// <summary> /// Creates a FileTags from a file name. /// </summary> public static FileTags Create(string fileNameWithoutExtension) { FileTags ret = new FileTags(); // Go through each tag match, and apply it foreach (Match match in _tagRegex.Matches(fileNameWithoutExtension)) { ret.ApplyTag(match.Groups["tag"].Value, match.Groups["value"].Value, fileNameWithoutExtension); } // Get the title int braceIndex = fileNameWithoutExtension.IndexOf('['); if (braceIndex > 0) ret.Title = fileNameWithoutExtension.Substring(0, braceIndex).Trim(); else ret.Title = fileNameWithoutExtension; if (ret.Title.Contains("[") || ret.Title.Contains("]")) { throw new Exception("GrhData update failed for filename `" + fileNameWithoutExtension + "` because a [ or ] character was found in the sprite title." + " Make sure your file name is correctly formed, and each [ has a matching ]."); } return ret; } /// <summary> /// Apply a tag to this FileTags. /// </summary> /// <param name="tag">The tag character.</param> /// <param name="strValue">The corresponding tag value (unparsed string).</param> /// <param name="fileNameWithoutSuffix">The file name (for showing details in exception message).</param> void ApplyTag(string tag, string strValue, string fileNameWithoutSuffix) { tag = tag.ToLowerInvariant(); if (tag == "s") { // Animation speed ushort val; if (!ushort.TryParse(strValue, out val)) throw CreateApplyTagException(tag, strValue, fileNameWithoutSuffix, "Failed to parse the value as an ushort"); AnimationSpeed = val; } else if (tag == "w") { // Wall BoundWallType wall; Rectangle? wallArea; Match wallDefinitionMatch = _tagWallDefinitionRegex.Match(strValue); if (wallDefinitionMatch.Success) { // Wall definition (doesn't cover whole sprite) wall = (BoundWallType)int.Parse(wallDefinitionMatch.Groups["wallType"].Value); wallArea = new Rectangle { X = int.Parse(wallDefinitionMatch.Groups["x"].Value), Y = int.Parse(wallDefinitionMatch.Groups["y"].Value), Width = int.Parse(wallDefinitionMatch.Groups["w"].Value), Height = int.Parse(wallDefinitionMatch.Groups["h"].Value) }; } else { // Wall covers whole sprite byte val; if (!byte.TryParse(strValue, out val)) throw CreateApplyTagException(tag, strValue, fileNameWithoutSuffix, "Failed to parse the value as a byte"); wall = (BoundWallType)val; wallArea = null; } if (!EnumHelper<BoundWallType>.IsDefined(wall)) throw CreateApplyTagException(tag, strValue, fileNameWithoutSuffix, string.Format("The value is not a valid BoundWallType value (use values {0} to {1})", EnumHelper<BoundWallType>.MinValue, EnumHelper<BoundWallType>.MaxValue)); if (Walls == null) Walls = new List<Tuple<BoundWallType, Rectangle?>>(1); Walls.Add(new Tuple<BoundWallType, Rectangle?>(wall, wallArea)); } else if (tag == "l") { // Layer byte val; if (!byte.TryParse(strValue, out val)) throw CreateApplyTagException(tag, strValue, fileNameWithoutSuffix, "Failed to parse the value as a byte"); if (val == 0) Layer = MapRenderLayer.SpriteBackground; else if (val == 1) Layer = MapRenderLayer.Dynamic; else if (val == 2) Layer = MapRenderLayer.SpriteForeground; else { throw CreateApplyTagException(tag, strValue, fileNameWithoutSuffix, "The value is out of range (use 0 for background, 1 for dynamic, and 2 for foreground)"); } } else { // Unknown/invalid throw CreateApplyTagException(tag, strValue, fileNameWithoutSuffix, "The specified tag does not exist"); } } static Exception CreateApplyTagException(string tag, string strValue, string fileNameWithoutSuffix, string reason) { return new Exception("GrhData update failed to parse the value `" + strValue + "` for tag `" + tag + "` on the file `" + fileNameWithoutSuffix + "`. Reason: " + reason + ". Please correct the corresponding Grh file name under the Grh content directory."); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Database data /// masking. Contains operations to: Create, Retrieve, Update, and Delete /// data masking rules, as well as Create, Retreive and Update data /// masking policy. /// </summary> internal partial class DataMaskingOperations : IServiceOperations<SqlManagementClient>, IDataMaskingOperations { /// <summary> /// Initializes a new instance of the DataMaskingOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataMaskingOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Creates or updates an Azure SQL Database data masking policy /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// firewall rule. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdatePolicyAsync(string resourceGroupName, string serverName, string databaseName, DataMaskingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.DataMaskingState == null) { throw new ArgumentNullException("parameters.Properties.DataMaskingState"); } if (parameters.Properties.ExemptPrincipals == null) { throw new ArgumentNullException("parameters.Properties.ExemptPrincipals"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdatePolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/dataMaskingPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataMaskingPolicyCreateOrUpdateParametersValue = new JObject(); requestDoc = dataMaskingPolicyCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); dataMaskingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["dataMaskingState"] = parameters.Properties.DataMaskingState; propertiesValue["exemptPrincipals"] = parameters.Properties.ExemptPrincipals; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates or updates an Azure SQL Database Server Firewall rule. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a data /// masking rule. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdateRuleAsync(string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, DataMaskingRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (dataMaskingRule == null) { throw new ArgumentNullException("dataMaskingRule"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.Id == null) { throw new ArgumentNullException("parameters.Properties.Id"); } if (parameters.Properties.MaskingFunction == null) { throw new ArgumentNullException("parameters.Properties.MaskingFunction"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("dataMaskingRule", dataMaskingRule); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateRuleAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/dataMaskingPolicies/Default/rules/"; url = url + Uri.EscapeDataString(dataMaskingRule); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataMaskingRuleCreateOrUpdateParametersValue = new JObject(); requestDoc = dataMaskingRuleCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); dataMaskingRuleCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["id"] = parameters.Properties.Id; if (parameters.Properties.SchemaName != null) { propertiesValue["schemaName"] = parameters.Properties.SchemaName; } if (parameters.Properties.TableName != null) { propertiesValue["tableName"] = parameters.Properties.TableName; } if (parameters.Properties.ColumnName != null) { propertiesValue["columnName"] = parameters.Properties.ColumnName; } propertiesValue["maskingFunction"] = parameters.Properties.MaskingFunction; if (parameters.Properties.NumberFrom != null) { propertiesValue["numberFrom"] = parameters.Properties.NumberFrom; } if (parameters.Properties.NumberTo != null) { propertiesValue["numberTo"] = parameters.Properties.NumberTo; } if (parameters.Properties.PrefixSize != null) { propertiesValue["prefixSize"] = parameters.Properties.PrefixSize; } if (parameters.Properties.SuffixSize != null) { propertiesValue["suffixSize"] = parameters.Properties.SuffixSize; } if (parameters.Properties.ReplacementString != null) { propertiesValue["replacementString"] = parameters.Properties.ReplacementString; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes an Azure SQL Server data masking rule. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (dataMaskingRule == null) { throw new ArgumentNullException("dataMaskingRule"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("dataMaskingRule", dataMaskingRule); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/dataMaskingPolicies/Default/rules/"; url = url + Uri.EscapeDataString(dataMaskingRule); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database data masking policy. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking policy applies. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a data masking policy get request. /// </returns> public async Task<DataMaskingPolicyGetResponse> GetPolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "GetPolicyAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/dataMaskingPolicies/Default"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataMaskingPolicyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataMaskingPolicyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataMaskingPolicy dataMaskingPolicyInstance = new DataMaskingPolicy(); result.DataMaskingPolicy = dataMaskingPolicyInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataMaskingPolicyProperties propertiesInstance = new DataMaskingPolicyProperties(); dataMaskingPolicyInstance.Properties = propertiesInstance; JToken dataMaskingStateValue = propertiesValue["dataMaskingState"]; if (dataMaskingStateValue != null && dataMaskingStateValue.Type != JTokenType.Null) { string dataMaskingStateInstance = ((string)dataMaskingStateValue); propertiesInstance.DataMaskingState = dataMaskingStateInstance; } JToken exemptPrincipalsValue = propertiesValue["exemptPrincipals"]; if (exemptPrincipalsValue != null && exemptPrincipalsValue.Type != JTokenType.Null) { string exemptPrincipalsInstance = ((string)exemptPrincipalsValue); propertiesInstance.ExemptPrincipals = exemptPrincipalsInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); dataMaskingPolicyInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataMaskingPolicyInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dataMaskingPolicyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataMaskingPolicyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataMaskingPolicyInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns an Azure SQL Database data masking rule. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a data masking rule get request. /// </returns> public async Task<DataMaskingRuleGetResponse> GetRuleAsync(string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (dataMaskingRule == null) { throw new ArgumentNullException("dataMaskingRule"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("dataMaskingRule", dataMaskingRule); TracingAdapter.Enter(invocationId, this, "GetRuleAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/dataMaskingPolicies/Default/rules/"; url = url + Uri.EscapeDataString(dataMaskingRule); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataMaskingRuleGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataMaskingRuleGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DataMaskingRule dataMaskingRuleInstance = new DataMaskingRule(); result.DataMaskingRule = dataMaskingRuleInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataMaskingRuleProperties propertiesInstance = new DataMaskingRuleProperties(); dataMaskingRuleInstance.Properties = propertiesInstance; JToken idValue = propertiesValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); propertiesInstance.Id = idInstance; } JToken schemaNameValue = propertiesValue["schemaName"]; if (schemaNameValue != null && schemaNameValue.Type != JTokenType.Null) { string schemaNameInstance = ((string)schemaNameValue); propertiesInstance.SchemaName = schemaNameInstance; } JToken tableNameValue = propertiesValue["tableName"]; if (tableNameValue != null && tableNameValue.Type != JTokenType.Null) { string tableNameInstance = ((string)tableNameValue); propertiesInstance.TableName = tableNameInstance; } JToken columnNameValue = propertiesValue["columnName"]; if (columnNameValue != null && columnNameValue.Type != JTokenType.Null) { string columnNameInstance = ((string)columnNameValue); propertiesInstance.ColumnName = columnNameInstance; } JToken maskingFunctionValue = propertiesValue["maskingFunction"]; if (maskingFunctionValue != null && maskingFunctionValue.Type != JTokenType.Null) { string maskingFunctionInstance = ((string)maskingFunctionValue); propertiesInstance.MaskingFunction = maskingFunctionInstance; } JToken numberFromValue = propertiesValue["numberFrom"]; if (numberFromValue != null && numberFromValue.Type != JTokenType.Null) { string numberFromInstance = ((string)numberFromValue); propertiesInstance.NumberFrom = numberFromInstance; } JToken numberToValue = propertiesValue["numberTo"]; if (numberToValue != null && numberToValue.Type != JTokenType.Null) { string numberToInstance = ((string)numberToValue); propertiesInstance.NumberTo = numberToInstance; } JToken prefixSizeValue = propertiesValue["prefixSize"]; if (prefixSizeValue != null && prefixSizeValue.Type != JTokenType.Null) { string prefixSizeInstance = ((string)prefixSizeValue); propertiesInstance.PrefixSize = prefixSizeInstance; } JToken suffixSizeValue = propertiesValue["suffixSize"]; if (suffixSizeValue != null && suffixSizeValue.Type != JTokenType.Null) { string suffixSizeInstance = ((string)suffixSizeValue); propertiesInstance.SuffixSize = suffixSizeInstance; } JToken replacementStringValue = propertiesValue["replacementString"]; if (replacementStringValue != null && replacementStringValue.Type != JTokenType.Null) { string replacementStringInstance = ((string)replacementStringValue); propertiesInstance.ReplacementString = replacementStringInstance; } } JToken idValue2 = responseDoc["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); dataMaskingRuleInstance.Id = idInstance2; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataMaskingRuleInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dataMaskingRuleInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataMaskingRuleInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataMaskingRuleInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns a list of Azure SQL Database data masking rules. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rules applies. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List data masking rules request. /// </returns> public async Task<DataMaskingRuleListResponse> ListAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/dataMaskingPolicies/Default/Rules"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataMaskingRuleListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataMaskingRuleListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataMaskingRule dataMaskingRuleInstance = new DataMaskingRule(); result.DataMaskingRules.Add(dataMaskingRuleInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DataMaskingRuleProperties propertiesInstance = new DataMaskingRuleProperties(); dataMaskingRuleInstance.Properties = propertiesInstance; JToken idValue = propertiesValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); propertiesInstance.Id = idInstance; } JToken schemaNameValue = propertiesValue["schemaName"]; if (schemaNameValue != null && schemaNameValue.Type != JTokenType.Null) { string schemaNameInstance = ((string)schemaNameValue); propertiesInstance.SchemaName = schemaNameInstance; } JToken tableNameValue = propertiesValue["tableName"]; if (tableNameValue != null && tableNameValue.Type != JTokenType.Null) { string tableNameInstance = ((string)tableNameValue); propertiesInstance.TableName = tableNameInstance; } JToken columnNameValue = propertiesValue["columnName"]; if (columnNameValue != null && columnNameValue.Type != JTokenType.Null) { string columnNameInstance = ((string)columnNameValue); propertiesInstance.ColumnName = columnNameInstance; } JToken maskingFunctionValue = propertiesValue["maskingFunction"]; if (maskingFunctionValue != null && maskingFunctionValue.Type != JTokenType.Null) { string maskingFunctionInstance = ((string)maskingFunctionValue); propertiesInstance.MaskingFunction = maskingFunctionInstance; } JToken numberFromValue = propertiesValue["numberFrom"]; if (numberFromValue != null && numberFromValue.Type != JTokenType.Null) { string numberFromInstance = ((string)numberFromValue); propertiesInstance.NumberFrom = numberFromInstance; } JToken numberToValue = propertiesValue["numberTo"]; if (numberToValue != null && numberToValue.Type != JTokenType.Null) { string numberToInstance = ((string)numberToValue); propertiesInstance.NumberTo = numberToInstance; } JToken prefixSizeValue = propertiesValue["prefixSize"]; if (prefixSizeValue != null && prefixSizeValue.Type != JTokenType.Null) { string prefixSizeInstance = ((string)prefixSizeValue); propertiesInstance.PrefixSize = prefixSizeInstance; } JToken suffixSizeValue = propertiesValue["suffixSize"]; if (suffixSizeValue != null && suffixSizeValue.Type != JTokenType.Null) { string suffixSizeInstance = ((string)suffixSizeValue); propertiesInstance.SuffixSize = suffixSizeInstance; } JToken replacementStringValue = propertiesValue["replacementString"]; if (replacementStringValue != null && replacementStringValue.Type != JTokenType.Null) { string replacementStringInstance = ((string)replacementStringValue); propertiesInstance.ReplacementString = replacementStringInstance; } } JToken idValue2 = valueValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); dataMaskingRuleInstance.Id = idInstance2; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); dataMaskingRuleInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); dataMaskingRuleInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); dataMaskingRuleInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); dataMaskingRuleInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.Metadata.Ecma335.Tests { public class MetadataTokensTests { // MetadataReader handles: private static readonly EntityHandle s_assemblyRefHandle = AssemblyReferenceHandle.FromRowId(1); private static readonly EntityHandle s_virtualAssemblyRefHandle = AssemblyReferenceHandle.FromVirtualIndex(AssemblyReferenceHandle.VirtualIndex.System_Runtime); private static readonly Handle s_virtualBlobHandle = BlobHandle.FromVirtualIndex(BlobHandle.VirtualIndex.AttributeUsage_AllowSingle, 0); private static readonly Handle s_userStringHandle = UserStringHandle.FromOffset(1); private static readonly Handle s_stringHandle = StringHandle.FromOffset(1); private static readonly Handle s_winrtPrefixedStringHandle = StringHandle.FromOffset(1).WithWinRTPrefix(); private static readonly Handle s_blobHandle = BlobHandle.FromOffset(1); private static readonly Handle s_guidHandle = GuidHandle.FromIndex(5); private static readonly EntityHandle s_exportedTypeHandle = ExportedTypeHandle.FromRowId(42); // MetadataBuilder handles: private static readonly Handle s_writerStringHandle = StringHandle.FromWriterVirtualIndex(1); private static readonly Handle s_writerBlobHandle = BlobHandle.FromOffset(1); private static readonly Handle s_writerGuidHandle = GuidHandle.FromIndex(1); private static readonly Handle s_writerUserStringHandle = UserStringHandle.FromOffset(1); [Fact] public void GetRowNumber() { Assert.Equal(1, MetadataTokens.GetRowNumber(s_assemblyRefHandle)); Assert.Equal(-1, MetadataTokens.GetRowNumber(s_virtualAssemblyRefHandle)); } [Fact] public void GetHeapOffset() { Assert.Equal(-1, MetadataTokens.GetHeapOffset(s_virtualBlobHandle)); Assert.Equal(-1, MetadataTokens.GetHeapOffset((BlobHandle)s_virtualBlobHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset(s_userStringHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset((UserStringHandle)s_userStringHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset(s_stringHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset((StringHandle)s_stringHandle)); Assert.Equal(-1, MetadataTokens.GetHeapOffset(s_winrtPrefixedStringHandle)); Assert.Equal(-1, MetadataTokens.GetHeapOffset((StringHandle)s_winrtPrefixedStringHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset(s_blobHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset((BlobHandle)s_blobHandle)); Assert.Equal(5, MetadataTokens.GetHeapOffset(s_guidHandle)); Assert.Equal(5, MetadataTokens.GetHeapOffset((GuidHandle)s_guidHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset(s_writerUserStringHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset((UserStringHandle)s_writerUserStringHandle)); Assert.Equal(-1, MetadataTokens.GetHeapOffset(s_writerStringHandle)); Assert.Equal(-1, MetadataTokens.GetHeapOffset((StringHandle)s_writerStringHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset(s_writerBlobHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset((BlobHandle)s_writerBlobHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset(s_writerGuidHandle)); Assert.Equal(1, MetadataTokens.GetHeapOffset((GuidHandle)s_writerGuidHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetHeapOffset(s_assemblyRefHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetHeapOffset(s_virtualAssemblyRefHandle)); } [Fact] public void GetToken() { Assert.Equal(0x23000001, MetadataTokens.GetToken((Handle)s_assemblyRefHandle)); Assert.Equal(0, MetadataTokens.GetToken((Handle)s_virtualAssemblyRefHandle)); Assert.Equal(0x23000001, MetadataTokens.GetToken(s_assemblyRefHandle)); Assert.Equal(0, MetadataTokens.GetToken(s_virtualAssemblyRefHandle)); Assert.Equal(0x70000001, MetadataTokens.GetToken(s_userStringHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetToken(s_virtualBlobHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetToken(s_stringHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetToken(s_winrtPrefixedStringHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetToken(s_blobHandle)); AssertExtensions.Throws<ArgumentException>("handle", () => MetadataTokens.GetToken(s_guidHandle)); } [Fact] public void TryGetTableIndex() { var kinds = from i in Enumerable.Range(0, 255) let index = new Func<HandleKind, TableIndex?>(k => { TableIndex ti; if (MetadataTokens.TryGetTableIndex(k, out ti)) { Assert.Equal((int)k, (int)ti); return ti; } return null; })((HandleKind)i) where index != null select index.Value; AssertEx.Equal(new TableIndex[] { TableIndex.Module, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.FieldPtr, TableIndex.Field, TableIndex.MethodPtr, TableIndex.MethodDef, TableIndex.ParamPtr, TableIndex.Param, TableIndex.InterfaceImpl, TableIndex.MemberRef, TableIndex.Constant, TableIndex.CustomAttribute, TableIndex.FieldMarshal, TableIndex.DeclSecurity, TableIndex.ClassLayout, TableIndex.FieldLayout, TableIndex.StandAloneSig, TableIndex.EventMap, TableIndex.EventPtr, TableIndex.Event, TableIndex.PropertyMap, TableIndex.PropertyPtr, TableIndex.Property, TableIndex.MethodSemantics, TableIndex.MethodImpl, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.ImplMap, TableIndex.FieldRva, TableIndex.EncLog, TableIndex.EncMap, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.File, TableIndex.ExportedType, TableIndex.ManifestResource, TableIndex.NestedClass, TableIndex.GenericParam, TableIndex.MethodSpec, TableIndex.GenericParamConstraint, TableIndex.Document, TableIndex.MethodDebugInformation, TableIndex.LocalScope, TableIndex.LocalVariable, TableIndex.LocalConstant, TableIndex.ImportScope, TableIndex.StateMachineMethod, TableIndex.CustomDebugInformation }, kinds); } [Fact] public void TryGetHeapIndex() { HeapIndex index; Assert.True(MetadataTokens.TryGetHeapIndex(HandleKind.Blob, out index)); Assert.Equal(HeapIndex.Blob, index); Assert.True(MetadataTokens.TryGetHeapIndex(HandleKind.String, out index)); Assert.Equal(HeapIndex.String, index); Assert.True(MetadataTokens.TryGetHeapIndex(HandleKind.UserString, out index)); Assert.Equal(HeapIndex.UserString, index); Assert.True(MetadataTokens.TryGetHeapIndex(HandleKind.NamespaceDefinition, out index)); Assert.Equal(HeapIndex.String, index); Assert.True(MetadataTokens.TryGetHeapIndex(HandleKind.Guid, out index)); Assert.Equal(HeapIndex.Guid, index); Assert.False(MetadataTokens.TryGetHeapIndex(HandleKind.Constant, out index)); Assert.False(MetadataTokens.TryGetHeapIndex((HandleKind)255, out index)); } [Fact] public void HandleFactories_FromToken() { Assert.Equal(s_assemblyRefHandle, MetadataTokens.Handle(0x23000001)); Assert.Equal(s_userStringHandle, MetadataTokens.Handle(0x70000001)); Assert.Equal(s_exportedTypeHandle, MetadataTokens.ExportedTypeHandle((int)(TokenTypeIds.ExportedType | s_exportedTypeHandle.RowId))); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(-1)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x71000001)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x72000001)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x73000001)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x74000001)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x7a000001)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x7e000001)); AssertExtensions.Throws<ArgumentException>("token", () => MetadataTokens.Handle(0x7fffffff)); } [Fact] public void HandleFactories_FromTableIndex() { Assert.Equal(s_assemblyRefHandle, MetadataTokens.Handle(TableIndex.AssemblyRef, 1)); Assert.Equal(s_exportedTypeHandle, MetadataTokens.Handle(TableIndex.ExportedType, s_exportedTypeHandle.RowId)); Assert.Equal(s_assemblyRefHandle, MetadataTokens.EntityHandle(TableIndex.AssemblyRef, 1)); Assert.Equal(s_exportedTypeHandle, MetadataTokens.EntityHandle(TableIndex.ExportedType, s_exportedTypeHandle.RowId)); Assert.Equal(s_userStringHandle, MetadataTokens.Handle((TableIndex)0x70, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x71, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x72, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x73, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x74, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x7a, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x7e, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MetadataTokens.Handle((TableIndex)0x7f, 0xffffff)); } [Fact] public void SpecificHandleFactories() { Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodDefinitionHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodImplementationHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodSpecificationHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.TypeDefinitionHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ExportedTypeHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.TypeReferenceHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.TypeSpecificationHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.InterfaceImplementationHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MemberReferenceHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.FieldDefinitionHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.EventDefinitionHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.PropertyDefinitionHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.StandaloneSignatureHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ParameterHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.GenericParameterHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.GenericParameterConstraintHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ModuleReferenceHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.AssemblyReferenceHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.CustomAttributeHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.DeclarativeSecurityAttributeHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ConstantHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ManifestResourceHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.AssemblyFileHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.DocumentHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.MethodDebugInformationHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.LocalScopeHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.LocalVariableHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.LocalConstantHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.ImportScopeHandle(1))); Assert.Equal(1, MetadataTokens.GetRowNumber(MetadataTokens.CustomDebugInformationHandle(1))); Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.UserStringHandle(1))); Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.StringHandle(1))); Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.BlobHandle(1))); Assert.Equal(1, MetadataTokens.GetHeapOffset(MetadataTokens.GuidHandle(1))); Assert.Equal(1, MetadataTokens.GetHeapOffset((BlobHandle)MetadataTokens.DocumentNameBlobHandle(1))); } } }
// ReSharper disable RedundantUsingDirective // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialTypeWithSinglePart // ReSharper disable PartialMethodWithSinglePart // ReSharper disable RedundantNameQualifier // TargetFrameworkVersion = 4.51 #pragma warning disable 1591 // Ignore "Missing XML Comment" warning using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Data.Entity.Infrastructure; using System.Linq.Expressions; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Data.Entity.ModelConfiguration; using System.Threading; using DatabaseGeneratedOption = System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption; namespace MapperExemple.Entity.EF { public class ExempleDbContext : DbContext, IExempleDbContext { public DbSet<AlphabeticalListOfProduct> AlphabeticalListOfProducts { get; set; } // Alphabetical list of products public DbSet<Category> Categories { get; set; } // Categories public DbSet<CategorySalesFor1997> CategorySalesFor1997 { get; set; } // Category Sales for 1997 public DbSet<CurrentProductList> CurrentProductLists { get; set; } // Current Product List public DbSet<Customer> Customers { get; set; } // Customers public DbSet<CustomerAndSuppliersByCity> CustomerAndSuppliersByCities { get; set; } // Customer and Suppliers by City public DbSet<CustomerDemographic> CustomerDemographics { get; set; } // CustomerDemographics public DbSet<Employee> Employees { get; set; } // Employees public DbSet<Invoice> Invoices { get; set; } // Invoices public DbSet<Order> Orders { get; set; } // Orders public DbSet<OrderDetail> OrderDetails { get; set; } // Order Details public DbSet<OrderDetailsExtended> OrderDetailsExtendeds { get; set; } // Order Details Extended public DbSet<OrdersQry> OrdersQries { get; set; } // Orders Qry public DbSet<OrderSubtotal> OrderSubtotals { get; set; } // Order Subtotals public DbSet<Product> Products { get; set; } // Products public DbSet<ProductsAboveAveragePrice> ProductsAboveAveragePrices { get; set; } // Products Above Average Price public DbSet<ProductSalesFor1997> ProductSalesFor1997 { get; set; } // Product Sales for 1997 public DbSet<ProductsByCategory> ProductsByCategories { get; set; } // Products by Category public DbSet<Region> Regions { get; set; } // Region public DbSet<SalesByCategory> SalesByCategories { get; set; } // Sales by Category public DbSet<SalesTotalsByAmount> SalesTotalsByAmounts { get; set; } // Sales Totals by Amount public DbSet<Shipper> Shippers { get; set; } // Shippers public DbSet<SummaryOfSalesByQuarter> SummaryOfSalesByQuarters { get; set; } // Summary of Sales by Quarter public DbSet<SummaryOfSalesByYear> SummaryOfSalesByYears { get; set; } // Summary of Sales by Year public DbSet<Supplier> Suppliers { get; set; } // Suppliers public DbSet<Sysdiagram> Sysdiagrams { get; set; } // sysdiagrams public DbSet<Territory> Territories { get; set; } // Territories static ExempleDbContext() { System.Data.Entity.Database.SetInitializer<ExempleDbContext>(null); } public ExempleDbContext() : base("Name=NorthwingDbContext") { } public ExempleDbContext(string connectionString) : base(connectionString) { } public ExempleDbContext(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model) { } protected override void Dispose(bool disposing) { base.Dispose(disposing); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Configurations.Add(new AlphabeticalListOfProductConfiguration()); modelBuilder.Configurations.Add(new CategoryConfiguration()); modelBuilder.Configurations.Add(new CategorySalesFor1997Configuration()); modelBuilder.Configurations.Add(new CurrentProductListConfiguration()); modelBuilder.Configurations.Add(new CustomerConfiguration()); modelBuilder.Configurations.Add(new CustomerAndSuppliersByCityConfiguration()); modelBuilder.Configurations.Add(new CustomerDemographicConfiguration()); modelBuilder.Configurations.Add(new EmployeeConfiguration()); modelBuilder.Configurations.Add(new InvoiceConfiguration()); modelBuilder.Configurations.Add(new OrderConfiguration()); modelBuilder.Configurations.Add(new OrderDetailConfiguration()); modelBuilder.Configurations.Add(new OrderDetailsExtendedConfiguration()); modelBuilder.Configurations.Add(new OrdersQryConfiguration()); modelBuilder.Configurations.Add(new OrderSubtotalConfiguration()); modelBuilder.Configurations.Add(new ProductConfiguration()); modelBuilder.Configurations.Add(new ProductsAboveAveragePriceConfiguration()); modelBuilder.Configurations.Add(new ProductSalesFor1997Configuration()); modelBuilder.Configurations.Add(new ProductsByCategoryConfiguration()); modelBuilder.Configurations.Add(new RegionConfiguration()); modelBuilder.Configurations.Add(new SalesByCategoryConfiguration()); modelBuilder.Configurations.Add(new SalesTotalsByAmountConfiguration()); modelBuilder.Configurations.Add(new ShipperConfiguration()); modelBuilder.Configurations.Add(new SummaryOfSalesByQuarterConfiguration()); modelBuilder.Configurations.Add(new SummaryOfSalesByYearConfiguration()); modelBuilder.Configurations.Add(new SupplierConfiguration()); modelBuilder.Configurations.Add(new SysdiagramConfiguration()); modelBuilder.Configurations.Add(new TerritoryConfiguration()); } public static DbModelBuilder CreateModel(DbModelBuilder modelBuilder, string schema) { modelBuilder.Configurations.Add(new AlphabeticalListOfProductConfiguration(schema)); modelBuilder.Configurations.Add(new CategoryConfiguration(schema)); modelBuilder.Configurations.Add(new CategorySalesFor1997Configuration(schema)); modelBuilder.Configurations.Add(new CurrentProductListConfiguration(schema)); modelBuilder.Configurations.Add(new CustomerConfiguration(schema)); modelBuilder.Configurations.Add(new CustomerAndSuppliersByCityConfiguration(schema)); modelBuilder.Configurations.Add(new CustomerDemographicConfiguration(schema)); modelBuilder.Configurations.Add(new EmployeeConfiguration(schema)); modelBuilder.Configurations.Add(new InvoiceConfiguration(schema)); modelBuilder.Configurations.Add(new OrderConfiguration(schema)); modelBuilder.Configurations.Add(new OrderDetailConfiguration(schema)); modelBuilder.Configurations.Add(new OrderDetailsExtendedConfiguration(schema)); modelBuilder.Configurations.Add(new OrdersQryConfiguration(schema)); modelBuilder.Configurations.Add(new OrderSubtotalConfiguration(schema)); modelBuilder.Configurations.Add(new ProductConfiguration(schema)); modelBuilder.Configurations.Add(new ProductsAboveAveragePriceConfiguration(schema)); modelBuilder.Configurations.Add(new ProductSalesFor1997Configuration(schema)); modelBuilder.Configurations.Add(new ProductsByCategoryConfiguration(schema)); modelBuilder.Configurations.Add(new RegionConfiguration(schema)); modelBuilder.Configurations.Add(new SalesByCategoryConfiguration(schema)); modelBuilder.Configurations.Add(new SalesTotalsByAmountConfiguration(schema)); modelBuilder.Configurations.Add(new ShipperConfiguration(schema)); modelBuilder.Configurations.Add(new SummaryOfSalesByQuarterConfiguration(schema)); modelBuilder.Configurations.Add(new SummaryOfSalesByYearConfiguration(schema)); modelBuilder.Configurations.Add(new SupplierConfiguration(schema)); modelBuilder.Configurations.Add(new SysdiagramConfiguration(schema)); modelBuilder.Configurations.Add(new TerritoryConfiguration(schema)); return modelBuilder; } // Stored Procedures public List<CustOrderHistReturnModel> CustOrderHist(string customerId) { int procResult; return CustOrderHist(customerId, out procResult); } public List<CustOrderHistReturnModel> CustOrderHist(string customerId, out int procResult) { var customerIdParam = new SqlParameter { ParameterName = "@CustomerID", SqlDbType = SqlDbType.NChar, Direction = ParameterDirection.Input, Value = customerId, Size = 5 }; if (customerIdParam.Value == null) customerIdParam.Value = DBNull.Value; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<CustOrderHistReturnModel>("EXEC @procResult = [dbo].[CustOrderHist] @CustomerID", customerIdParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<CustOrdersDetailReturnModel> CustOrdersDetail(int? orderId) { int procResult; return CustOrdersDetail(orderId, out procResult); } public List<CustOrdersDetailReturnModel> CustOrdersDetail(int? orderId, out int procResult) { var orderIdParam = new SqlParameter { ParameterName = "@OrderID", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input, Value = orderId.GetValueOrDefault() }; if (!orderId.HasValue) orderIdParam.Value = DBNull.Value; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<CustOrdersDetailReturnModel>("EXEC @procResult = [dbo].[CustOrdersDetail] @OrderID", orderIdParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<CustOrdersOrdersReturnModel> CustOrdersOrders(string customerId) { int procResult; return CustOrdersOrders(customerId, out procResult); } public List<CustOrdersOrdersReturnModel> CustOrdersOrders(string customerId, out int procResult) { var customerIdParam = new SqlParameter { ParameterName = "@CustomerID", SqlDbType = SqlDbType.NChar, Direction = ParameterDirection.Input, Value = customerId, Size = 5 }; if (customerIdParam.Value == null) customerIdParam.Value = DBNull.Value; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<CustOrdersOrdersReturnModel>("EXEC @procResult = [dbo].[CustOrdersOrders] @CustomerID", customerIdParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<EmployeeSalesByCountryReturnModel> EmployeeSalesByCountry(DateTime? beginningDate, DateTime? endingDate) { int procResult; return EmployeeSalesByCountry(beginningDate, endingDate, out procResult); } public List<EmployeeSalesByCountryReturnModel> EmployeeSalesByCountry(DateTime? beginningDate, DateTime? endingDate, out int procResult) { var beginningDateParam = new SqlParameter { ParameterName = "@Beginning_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = beginningDate.GetValueOrDefault() }; if (!beginningDate.HasValue) beginningDateParam.Value = DBNull.Value; var endingDateParam = new SqlParameter { ParameterName = "@Ending_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = endingDate.GetValueOrDefault() }; if (!endingDate.HasValue) endingDateParam.Value = DBNull.Value; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<EmployeeSalesByCountryReturnModel>("EXEC @procResult = [dbo].[Employee Sales by Country] @Beginning_Date, @Ending_Date", beginningDateParam, endingDateParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<SalesByYearReturnModel> SalesByYear(DateTime? beginningDate, DateTime? endingDate) { int procResult; return SalesByYear(beginningDate, endingDate, out procResult); } public List<SalesByYearReturnModel> SalesByYear(DateTime? beginningDate, DateTime? endingDate, out int procResult) { var beginningDateParam = new SqlParameter { ParameterName = "@Beginning_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = beginningDate.GetValueOrDefault() }; if (!beginningDate.HasValue) beginningDateParam.Value = DBNull.Value; var endingDateParam = new SqlParameter { ParameterName = "@Ending_Date", SqlDbType = SqlDbType.DateTime, Direction = ParameterDirection.Input, Value = endingDate.GetValueOrDefault() }; if (!endingDate.HasValue) endingDateParam.Value = DBNull.Value; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<SalesByYearReturnModel>("EXEC @procResult = [dbo].[Sales by Year] @Beginning_Date, @Ending_Date", beginningDateParam, endingDateParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<SalesByCategoryReturnModel> SalesByCategory(string categoryName, string ordYear) { int procResult; return SalesByCategory(categoryName, ordYear, out procResult); } public List<SalesByCategoryReturnModel> SalesByCategory(string categoryName, string ordYear, out int procResult) { var categoryNameParam = new SqlParameter { ParameterName = "@CategoryName", SqlDbType = SqlDbType.NVarChar, Direction = ParameterDirection.Input, Value = categoryName, Size = 15 }; if (categoryNameParam.Value == null) categoryNameParam.Value = DBNull.Value; var ordYearParam = new SqlParameter { ParameterName = "@OrdYear", SqlDbType = SqlDbType.NVarChar, Direction = ParameterDirection.Input, Value = ordYear, Size = 4 }; if (ordYearParam.Value == null) ordYearParam.Value = DBNull.Value; var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<SalesByCategoryReturnModel>("EXEC @procResult = [dbo].[SalesByCategory] @CategoryName, @OrdYear", categoryNameParam, ordYearParam, procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } public List<TenMostExpensiveProductsReturnModel> TenMostExpensiveProducts() { int procResult; return TenMostExpensiveProducts(out procResult); } public List<TenMostExpensiveProductsReturnModel> TenMostExpensiveProducts( out int procResult) { var procResultParam = new SqlParameter { ParameterName = "@procResult", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output }; var procResultData = Database.SqlQuery<TenMostExpensiveProductsReturnModel>("EXEC @procResult = [dbo].[Ten Most Expensive Products] ", procResultParam).ToList(); procResult = (int) procResultParam.Value; return procResultData; } } }
using System; using System.Collections.Generic; using System.Linq; using DocumentFormat.OpenXml.Wordprocessing; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Remote; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Utilities; namespace Signum.React.Selenium { public class ResultTableProxy { public RemoteWebDriver Selenium { get; private set; } public IWebElement Element; SearchControlProxy SearchControl; public ResultTableProxy(IWebElement element, SearchControlProxy searchControl) { this.Selenium = element.GetDriver(); this.Element = element; this.SearchControl = searchControl; } public WebElementLocator ResultTableElement { get { return this.Element.WithLocator(By.CssSelector("table.sf-search-results")); } } public WebElementLocator RowsLocator { get { return this.Element.WithLocator(By.CssSelector("table.sf-search-results > tbody > tr")); } } public List<ResultRowProxy> AllRows() { return RowsLocator.FindElements().Select(e => new ResultRowProxy(e)).ToList(); } public ResultRowProxy RowElement(int rowIndex) { return new ResultRowProxy(RowElementLocator(rowIndex).WaitVisible()); } private WebElementLocator RowElementLocator(int rowIndex) { return this.Element.WithLocator(By.CssSelector("tr[data-row-index='{0}']".FormatWith(rowIndex))); } public ResultRowProxy RowElement(Lite<IEntity> lite) { return new ResultRowProxy(RowElementLocator(lite).WaitVisible()); } private WebElementLocator RowElementLocator(Lite<IEntity> lite) { return this.Element.WithLocator(By.CssSelector("tr[data-entity='{0}']".FormatWith(lite.Key()))); } public List<Lite<IEntity>> SelectedEntities() { return RowsLocator.FindElements() .Where(tr => tr.IsElementPresent(By.CssSelector("input.sf-td-selection:checked"))) .Select(a => Lite.Parse<IEntity>(a.GetAttribute("data-entity"))) .ToList(); } public WebElementLocator CellElement(int rowIndex, string token) { var columnIndex = GetColumnIndex(token); return RowElement(rowIndex).CellElement(columnIndex); } public WebElementLocator CellElement(Lite<IEntity> lite, string token) { var columnIndex = GetColumnIndex(token); return RowElement(lite).CellElement(columnIndex); } public int GetColumnIndex(string token) { var tokens = this.GetColumnTokens(); var index = tokens.IndexOf(token); if (index == -1) throw new InvalidOperationException("Token {0} not found between {1}".FormatWith(token, tokens.NotNull().CommaAnd())); return index; } public void SelectRow(int rowIndex) { RowElement(rowIndex).SelectedCheckbox.Find().Click(); } public void SelectRow(params int[] rowIndexes) { foreach (var index in rowIndexes) SelectRow(index); } public void SelectRow(Lite<IEntity> lite) { RowElement(lite).SelectedCheckbox.Find().Click(); } public WebElementLocator HeaderElement { get { return this.Element.WithLocator(By.CssSelector("thead > tr > th")); } } public string[] GetColumnTokens() { var ths = this.Element.FindElements(By.CssSelector("thead > tr > th")).ToList(); return ths.Select(a => a.GetAttribute("data-column-name")).ToArray(); } public WebElementLocator HeaderCellElement(string token) { return this.HeaderElement.CombineCss("[data-column-name='{0}']".FormatWith(token)); } public ResultTableProxy OrderBy(string token) { OrderBy(token, OrderType.Ascending); return this; } public ResultTableProxy OrderByDescending(string token) { OrderBy(token, OrderType.Descending); return this; } public ResultTableProxy ThenBy(string token) { OrderBy(token, OrderType.Ascending, thenBy: true); return this; } public ResultTableProxy ThenByDescending(string token) { OrderBy(token, OrderType.Descending, thenBy: true); return this; } private void OrderBy(string token, OrderType orderType, bool thenBy = false) { do { SearchControl.WaitSearchCompleted(() => { Actions action = new Actions(Selenium); if (thenBy) action.KeyDown(Keys.Shift); HeaderCellElement(token).Find().Click(); if (thenBy) action.KeyUp(Keys.Shift); }); } while (!HeaderCellElement(token).CombineCss(SortSpan(orderType)).IsPresent()); } public bool HasColumn(string token) { return HeaderCellElement(token).IsPresent(); } public void RemoveColumn(string token) { var headerLocator = HeaderCellElement(token); headerLocator.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.CssSelector(".sf-remove-header")).Click(); headerLocator.WaitNoPresent(); } public WebElementLocator EntityLink(Lite<IEntity> lite) { var entityIndex = GetColumnIndex("Entity"); return RowElement(lite).EntityLink(entityIndex); } public WebElementLocator EntityLink(int rowIndex) { var entityIndex = GetColumnIndex("Entity"); return RowElement(rowIndex).EntityLink(entityIndex); } public FramePageProxy<T> EntityClickInPlace<T>(Lite<T> lite) where T : Entity { EntityLink(lite).Find().Click(); return new FramePageProxy<T>(this.Selenium); } public FramePageProxy<T> EntityClickInPlace<T>(int rowIndex) where T : Entity { EntityLink(rowIndex).Find().Click(); return new FramePageProxy<T>(this.Selenium); } public FrameModalProxy<T> EntityClick<T>(Lite<T> lite) where T : Entity { var element = EntityLink(lite).Find().CaptureOnClick(); return new FrameModalProxy<T>(element); } public void WaitRows(int rows) { this.Selenium.Wait(() => this.RowsCount() == rows); } public FrameModalProxy<T> EntityClick<T>(int rowIndex) where T : Entity { var element = EntityLink(rowIndex).Find().CaptureOnClick(); return new FrameModalProxy<T>(element); } public FramePageProxy<T> EntityClickNormalPage<T>(Lite<T> lite) where T : Entity { EntityLink(lite).Find().Click(); return new FramePageProxy<T>(this.Element.GetDriver()); } public FramePageProxy<T> EntityClickNormalPage<T>(int rowIndex) where T : Entity { EntityLink(rowIndex).Find().Click(); return new FramePageProxy<T>(this.Element.GetDriver()); } public EntityContextMenuProxy EntityContextMenu(int rowIndex, string columnToken = "Entity") { CellElement(rowIndex, columnToken).Find().ContextClick(); var element = this.SearchControl.WaitContextMenu(); return new EntityContextMenuProxy(this, element); } public EntityContextMenuProxy EntityContextMenu(Lite<Entity> lite, string columnToken = "Entity") { CellElement(lite, columnToken).Find().ContextClick(); var element = this.SearchControl.WaitContextMenu(); return new EntityContextMenuProxy(this, element); } public int RowsCount() { return this.Element.FindElements(By.CssSelector("tbody > tr[data-entity]")).Count; } public Lite<Entity> EntityInIndex(int rowIndex) { var result = this.Element.FindElement(By.CssSelector("tbody > tr:nth-child(" + (rowIndex + 1) + ")")).GetAttribute("data-entity"); return Lite.Parse(result); } public bool IsHeaderMarkedSorted(string token) { return IsHeaderMarkedSorted(token, OrderType.Ascending) || IsHeaderMarkedSorted(token, OrderType.Descending); } public bool IsHeaderMarkedSorted(string token, OrderType orderType) { return HeaderCellElement(token).CombineCss(SortSpan(orderType)).IsPresent(); } private static string SortSpan(OrderType orderType) { return " span.sf-header-sort." + (orderType == OrderType.Ascending ? "asc" : "desc"); } public bool IsElementInCell(int rowIndex, string token, By locator) { return CellElement(rowIndex, token).Find().FindElements(locator).Any(); } public ColumnEditorProxy EditColumnName(string token) { var headerSelector = this.HeaderCellElement(token); headerSelector.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.ClassName("sf-edit-header")).Click(); return SearchControl.ColumnEditor(); } public ColumnEditorProxy AddColumnBefore(string token) { var headerSelector = this.HeaderCellElement(token); headerSelector.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.ClassName("sf-insert-header")).Click(); return SearchControl.ColumnEditor(); } public void RemoveColumnBefore(string token) { var headerSelector = this.HeaderCellElement(token); headerSelector.Find().ContextClick(); SearchControl.WaitContextMenu().FindElement(By.ClassName("sf-remove-header")).Click(); } public void WaitSuccess(Lite<IEntity> lite) => WaitSuccess(new List<Lite<IEntity>> { lite }); public void WaitSuccess(List<Lite<IEntity>> lites) { lites.ForEach(lite => RowElementLocator(lite).CombineCss(".sf-entity-ctxmenu-success").WaitVisible()); } public void WaitNoVisible(Lite<IEntity> lite) => WaitNoVisible(new List<Lite<IEntity>> { lite }); public void WaitNoVisible(List<Lite<IEntity>> lites) { lites.ToList().ForEach(lite => RowElementLocator(lite).WaitNoVisible()); } } public class ResultRowProxy { public IWebElement RowElement; public ResultRowProxy(IWebElement rowElement) { this.RowElement = rowElement; } public WebElementLocator SelectedCheckbox => new WebElementLocator(RowElement, By.CssSelector("input.sf-td-selection")); public WebElementLocator CellElement(int columnIndex) => new WebElementLocator(RowElement, By.CssSelector("td:nth-child({0})".FormatWith(columnIndex + 1))); public WebElementLocator EntityLink(int entityColumnIndex) => CellElement(entityColumnIndex).CombineCss("> a"); } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Algo File: OrderLogHelper.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Reasons for orders cancelling in the orders log. /// </summary> public enum OrderLogCancelReasons { /// <summary> /// The order re-registration. /// </summary> ReRegistered, /// <summary> /// Cancel order. /// </summary> Canceled, /// <summary> /// Group canceling of orders. /// </summary> GroupCanceled, /// <summary> /// The sign of deletion of order residual due to cross-trade. /// </summary> CrossTrade, } /// <summary> /// Building order book by the orders log. /// </summary> public static class OrderLogHelper { /// <summary> /// To check, does the string contain the order registration. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains the order registration, otherwise, <see langword="false" />.</returns> public static bool IsOrderLogRegistered(this ExecutionMessage item) { if (item == null) throw new ArgumentNullException(nameof(item)); return item.OrderState == OrderStates.Active && item.TradePrice == null; } /// <summary> /// To check, does the string contain the order registration. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains the order registration, otherwise, <see langword="false" />.</returns> public static bool IsRegistered(this OrderLogItem item) { return item.ToMessage().IsOrderLogRegistered(); } /// <summary> /// To check, does the string contain the cancelled order. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contain the cancelled order, otherwise, <see langword="false" />.</returns> public static bool IsOrderLogCanceled(this ExecutionMessage item) { if (item == null) throw new ArgumentNullException(nameof(item)); return item.OrderState == OrderStates.Done && item.TradePrice == null; } /// <summary> /// To check, does the string contain the cancelled order. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contain the cancelled order, otherwise, <see langword="false" />.</returns> public static bool IsCanceled(this OrderLogItem item) { return item.ToMessage().IsOrderLogCanceled(); } /// <summary> /// To check, does the string contain the order matching. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains order matching, otherwise, <see langword="false" />.</returns> public static bool IsOrderLogMatched(this ExecutionMessage item) { if (item == null) throw new ArgumentNullException(nameof(item)); return item.TradeId != null; } /// <summary> /// To check, does the string contain the order matching. /// </summary> /// <param name="item">Order log item.</param> /// <returns><see langword="true" />, if the string contains order matching, otherwise, <see langword="false" />.</returns> public static bool IsMatched(this OrderLogItem item) { return item.ToMessage().IsOrderLogMatched(); } /// <summary> /// To get the reason for cancelling order in orders log. /// </summary> /// <param name="item">Order log item.</param> /// <returns>The reason for order cancelling in order log.</returns> public static OrderLogCancelReasons GetOrderLogCancelReason(this ExecutionMessage item) { if (!item.IsOrderLogCanceled()) throw new ArgumentException(LocalizedStrings.Str937, nameof(item)); if (item.OrderStatus == null) throw new ArgumentException(LocalizedStrings.Str938, nameof(item)); var status = (int)item.OrderStatus; if (status.HasBits(0x100000)) return OrderLogCancelReasons.ReRegistered; else if (status.HasBits(0x200000)) return OrderLogCancelReasons.Canceled; else if (status.HasBits(0x400000)) return OrderLogCancelReasons.GroupCanceled; else if (status.HasBits(0x800000)) return OrderLogCancelReasons.CrossTrade; else throw new ArgumentOutOfRangeException(nameof(item), status, LocalizedStrings.Str939); } /// <summary> /// To get the reason for cancelling order in orders log. /// </summary> /// <param name="item">Order log item.</param> /// <returns>The reason for order cancelling in order log.</returns> public static OrderLogCancelReasons GetCancelReason(this OrderLogItem item) { return item.ToMessage().GetOrderLogCancelReason(); } private sealed class DepthEnumerable : SimpleEnumerable<QuoteChangeMessage>//, IEnumerableEx<QuoteChangeMessage> { private sealed class DepthEnumerator : IEnumerator<QuoteChangeMessage> { private readonly TimeSpan _interval; private readonly IEnumerator<ExecutionMessage> _itemsEnumerator; private readonly IOrderLogMarketDepthBuilder _builder; private readonly int _maxDepth; public DepthEnumerator(IEnumerable<ExecutionMessage> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval, int maxDepth) { if (builder == null) throw new ArgumentNullException(nameof(builder)); if (items == null) throw new ArgumentNullException(nameof(items)); if (maxDepth < 1) throw new ArgumentOutOfRangeException(nameof(maxDepth), maxDepth, LocalizedStrings.Str941); _itemsEnumerator = items.GetEnumerator(); _builder = builder; _interval = interval; _maxDepth = maxDepth; } public QuoteChangeMessage Current { get; private set; } bool IEnumerator.MoveNext() { while (_itemsEnumerator.MoveNext()) { var item = _itemsEnumerator.Current; //if (_builder == null) // _builder = new OrderLogMarketDepthBuilder(new QuoteChangeMessage { SecurityId = item.SecurityId, IsSorted = true }, _maxDepth); if (!_builder.Update(item)) continue; if (Current != null && (_builder.Depth.ServerTime - Current.ServerTime) < _interval) continue; Current = (QuoteChangeMessage)_builder.Depth.Clone(); if (_maxDepth < int.MaxValue) { //Current.MaxDepth = _maxDepth; Current.Bids = Current.Bids.Take(_maxDepth).ToArray(); Current.Asks = Current.Asks.Take(_maxDepth).ToArray(); } return true; } Current = null; return false; } public void Reset() { _itemsEnumerator.Reset(); Current = null; } object IEnumerator.Current => Current; void IDisposable.Dispose() { Reset(); _itemsEnumerator.Dispose(); } } //private readonly IEnumerableEx<ExecutionMessage> _items; public DepthEnumerable(IEnumerable<ExecutionMessage> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval, int maxDepth) : base(() => new DepthEnumerator(items, builder, interval, maxDepth)) { if (items == null) throw new ArgumentNullException(nameof(items)); if (interval < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(interval), interval, LocalizedStrings.Str940); //_items = items; } //int IEnumerableEx.Count => _items.Count; } /// <summary> /// Build market depths from order log. /// </summary> /// <param name="items">Orders log lines.</param> /// <param name="builder">Order log to market depth builder.</param> /// <param name="interval">The interval of the order book generation. The default is <see cref="TimeSpan.Zero"/>, which means order books generation at each new string of orders log.</param> /// <param name="maxDepth">The maximal depth of order book. The default is <see cref="Int32.MaxValue"/>, which means endless depth.</param> /// <returns>Market depths.</returns> public static IEnumerable<MarketDepth> ToMarketDepths(this IEnumerable<OrderLogItem> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval = default(TimeSpan), int maxDepth = int.MaxValue) { var first = items.FirstOrDefault(); if (first == null) return Enumerable.Empty<MarketDepth>(); return items.ToMessages<OrderLogItem, ExecutionMessage>() .ToMarketDepths(builder, interval) .ToEntities<QuoteChangeMessage, MarketDepth>(first.Order.Security); } /// <summary> /// Build market depths from order log. /// </summary> /// <param name="items">Orders log lines.</param> /// <param name="builder">Order log to market depth builder.</param> /// <param name="interval">The interval of the order book generation. The default is <see cref="TimeSpan.Zero"/>, which means order books generation at each new string of orders log.</param> /// <param name="maxDepth">The maximal depth of order book. The default is <see cref="Int32.MaxValue"/>, which means endless depth.</param> /// <returns>Market depths.</returns> public static IEnumerable<QuoteChangeMessage> ToMarketDepths(this IEnumerable<ExecutionMessage> items, IOrderLogMarketDepthBuilder builder, TimeSpan interval = default(TimeSpan), int maxDepth = int.MaxValue) { return new DepthEnumerable(items, builder, interval, maxDepth); } private sealed class OrderLogTickEnumerable : SimpleEnumerable<ExecutionMessage>//, IEnumerableEx<ExecutionMessage> { private sealed class OrderLogTickEnumerator : IEnumerator<ExecutionMessage> { private readonly IEnumerator<ExecutionMessage> _itemsEnumerator; private readonly Dictionary<long, Tuple<long, Sides>> _trades = new Dictionary<long, Tuple<long, Sides>>(); public OrderLogTickEnumerator(IEnumerable<ExecutionMessage> items) { if (items == null) throw new ArgumentNullException(nameof(items)); _itemsEnumerator = items.GetEnumerator(); } public ExecutionMessage Current { get; private set; } bool IEnumerator.MoveNext() { while (_itemsEnumerator.MoveNext()) { var currItem = _itemsEnumerator.Current; var tradeId = currItem.TradeId; if (tradeId == null) continue; var prevItem = _trades.TryGetValue(tradeId.Value); if (prevItem == null) { _trades.Add(tradeId.Value, Tuple.Create(currItem.SafeGetOrderId(), currItem.Side)); } else { _trades.Remove(tradeId.Value); Current = new ExecutionMessage { ExecutionType = ExecutionTypes.Tick, SecurityId = currItem.SecurityId, TradeId = tradeId, TradePrice = currItem.TradePrice, TradeStatus = currItem.TradeStatus, TradeVolume = currItem.TradeVolume, ServerTime = currItem.ServerTime, LocalTime = currItem.LocalTime, OpenInterest = currItem.OpenInterest, OriginSide = prevItem.Item2 == Sides.Buy ? (prevItem.Item1 > currItem.OrderId ? Sides.Buy : Sides.Sell) : (prevItem.Item1 > currItem.OrderId ? Sides.Sell : Sides.Buy), }; return true; } } Current = null; return false; } void IEnumerator.Reset() { _itemsEnumerator.Reset(); Current = null; } object IEnumerator.Current => Current; void IDisposable.Dispose() { _itemsEnumerator.Dispose(); } } //private readonly IEnumerable<ExecutionMessage> _items; public OrderLogTickEnumerable(IEnumerable<ExecutionMessage> items) : base(() => new OrderLogTickEnumerator(items)) { if (items == null) throw new ArgumentNullException(nameof(items)); //_items = items; } //int IEnumerableEx.Count => _items.Count; } /// <summary> /// To build tick trades from the orders log. /// </summary> /// <param name="items">Orders log lines.</param> /// <returns>Tick trades.</returns> public static IEnumerable<Trade> ToTrades(this IEnumerable<OrderLogItem> items) { var first = items.FirstOrDefault(); if (first == null) return Enumerable.Empty<Trade>(); var ticks = items .Select(i => i.ToMessage()) .ToTicks(); return ticks.Select(m => m.ToTrade(first.Order.Security)); } /// <summary> /// To build tick trades from the orders log. /// </summary> /// <param name="items">Orders log lines.</param> /// <returns>Tick trades.</returns> public static IEnumerable<ExecutionMessage> ToTicks(this IEnumerable<ExecutionMessage> items) { return new OrderLogTickEnumerable(items); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Presentation.Model { using System.Activities.Expressions; using System.Activities.Presentation; using System.Activities.Presentation.Hosting; using System.Activities.Presentation.Internal.PropertyEditing; using System.Activities.Presentation.Services; using System.Activities.Presentation.Validation; using System.Activities.Presentation.View; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime; using System.Text; using Microsoft.Activities.Presentation.Xaml; // This class manages the model tree, provides the root model item and the modelservice // This also provides syncing the model tree with the xaml text // The model service is publishes on the editing context passed to the constructor. [Fx.Tag.XamlVisible(false)] public class ModelTreeManager { internal ModelServiceImpl modelService; EditingContext context; // The value of this dictionary is a WeakReference to ModelItem. // This need to be a WeakReference because if the ModelItem has a strong reference, it // will have a strong reference to the underlying object instance as well. WeakKeyDictionary<object, WeakReference> objectMap; ModelItem rootItem; ImmediateEditingScope immediateEditingScope; Stack<ModelEditingScope> editingScopes; int redoUndoInProgressCount = 0; FeatureManager featureManager; ModelGraphManager graphManager; public ModelTreeManager(EditingContext context) { if (context == null) { throw FxTrace.Exception.AsError(new ArgumentNullException("context")); } this.context = context; // We want to check reference equality for keys in ObjectMap. // If the user overrides Equals method for their class we still want to use referential equality. objectMap = new WeakKeyDictionary<object, WeakReference>(ObjectReferenceEqualityComparer<object>.Default); editingScopes = new Stack<ModelEditingScope>(); this.graphManager = new ModelGraphManager(this); } public event EventHandler<EditingScopeEventArgs> EditingScopeCompleted; // Private event only for EditingScope. private event EventHandler<ModelItemsRemovedEventArgs> ModelItemsRemoved; private event EventHandler<ModelItemsAddedEventArgs> ModelItemsAdded; public ModelItem Root { get { return this.rootItem; } } internal EditingContext Context { get { return this.context; } } FeatureManager FeatureManager { get { if (this.featureManager == null) { this.featureManager = this.context.Services.GetService<FeatureManager>(); } return this.featureManager; } } internal bool RedoUndoInProgress { get { return this.redoUndoInProgressCount > 0; } } internal void StartTracking() { redoUndoInProgressCount--; } internal void StopTracking() { redoUndoInProgressCount++; } public ModelItem CreateModelItem(ModelItem parent, object instance) { if (instance == null) { throw FxTrace.Exception.AsError(new ArgumentNullException("instance")); } ModelItem retval; Type instanceType = instance.GetType(); object[] result = new object[2] { false, false }; Type[] interfaces = instanceType.FindInterfaces(ModelTreeManager.CheckInterface, result); bool isList = (bool)result[0]; bool isDictionary = (bool)result[1]; if (isDictionary) { foreach (Type type in interfaces) { if (type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { // To expose one more property, a collection of MutableKeyValuePairs, to the model tree. TypeDescriptor.AddProvider(new DictionaryTypeDescriptionProvider(instanceType), instance); break; } } ModelItemDictionary modelItem = new ModelItemDictionaryImpl(this, instance.GetType(), instance, parent); retval = modelItem; } else if (isList) { ModelItemCollectionImpl modelItem = new ModelItemCollectionImpl(this, instance.GetType(), instance, parent); retval = modelItem; } else { retval = new ModelItemImpl(this, instance.GetType(), instance, parent); } if (!((instance is ValueType) || (instance is string))) { // // ValueType do not have a concept of shared reference, they are always copied. // strings are immutatable, therefore the risk of making all shared string references to different // string ModelItems is low. // // To special case string is because underlying OM are sharing string objects for DisplayName across // Different activity object instances. These shared references is causing memory leak because of bugs. // // We will need to fix these issues in Beta2. // objectMap[instance] = new WeakReference(retval); } if (this.FeatureManager != null) { this.FeatureManager.InitializeFeature(instance.GetType()); } return retval; } static bool CheckInterface(Type type, object result) { object[] values = (object[])result; if (typeof(IList).IsAssignableFrom(type)) { values[0] = true; return true; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { values[0] = true; return true; } if (typeof(IDictionary).IsAssignableFrom(type)) { values[1] = true; return true; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { values[1] = true; return true; } return false; } public void Load(object rootInstance) { if (rootInstance == null) { throw FxTrace.Exception.AsError(new ArgumentNullException("rootInstance")); } objectMap.Clear(); ModelItem oldRoot = this.rootItem; this.rootItem = WrapAsModelItem(rootInstance); this.graphManager.OnRootChanged(oldRoot, this.rootItem); if (this.modelService == null) { this.modelService = new ModelServiceImpl(this); this.context.Services.Publish<ModelService>(modelService); } } // This methods clears the value of a property , if the property is // a reference type then its set to null, if its a value type the // property value is reset to the default. this also clears the sub ModelItem corresponding // to the old value from the parent ModelItem's modelPropertyStore. internal void ClearValue(ModelPropertyImpl modelProperty) { Fx.Assert(modelProperty != null, "modelProperty should not be null"); Fx.Assert(modelProperty.Parent is IModelTreeItem, "modelProperty.Parent should be an IModelTreeItem"); ModelItem newValueModelItem = null; newValueModelItem = WrapAsModelItem(modelProperty.DefaultValue); PropertyChange propertyChange = new PropertyChange() { Owner = modelProperty.Parent, PropertyName = modelProperty.Name, OldValue = modelProperty.Value, NewValue = newValueModelItem, ModelTreeManager = this }; AddToCurrentEditingScope(propertyChange); } internal void CollectionAdd(ModelItemCollectionImpl dataModelItemCollection, ModelItem item) { CollectionInsert(dataModelItemCollection, -1, item); } internal void CollectionInsert(ModelItemCollectionImpl dataModelItemCollection, int index, ModelItem item) { Fx.Assert(dataModelItemCollection != null, "collection should not be null"); CollectionChange change = new CollectionChange() { Collection = dataModelItemCollection, Item = item, Index = index, ModelTreeManager = this, Operation = CollectionChange.OperationType.Insert }; AddToCurrentEditingScope(change); } internal void CollectionClear(ModelItemCollectionImpl modelItemCollectionImpl) { Fx.Assert(modelItemCollectionImpl != null, "collection should not be null"); Fx.Assert(this.modelService != null, "modelService should not be null"); List<ModelItem> removedItems = new List<ModelItem>(); removedItems.AddRange(modelItemCollectionImpl); using (ModelEditingScope editingScope = CreateEditingScope(SR.CollectionClearEditingScopeDescription)) { foreach (ModelItem modelItem in removedItems) { this.CollectionRemove(modelItemCollectionImpl, modelItem); } editingScope.Complete(); } this.modelService.OnModelItemsRemoved(removedItems); } internal void NotifyCollectionInsert(ModelItem item, ModelChangeInfo changeInfo) { this.modelService.OnModelItemAdded(item, changeInfo); } internal void CollectionRemove(ModelItemCollectionImpl dataModelItemCollection, ModelItem item) { CollectionRemove(dataModelItemCollection, item, -1); } internal void CollectionRemoveAt(ModelItemCollectionImpl dataModelItemCollection, int index) { ModelItem item = dataModelItemCollection[index]; CollectionRemove(dataModelItemCollection, item, index); } private void CollectionRemove(ModelItemCollectionImpl dataModelItemCollection, ModelItem item, int index) { Fx.Assert(dataModelItemCollection != null, "collection should not be null"); CollectionChange change = new CollectionChange() { Collection = dataModelItemCollection, Item = item, Index = index, ModelTreeManager = this, Operation = CollectionChange.OperationType.Delete }; AddToCurrentEditingScope(change); } internal void NotifyCollectionRemove(ModelItem item, ModelChangeInfo changeInfo) { this.modelService.OnModelItemRemoved(item, changeInfo); } internal void DictionaryClear(ModelItemDictionaryImpl modelDictionary) { Fx.Assert(modelDictionary != null, "dictionary should not be null"); Fx.Assert(this.modelService != null, "modelService should not be null"); ModelItem[] keys = modelDictionary.Keys.ToArray<ModelItem>(); using (ModelEditingScope editingScope = CreateEditingScope(SR.DictionaryClearEditingScopeDescription)) { foreach (ModelItem key in keys) { this.DictionaryRemove(modelDictionary, key); } editingScope.Complete(); } } internal void DictionaryEdit(ModelItemDictionaryImpl dataModelItemDictionary, ModelItem key, ModelItem newValue, ModelItem oldValue) { Fx.Assert(dataModelItemDictionary != null, "dictionary should not be null"); Fx.Assert(this.modelService != null, "modelService should not be null"); DictionaryEditChange change = new DictionaryEditChange() { Dictionary = dataModelItemDictionary, Key = key, NewValue = newValue, OldValue = oldValue, ModelTreeManager = this }; AddToCurrentEditingScope(change); } internal void DictionaryAdd(ModelItemDictionaryImpl dataModelItemDictionary, ModelItem key, ModelItem value) { Fx.Assert(dataModelItemDictionary != null, "dictionary should not be null"); Fx.Assert(this.modelService != null, "modelService should not be null"); DictionaryChange change = new DictionaryChange() { Dictionary = dataModelItemDictionary, Key = key, Value = value, Operation = DictionaryChange.OperationType.Insert, ModelTreeManager = this }; AddToCurrentEditingScope(change); } internal void OnPropertyEdgeAdded(string propertyName, ModelItem from, ModelItem to) { this.graphManager.OnPropertyEdgeAdded(propertyName, from, to); } internal void OnItemEdgeAdded(ModelItem from, ModelItem to) { this.graphManager.OnItemEdgeAdded(from, to); } internal void OnPropertyEdgeRemoved(string propertyName, ModelItem from, ModelItem to) { this.graphManager.OnPropertyEdgeRemoved(propertyName, from, to); } internal void OnItemEdgeRemoved(ModelItem from, ModelItem to) { this.graphManager.OnItemEdgeRemoved(from, to); } internal void DictionaryRemove(ModelItemDictionaryImpl dataModelItemDictionary, ModelItem key) { Fx.Assert(dataModelItemDictionary != null, "dictionary should not be null"); Fx.Assert(this.modelService != null, "modelService should not be null"); ModelItem value = dataModelItemDictionary[key]; DictionaryChange change = new DictionaryChange() { Dictionary = dataModelItemDictionary, Key = key, Value = value, Operation = DictionaryChange.OperationType.Delete, ModelTreeManager = this }; AddToCurrentEditingScope(change); } internal static IEnumerable<ModelItem> Find(ModelItem startingItem, Predicate<ModelItem> matcher, bool skipCollapsedAndUnrootable) { Fx.Assert(startingItem != null, "starting item should not be null"); Fx.Assert(matcher != null, "matching predicate should not be null"); WorkflowViewService viewService = startingItem.GetEditingContext().Services.GetService<ViewService>() as WorkflowViewService; if (skipCollapsedAndUnrootable) { Fx.Assert(viewService != null, "ViewService must be available in order to skip exploring ModelItems whose views are collapsed."); } Predicate<ModelItem> shouldSearchThroughProperties = (currentModelItem) => (!skipCollapsedAndUnrootable) || (!typeof(WorkflowViewElement).IsAssignableFrom(viewService.GetDesignerType(currentModelItem.ItemType))) || (ViewUtilities.IsViewExpanded(currentModelItem, startingItem.GetEditingContext()) && viewService.ShouldAppearOnBreadCrumb(currentModelItem, true)); List<ModelItem> foundItems = new List<ModelItem>(); Queue<ModelItem> modelItems = new Queue<ModelItem>(); modelItems.Enqueue(startingItem); HashSet<ModelItem> alreadyVisited = new HashSet<ModelItem>(); while (modelItems.Count > 0) { ModelItem currentModelItem = modelItems.Dequeue(); if (currentModelItem == null) { continue; } if (matcher(currentModelItem)) { foundItems.Add(currentModelItem); } List<ModelItem> neighbors = GetNeighbors(currentModelItem, shouldSearchThroughProperties); foreach (ModelItem neighbor in neighbors) { if (!alreadyVisited.Contains(neighbor)) { alreadyVisited.Add(neighbor); modelItems.Enqueue(neighbor); } } } return foundItems; } private static List<ModelItem> GetNeighbors(ModelItem currentModelItem, Predicate<ModelItem> extraShouldSearchThroughProperties) { List<ModelItem> neighbors = new List<ModelItem>(); // do not search through Type and its derivatives if (typeof(Type).IsAssignableFrom(currentModelItem.ItemType)) { return neighbors; } ModelItemCollection collection = currentModelItem as ModelItemCollection; if (collection != null) { foreach (ModelItem modelItem in collection) { if (modelItem != null) { neighbors.Add(modelItem); } } } else { ModelItemDictionary dictionary = currentModelItem as ModelItemDictionary; if (dictionary != null) { foreach (KeyValuePair<ModelItem, ModelItem> kvp in dictionary) { ModelItem miKey = kvp.Key; if (miKey != null) { neighbors.Add(miKey); } ModelItem miValue = kvp.Value; if (miValue != null) { neighbors.Add(miValue); } } } } if (extraShouldSearchThroughProperties(currentModelItem)) { ModelPropertyCollection modelProperties = currentModelItem.Properties; foreach (ModelProperty property in modelProperties) { if (currentModelItem is ModelItemDictionary && string.Equals(property.Name, "ItemsCollection")) { // Don't search the item collection since we already search the items above. continue; } // we don't want to even try to get the value for a value type property // because that will create a new ModelItem every time. // System.Type has properties that throw when we try to get value // we don't want to expand system.type further during a search. if (typeof(Type).IsAssignableFrom(property.PropertyType) || property.PropertyType.IsValueType) { continue; } else { if (property.Value != null) { neighbors.Add(property.Value); } } } } return neighbors; } internal static ModelItem FindFirst(ModelItem startingItem, Predicate<ModelItem> matcher) { return FindFirst(startingItem, matcher, (m) => true); } internal static ModelItem FindFirst(ModelItem startingItem, Predicate<ModelItem> matcher, Predicate<ModelItem> extraShouldSearchThroughProperties) { Fx.Assert(startingItem != null, "starting item should not be null"); Fx.Assert(matcher != null, "matching predicate should not be null"); Fx.Assert(extraShouldSearchThroughProperties != null, "extraShouldSearchThroughProperties should not be null"); ModelItem foundItem = null; Queue<ModelItem> modelItems = new Queue<ModelItem>(); modelItems.Enqueue(startingItem); HashSet<ModelItem> alreadyVisited = new HashSet<ModelItem>(); while (modelItems.Count > 0) { ModelItem currentModelItem = modelItems.Dequeue(); if (currentModelItem == null) { continue; } if (matcher(currentModelItem)) { foundItem = currentModelItem; break; } List<ModelItem> neighbors = GetNeighbors(currentModelItem, extraShouldSearchThroughProperties); foreach (ModelItem neighbor in neighbors) { if (!alreadyVisited.Contains(neighbor)) { alreadyVisited.Add(neighbor); modelItems.Enqueue(neighbor); } } } return foundItem; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If the property getter threw here we dont want to crash, we just dont want to wrap that property value")] [SuppressMessage("Reliability", "Reliability108:IsFatalRule", Justification = "If the property getter threw here we dont want to crash, we just dont want to wrap that property value")] internal ModelItem GetValue(ModelPropertyImpl dataModelProperty) { Fx.Assert(dataModelProperty != null, "modelproperty should not be null"); Fx.Assert(dataModelProperty.Parent is IModelTreeItem, "modelproperty.Parent should be an IModelTreeItem"); IModelTreeItem parent = (IModelTreeItem)dataModelProperty.Parent; ModelItem value; // always reevaluate attached properties. the cache in attached properties case is only to remember the old value. if (!dataModelProperty.IsAttached && parent.ModelPropertyStore.ContainsKey(dataModelProperty.Name)) { value = parent.ModelPropertyStore[dataModelProperty.Name]; } // Create a ModelItem on demand for the value of the property. else { try { value = WrapAsModelItem(dataModelProperty.PropertyDescriptor.GetValue(parent.ModelItem.GetCurrentValue())); } catch (System.Exception) { // GetValue throws an exception if Value is not available value = null; } if (value != null) { if (!dataModelProperty.IsAttached) { parent.ModelPropertyStore.Add(dataModelProperty.Name, value); this.graphManager.OnPropertyEdgeAdded(dataModelProperty.Name, (ModelItem)parent, value); } } } return value; } internal ModelItem SetValue(ModelPropertyImpl modelProperty, object value) { Fx.Assert(modelProperty != null, "modelProperty should not be null"); ModelItem newValueModelItem = null; RefreshPropertiesAttribute refreshPropertiesAttribute = ExtensibilityAccessor.GetAttribute<RefreshPropertiesAttribute>(modelProperty.Attributes); if (refreshPropertiesAttribute != null && refreshPropertiesAttribute.RefreshProperties == RefreshProperties.All) { Dictionary<string, ModelItem> modelPropertyStore = ((IModelTreeItem)modelProperty.Parent).ModelPropertyStore; Dictionary<string, ModelItem> removedModelItems = new Dictionary<string, ModelItem>(modelPropertyStore); modelPropertyStore.Clear(); foreach (KeyValuePair<string, ModelItem> kvp in removedModelItems) { if (kvp.Value != null) { this.OnPropertyEdgeRemoved(kvp.Key, modelProperty.Parent, kvp.Value); } } } if (value is ModelItem) { newValueModelItem = (ModelItem)value; } else { newValueModelItem = WrapAsModelItem(value); } // dont do deferred updates for attached properties if (modelProperty.IsAttached) { modelProperty.SetValueCore(newValueModelItem); } else { PropertyChange propertyChange = new PropertyChange() { Owner = modelProperty.Parent, PropertyName = modelProperty.Name, OldValue = modelProperty.Value, NewValue = newValueModelItem, ModelTreeManager = this }; AddToCurrentEditingScope(propertyChange); } return newValueModelItem; } internal void AddToCurrentEditingScope(Change change) { EditingScope editingScope; if (editingScopes.Count > 0) { editingScope = (EditingScope)editingScopes.Peek(); // Automatic generated change during apply changes of Redo/Undo should be ignored. if (!RedoUndoInProgress) { editingScope.Changes.Add(change); } } else { //edit operation without editingscope create an editing scope and complete it immediately. editingScope = CreateEditingScope(change.Description); editingScope.Changes.Add(change); try { editingScope.Complete(); } catch { editingScope.Revert(); throw; } } } internal bool CanCreateImmediateEditingScope() { return this.editingScopes.Count == 0 && !this.Context.Services.GetService<UndoEngine>().IsBookmarkInPlace; } internal EditingScope CreateEditingScope(string description, bool shouldApplyChangesImmediately) { EditingScope editingScope = null; EditingScope outerScope = editingScopes.Count > 0 ? (EditingScope)editingScopes.Peek() : null; if (shouldApplyChangesImmediately) { // shouldApplyChangesImmediately won't have any effect if outer scope exists if (outerScope != null) { return null; } this.immediateEditingScope = context.Services.GetRequiredService<UndoEngine>().CreateImmediateEditingScope(description, this); editingScope = this.immediateEditingScope; // ImmediateEditingScope should not be pushed onto the editingScopes, // otherwise it will become delay applied instead of immediate applied. } else { editingScope = new EditingScope(this, outerScope); editingScopes.Push(editingScope); } editingScope.Description = description; return editingScope; } internal EditingScope CreateEditingScope(string description) { return this.CreateEditingScope(description, false); } internal void NotifyPropertyChange(ModelPropertyImpl dataModelProperty, ModelChangeInfo changeInfo) { modelService.OnModelPropertyChanged(dataModelProperty, changeInfo); } internal void SyncModelAndText() { // Place holder for xaml generation ModelTreeManager now is instance only. } internal ModelItem WrapAsModelItem(object instance) { ModelItem modelItem = GetModelItem(instance); if (null != instance && null == modelItem) { modelItem = CreateModelItem(null, instance); } return modelItem; } internal ModelItem GetModelItem(object instance) { return this.GetModelItem(instance, false); } public ModelItem GetModelItem(object instance, bool shouldExpandModelTree) { if (instance == null) { return null; } ModelItem modelItem = null; WeakReference mappedModelItem = null; objectMap.TryGetValue(instance, out mappedModelItem); if (mappedModelItem != null) { modelItem = (ModelItem)mappedModelItem.Target; } if (modelItem == null && shouldExpandModelTree) { if (instance is ValueType || instance is string) { return null; } modelItem = FindFirst(this.Root, (m) => { return m.GetCurrentValue() == instance; }); } return modelItem; } internal void RegisterModelTreeChangeEvents(EditingScope editingScope) { this.ModelItemsAdded += editingScope.EditingScope_ModelItemsAdded; this.ModelItemsRemoved += editingScope.EditingScope_ModelItemsRemoved; } internal void UnregisterModelTreeChangeEvents(EditingScope editingScope) { this.ModelItemsAdded -= editingScope.EditingScope_ModelItemsAdded; this.ModelItemsRemoved -= editingScope.EditingScope_ModelItemsRemoved; } // The method should be called when an EditingScope completed. But if the EditingScope has an outer EditingScope, // Changes are not applied, so itemsAdded and itemsRemoved won't update until the outer EditingScope.Complete() internal void OnEditingScopeCompleted(EditingScope modelEditingScopeImpl) { if (editingScopes.Contains(modelEditingScopeImpl)) { editingScopes.Pop(); } if (editingScopes.Count == 0 && this.immediateEditingScope != null) { // if immediateEditingScope is in place and last nested normal editing scope completes, // we copy the information from the nested normal editing scope to the immediateEditingScope // and put the Changes into undo engine, so that when immediateEditingScope completes the undo unit // generated by nested editing scope will be collected as one undo unit if (this.immediateEditingScope != modelEditingScopeImpl) { UndoEngine undoEngine = this.Context.Services.GetService<UndoEngine>(); this.immediateEditingScope.Changes.AddRange(modelEditingScopeImpl.Changes); this.immediateEditingScope.HasModelChanges = this.immediateEditingScope.HasModelChanges || modelEditingScopeImpl.HasModelChanges; this.immediateEditingScope.HasEffectiveChanges = this.immediateEditingScope.HasEffectiveChanges || modelEditingScopeImpl.HasEffectiveChanges; this.immediateEditingScope.HandleModelItemsAdded(modelEditingScopeImpl.ItemsAdded); this.immediateEditingScope.HandleModelItemsRemoved(modelEditingScopeImpl.ItemsRemoved); if (modelEditingScopeImpl.HasEffectiveChanges) { if (!this.RedoUndoInProgress && !modelEditingScopeImpl.SuppressUndo && undoEngine != null) { undoEngine.AddUndoUnit(new EditingScopeUndoUnit(this.Context, this, modelEditingScopeImpl)); } } } } if (editingScopes.Count == 0 && !(modelEditingScopeImpl is ImmediateEditingScope) && modelEditingScopeImpl.HasModelChanges) { if (!modelEditingScopeImpl.SuppressValidationOnComplete) { ValidationService validationService = this.Context.Services.GetService<ValidationService>(); if (validationService != null) { validationService.ValidateWorkflow(ValidationReason.ModelChange); } } } if (this.immediateEditingScope == modelEditingScopeImpl) { this.immediateEditingScope = null; } // if the outer most scope completed notify listeners if (this.EditingScopeCompleted != null && editingScopes.Count == 0 && this.immediateEditingScope == null) { this.EditingScopeCompleted(this, new EditingScopeEventArgs() { EditingScope = modelEditingScopeImpl }); } Fx.Assert(editingScopes.Count == 0 || (modelEditingScopeImpl.ItemsAdded.Count == 0 && modelEditingScopeImpl.ItemsRemoved.Count == 0), "Inner editing scope shouldn't have changes applied."); #if DEBUG this.graphManager.VerifyBackPointers(); #endif } internal bool CanEditingScopeComplete(EditingScope modelEditingScopeImpl) { ReadOnlyState readOnlyState = this.Context.Items.GetValue<ReadOnlyState>(); return (modelEditingScopeImpl == editingScopes.Peek()) && (readOnlyState == null || !readOnlyState.IsReadOnly); } internal void OnEditingScopeReverted(EditingScope modelEditingScopeImpl) { if (editingScopes.Contains(modelEditingScopeImpl)) { editingScopes.Pop(); } if (this.immediateEditingScope == modelEditingScopeImpl) { this.immediateEditingScope = null; } } internal static IList<ModelItem> DepthFirstSearch(ModelItem currentItem, Predicate<Type> filter, Predicate<ModelItem> shouldTraverseSubTree, bool preOrder) { IList<ModelItem> foundItems = new List<ModelItem>(); HashSet<ModelItem> alreadyVisitedItems = new HashSet<ModelItem>(); RecursiveDepthFirstSearch(currentItem, filter, shouldTraverseSubTree, foundItems, alreadyVisitedItems, preOrder); return foundItems; } private static void RecursiveDepthFirstSearch(ModelItem currentItem, Predicate<Type> filter, Predicate<ModelItem> shouldTraverseSubTree, IList<ModelItem> foundItems, HashSet<ModelItem> alreadyVisitedItems, bool preOrder) { if (currentItem == null) { return; } if (typeof(Type).IsAssignableFrom(currentItem.ItemType)) { return; } if (currentItem.ItemType.IsGenericType && currentItem.ItemType.GetGenericTypeDefinition() == typeof(Action<>)) { return; } if (!shouldTraverseSubTree(currentItem)) { return; } if (preOrder) { if (filter(currentItem.ItemType)) { foundItems.Add(currentItem); } } alreadyVisitedItems.Add(currentItem); List<ModelItem> neighbors = GetNeighbors(currentItem, (m) => true); foreach (ModelItem neighbor in neighbors) { if (!alreadyVisitedItems.Contains(neighbor)) { RecursiveDepthFirstSearch(neighbor, filter, shouldTraverseSubTree, foundItems, alreadyVisitedItems, preOrder); } } if (!preOrder) { if (filter(currentItem.ItemType)) { foundItems.Add(currentItem); } } } private void OnModelItemsAdded(IEnumerable<ModelItem> addedModelItems) { Fx.Assert(addedModelItems != null, "addedModelItems should not be null."); EventHandler<ModelItemsAddedEventArgs> tempModelItemsAdded = this.ModelItemsAdded; if (tempModelItemsAdded != null) { tempModelItemsAdded(this, new ModelItemsAddedEventArgs(addedModelItems)); } } private void OnModelItemsRemoved(IEnumerable<ModelItem> removedModelItems) { Fx.Assert(removedModelItems != null, "removedModelItems should not be null."); EventHandler<ModelItemsRemovedEventArgs> tempModelItemsRemoved = this.ModelItemsRemoved; if (tempModelItemsRemoved != null) { tempModelItemsRemoved(this, new ModelItemsRemovedEventArgs(removedModelItems)); } } internal class ModelGraphManager : GraphManager<ModelItem, Edge, BackPointer> { private ModelTreeManager modelTreeManager; public ModelGraphManager(ModelTreeManager modelTreeManager) { Fx.Assert(modelTreeManager != null, "modelTreeManager should not be null"); this.modelTreeManager = modelTreeManager; } public void OnPropertyEdgeAdded(string propertyName, ModelItem from, ModelItem to) { base.OnEdgeAdded(new Edge(propertyName, from, to)); } public void OnItemEdgeAdded(ModelItem from, ModelItem to) { base.OnEdgeAdded(new Edge(from, to)); } public void OnPropertyEdgeRemoved(string propertyName, ModelItem from, ModelItem to) { base.OnEdgeRemoved(new Edge(propertyName, from, to)); } public void OnItemEdgeRemoved(ModelItem from, ModelItem to) { base.OnEdgeRemoved(new Edge(from, to)); } public new void OnRootChanged(ModelItem oldRoot, ModelItem newRoot) { base.OnRootChanged(oldRoot, newRoot); } protected override ModelItem Root { get { return this.modelTreeManager.Root; } } protected override IEnumerable<ModelItem> GetVertices() { foreach (WeakReference weakReference in this.modelTreeManager.objectMap.Values) { ModelItem modelItem = weakReference.Target as ModelItem; if (modelItem != null) { yield return modelItem; } } } // This method will not expand any ModelItem protected override IEnumerable<Edge> GetOutEdges(ModelItem vertex) { Fx.Assert(vertex != null, "vertex should not be null"); List<Edge> edges = new List<Edge>(); foreach (KeyValuePair<string, ModelItem> kvp in ((IModelTreeItem)vertex).ModelPropertyStore) { if (kvp.Value != null) { edges.Add(new Edge(kvp.Key, vertex, kvp.Value)); } } ModelItemCollection collection = vertex as ModelItemCollection; if (collection != null) { foreach (ModelItem modelItem in collection.Distinct()) { if (modelItem != null) { edges.Add(new Edge(vertex, modelItem)); } } } ModelItemDictionaryImpl dictionary = vertex as ModelItemDictionaryImpl; if (dictionary != null) { List<ModelItem> items = new List<ModelItem>(dictionary.Keys); items.AddRange(dictionary.Values); items.Add(dictionary.updateKeySavedValue); foreach (ModelItem modelItem in items.Distinct()) { if (modelItem != null) { edges.Add(new Edge(vertex, modelItem)); } } } return edges; } protected override IEnumerable<BackPointer> GetBackPointers(ModelItem vertex) { List<BackPointer> backPointers = new List<BackPointer>(); foreach (ModelItem parent in ((IModelTreeItem)vertex).ItemBackPointers) { backPointers.Add(new BackPointer(vertex, parent)); } foreach (ModelProperty property in vertex.Sources) { backPointers.Add(new BackPointer(property.Name, vertex, property.Parent)); } foreach (BackPointer backPointer in ((IModelTreeItem)vertex).ExtraPropertyBackPointers) { backPointers.Add(backPointer); } return backPointers; } protected override ModelItem GetDestinationVertexFromEdge(Edge edge) { return edge.DestinationVertex; } protected override ModelItem GetSourceVertexFromEdge(Edge edge) { return edge.SourceVertex; } protected override ModelItem GetDestinationVertexFromBackPointer(BackPointer backPointer) { return backPointer.DestinationVertex; } protected override void RemoveAssociatedBackPointer(Edge edge) { if (edge.LinkType == LinkType.Property) { ModelProperty modelProperty = edge.SourceVertex.Properties[edge.PropertyName]; if (modelProperty != null) { ((IModelTreeItem)edge.DestinationVertex).RemoveSource(modelProperty); } else { // in case of custom type descriptor, it may return a list of ModelProperties different from IModelTreeItem.ModelPropertyStore // manually manipulate IModelTreeItem.Sources to remove back pointer ((IModelTreeItem)edge.DestinationVertex).RemoveSource(edge.SourceVertex, edge.PropertyName); } } else { Fx.Assert(edge.LinkType == LinkType.Item, "unknown LinkType"); ((IModelTreeItem)edge.DestinationVertex).RemoveParent(edge.SourceVertex); } } protected override void AddAssociatedBackPointer(Edge edge) { if (edge.LinkType == LinkType.Property) { ModelProperty modelProperty = edge.SourceVertex.Properties[edge.PropertyName]; if (modelProperty != null) { ((IModelTreeItem)edge.DestinationVertex).SetSource(modelProperty); } else { ((IModelTreeItem)edge.DestinationVertex).ExtraPropertyBackPointers.Add(new BackPointer(edge.PropertyName, edge.DestinationVertex, edge.SourceVertex)); } } else { Fx.Assert(edge.LinkType == LinkType.Item, "unknown LinkType"); ((IModelTreeItem)edge.DestinationVertex).SetParent(edge.SourceVertex); } } protected override bool HasBackPointer(Edge edge) { ModelItem from = edge.SourceVertex; if (edge.LinkType == LinkType.Property) { foreach (ModelProperty p in edge.DestinationVertex.Sources) { if (p.Parent == from && p.Name == edge.PropertyName) { return true; } } foreach (BackPointer bp in ((IModelTreeItem)edge.DestinationVertex).ExtraPropertyBackPointers) { if (bp.DestinationVertex == from && bp.PropertyName == edge.PropertyName) { return true; } } return false; } else { Fx.Assert(edge.LinkType == LinkType.Item, "unknown LinkType"); return ((IModelTreeItem)edge.DestinationVertex).ItemBackPointers.Contains(from); } } protected override bool HasAssociatedEdge(BackPointer backPointer) { if (backPointer.LinkType == LinkType.Property) { return ((IModelTreeItem)backPointer.DestinationVertex).ModelPropertyStore[backPointer.PropertyName] == backPointer.SourceVertex; } else { Fx.Assert(backPointer.LinkType == LinkType.Item, "unknown LinkType"); ModelItemCollection collection = backPointer.DestinationVertex as ModelItemCollection; if (collection != null) { return collection.Contains(backPointer.SourceVertex); } ModelItemDictionary dictionary = (ModelItemDictionary)backPointer.DestinationVertex; return dictionary.Keys.Concat(dictionary.Values).Contains(backPointer.SourceVertex); } } protected override void OnVerticesBecameReachable(IEnumerable<ModelItem> reachableVertices) { Fx.Assert(reachableVertices != null, "reachableVertices should not be null"); this.modelTreeManager.OnModelItemsAdded(reachableVertices); } protected override void OnVerticesBecameUnreachable(IEnumerable<ModelItem> unreachableVertices) { Fx.Assert(unreachableVertices != null, "unreachableVertices should not be null"); this.modelTreeManager.OnModelItemsRemoved(unreachableVertices); } } class DictionaryTypeDescriptionProvider : TypeDescriptionProvider { Type type; public DictionaryTypeDescriptionProvider(Type type) : base(TypeDescriptor.GetProvider(type)) { this.type = type; } public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance); return new DictionaryTypeDescriptor(defaultDescriptor, this.type); } } class DictionaryTypeDescriptor : CustomTypeDescriptor { Type type; public DictionaryTypeDescriptor(ICustomTypeDescriptor parent, Type type) : base(parent) { this.type = type; } // Expose one more property, a collection of MutableKeyValuePairs, described by ItemsCollectionPropertyDescriptor public override PropertyDescriptorCollection GetProperties() { return new PropertyDescriptorCollection(base.GetProperties().Cast<PropertyDescriptor>() .Union(new PropertyDescriptor[] { new ItemsCollectionPropertyDescriptor(type) }).ToArray()); } // Expose one more property, a collection of MutableKeyValuePairs, described by ItemsCollectionPropertyDescriptor public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { return new PropertyDescriptorCollection(base.GetProperties(attributes).Cast<PropertyDescriptor>() .Union(new PropertyDescriptor[] { new ItemsCollectionPropertyDescriptor(type) }).ToArray()); } } class ItemsCollectionPropertyDescriptor : PropertyDescriptor { Type dictionaryType; Type[] genericArguments; Type kvpairType; Type itemType; Type propertyType; internal ItemsCollectionPropertyDescriptor(Type type) : base("ItemsCollection", null) { this.dictionaryType = type; } Type[] GenericArguments { get { if (this.genericArguments == null) { object[] result = new object[2] { false, false }; Type[] interfaces = this.ComponentType.FindInterfaces(ModelTreeManager.CheckInterface, result); foreach (Type type in interfaces) { if (type.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { this.genericArguments = type.GetGenericArguments(); Fx.Assert(this.genericArguments.Length == 2, "this.genericArguments.Length should be = 2"); return this.genericArguments; } } Debug.Fail("Cannot find generic arguments for IDictionary<,>."); } return this.genericArguments; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is intended for use through reflection")] Type KVPairType { get { if (this.kvpairType == null) { this.kvpairType = typeof(KeyValuePair<,>).MakeGenericType(this.GenericArguments); } return this.kvpairType; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is intended for use through reflection")] Type ItemType { get { if (this.itemType == null) { this.itemType = typeof(ModelItemKeyValuePair<,>).MakeGenericType(this.GenericArguments); } return this.itemType; } } public override Type ComponentType { get { return this.dictionaryType; } } public override bool IsReadOnly { get { return true; } } public override Type PropertyType { get { if (this.propertyType == null) { this.propertyType = typeof(DictionaryItemsCollection<,>).MakeGenericType(this.GenericArguments); } return this.propertyType; } } public override bool IsBrowsable { get { return false; } } public override bool CanResetValue(object component) { return false; } public override object GetValue(object component) { return Activator.CreateInstance(this.PropertyType, new object[] { component }); } public override void ResetValue(object component) { Debug.Fail("ResetValue is not implemented."); throw FxTrace.Exception.AsError(new NotImplementedException()); } public override void SetValue(object component, object value) { Debug.Fail("SetValue is not implemented."); throw FxTrace.Exception.AsError(new NotImplementedException()); } public override bool ShouldSerializeValue(object component) { return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection.Emit { using System.Text; using System; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Permissions; [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_SignatureHelper))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class SignatureHelper : _SignatureHelper { #region Consts Fields private const int NO_SIZE_IN_SIG = -1; #endregion #region Static Members [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes) { return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null); } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam) { return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null); } [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType) { return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null); } internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst) { SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst); sigHelp.AddData(inst.Length); foreach(Type t in inst) sigHelp.AddArgument(t); return sigHelp; } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper( Module scope, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper( Module scope, CallingConventions callingConvention, int cGenericParam, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { SignatureHelper sigHelp; MdSigCallingConvention intCall; if (returnType == null) { returnType = typeof(void); } intCall = MdSigCallingConvention.Default; if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) intCall = MdSigCallingConvention.Vararg; if (cGenericParam > 0) { intCall |= MdSigCallingConvention.Generic; } if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) intCall |= MdSigCallingConvention.HasThis; sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers); sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); return sigHelp; } [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType) { SignatureHelper sigHelp; MdSigCallingConvention intCall; if (returnType == null) returnType = typeof(void); if (unmanagedCallConv == CallingConvention.Cdecl) { intCall = MdSigCallingConvention.C; } else if (unmanagedCallConv == CallingConvention.StdCall || unmanagedCallConv == CallingConvention.Winapi) { intCall = MdSigCallingConvention.StdCall; } else if (unmanagedCallConv == CallingConvention.ThisCall) { intCall = MdSigCallingConvention.ThisCall; } else if (unmanagedCallConv == CallingConvention.FastCall) { intCall = MdSigCallingConvention.FastCall; } else { throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), "unmanagedCallConv"); } sigHelp = new SignatureHelper(mod, intCall, returnType, null, null); return sigHelp; } public static SignatureHelper GetLocalVarSigHelper() { return GetLocalVarSigHelper(null); } public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType) { return GetMethodSigHelper(null, callingConvention, returnType); } public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType) { return GetMethodSigHelper(null, unmanagedCallingConvention, returnType); } public static SignatureHelper GetLocalVarSigHelper(Module mod) { return new SignatureHelper(mod, MdSigCallingConvention.LocalSig); } public static SignatureHelper GetFieldSigHelper(Module mod) { return new SignatureHelper(mod, MdSigCallingConvention.Field); } public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes) { return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null); } public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { SignatureHelper sigHelp; if (returnType == null) { returnType = typeof(void); } MdSigCallingConvention intCall = MdSigCallingConvention.Property; if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) intCall |= MdSigCallingConvention.HasThis; sigHelp = new SignatureHelper(mod, intCall, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers); sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); return sigHelp; } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetTypeSigToken(Module mod, Type type) { if (mod == null) throw new ArgumentNullException("module"); if (type == null) throw new ArgumentNullException("type"); return new SignatureHelper(mod, type); } #endregion #region Private Data Members private byte[] m_signature; private int m_currSig; // index into m_signature buffer for next available byte private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed) private ModuleBuilder m_module; private bool m_sigDone; private int m_argCount; // tracking number of arguments in the signature #endregion #region Constructor private SignatureHelper(Module mod, MdSigCallingConvention callingConvention) { // Use this constructor to instantiate a local var sig or Field where return type is not applied. Init(mod, callingConvention); } [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { // Use this constructor to instantiate a any signatures that will require a return type. Init(mod, callingConvention, cGenericParameters); if (callingConvention == MdSigCallingConvention.Field) throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig")); AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers); } [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) : this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers) { } [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, Type type) { Init(mod); AddOneArgTypeHelper(type); } private void Init(Module mod) { m_signature = new byte[32]; m_currSig = 0; m_module = mod as ModuleBuilder; m_argCount = 0; m_sigDone = false; m_sizeLoc = NO_SIZE_IN_SIG; if (m_module == null && mod != null) throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder")); } private void Init(Module mod, MdSigCallingConvention callingConvention) { Init(mod, callingConvention, 0); } private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam) { Init(mod); AddData((byte)callingConvention); if (callingConvention == MdSigCallingConvention.Field || callingConvention == MdSigCallingConvention.GenericInst) { m_sizeLoc = NO_SIZE_IN_SIG; } else { if (cGenericParam > 0) AddData(cGenericParam); m_sizeLoc = m_currSig++; } } #endregion #region Private Members [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type argument, bool pinned) { if (pinned) AddElementType(CorElementType.Pinned); AddOneArgTypeHelper(argument); } [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { // This function will not increase the argument count. It only fills in bytes // in the signature based on clsArgument. This helper is called for return type. Contract.Requires(clsArgument != null); Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters); if (optionalCustomModifiers != null) { for (int i = 0; i < optionalCustomModifiers.Length; i++) { Type t = optionalCustomModifiers[i]; if (t == null) throw new ArgumentNullException("optionalCustomModifiers"); if (t.HasElementType) throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "optionalCustomModifiers"); if (t.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "optionalCustomModifiers"); AddElementType(CorElementType.CModOpt); int token = m_module.GetTypeToken(t).Token; Contract.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } if (requiredCustomModifiers != null) { for (int i = 0; i < requiredCustomModifiers.Length; i++) { Type t = requiredCustomModifiers[i]; if (t == null) throw new ArgumentNullException("requiredCustomModifiers"); if (t.HasElementType) throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "requiredCustomModifiers"); if (t.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "requiredCustomModifiers"); AddElementType(CorElementType.CModReqd); int token = m_module.GetTypeToken(t).Token; Contract.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } AddOneArgTypeHelper(clsArgument); } [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); } [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst) { if (clsArgument.IsGenericParameter) { if (clsArgument.DeclaringMethod != null) AddElementType(CorElementType.MVar); else AddElementType(CorElementType.Var); AddData(clsArgument.GenericParameterPosition); } else if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst)) { AddElementType(CorElementType.GenericInst); AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), true); Type[] args = clsArgument.GetGenericArguments(); AddData(args.Length); foreach (Type t in args) AddOneArgTypeHelper(t); } else if (clsArgument is TypeBuilder) { TypeBuilder clsBuilder = (TypeBuilder)clsArgument; TypeToken tkType; if (clsBuilder.Module.Equals(m_module)) { tkType = clsBuilder.TypeToken; } else { tkType = m_module.GetTypeToken(clsArgument); } if (clsArgument.IsValueType) { InternalAddTypeToken(tkType, CorElementType.ValueType); } else { InternalAddTypeToken(tkType, CorElementType.Class); } } else if (clsArgument is EnumBuilder) { TypeBuilder clsBuilder = ((EnumBuilder)clsArgument).m_typeBuilder; TypeToken tkType; if (clsBuilder.Module.Equals(m_module)) { tkType = clsBuilder.TypeToken; } else { tkType = m_module.GetTypeToken(clsArgument); } if (clsArgument.IsValueType) { InternalAddTypeToken(tkType, CorElementType.ValueType); } else { InternalAddTypeToken(tkType, CorElementType.Class); } } else if (clsArgument.IsByRef) { AddElementType(CorElementType.ByRef); clsArgument = clsArgument.GetElementType(); AddOneArgTypeHelper(clsArgument); } else if (clsArgument.IsPointer) { AddElementType(CorElementType.Ptr); AddOneArgTypeHelper(clsArgument.GetElementType()); } else if (clsArgument.IsArray) { if (clsArgument.IsSzArray) { AddElementType(CorElementType.SzArray); AddOneArgTypeHelper(clsArgument.GetElementType()); } else { AddElementType(CorElementType.Array); AddOneArgTypeHelper(clsArgument.GetElementType()); // put the rank information int rank = clsArgument.GetArrayRank(); AddData(rank); // rank AddData(0); // upper bounds AddData(rank); // lower bound for (int i = 0; i < rank; i++) AddData(0); } } else { CorElementType type = CorElementType.Max; if (clsArgument is RuntimeType) { type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument); //GetCorElementType returns CorElementType.Class for both object and string if (type == CorElementType.Class) { if (clsArgument == typeof(object)) type = CorElementType.Object; else if (clsArgument == typeof(string)) type = CorElementType.String; } } if (IsSimpleType(type)) { AddElementType(type); } else if (m_module == null) { InternalAddRuntimeType(clsArgument); } else if (clsArgument.IsValueType) { InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ValueType); } else { InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.Class); } } } private void AddData(int data) { // A managed representation of CorSigCompressData; if (m_currSig + 4 > m_signature.Length) { m_signature = ExpandArray(m_signature); } if (data <= 0x7F) { m_signature[m_currSig++] = (byte)(data & 0xFF); } else if (data <= 0x3FFF) { m_signature[m_currSig++] = (byte)((data >>8) | 0x80); m_signature[m_currSig++] = (byte)(data & 0xFF); } else if (data <= 0x1FFFFFFF) { m_signature[m_currSig++] = (byte)((data >>24) | 0xC0); m_signature[m_currSig++] = (byte)((data >>16) & 0xFF); m_signature[m_currSig++] = (byte)((data >>8) & 0xFF); m_signature[m_currSig++] = (byte)((data) & 0xFF); } else { throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger")); } } private void AddData(uint data) { if (m_currSig + 4 > m_signature.Length) { m_signature = ExpandArray(m_signature); } m_signature[m_currSig++] = (byte)((data) & 0xFF); m_signature[m_currSig++] = (byte)((data>>8) & 0xFF); m_signature[m_currSig++] = (byte)((data>>16) & 0xFF); m_signature[m_currSig++] = (byte)((data>>24) & 0xFF); } private void AddData(ulong data) { if (m_currSig + 8 > m_signature.Length) { m_signature = ExpandArray(m_signature); } m_signature[m_currSig++] = (byte)((data) & 0xFF); m_signature[m_currSig++] = (byte)((data>>8) & 0xFF); m_signature[m_currSig++] = (byte)((data>>16) & 0xFF); m_signature[m_currSig++] = (byte)((data>>24) & 0xFF); m_signature[m_currSig++] = (byte)((data>>32) & 0xFF); m_signature[m_currSig++] = (byte)((data>>40) & 0xFF); m_signature[m_currSig++] = (byte)((data>>48) & 0xFF); m_signature[m_currSig++] = (byte)((data>>56) & 0xFF); } private void AddElementType(CorElementType cvt) { // Adds an element to the signature. A managed represenation of CorSigCompressElement if (m_currSig + 1 > m_signature.Length) m_signature = ExpandArray(m_signature); m_signature[m_currSig++] = (byte)cvt; } private void AddToken(int token) { // A managed represenation of CompressToken // Pulls the token appart to get a rid, adds some appropriate bits // to the token and then adds this to the signature. int rid = (token & 0x00FFFFFF); //This is RidFromToken; MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken; if (rid > 0x3FFFFFF) { // token is too big to be compressed throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger")); } rid = (rid << 2); // TypeDef is encoded with low bits 00 // TypeRef is encoded with low bits 01 // TypeSpec is encoded with low bits 10 if (type == MetadataTokenType.TypeRef) { //if type is mdtTypeRef rid|=0x1; } else if (type == MetadataTokenType.TypeSpec) { //if type is mdtTypeSpec rid|=0x2; } AddData(rid); } private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType) { // Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType AddElementType(CorType); AddToken(clsToken.Token); } [System.Security.SecurityCritical] // auto-generated private unsafe void InternalAddRuntimeType(Type type) { // Add a runtime type into the signature. AddElementType(CorElementType.Internal); IntPtr handle = type.GetTypeHandleInternal().Value; // Internal types must have their pointer written into the signature directly (we don't // want to convert to little-endian format on big-endian machines because the value is // going to be extracted and used directly as a pointer (and only within this process)). if (m_currSig + sizeof(void*) > m_signature.Length) m_signature = ExpandArray(m_signature); byte *phandle = (byte*)&handle; for (int i = 0; i < sizeof(void*); i++) m_signature[m_currSig++] = phandle[i]; } private byte[] ExpandArray(byte[] inArray) { // Expand the signature buffer size return ExpandArray(inArray, inArray.Length * 2); } private byte[] ExpandArray(byte[] inArray, int requiredLength) { // Expand the signature buffer size if (requiredLength < inArray.Length) requiredLength = inArray.Length*2; byte[] outArray = new byte[requiredLength]; Array.Copy(inArray, outArray, inArray.Length); return outArray; } private void IncrementArgCounts() { if (m_sizeLoc == NO_SIZE_IN_SIG) { //We don't have a size if this is a field. return; } m_argCount++; } private void SetNumberOfSignatureElements(bool forceCopy) { // For most signatures, this will set the number of elements in a byte which we have reserved for it. // However, if we have a field signature, we don't set the length and return. // If we have a signature with more than 128 arguments, we can't just set the number of elements, // we actually have to allocate more space (e.g. shift everything in the array one or more spaces to the // right. We do this by making a copy of the array and leaving the correct number of blanks. This new // array is now set to be m_signature and we use the AddData method to set the number of elements properly. // The forceCopy argument can be used to force SetNumberOfSignatureElements to make a copy of // the array. This is useful for GetSignature which promises to trim the array to be the correct size anyway. byte[] temp; int newSigSize; int currSigHolder = m_currSig; if (m_sizeLoc == NO_SIZE_IN_SIG) return; //If we have fewer than 128 arguments and we haven't been told to copy the //array, we can just set the appropriate bit and return. if (m_argCount < 0x80 && !forceCopy) { m_signature[m_sizeLoc] = (byte)m_argCount; return; } //We need to have more bytes for the size. Figure out how many bytes here. //Since we need to copy anyway, we're just going to take the cost of doing a //new allocation. if (m_argCount < 0x80) { newSigSize = 1; } else if (m_argCount < 0x4000) { newSigSize = 2; } else { newSigSize = 4; } //Allocate the new array. temp = new byte[m_currSig + newSigSize - 1]; //Copy the calling convention. The calling convention is always just one byte //so we just copy that byte. Then copy the rest of the array, shifting everything //to make room for the new number of elements. temp[0] = m_signature[0]; Array.Copy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1)); m_signature = temp; //Use the AddData method to add the number of elements appropriately compressed. m_currSig = m_sizeLoc; AddData(m_argCount); m_currSig = currSigHolder + (newSigSize - 1); } #endregion #region Internal Members internal int ArgumentCount { get { return m_argCount; } } internal static bool IsSimpleType(CorElementType type) { if (type <= CorElementType.String) return true; if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object) return true; return false; } internal byte[] InternalGetSignature(out int length) { // An internal method to return the signature. Does not trim the // array, but passes out the length of the array in an out parameter. // This is the actual array -- not a copy -- so the callee must agree // to not copy it. // // param length : an out param indicating the length of the array. // return : A reference to the internal ubyte array. if (!m_sigDone) { m_sigDone = true; // If we have more than 128 variables, we can't just set the length, we need // to compress it. Unfortunately, this means that we need to copy the entire // array. Bummer, eh? SetNumberOfSignatureElements(false); } length = m_currSig; return m_signature; } internal byte[] InternalGetSignatureArray() { int argCount = m_argCount; int currSigLength = m_currSig; int newSigSize = currSigLength; //Allocate the new array. if (argCount < 0x7F) newSigSize += 1; else if (argCount < 0x3FFF) newSigSize += 2; else newSigSize += 4; byte[] temp = new byte[newSigSize]; // copy the sig int sigCopyIndex = 0; // calling convention temp[sigCopyIndex++] = m_signature[0]; // arg size if (argCount <= 0x7F) temp[sigCopyIndex++] = (byte)(argCount & 0xFF); else if (argCount <= 0x3FFF) { temp[sigCopyIndex++] = (byte)((argCount >>8) | 0x80); temp[sigCopyIndex++] = (byte)(argCount & 0xFF); } else if (argCount <= 0x1FFFFFFF) { temp[sigCopyIndex++] = (byte)((argCount >>24) | 0xC0); temp[sigCopyIndex++] = (byte)((argCount >>16) & 0xFF); temp[sigCopyIndex++] = (byte)((argCount >>8) & 0xFF); temp[sigCopyIndex++] = (byte)((argCount) & 0xFF); } else throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger")); // copy the sig part of the sig Array.Copy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2); // mark the end of sig temp[newSigSize - 1] = (byte)CorElementType.End; return temp; } #endregion #region Public Methods public void AddArgument(Type clsArgument) { AddArgument(clsArgument, null, null); } [System.Security.SecuritySafeCritical] // auto-generated public void AddArgument(Type argument, bool pinned) { if (argument == null) throw new ArgumentNullException("argument"); IncrementArgCounts(); AddOneArgTypeHelper(argument, pinned); } public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) { if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "requiredCustomModifiers", "arguments")); if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "optionalCustomModifiers", "arguments")); if (arguments != null) { for (int i =0; i < arguments.Length; i++) { AddArgument(arguments[i], requiredCustomModifiers == null ? null : requiredCustomModifiers[i], optionalCustomModifiers == null ? null : optionalCustomModifiers[i]); } } } [System.Security.SecuritySafeCritical] // auto-generated public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { if (m_sigDone) throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized")); if (argument == null) throw new ArgumentNullException("argument"); IncrementArgCounts(); // Add an argument to the signature. Takes a Type and determines whether it // is one of the primitive types of which we have special knowledge or a more // general class. In the former case, we only add the appropriate short cut encoding, // otherwise we will calculate proper description for the type. AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers); } public void AddSentinel() { AddElementType(CorElementType.Sentinel); } public override bool Equals(Object obj) { if (!(obj is SignatureHelper)) { return false; } SignatureHelper temp = (SignatureHelper)obj; if ( !temp.m_module.Equals(m_module) || temp.m_currSig!=m_currSig || temp.m_sizeLoc!=m_sizeLoc || temp.m_sigDone !=m_sigDone ) { return false; } for (int i=0; i<m_currSig; i++) { if (m_signature[i]!=temp.m_signature[i]) return false; } return true; } public override int GetHashCode() { // Start the hash code with the hash code of the module and the values of the member variables. int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc; // Add one if the sig is done. if (m_sigDone) HashCode += 1; // Then add the hash code of all the arguments. for (int i=0; i < m_currSig; i++) HashCode += m_signature[i].GetHashCode(); return HashCode; } public byte[] GetSignature() { return GetSignature(false); } internal byte[] GetSignature(bool appendEndOfSig) { // Chops the internal signature to the appropriate length. Adds the // end token to the signature and marks the signature as finished so that // no further tokens can be added. Return the full signature in a trimmed array. if (!m_sigDone) { if (appendEndOfSig) AddElementType(CorElementType.End); SetNumberOfSignatureElements(true); m_sigDone = true; } // This case will only happen if the user got the signature through // InternalGetSignature first and then called GetSignature. if (m_signature.Length > m_currSig) { byte[] temp = new byte[m_currSig]; Array.Copy(m_signature, temp, m_currSig); m_signature = temp; } return m_signature; } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append("Length: " + m_currSig + Environment.NewLine); if (m_sizeLoc != -1) { sb.Append("Arguments: " + m_signature[m_sizeLoc] + Environment.NewLine); } else { sb.Append("Field Signature" + Environment.NewLine); } sb.Append("Signature: " + Environment.NewLine); for (int i=0; i<=m_currSig; i++) { sb.Append(m_signature[i] + " "); } sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #if !FEATURE_CORECLR void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Text; using System.Threading; using System.Reflection; using System.Xml; using LothianProductions.Data; using LothianProductions.Util; using LothianProductions.Util.Settings; using LothianProductions.VoIP.Monitor; using LothianProductions.VoIP.Monitor.Impl; using LothianProductions.VoIP.State; namespace LothianProductions.VoIP { public delegate void StateUpdateHandler( IDeviceMonitor monitor, StateUpdateEventArgs e ); public class StateManager { protected static readonly StateManager mInstance = new StateManager(); protected Dictionary<Call, CallRecord> mCalls = new Dictionary<Call, CallRecord>(); protected Dictionary<Object, Dictionary<String, PropertyBehaviour>> mStateProperties = new Dictionary<Object, Dictionary<String, PropertyBehaviour>>(); public static StateManager Instance() { return mInstance; } public event StateUpdateHandler StateUpdate; protected Dictionary<DeviceMonitorControl, Thread> mDeviceMonitorControls = new Dictionary<DeviceMonitorControl, Thread>(); protected StateManager() { // Initialize device monitors, have to give each its own thread. ReloadDeviceStateMonitors(); } public void ReloadDeviceStateMonitors() { lock (mDeviceMonitorControls) { // Stop currently running threads. foreach( DeviceMonitorControl control in mDeviceMonitorControls.Keys ) mDeviceMonitorControls[ control ].Abort(); mDeviceMonitorControls.Clear(); NameValueCollection config = (NameValueCollection) ConfigurationManager.GetSection( "hvoipm/deviceStateMonitors" ); if( config == null ) throw new MissingAppSettingsException( "The section \"hvoipm/deviceStateMonitors\" was not present in the application configuration." ); foreach( String key in config.Keys ) { Type type = Type.GetType( config[ key ], true ); IDeviceMonitor monitor = (IDeviceMonitor) type.InvokeMember( "", BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance, null, null, new String[] { key } ); DeviceMonitorControl control = new DeviceMonitorControl( monitor ); Thread thread = new Thread( new ThreadStart( control.Run ) ); mDeviceMonitorControls.Add( control, thread ); thread.Start(); } Logger.Instance().Log( "Loaded " + mDeviceMonitorControls.Count + " device state monitor(s)" ); } } public ICollection<DeviceMonitorControl> DeviceMonitorControls { get{ return mDeviceMonitorControls.Keys; } } public void DeviceUpdated( IDeviceMonitor monitor, IList<DevicePropertyChange> deviceChanges, IList<LinePropertyChange> lineChanges, IList<CallPropertyChange> callChanges ) { // FIXME this is very inefficient List<PropertyChange> changes = new List<PropertyChange>(); foreach( PropertyChange change in deviceChanges ) changes.Add( change ); foreach( PropertyChange change in lineChanges ) changes.Add( change ); foreach( PropertyChange change in callChanges ) changes.Add( change ); foreach( PropertyChange change in changes ) // Note that we log changing to or from any given logging criteria if( LookupPropertyChangeBehaviour( change.Underlying, change.Property, change.ChangedTo ).Log || LookupPropertyChangeBehaviour( change.Underlying, change.Property, change.ChangedFrom ).Log ) Logger.Instance().Log( change.Underlying.GetType().Name + " property " + change.Property + " has changed from " + change.ChangedFrom + " to " + change.ChangedTo ); // Logging happens here: foreach( CallPropertyChange change in callChanges ) { if( change.Property == DeviceMonitor.PROPERTY_CALL_ACTIVITY ) { if ( change.ChangedTo == Activity.Connected.ToString() ) { CallRecord call = new CallRecord( monitor.GetDeviceState(), GetLine( change.Call ), change.Call, DateTime.Now, new DateTime() ); // Sanity check in case somehow call is already there if ( mCalls.ContainsKey( change.Call ) ) { mCalls.Remove( change.Call ); Logger.Instance().Log("Call #" + change.Call.Name + " had to be removed from the call list - did the previous call fail?"); } mCalls.Add( change.Call, call ); } else if ( change.ChangedFrom == Activity.Connected.ToString() ) { CallRecord call = mCalls[change.Call]; call.EndTime = DateTime.Now; CallLogger.Instance().Log(call); mCalls.Remove( change.Call ); } } if (change.Call.Activity != Activity.IdleDisconnected) { if ( mCalls.ContainsKey( change.Call ) ) { CallRecord call = mCalls[change.Call]; call.Call = change.Call; call.Line = GetLine(change.Call); mCalls[change.Call] = call; } } } if( StateUpdate != null ) StateUpdate( monitor, new StateUpdateEventArgs( deviceChanges, lineChanges, callChanges ) ); } public PropertyChangeBehaviour LookupPropertyChangeBehaviour( Object state, String property, String criteria ) { if( LookupPropertyBehaviour( state, property ).PropertyChangeBehaviours.ContainsKey( criteria ) ) return LookupPropertyBehaviour( state, property ).PropertyChangeBehaviours[ criteria ]; if( LookupPropertyBehaviour( state, property ).PropertyChangeBehaviours.ContainsKey( "" ) ) return LookupPropertyBehaviour( state, property ).PropertyChangeBehaviours[ "" ]; throw new ConfigurationErrorsException( "Could not find behaviours suitable for criteria \"" + criteria + "\" for property \"" + property + "\" in application configuration." ); } public PropertyBehaviour LookupPropertyBehaviour( Object state, String property ) { // Behaviour not set yet. if( ! mStateProperties.ContainsKey( state ) ) mStateProperties.Add( state, new Dictionary<String, PropertyBehaviour>() ); Dictionary<String, PropertyBehaviour> propertyBehaviours = mStateProperties[ state ]; if( ! propertyBehaviours.ContainsKey( property ) ) propertyBehaviours.Add( property, GetPropertyBehaviourFromXml( state.GetType().Name, property ) ); return propertyBehaviours[ property ]; } protected PropertyBehaviour GetPropertyBehaviourFromXml( String stateType, String property ) { XmlNode node = (XmlNode) ConfigurationManager.GetSection( "hvoipm/behaviours" ); if( node == null ) throw new ConfigurationErrorsException( "Could not find behaviours section in application configuration." ); XmlNode propertyNode = node.SelectSingleNode( "property[@stateType='" + stateType + "' and @property='" + property + "']" ); if( propertyNode == null ) throw new ConfigurationErrorsException( "Could not find behaviour description for " + stateType + "." + property + "\" in application configuration." ); Dictionary<String, PropertyChangeBehaviour> changeBehaviours = new Dictionary<String, PropertyChangeBehaviour>(); PropertyBehaviour behaviour = new PropertyBehaviour( propertyNode.Attributes[ "label" ].Value, changeBehaviours ); foreach( XmlNode behaviourNode in propertyNode.ChildNodes ) // Just add a single behaviour entry if it's a catch-all criteria // or if there's only one. if( behaviourNode.Attributes[ "warningCriteria" ] == null || ! behaviourNode.Attributes[ "warningCriteria" ].Value.Contains( "," ) ) changeBehaviours.Add( ( behaviourNode.Attributes[ "warningCriteria" ] == null ? "" : behaviourNode.Attributes[ "warningCriteria" ].Value ), new PropertyChangeBehaviour( Boolean.Parse( behaviourNode.Attributes[ "showBubble" ].Value ), behaviourNode.Attributes[ "bubbleText" ].Value, Boolean.Parse( behaviourNode.Attributes[ "systemTrayWarning" ].Value ), Boolean.Parse( behaviourNode.Attributes[ "showApplication" ].Value ), behaviourNode.Attributes[ "externalProcess" ].Value, ( behaviourNode.Attributes[ "warningCriteria" ] == null ? "" : behaviourNode.Attributes[ "warningCriteria" ].Value ), Boolean.Parse( behaviourNode.Attributes[ "log" ].Value ) ) ); else foreach( String criteria in behaviourNode.Attributes[ "warningCriteria" ].Value.Split( ',' ) ) changeBehaviours.Add( criteria, new PropertyChangeBehaviour( Boolean.Parse( behaviourNode.Attributes[ "showBubble" ].Value ), behaviourNode.Attributes[ "bubbleText" ].Value, Boolean.Parse( behaviourNode.Attributes[ "systemTrayWarning" ].Value ), Boolean.Parse( behaviourNode.Attributes[ "showApplication" ].Value ), behaviourNode.Attributes[ "externalProcess" ].Value, criteria, Boolean.Parse( behaviourNode.Attributes[ "log" ].Value ) ) ); return behaviour; } // Helper functions for linking states. public IDeviceMonitor GetMonitor( Device deviceState ) { foreach( DeviceMonitorControl control in DeviceMonitorControls ) if( control.DeviceMonitor.GetDeviceState() == deviceState ) return control.DeviceMonitor; throw new DomainObjectNotFoundException( "Couldn't find a monitor owning the specified device." ); } public IDeviceMonitor GetMonitor( Line lineState ) { foreach( DeviceMonitorControl control in DeviceMonitorControls ) foreach( Line line in control.DeviceMonitor.GetDeviceState().Lines ) if( line == lineState ) return control.DeviceMonitor; throw new DomainObjectNotFoundException( "Couldn't find a monitor owning the specified line." ); } public IDeviceMonitor GetMonitor( Call callState ) { foreach( DeviceMonitorControl control in DeviceMonitorControls ) foreach( Line line in control.DeviceMonitor.GetDeviceState().Lines ) foreach( Call call in line.Calls ) if( call == callState ) return control.DeviceMonitor; throw new DomainObjectNotFoundException( "Couldn't find a monitor owning the specified call." ); } public Device GetDevice( Line lineState ) { foreach( DeviceMonitorControl control in DeviceMonitorControls ) foreach( Line line in control.DeviceMonitor.GetDeviceState().Lines ) if( line == lineState ) return control.DeviceMonitor.GetDeviceState(); throw new DomainObjectNotFoundException( "Couldn't find a device owning the specified line." ); } public Device GetDevice( Call callState ) { foreach( DeviceMonitorControl control in DeviceMonitorControls ) foreach( Line line in control.DeviceMonitor.GetDeviceState().Lines ) foreach( Call call in line.Calls ) if( call == callState ) return control.DeviceMonitor.GetDeviceState(); throw new DomainObjectNotFoundException( "Couldn't find a device owning the specified call." ); } public Line GetLine( Call callState ) { foreach( DeviceMonitorControl control in DeviceMonitorControls ) foreach( Line line in control.DeviceMonitor.GetDeviceState().Lines ) foreach( Call call in line.Calls ) if( call == callState ) return line; throw new DomainObjectNotFoundException( "Couldn't find a line owning the specified call." ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Runtime.InteropServices.WindowsRuntime; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; namespace System { /// <summary>Provides extension methods in the System namespace for working with the Windows Runtime.<br /> /// Currently contains:<br /> /// <ul> /// <li>Extension methods for conversion between <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces /// and <code>System.Threading.Tasks.Task</code>.</li> /// <li>Extension methods for conversion between <code>System.Threading.Tasks.Task</code> /// and <code>Windows.Foundation.IAsyncInfo</code> and deriving generic interfaces.</li> /// </ul></summary> [CLSCompliant(false)] public static class WindowsRuntimeSystemExtensions { #region Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task #region Convenience Helpers private static void ConcatenateCancelTokens(CancellationToken source, CancellationTokenSource sink, Task concatenationLifetime) { Debug.Assert(sink != null); CancellationTokenRegistration ctReg = source.Register((state) => { ((CancellationTokenSource)state).Cancel(); }, sink); concatenationLifetime.ContinueWith((_, state) => { ((CancellationTokenRegistration)state).Dispose(); }, ctReg, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private static void ConcatenateProgress<TProgress>(IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> sink) { // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. source.Progress += new AsyncActionProgressHandler<TProgress>((_, info) => sink.Report(info)); } private static void ConcatenateProgress<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> sink) { // This is separated out into a separate method so that we only pay the costs of compiler-generated closure if progress is non-null. source.Progress += new AsyncOperationProgressHandler<TResult, TProgress>((_, info) => sink.Report(info)); } #endregion Convenience Helpers #region Converters from IAsyncAction to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter GetAwaiter(this IAsyncAction source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask(this IAsyncAction source) { return AsTask(source, CancellationToken.None); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask(this IAsyncAction source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncActionAdapter; if (wrapper != null && !wrapper.CompletedSynchronously) { Task innerTask = wrapper.Task; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatination is useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); } return innerTask; } // Fast path to return a completed Task if the operation has already completed: switch (source.Status) { case AsyncStatus.Completed: return Task.CompletedTask; case AsyncStatus.Error: return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, VoidValueTypeParameter>(cancellationToken); source.Completed = new AsyncActionCompletedHandler(bridge.CompleteFromAsyncAction); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncAction to Task #region Converters from IAsyncOperation<TResult> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter<TResult> GetAwaiter<TResult>(this IAsyncOperation<TResult> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source) { return AsTask(source, CancellationToken.None); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult>(this IAsyncOperation<TResult> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncOperationAdapter<TResult>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task<TResult> innerTask = wrapper.Task as Task<TResult>; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatination is useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); } return innerTask; } // Fast path to return a completed Task if the operation has already completed switch (source.Status) { case AsyncStatus.Completed: return Task.FromResult(source.GetResults()); case AsyncStatus.Error: return Task.FromException<TResult>(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<TResult, VoidValueTypeParameter>(cancellationToken); source.Completed = new AsyncOperationCompletedHandler<TResult>(bridge.CompleteFromAsyncOperation); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncOperation<TResult> to Task #region Converters from IAsyncActionWithProgress<TProgress> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter GetAwaiter<TProgress>(this IAsyncActionWithProgress<TProgress> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source) { return AsTask(source, CancellationToken.None, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken) { return AsTask(source, cancellationToken, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, IProgress<TProgress> progress) { return AsTask(source, CancellationToken.None, progress); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task AsTask<TProgress>(this IAsyncActionWithProgress<TProgress> source, CancellationToken cancellationToken, IProgress<TProgress> progress) { if (source == null) throw new ArgumentNullException(nameof(source)); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncActionWithProgressAdapter<TProgress>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task innerTask = wrapper.Task; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); if (progress != null) ConcatenateProgress(source, progress); } return innerTask; } // Fast path to return a completed Task if the operation has already completed: switch (source.Status) { case AsyncStatus.Completed: return Task.CompletedTask; case AsyncStatus.Error: return Task.FromException(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Forward progress reports: if (progress != null) ConcatenateProgress(source, progress); // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<VoidValueTypeParameter, TProgress>(cancellationToken); source.Completed = new AsyncActionWithProgressCompletedHandler<TProgress>(bridge.CompleteFromAsyncActionWithProgress); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncActionWithProgress<TProgress> to Task #region Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task /// <summary>Gets an awaiter used to await this asynchronous operation.</summary> /// <returns>An awaiter instance.</returns> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public static TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source) { return AsTask(source).GetAwaiter(); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <returns>The Task representing the started asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source) { return AsTask(source, CancellationToken.None, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, CancellationToken cancellationToken) { return AsTask(source, cancellationToken, null); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, IProgress<TProgress> progress) { return AsTask(source, CancellationToken.None, progress); } /// <summary>Gets a Task to represent the asynchronous operation.</summary> /// <param name="source">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> /// <param name="progress">The progress object used to receive progress updates.</param> /// <returns>The Task representing the asynchronous operation.</returns> public static Task<TResult> AsTask<TResult, TProgress>(this IAsyncOperationWithProgress<TResult, TProgress> source, CancellationToken cancellationToken, IProgress<TProgress> progress) { if (source == null) throw new ArgumentNullException(nameof(source)); // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task: var wrapper = source as TaskToAsyncOperationWithProgressAdapter<TResult, TProgress>; if (wrapper != null && !wrapper.CompletedSynchronously) { Task<TResult> innerTask = wrapper.Task as Task<TResult>; Debug.Assert(innerTask != null); Debug.Assert(innerTask.Status != TaskStatus.Created); // Is WaitingForActivation a legal state at this moment? if (!innerTask.IsCompleted) { // The race here is benign: If the task completes here, the concatinations are useless, but not damaging. if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null) ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask); if (progress != null) ConcatenateProgress(source, progress); } return innerTask; } // Fast path to return a completed Task if the operation has already completed switch (source.Status) { case AsyncStatus.Completed: return Task.FromResult(source.GetResults()); case AsyncStatus.Error: return Task.FromException<TResult>(ExceptionSupport.AttachRestrictedErrorInfo(source.ErrorCode)); case AsyncStatus.Canceled: return Task.FromCanceled<TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); } // Benign race: source may complete here. Things still work, just not taking the fast path. // Forward progress reports: if (progress != null) ConcatenateProgress(source, progress); // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task: var bridge = new AsyncInfoToTaskBridge<TResult, TProgress>(cancellationToken); source.Completed = new AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress); bridge.RegisterForCancellation(source); return bridge.Task; } #endregion Converters from IAsyncOperationWithProgress<TResult,TProgress> to Task #endregion Converters from Windows.Foundation.IAsyncInfo (and interfaces that derive from it) to System.Threading.Tasks.Task #region Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) public static IAsyncAction AsAsyncAction(this Task source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new TaskToAsyncActionAdapter(source, underlyingCancelTokenSource: null); } public static IAsyncOperation<TResult> AsAsyncOperation<TResult>(this Task<TResult> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return new TaskToAsyncOperationAdapter<TResult>(source, underlyingCancelTokenSource: null); } #endregion Converters from System.Threading.Tasks.Task to Windows.Foundation.IAsyncInfo (and interfaces that derive from it) private static void CommonlyUsedGenericInstantiations() { // This method is an aid for NGen to save common generic // instantiations into the ngen image. ((IAsyncOperation<bool>)null).AsTask(); ((IAsyncOperation<string>)null).AsTask(); ((IAsyncOperation<object>)null).AsTask(); ((IAsyncOperation<uint>)null).AsTask(); ((IAsyncOperationWithProgress<uint, uint>)null).AsTask(); ((IAsyncOperationWithProgress<ulong, ulong>)null).AsTask(); ((IAsyncOperationWithProgress<string, ulong>)null).AsTask(); } } // class WindowsRuntimeSystemExtensions } // namespace // WindowsRuntimeExtensions.cs
using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using System; using System.Collections.Generic; using System.ComponentModel; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using Toggl.Core.Analytics; using Toggl.Core.UI.Helper; using Toggl.Core.UI.ViewModels; using Toggl.Droid.Extensions; using Toggl.Droid.Extensions.Reactive; using Toggl.Droid.Presentation; using Toggl.Droid.ViewHelpers; using Toggl.Shared.Extensions; using static Toggl.Core.UI.Helper.TemporalInconsistency; namespace Toggl.Droid.Activities { [Activity(Theme = "@style/Theme.Splash", WindowSoftInputMode = SoftInput.StateHidden | SoftInput.AdjustPan, ScreenOrientation = ScreenOrientation.Portrait, ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)] public sealed partial class EditDurationActivity : ReactiveActivity<EditDurationViewModel> { private readonly Dictionary<TemporalInconsistency, string> inconsistencyMessages = new Dictionary<TemporalInconsistency, string> { [StartTimeAfterCurrentTime] = Shared.Resources.StartTimeAfterCurrentTimeWarning, [StartTimeAfterStopTime] = Shared.Resources.StartTimeAfterStopTimeWarning, [StopTimeBeforeStartTime] = Shared.Resources.StopTimeBeforeStartTimeWarning, [DurationTooLong] = Shared.Resources.DurationTooLong, }; private readonly Subject<Unit> viewClosedSubject = new Subject<Unit>(); private readonly Subject<DateTimeOffset> activeEditionChangedSubject = new Subject<DateTimeOffset>(); private DateTimeOffset minDateTime; private DateTimeOffset maxDateTime; private EditMode editMode = EditMode.None; private bool canDismiss = true; private bool is24HoursFormat; private Dialog editDialog; private Toast toast; public EditDurationActivity() : base( Resource.Layout.EditDurationActivity, Resource.Style.AppTheme, Transitions.SlideInFromBottom) { } public EditDurationActivity(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } protected override void InitializeBindings() { ViewModel.TimeFormat .Subscribe(v => is24HoursFormat = v.IsTwentyFourHoursFormat) .DisposedBy(DisposeBag); ViewModel.StartTimeString .Subscribe(startTimeText.Rx().TextObserver()) .DisposedBy(DisposeBag); ViewModel.StartDateString .Subscribe(startDateText.Rx().TextObserver()) .DisposedBy(DisposeBag); ViewModel.StopTimeString .Subscribe(stopTimeText.Rx().TextObserver()) .DisposedBy(DisposeBag); ViewModel.StopDateString .Subscribe(stopDateText.Rx().TextObserver()) .DisposedBy(DisposeBag); ViewModel.IsRunning .Subscribe(updateStopTimeUIVisibility) .DisposedBy(DisposeBag); ViewModel.MinimumDateTime .Subscribe(min => minDateTime = min) .DisposedBy(DisposeBag); ViewModel.MaximumDateTime .Subscribe(max => maxDateTime = max) .DisposedBy(DisposeBag); stopTimerLabel.Rx() .BindAction(ViewModel.StopTimeEntry) .DisposedBy(DisposeBag); startTimeText.Rx().Tap() .Subscribe(_ => { editMode = EditMode.StartTime; }) .DisposedBy(DisposeBag); startDateText.Rx().Tap() .Subscribe(_ => { editMode = EditMode.StartDate; }) .DisposedBy(DisposeBag); startTimeText.Rx() .BindAction(ViewModel.EditStartTime) .DisposedBy(DisposeBag); startDateText.Rx() .BindAction(ViewModel.EditStartTime) .DisposedBy(DisposeBag); stopTimeText.Rx().Tap() .Subscribe(_ => { editMode = EditMode.EndTime; }) .DisposedBy(DisposeBag); stopDateText.Rx().Tap() .Subscribe(_ => { editMode = EditMode.EndDate; }) .DisposedBy(DisposeBag); stopTimeText.Rx() .BindAction(ViewModel.EditStopTime) .DisposedBy(DisposeBag); stopDateText.Rx() .BindAction(ViewModel.EditStopTime) .DisposedBy(DisposeBag); ViewModel.TemporalInconsistencies .Subscribe(onTemporalInconsistency) .DisposedBy(DisposeBag); ViewModel.IsEditingStartTime .Where(CommonFunctions.Identity) .SelectMany(_ => ViewModel.StartTime) .Subscribe(startEditing) .DisposedBy(DisposeBag); ViewModel.IsEditingStopTime .Where(CommonFunctions.Identity) .SelectMany(_ => ViewModel.StopTime) .Subscribe(startEditing) .DisposedBy(DisposeBag); activeEditionChangedSubject .Subscribe(ViewModel.ChangeActiveTime.Inputs) .DisposedBy(DisposeBag); viewClosedSubject .Subscribe(ViewModel.StopEditingTime.Inputs) .DisposedBy(DisposeBag); ViewModel.IsEditingTime .Invert() .Subscribe(wheelNumericInput.Rx().Enabled()) .DisposedBy(DisposeBag); ViewModel.Duration .Where(_ => !wheelNumericInput.HasFocus) .Subscribe(wheelNumericInput.SetDuration) .DisposedBy(DisposeBag); wheelNumericInput.Duration .Subscribe(ViewModel.ChangeDuration.Inputs) .DisposedBy(DisposeBag); ViewModel.MinimumStartTime .Subscribe(v => wheelForeground.MinimumStartTime = v) .DisposedBy(DisposeBag); ViewModel.MaximumStartTime .Subscribe(v => wheelForeground.MaximumStartTime = v) .DisposedBy(DisposeBag); ViewModel.MinimumStopTime .Subscribe(v => wheelForeground.MinimumEndTime = v) .DisposedBy(DisposeBag); ViewModel.MaximumStopTime .Subscribe(v => wheelForeground.MaximumEndTime = v) .DisposedBy(DisposeBag); ViewModel.StartTime .DistinctUntilChanged() .Subscribe(v => wheelForeground.StartTime = v) .DisposedBy(DisposeBag); ViewModel.StopTime .Select(endTime => endTime.RoundDownToMinute()) .DistinctUntilChanged() .Subscribe(v => wheelForeground.EndTime = v) .DisposedBy(DisposeBag); ViewModel.IsRunning .Subscribe(v => wheelForeground.IsRunning = v) .DisposedBy(DisposeBag); wheelForeground.StartTimeObservable .Subscribe(ViewModel.ChangeStartTime.Inputs) .DisposedBy(DisposeBag); wheelForeground.EndTimeObservable .Subscribe(ViewModel.ChangeStopTime.Inputs) .DisposedBy(DisposeBag); var timeEditedFromNumericInput = wheelNumericInput .Duration .SelectValue(EditTimeSource.NumpadDuration); var timeEditedFromPickers = activeEditionChangedSubject .SelectValue(editMode) .Where(mode => mode != EditMode.None) .Select(editModeToEditTimeSource); Observable.Merge( wheelForeground.TimeEdited, timeEditedFromNumericInput, timeEditedFromPickers) .Distinct() .Subscribe(ViewModel.TimeEditedWithSource) .DisposedBy(DisposeBag); } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.OneButtonMenu, menu); var saveMenuItem = menu.FindItem(Resource.Id.ButtonMenuItem); saveMenuItem.SetTitle(Shared.Resources.Save); return true; } public override bool OnOptionsItemSelected(IMenuItem item) { if (item.ItemId == Resource.Id.ButtonMenuItem) { wheelNumericInput.ApplyDurationIfBeingEdited(); ViewModel.Save.Execute(); return true; } return base.OnOptionsItemSelected(item); } private void updateStopTimeUIVisibility(bool isRunning) { var stopDateTimeViewsVisibility = (!isRunning).ToVisibility(); stopTimerLabel.Visibility = isRunning.ToVisibility(); stopTimeText.Visibility = stopDateTimeViewsVisibility; stopDateText.Visibility = stopDateTimeViewsVisibility; stopDotSeparator.Visibility = stopDateTimeViewsVisibility; } protected override void OnStop() { base.OnStop(); canDismiss = true; editDialog?.Dismiss(); } private void onTemporalInconsistency(TemporalInconsistency temporalInconsistency) { canDismiss = false; toast?.Cancel(); toast = null; var message = inconsistencyMessages[temporalInconsistency]; toast = Toast.MakeText(this, message, ToastLength.Short); toast.Show(); } private void startEditing(DateTimeOffset initialValue) { if (editMode == EditMode.None) return; var localInitialValue = initialValue.ToLocalTime(); if (editMode == EditMode.StartTime || editMode == EditMode.EndTime) { editTime(localInitialValue); } else { editDate(localInitialValue); } } private void editTime(DateTimeOffset currentTime) { if (editDialog == null) { var timePickerDialog = new TimePickerDialog(this, Resource.Style.WheelDialogStyle, new TimePickerListener(currentTime, activeEditionChangedSubject.OnNext), currentTime.Hour, currentTime.Minute, is24HoursFormat); void resetAction() { timePickerDialog.UpdateTime(currentTime.Hour, currentTime.Minute); } editDialog = timePickerDialog; editDialog.DismissEvent += (_, __) => onCurrentEditDialogDismiss(resetAction); editDialog.Show(); } } private void editDate(DateTimeOffset currentDate) { if (editDialog == null) { var datePickerDialog = new DatePickerDialog(this, Resource.Style.WheelDialogStyle, new DatePickerListener(currentDate, activeEditionChangedSubject.OnNext), currentDate.Year, currentDate.Month - 1, currentDate.Day); // FirstDayOfWeek days start with sunday at 1 and finish with saturday at 7 var normalizedBeginningOfWeek = (int)ViewModel.BeginningOfWeek + 1; datePickerDialog.DatePicker.FirstDayOfWeek = normalizedBeginningOfWeek; void updateDateBounds() { datePickerDialog.DatePicker.MinDate = minDateTime.ToUnixTimeMilliseconds(); datePickerDialog.DatePicker.MaxDate = maxDateTime.ToUnixTimeMilliseconds(); datePickerDialog.SetTitle(""); } updateDateBounds(); void resetAction() { updateDateBounds(); datePickerDialog.UpdateDate(currentDate.Year, currentDate.Month - 1, currentDate.Day); } editDialog = datePickerDialog; editDialog.DismissEvent += (_, __) => onCurrentEditDialogDismiss(resetAction); editDialog.Show(); } } private void onCurrentEditDialogDismiss(Action resetAction) { if (canDismiss) { editDialog = null; viewClosedSubject.OnNext(Unit.Default); editMode = EditMode.None; } else { resetAction(); editDialog.Show(); canDismiss = true; } } private EditTimeSource editModeToEditTimeSource(EditMode targetEditMode) => targetEditMode switch { EditMode.StartTime => EditTimeSource.BarrelStartTime, EditMode.EndTime => EditTimeSource.BarrelStopTime, EditMode.StartDate => EditTimeSource.BarrelStartDate, EditMode.EndDate => EditTimeSource.BarrelStopDate, _ => throw new InvalidEnumArgumentException($"It's not possible to convert {targetEditMode} into a EditTimeSource") }; private enum EditMode { StartTime, EndTime, StartDate, EndDate, None } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.FrameworkPropertyMetadata.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows { public partial class FrameworkPropertyMetadata : UIPropertyMetadata { #region Methods and constructors public FrameworkPropertyMetadata(Object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback, bool isAnimationProhibited) { } public FrameworkPropertyMetadata(Object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback, bool isAnimationProhibited, System.Windows.Data.UpdateSourceTrigger defaultUpdateSourceTrigger) { } public FrameworkPropertyMetadata(PropertyChangedCallback propertyChangedCallback) { } public FrameworkPropertyMetadata(PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback) { } public FrameworkPropertyMetadata() { } public FrameworkPropertyMetadata(Object defaultValue) { } public FrameworkPropertyMetadata(Object defaultValue, PropertyChangedCallback propertyChangedCallback) { } public FrameworkPropertyMetadata(Object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback) { } public FrameworkPropertyMetadata(Object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback) { } public FrameworkPropertyMetadata(Object defaultValue, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback) { } public FrameworkPropertyMetadata(Object defaultValue, FrameworkPropertyMetadataOptions flags) { } protected override void Merge(PropertyMetadata baseMetadata, DependencyProperty dp) { } protected override void OnApply(DependencyProperty dp, Type targetType) { } #endregion #region Properties and indexers public bool AffectsArrange { get { return default(bool); } set { } } public bool AffectsMeasure { get { return default(bool); } set { } } public bool AffectsParentArrange { get { return default(bool); } set { } } public bool AffectsParentMeasure { get { return default(bool); } set { } } public bool AffectsRender { get { return default(bool); } set { } } public bool BindsTwoWayByDefault { get { return default(bool); } set { } } public System.Windows.Data.UpdateSourceTrigger DefaultUpdateSourceTrigger { get { Contract.Ensures(((System.Windows.Data.UpdateSourceTrigger)(0)) <= Contract.Result<System.Windows.Data.UpdateSourceTrigger>()); Contract.Ensures(Contract.Result<System.Windows.Data.UpdateSourceTrigger>() <= ((System.Windows.Data.UpdateSourceTrigger)(3))); return default(System.Windows.Data.UpdateSourceTrigger); } set { } } public bool Inherits { get { return default(bool); } set { } } public bool IsDataBindingAllowed { get { return default(bool); } } public bool IsNotDataBindable { get { return default(bool); } set { } } public bool Journal { get { return default(bool); } set { } } public bool OverridesInheritanceBehavior { get { return default(bool); } set { } } public bool SubPropertiesDoNotAffectRender { get { return default(bool); } set { } } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.IO; using System.Resources; using System.Reflection; using System.Text.RegularExpressions; using NUnit.Framework; namespace DDay.iCal.Test { [TestFixture] public class TodoTest { private string tzid; [TestFixtureSetUp] public void InitAll() { tzid = "US-Eastern"; } public void TestTodoActive(string calendar, ArrayList items, params int[] numPeriods) { IICalendar iCal = iCalendar.LoadFromFile(@"Calendars/Todo/" + calendar)[0]; ProgramTest.TestCal(iCal); ITodo todo = iCal.Todos[0]; for (int i = 0; i < items.Count; i += 2) { iCalDateTime dt = (iCalDateTime)items[i]; dt.TZID = tzid; bool tf = (bool)items[i + 1]; if (tf) Assert.IsTrue(todo.IsActive(dt), "Todo should be active at " + dt); else Assert.IsFalse(todo.IsActive(dt), "Todo should not be active at " + dt); } if (numPeriods != null && numPeriods.Length > 0) { IEvaluator evaluator = todo.GetService(typeof(IEvaluator)) as IEvaluator; Assert.IsNotNull(evaluator); Assert.AreEqual( numPeriods[0], evaluator.Periods.Count, "Todo should have " + numPeriods[0] + " occurrences after evaluation; it had " + evaluator.Periods.Count); } } public void TestTodoCompleted(string calendar, ArrayList items) { IICalendar iCal = iCalendar.LoadFromFile(@"Calendars/Todo/" + calendar)[0]; ProgramTest.TestCal(iCal); ITodo todo = iCal.Todos[0]; for (int i = 0; i < items.Count; i += 2) { IDateTime dt = (IDateTime)items[i]; dt.TZID = tzid; bool tf = (bool)items[i + 1]; if (tf) Assert.IsTrue(todo.IsCompleted(dt), "Todo should be completed at " + dt); else Assert.IsFalse(todo.IsCompleted(dt), "Todo should not be completed at " + dt); } } [Test, Category("Todo")] public void Todo1() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2200, 12, 31, 0, 0, 0)); items.Add(true); TestTodoActive("Todo1.ics", items); } [Test, Category("Todo")] public void Todo2() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 8, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 28, 8, 59, 59)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2200, 12, 31, 0, 0, 0)); items.Add(true); TestTodoActive("Todo2.ics", items); } [Test, Category("Todo")] public void Todo3() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 8, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2200, 12, 31, 0, 0, 0)); items.Add(false); TestTodoActive("Todo3.ics", items); } [Test, Category("Todo")] public void Todo4() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 07, 28, 8, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 07, 28, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 1, 0, 0, 0)); items.Add(true); TestTodoCompleted("Todo4.ics", items); } [Test, Category("Todo")] public void Todo5() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 29, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 1, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 2, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 3, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 4, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 5, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 6, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 7, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 8, 9, 0, 0)); items.Add(true); TestTodoActive("Todo5.ics", items); } [Test, Category("Todo")] public void Todo6() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 29, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 1, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 2, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 3, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 4, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 5, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 6, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 7, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 8, 8, 9, 0, 0)); items.Add(true); TestTodoActive("Todo6.ics", items); } [Test, Category("Todo")] public void Todo7() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 29, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 1, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 2, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 3, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 4, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 5, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 6, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 1, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 9, 2, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 9, 3, 9, 0, 0)); items.Add(true); TestTodoActive("Todo7.ics", items); } [Test, Category("Todo")] public void Todo7_1() { IICalendar iCal = iCalendar.LoadFromFile(@"Calendars/Todo/Todo7.ics")[0]; ITodo todo = iCal.Todos[0]; ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2006, 8, 4, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2006, 9, 1, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2006, 10, 6, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2006, 11, 3, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2006, 12, 1, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2007, 1, 5, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2007, 2, 2, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2007, 3, 2, 9, 0, 0, tzid)); items.Add(new iCalDateTime(2007, 4, 6, 9, 0, 0, tzid)); IList<Occurrence> occurrences = todo.GetOccurrences( new iCalDateTime(2006, 7, 1, 9, 0, 0), new iCalDateTime(2007, 7, 1, 9, 0, 0)); // FIXME: Count is not properly restricting recurrences to 10. // What's going wrong here? Assert.AreEqual( items.Count, occurrences.Count, "TODO should have " + items.Count + " occurrences; it has " + occurrences.Count); for (int i = 0; i < items.Count; i++) Assert.AreEqual(items[i], occurrences[i].Period.StartTime, "TODO should occur at " + items[i] + ", but does not."); } [Test, Category("Todo")] public void Todo8() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 29, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 1, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 2, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 3, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 4, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 5, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 6, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 31, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 1, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 2, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 3, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 10, 10, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 11, 15, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 12, 5, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 1, 3, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 1, 4, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 1, 5, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 1, 6, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 1, 7, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 2, 1, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2007, 2, 2, 8, 59, 59)); items.Add(false); items.Add(new iCalDateTime(2007, 2, 2, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2007, 2, 3, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2007, 2, 4, 9, 0, 0)); items.Add(true); TestTodoActive("Todo8.ics", items); } [Test, Category("Todo")] public void Todo9() { ArrayList items = new ArrayList(); items.Add(new iCalDateTime(2006, 7, 28, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 29, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 7, 30, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 17, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 18, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 8, 19, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 7, 9, 0, 0)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 8, 8, 59, 59)); items.Add(false); items.Add(new iCalDateTime(2006, 9, 8, 9, 0, 0)); items.Add(true); items.Add(new iCalDateTime(2006, 9, 9, 9, 0, 0)); items.Add(true); TestTodoActive("Todo9.ics", items, 3); } // FIXME: re-implement //[Test, Category("Todo")] //public void TODO10() //{ // iCalendar iCal = new iCalendar(); // Todo todo = iCal.Create<Todo>(); // todo.Summary = "xxxx"; // todo.Description = "fdsdsfds"; // // Set Start & Due date // todo.DTStart = new iCalDateTime(2007, 1, 1, 8, 0, 0); // todo.Due = new iCalDateTime(2007, 1, 7); // todo.Created = new iCalDateTime(DateTime.SpecifyKind(new DateTime(2007, 1, 1), DateTimeKind.Utc)); // todo.DTStamp = new iCalDateTime(DateTime.SpecifyKind(new DateTime(2007, 1, 1), DateTimeKind.Utc)); // todo.UID = "b6709c95-5523-46aa-a7e5-1b5ea034b86a"; // // Create an alarm // Alarm al = new Alarm(); // al.Trigger = new Trigger(TimeSpan.FromMinutes(-30)); // al.Action = AlarmAction.Display; // al.Description = "Reminder"; // // Add the alarm to the todo item // todo.Alarms.Add(al); // // Save into calendar file. // iCalendarSerializer serializer = new iCalendarSerializer(); // string serializedTodo = serializer.SerializeToString(iCal); // Assert.AreEqual( // "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//ddaysoftware.com//NONSGML DDay.iCal 1.0//EN\r\nBEGIN:VTODO\r\nCREATED:20070101T000000Z\r\nDESCRIPTION:fdsdsfds\r\nDTSTAMP:20070101T000000Z\r\nDTSTART:20070101T080000\r\nDUE;VALUE=DATE:20070107\r\nSEQUENCE:0\r\nSTATUS:NEEDS-ACTION\r\nSUMMARY:xxxx\r\nUID:b6709c95-5523-46aa-a7e5-1b5ea034b86a\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:Reminder\r\nTRIGGER:-PT30M\r\nEND:VALARM\r\nEND:VTODO\r\nEND:VCALENDAR\r\n", // serializedTodo); // List<AlarmOccurrence> alarms = todo.PollAlarms( // new iCalDateTime(2007, 1, 1), // new iCalDateTime(2007, 2, 1)); // iCalDateTime expectedAlarm = new iCalDateTime(2007, 1, 1, 7, 30, 0); // Assert.AreEqual(1, alarms.Count, "There should be exactly 1 alarm"); // Assert.AreEqual(expectedAlarm, alarms[0].DateTime, "The alarm should occur at " + expectedAlarm); //} // FIXME: re-implement //[Test, Category("Todo")] //public void TODO11() //{ // iCalendar iCal = new iCalendar(); // Todo todo = iCal.Create<Todo>(); // todo.Summary = "xxxx"; // todo.Description = "fdsdsfds"; // // Set Start & Due date // todo.DTStart = new iCalDateTime(2007, 1, 1, 8, 0, 0); // todo.Due = new iCalDateTime(2007, 1, 7); // todo.Created = new iCalDateTime(DateTime.SpecifyKind(new DateTime(2007, 1, 1), DateTimeKind.Utc)); // todo.DTStamp = new iCalDateTime(DateTime.SpecifyKind(new DateTime(2007, 1, 1), DateTimeKind.Utc)); // todo.UID = "b6709c95-5523-46aa-a7e5-1b5ea034b86a"; // // Add an alarm in my task // Alarm al = new Alarm(todo); // al.Action = AlarmAction.Display; // al.Description = "Reminder"; // al.Trigger = new Trigger(); // // Set reminder time // al.Trigger.DateTime = new DateTime(2007, 1, 6, 8, 0, 0); // // Save into calendar file. // iCalendarSerializer serializer = new iCalendarSerializer(); // string serializedTodo = serializer.SerializeToString(iCal); // Assert.AreEqual( // "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//ddaysoftware.com//NONSGML DDay.iCal 1.0//EN\r\nBEGIN:VTODO\r\nCREATED:20070101T000000Z\r\nDESCRIPTION:fdsdsfds\r\nDTSTAMP:20070101T000000Z\r\nDTSTART:20070101T080000\r\nDUE;VALUE=DATE:20070107\r\nSEQUENCE:0\r\nSTATUS:NEEDS-ACTION\r\nSUMMARY:xxxx\r\nUID:b6709c95-5523-46aa-a7e5-1b5ea034b86a\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\nDESCRIPTION:Reminder\r\nTRIGGER;VALUE=DATE-TIME:20070106T080000\r\nEND:VALARM\r\nEND:VTODO\r\nEND:VCALENDAR\r\n", // serializedTodo); //} } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using QuantConnect.Data.Market; package com.quantconnect.lean.Data.Consolidators { /** * Provides a base class for consolidators that emit data based on the passing of a period of time * or after seeing a max count of data points. */ * <typeparam name="T The input type of the consolidator</typeparam> * <typeparam name="TConsolidated The output type of the consolidator</typeparam> public abstract class PeriodCountConsolidatorBase<T, TConsolidated> : DataConsolidator<T> where T : class, IBaseData where TConsolidated : BaseData { //The minimum timespan between creating new bars. private final TimeSpan? _period; //The number of data updates between creating new bars. private final OptionalInt _maxCount; //The number of pieces of data we've accumulated since our last emit private int _currentCount; //The working bar used for aggregating the data private TConsolidated _workingBar; //The last time we emitted a consolidated bar private DateTime? _lastEmit; /** * Creates a consolidator to produce a new <typeparamref name="TConsolidated"/> instance representing the period */ * @param period The minimum span of time before emitting a consolidated bar protected PeriodCountConsolidatorBase(TimeSpan period) { _period = period; } /** * Creates a consolidator to produce a new <typeparamref name="TConsolidated"/> instance representing the last count pieces of data */ * @param maxCount The number of pieces to accept before emiting a consolidated bar protected PeriodCountConsolidatorBase(int maxCount) { _maxCount = maxCount; } /** * Creates a consolidator to produce a new <typeparamref name="TConsolidated"/> instance representing the last count pieces of data or the period, whichever comes first */ * @param maxCount The number of pieces to accept before emiting a consolidated bar * @param period The minimum span of time before emitting a consolidated bar protected PeriodCountConsolidatorBase(int maxCount, Duration period) { _maxCount = maxCount; _period = period; } /** * Gets the type produced by this consolidator */ public @Override Class OutputType { get { return typeof(TConsolidated); } } /** * Gets a clone of the data being currently consolidated */ public @Override BaseData WorkingData { get { return _workingBar != null ? _workingBar.Clone() : null; } } /** * Event handler that fires when a new piece of data is produced. We define this as a 'new' * event so we can expose it as a <typeparamref name="TConsolidated"/> instead of a <see cref="BaseData"/> instance */ public new event EventHandler<TConsolidated> DataConsolidated; /** * Updates this consolidator with the specified data. This method is * responsible for raising the DataConsolidated event * In time span mode, the bar range is closed on the left and open on the right: [T, T+TimeSpan). * For example, if time span is 1 minute, we have [10:00, 10:01): so data at 10:01 is not * included in the bar starting at 10:00. */ * @param data The new data for the consolidator public @Override void Update(T data) { if( !ShouldProcess(data)) { // first allow the base class a chance to filter out data it doesn't want // before we start incrementing counts and what not return; } //Decide to fire the event fireDataConsolidated = false; // decide to aggregate data before or after firing OnDataConsolidated event // always aggregate before firing in counting mode boolean aggregateBeforeFire = _maxCount.HasValue; if( _maxCount.HasValue) { // we're in count mode _currentCount++; if( _currentCount >= _maxCount.Value) { _currentCount = 0; fireDataConsolidated = true; } } if( !_lastEmit.HasValue) { // initialize this value for period computations _lastEmit = data.Time; } if( _period.HasValue) { // we're in time span mode and initialized if( _workingBar != null && data.Time - _workingBar.Time >= _period.Value) { fireDataConsolidated = true; } // special case: always aggregate before event trigger when Duration is zero if( _period.Value == Duration.ZERO) { fireDataConsolidated = true; aggregateBeforeFire = true; } } if( aggregateBeforeFire) { AggregateBar(ref _workingBar, data); } //Fire the event if( fireDataConsolidated) { workingTradeBar = _workingBar as TradeBar; if( workingTradeBar != null ) { // we kind of are cheating here... if( _period.HasValue) { workingTradeBar.Period = _period.Value; } // since trade bar has period it aggregates this properly else if( !(data is TradeBar)) { workingTradeBar.Period = data.Time - _lastEmit.Value; } } OnDataConsolidated(_workingBar); _lastEmit = data.Time; _workingBar = null; } if( !aggregateBeforeFire) { AggregateBar(ref _workingBar, data); } } /** * Scans this consolidator to see if it should emit a bar due to time passing */ * @param currentLocalTime The current time in the local time zone (same as <see cref="BaseData.Time"/>) public @Override void Scan(DateTime currentLocalTime) { if( _period.HasValue) { if( _workingBar != null ) { fireDataConsolidated = _period.Value == Duration.ZERO; if( !fireDataConsolidated && currentLocalTime - _workingBar.Time >= _period.Value) { fireDataConsolidated = true; } if( fireDataConsolidated) { OnDataConsolidated(_workingBar); _lastEmit = currentLocalTime; _workingBar = null; } } } } /** * Determines whether or not the specified data should be processd */ * @param data The data to check @returns True if the consolidator should process this data, false otherwise protected boolean ShouldProcess(T data) { return true; } /** * Aggregates the new 'data' into the 'workingBar'. The 'workingBar' will be * null following the event firing */ * @param workingBar The bar we're building, null if the event was just fired and we're starting a new consolidated bar * @param data The new data protected abstract void AggregateBar(ref TConsolidated workingBar, T data); /** * Gets a rounded-down bar time. Called by AggregateBar in derived classes. */ * @param time The bar time to be rounded down @returns The rounded bar time protected DateTime GetRoundedBarTime(DateTime time) { // rounding is performed only in time span mode return _period.HasValue && !_maxCount.HasValue ? time.RoundDown((TimeSpan)_period) : time; } /** * Event invocator for the <see cref="DataConsolidated"/> event */ * @param e The consolidated data protected void OnDataConsolidated(TConsolidated e) { handler = DataConsolidated; if( handler != null ) handler(this, e); base.OnDataConsolidated(e); } } }
/*=================================\ * PlotterControl\Form_serialmonitor.Designer.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 *=================================*/ namespace CnC_WFA { partial class Form_SerialMonitor { /// <summary> /// Required designer variable. /// </summary> public System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> public void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form_SerialMonitor)); this.textBox_size_b1 = new System.Windows.Forms.TextBox(); this.textBox_size_b2 = new System.Windows.Forms.TextBox(); this.checkBox_size = new System.Windows.Forms.CheckBox(); this.textBox_command_b1 = new System.Windows.Forms.TextBox(); this.textBox_command_b2 = new System.Windows.Forms.TextBox(); this.comboBox_command = new System.Windows.Forms.ComboBox(); this.textBox_sender_b2 = new System.Windows.Forms.TextBox(); this.textBox_sender_b1 = new System.Windows.Forms.TextBox(); this.textBox_sender_b4 = new System.Windows.Forms.TextBox(); this.textBox_sender_b3 = new System.Windows.Forms.TextBox(); this.textBox_sender_b6 = new System.Windows.Forms.TextBox(); this.textBox_sender_b5 = new System.Windows.Forms.TextBox(); this.textBox_sender_b8 = new System.Windows.Forms.TextBox(); this.textBox_sender_b7 = new System.Windows.Forms.TextBox(); this.comboBox_sender = new System.Windows.Forms.ComboBox(); this.textBox_fill = new System.Windows.Forms.TextBox(); this.button_fill = new System.Windows.Forms.Button(); this.textBox_data = new System.Windows.Forms.TextBox(); this.label_data_sep = new System.Windows.Forms.Label(); this.textBox_conv_input = new System.Windows.Forms.TextBox(); this.comboBox_conv = new System.Windows.Forms.ComboBox(); this.textBox_conv_output = new System.Windows.Forms.TextBox(); this.checkBox_hash = new System.Windows.Forms.CheckBox(); this.textBox_hash_b2 = new System.Windows.Forms.TextBox(); this.textBox_hash_b1 = new System.Windows.Forms.TextBox(); this.label_size = new System.Windows.Forms.Label(); this.label_command = new System.Windows.Forms.Label(); this.label_command_send = new System.Windows.Forms.Label(); this.label_sender = new System.Windows.Forms.Label(); this.label_sender_type = new System.Windows.Forms.Label(); this.label_fill = new System.Windows.Forms.Label(); this.label_data = new System.Windows.Forms.Label(); this.label_conv = new System.Windows.Forms.Label(); this.label_conv_arr = new System.Windows.Forms.Label(); this.label_hash = new System.Windows.Forms.Label(); this.listBox = new System.Windows.Forms.ListBox(); this.label_list = new System.Windows.Forms.Label(); this.comboBox_bd = new System.Windows.Forms.ComboBox(); this.comboBox_port = new System.Windows.Forms.ComboBox(); this.button_conn = new System.Windows.Forms.Button(); this.label_port = new System.Windows.Forms.Label(); this.label_bd = new System.Windows.Forms.Label(); this.button_send = new System.Windows.Forms.Button(); this.button_exit = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.label_err = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // textBox_size_b1 // this.textBox_size_b1.Enabled = false; this.textBox_size_b1.Location = new System.Drawing.Point(24, 33); this.textBox_size_b1.Name = "textBox_size_b1"; this.textBox_size_b1.Size = new System.Drawing.Size(30, 20); this.textBox_size_b1.TabIndex = 0; // // textBox_size_b2 // this.textBox_size_b2.Enabled = false; this.textBox_size_b2.Location = new System.Drawing.Point(60, 33); this.textBox_size_b2.Name = "textBox_size_b2"; this.textBox_size_b2.Size = new System.Drawing.Size(30, 20); this.textBox_size_b2.TabIndex = 1; // // checkBox_size // this.checkBox_size.AutoSize = true; this.checkBox_size.Location = new System.Drawing.Point(24, 59); this.checkBox_size.Name = "checkBox_size"; this.checkBox_size.Size = new System.Drawing.Size(142, 17); this.checkBox_size.TabIndex = 2; this.checkBox_size.Text = "Change (Cause an Error)"; this.checkBox_size.UseVisualStyleBackColor = true; this.checkBox_size.CheckedChanged += new System.EventHandler(this.checkBox_size_CheckedChanged); // // textBox_command_b1 // this.textBox_command_b1.Location = new System.Drawing.Point(22, 107); this.textBox_command_b1.Name = "textBox_command_b1"; this.textBox_command_b1.Size = new System.Drawing.Size(30, 20); this.textBox_command_b1.TabIndex = 3; this.textBox_command_b1.TextChanged += new System.EventHandler(this.textBox_command_b1_TextChanged); // // textBox_command_b2 // this.textBox_command_b2.Location = new System.Drawing.Point(58, 107); this.textBox_command_b2.Name = "textBox_command_b2"; this.textBox_command_b2.Size = new System.Drawing.Size(30, 20); this.textBox_command_b2.TabIndex = 4; this.textBox_command_b2.TextChanged += new System.EventHandler(this.textBox_command_b2_TextChanged); // // comboBox_command // this.comboBox_command.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_command.FormattingEnabled = true; this.comboBox_command.Location = new System.Drawing.Point(112, 133); this.comboBox_command.Name = "comboBox_command"; this.comboBox_command.Size = new System.Drawing.Size(192, 21); this.comboBox_command.TabIndex = 5; this.comboBox_command.SelectedIndexChanged += new System.EventHandler(this.comboBox_command_SelectedIndexChanged); // // textBox_sender_b2 // this.textBox_sender_b2.Location = new System.Drawing.Point(58, 199); this.textBox_sender_b2.Name = "textBox_sender_b2"; this.textBox_sender_b2.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b2.TabIndex = 7; this.textBox_sender_b2.TextChanged += new System.EventHandler(this.textBox_sender_b2_TextChanged); // // textBox_sender_b1 // this.textBox_sender_b1.Enabled = false; this.textBox_sender_b1.Location = new System.Drawing.Point(22, 199); this.textBox_sender_b1.Name = "textBox_sender_b1"; this.textBox_sender_b1.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b1.TabIndex = 6; this.textBox_sender_b1.TextChanged += new System.EventHandler(this.textBox_sender_b1_TextChanged); // // textBox_sender_b4 // this.textBox_sender_b4.Location = new System.Drawing.Point(130, 199); this.textBox_sender_b4.Name = "textBox_sender_b4"; this.textBox_sender_b4.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b4.TabIndex = 9; this.textBox_sender_b4.TextChanged += new System.EventHandler(this.textBox_sender_b4_TextChanged); // // textBox_sender_b3 // this.textBox_sender_b3.Location = new System.Drawing.Point(94, 199); this.textBox_sender_b3.Name = "textBox_sender_b3"; this.textBox_sender_b3.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b3.TabIndex = 8; this.textBox_sender_b3.TextChanged += new System.EventHandler(this.textBox_sender_b3_TextChanged); // // textBox_sender_b6 // this.textBox_sender_b6.Location = new System.Drawing.Point(202, 199); this.textBox_sender_b6.Name = "textBox_sender_b6"; this.textBox_sender_b6.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b6.TabIndex = 11; this.textBox_sender_b6.TextChanged += new System.EventHandler(this.textBox_sender_b6_TextChanged); // // textBox_sender_b5 // this.textBox_sender_b5.Location = new System.Drawing.Point(166, 199); this.textBox_sender_b5.Name = "textBox_sender_b5"; this.textBox_sender_b5.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b5.TabIndex = 10; this.textBox_sender_b5.TextChanged += new System.EventHandler(this.textBox_sender_b5_TextChanged); // // textBox_sender_b8 // this.textBox_sender_b8.Location = new System.Drawing.Point(274, 199); this.textBox_sender_b8.Name = "textBox_sender_b8"; this.textBox_sender_b8.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b8.TabIndex = 13; this.textBox_sender_b8.TextChanged += new System.EventHandler(this.textBox_sender_b8_TextChanged); // // textBox_sender_b7 // this.textBox_sender_b7.Location = new System.Drawing.Point(238, 199); this.textBox_sender_b7.Name = "textBox_sender_b7"; this.textBox_sender_b7.Size = new System.Drawing.Size(30, 20); this.textBox_sender_b7.TabIndex = 12; this.textBox_sender_b7.TextChanged += new System.EventHandler(this.textBox_sender_b7_TextChanged); // // comboBox_sender // this.comboBox_sender.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_sender.FormattingEnabled = true; this.comboBox_sender.Location = new System.Drawing.Point(60, 225); this.comboBox_sender.Name = "comboBox_sender"; this.comboBox_sender.Size = new System.Drawing.Size(123, 21); this.comboBox_sender.TabIndex = 14; this.comboBox_sender.SelectedIndexChanged += new System.EventHandler(this.comboBox_sender_SelectedIndexChanged); // // textBox_fill // this.textBox_fill.Location = new System.Drawing.Point(189, 226); this.textBox_fill.Name = "textBox_fill"; this.textBox_fill.Size = new System.Drawing.Size(55, 20); this.textBox_fill.TabIndex = 15; // // button_fill // this.button_fill.Location = new System.Drawing.Point(250, 224); this.button_fill.Name = "button_fill"; this.button_fill.Size = new System.Drawing.Size(54, 22); this.button_fill.TabIndex = 16; this.button_fill.Text = "Fill"; this.button_fill.UseVisualStyleBackColor = true; this.button_fill.Click += new System.EventHandler(this.button_fill_Click); // // textBox_data // this.textBox_data.Location = new System.Drawing.Point(23, 294); this.textBox_data.Name = "textBox_data"; this.textBox_data.Size = new System.Drawing.Size(281, 20); this.textBox_data.TabIndex = 17; this.textBox_data.TextChanged += new System.EventHandler(this.textBox_data_TextChanged); // // label_data_sep // this.label_data_sep.AutoSize = true; this.label_data_sep.Location = new System.Drawing.Point(21, 317); this.label_data_sep.Name = "label_data_sep"; this.label_data_sep.Size = new System.Drawing.Size(132, 13); this.label_data_sep.TabIndex = 18; this.label_data_sep.Text = "Separate bytes with space"; // // textBox_conv_input // this.textBox_conv_input.Location = new System.Drawing.Point(94, 351); this.textBox_conv_input.Name = "textBox_conv_input"; this.textBox_conv_input.Size = new System.Drawing.Size(66, 20); this.textBox_conv_input.TabIndex = 19; // // comboBox_conv // this.comboBox_conv.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_conv.FormattingEnabled = true; this.comboBox_conv.Location = new System.Drawing.Point(166, 350); this.comboBox_conv.Name = "comboBox_conv"; this.comboBox_conv.Size = new System.Drawing.Size(138, 21); this.comboBox_conv.TabIndex = 20; // // textBox_conv_output // this.textBox_conv_output.Location = new System.Drawing.Point(163, 381); this.textBox_conv_output.Name = "textBox_conv_output"; this.textBox_conv_output.ReadOnly = true; this.textBox_conv_output.Size = new System.Drawing.Size(80, 20); this.textBox_conv_output.TabIndex = 21; // // checkBox_hash // this.checkBox_hash.AutoSize = true; this.checkBox_hash.Location = new System.Drawing.Point(23, 435); this.checkBox_hash.Name = "checkBox_hash"; this.checkBox_hash.Size = new System.Drawing.Size(142, 17); this.checkBox_hash.TabIndex = 24; this.checkBox_hash.Text = "Change (Cause an Error)"; this.checkBox_hash.UseVisualStyleBackColor = true; this.checkBox_hash.CheckedChanged += new System.EventHandler(this.checkBox_hash_CheckedChanged); // // textBox_hash_b2 // this.textBox_hash_b2.Enabled = false; this.textBox_hash_b2.Location = new System.Drawing.Point(59, 409); this.textBox_hash_b2.Name = "textBox_hash_b2"; this.textBox_hash_b2.Size = new System.Drawing.Size(30, 20); this.textBox_hash_b2.TabIndex = 23; // // textBox_hash_b1 // this.textBox_hash_b1.Enabled = false; this.textBox_hash_b1.Location = new System.Drawing.Point(23, 409); this.textBox_hash_b1.Name = "textBox_hash_b1"; this.textBox_hash_b1.Size = new System.Drawing.Size(30, 20); this.textBox_hash_b1.TabIndex = 22; // // label_size // this.label_size.AutoSize = true; this.label_size.Location = new System.Drawing.Point(21, 17); this.label_size.Name = "label_size"; this.label_size.Size = new System.Drawing.Size(76, 13); this.label_size.TabIndex = 25; this.label_size.Text = "Size of Packet"; // // label_command // this.label_command.AutoSize = true; this.label_command.Location = new System.Drawing.Point(21, 91); this.label_command.Name = "label_command"; this.label_command.Size = new System.Drawing.Size(54, 13); this.label_command.TabIndex = 26; this.label_command.Text = "Command"; // // label_command_send // this.label_command_send.AutoSize = true; this.label_command_send.Location = new System.Drawing.Point(20, 136); this.label_command_send.Name = "label_command_send"; this.label_command_send.Size = new System.Drawing.Size(86, 13); this.label_command_send.TabIndex = 27; this.label_command_send.Text = "Set From Default"; // // label_sender // this.label_sender.AutoSize = true; this.label_sender.Location = new System.Drawing.Point(21, 183); this.label_sender.Name = "label_sender"; this.label_sender.Size = new System.Drawing.Size(41, 13); this.label_sender.TabIndex = 28; this.label_sender.Text = "Sender"; // // label_sender_type // this.label_sender_type.AutoSize = true; this.label_sender_type.Location = new System.Drawing.Point(20, 229); this.label_sender_type.Name = "label_sender_type"; this.label_sender_type.Size = new System.Drawing.Size(31, 13); this.label_sender_type.TabIndex = 29; this.label_sender_type.Text = "Type"; // // label_fill // this.label_fill.Location = new System.Drawing.Point(105, 249); this.label_fill.Name = "label_fill"; this.label_fill.Size = new System.Drawing.Size(199, 15); this.label_fill.TabIndex = 30; this.label_fill.Text = "Fill by 7 char string"; this.label_fill.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label_data // this.label_data.AutoSize = true; this.label_data.Location = new System.Drawing.Point(19, 278); this.label_data.Name = "label_data"; this.label_data.Size = new System.Drawing.Size(30, 13); this.label_data.TabIndex = 31; this.label_data.Text = "Data"; // // label_conv // this.label_conv.AutoSize = true; this.label_conv.Location = new System.Drawing.Point(21, 354); this.label_conv.Name = "label_conv"; this.label_conv.Size = new System.Drawing.Size(53, 13); this.label_conv.TabIndex = 32; this.label_conv.Text = "Converter"; // // label_conv_arr // this.label_conv_arr.AutoSize = true; this.label_conv_arr.Location = new System.Drawing.Point(144, 384); this.label_conv_arr.Name = "label_conv_arr"; this.label_conv_arr.Size = new System.Drawing.Size(16, 13); this.label_conv_arr.TabIndex = 33; this.label_conv_arr.Text = "->"; // // label_hash // this.label_hash.AutoSize = true; this.label_hash.Location = new System.Drawing.Point(20, 393); this.label_hash.Name = "label_hash"; this.label_hash.Size = new System.Drawing.Size(32, 13); this.label_hash.TabIndex = 34; this.label_hash.Text = "Hash"; // // listBox // this.listBox.FormattingEnabled = true; this.listBox.Location = new System.Drawing.Point(315, 80); this.listBox.Name = "listBox"; this.listBox.Size = new System.Drawing.Size(263, 368); this.listBox.TabIndex = 35; this.listBox.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listBox_MouseDoubleClick); // // label_list // this.label_list.AutoSize = true; this.label_list.Location = new System.Drawing.Point(313, 451); this.label_list.Name = "label_list"; this.label_list.Size = new System.Drawing.Size(136, 13); this.label_list.TabIndex = 36; this.label_list.Text = "Double click to view details"; // // comboBox_bd // this.comboBox_bd.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_bd.FormattingEnabled = true; this.comboBox_bd.Location = new System.Drawing.Point(110, 40); this.comboBox_bd.Name = "comboBox_bd"; this.comboBox_bd.Size = new System.Drawing.Size(88, 21); this.comboBox_bd.TabIndex = 37; // // comboBox_port // this.comboBox_port.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox_port.FormattingEnabled = true; this.comboBox_port.Location = new System.Drawing.Point(110, 13); this.comboBox_port.Name = "comboBox_port"; this.comboBox_port.Size = new System.Drawing.Size(88, 21); this.comboBox_port.TabIndex = 38; this.comboBox_port.Click += new System.EventHandler(this.comboBox_port_SelectedIndexChanged); // // button_conn // this.button_conn.Location = new System.Drawing.Point(207, 23); this.button_conn.Name = "button_conn"; this.button_conn.Size = new System.Drawing.Size(67, 33); this.button_conn.TabIndex = 39; this.button_conn.Text = "Connect"; this.button_conn.UseVisualStyleBackColor = true; this.button_conn.Click += new System.EventHandler(this.button_conn_Click); // // label_port // this.label_port.Location = new System.Drawing.Point(16, 16); this.label_port.Name = "label_port"; this.label_port.Size = new System.Drawing.Size(89, 13); this.label_port.TabIndex = 40; this.label_port.Text = "Port"; this.label_port.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label_bd // this.label_bd.Location = new System.Drawing.Point(13, 43); this.label_bd.Name = "label_bd"; this.label_bd.Size = new System.Drawing.Size(91, 13); this.label_bd.TabIndex = 41; this.label_bd.Text = "Bd"; this.label_bd.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // button_send // this.button_send.Enabled = false; this.button_send.Location = new System.Drawing.Point(22, 462); this.button_send.Name = "button_send"; this.button_send.Size = new System.Drawing.Size(108, 31); this.button_send.TabIndex = 43; this.button_send.Text = "Combine and Send"; this.button_send.UseVisualStyleBackColor = true; this.button_send.Click += new System.EventHandler(this.button_send_Click); // // button_exit // this.button_exit.Location = new System.Drawing.Point(511, 454); this.button_exit.Name = "button_exit"; this.button_exit.Size = new System.Drawing.Size(67, 33); this.button_exit.TabIndex = 44; this.button_exit.Text = "Exit"; this.button_exit.UseVisualStyleBackColor = true; this.button_exit.Click += new System.EventHandler(this.button_exit_Click); // // button1 // this.button1.Location = new System.Drawing.Point(252, 378); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(52, 24); this.button1.TabIndex = 45; this.button1.Text = "Convert"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label_err // this.label_err.AutoSize = true; this.label_err.Location = new System.Drawing.Point(137, 474); this.label_err.Name = "label_err"; this.label_err.Size = new System.Drawing.Size(0, 13); this.label_err.TabIndex = 46; // // groupBox1 // this.groupBox1.Controls.Add(this.label_bd); this.groupBox1.Controls.Add(this.label_port); this.groupBox1.Controls.Add(this.button_conn); this.groupBox1.Controls.Add(this.comboBox_port); this.groupBox1.Controls.Add(this.comboBox_bd); this.groupBox1.Location = new System.Drawing.Point(300, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(278, 68); this.groupBox1.TabIndex = 47; this.groupBox1.TabStop = false; // // Form_SerialMonitor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(237)))), ((int)(((byte)(245))))); this.ClientSize = new System.Drawing.Size(588, 499); this.Controls.Add(this.groupBox1); this.Controls.Add(this.label_err); this.Controls.Add(this.button1); this.Controls.Add(this.button_exit); this.Controls.Add(this.button_send); this.Controls.Add(this.label_list); this.Controls.Add(this.listBox); this.Controls.Add(this.label_hash); this.Controls.Add(this.label_conv_arr); this.Controls.Add(this.label_conv); this.Controls.Add(this.label_data); this.Controls.Add(this.label_fill); this.Controls.Add(this.label_sender_type); this.Controls.Add(this.label_sender); this.Controls.Add(this.label_command_send); this.Controls.Add(this.label_command); this.Controls.Add(this.label_size); this.Controls.Add(this.checkBox_hash); this.Controls.Add(this.textBox_hash_b2); this.Controls.Add(this.textBox_hash_b1); this.Controls.Add(this.textBox_conv_output); this.Controls.Add(this.comboBox_conv); this.Controls.Add(this.textBox_conv_input); this.Controls.Add(this.label_data_sep); this.Controls.Add(this.textBox_data); this.Controls.Add(this.button_fill); this.Controls.Add(this.textBox_fill); this.Controls.Add(this.comboBox_sender); this.Controls.Add(this.textBox_sender_b8); this.Controls.Add(this.textBox_sender_b7); this.Controls.Add(this.textBox_sender_b6); this.Controls.Add(this.textBox_sender_b5); this.Controls.Add(this.textBox_sender_b4); this.Controls.Add(this.textBox_sender_b3); this.Controls.Add(this.textBox_sender_b2); this.Controls.Add(this.textBox_sender_b1); this.Controls.Add(this.comboBox_command); this.Controls.Add(this.textBox_command_b2); this.Controls.Add(this.textBox_command_b1); this.Controls.Add(this.checkBox_size); this.Controls.Add(this.textBox_size_b2); this.Controls.Add(this.textBox_size_b1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "Form_SerialMonitor"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Serial Monitor"; this.Load += new System.EventHandler(this.Form_SerialMonitor_Load); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion public System.Windows.Forms.TextBox textBox_size_b1; public System.Windows.Forms.TextBox textBox_size_b2; public System.Windows.Forms.CheckBox checkBox_size; public System.Windows.Forms.TextBox textBox_command_b1; public System.Windows.Forms.TextBox textBox_command_b2; public System.Windows.Forms.ComboBox comboBox_command; public System.Windows.Forms.TextBox textBox_sender_b2; public System.Windows.Forms.TextBox textBox_sender_b1; public System.Windows.Forms.TextBox textBox_sender_b4; public System.Windows.Forms.TextBox textBox_sender_b3; public System.Windows.Forms.TextBox textBox_sender_b6; public System.Windows.Forms.TextBox textBox_sender_b5; public System.Windows.Forms.TextBox textBox_sender_b8; public System.Windows.Forms.TextBox textBox_sender_b7; public System.Windows.Forms.ComboBox comboBox_sender; public System.Windows.Forms.TextBox textBox_fill; public System.Windows.Forms.Button button_fill; public System.Windows.Forms.TextBox textBox_data; public System.Windows.Forms.Label label_data_sep; public System.Windows.Forms.TextBox textBox_conv_input; public System.Windows.Forms.ComboBox comboBox_conv; public System.Windows.Forms.TextBox textBox_conv_output; public System.Windows.Forms.CheckBox checkBox_hash; public System.Windows.Forms.TextBox textBox_hash_b2; public System.Windows.Forms.TextBox textBox_hash_b1; public System.Windows.Forms.Label label_size; public System.Windows.Forms.Label label_command; public System.Windows.Forms.Label label_command_send; public System.Windows.Forms.Label label_sender; public System.Windows.Forms.Label label_sender_type; public System.Windows.Forms.Label label_fill; public System.Windows.Forms.Label label_data; public System.Windows.Forms.Label label_conv; public System.Windows.Forms.Label label_conv_arr; public System.Windows.Forms.Label label_hash; public System.Windows.Forms.ListBox listBox; public System.Windows.Forms.Label label_list; public System.Windows.Forms.ComboBox comboBox_bd; public System.Windows.Forms.ComboBox comboBox_port; public System.Windows.Forms.Button button_conn; public System.Windows.Forms.Label label_port; public System.Windows.Forms.Label label_bd; public System.Windows.Forms.Button button_send; public System.Windows.Forms.Button button_exit; public System.Windows.Forms.Button button1; public System.Windows.Forms.Label label_err; private System.Windows.Forms.GroupBox groupBox1; } }
using System; using System.Collections.Generic; using System.Linq; using System.Collections.Specialized; using Eto.Forms; using System.Collections; namespace Eto.CustomControls { public interface ITreeHandler { ITreeGridItem SelectedItem { get; } void SelectRow (int row); bool AllowMultipleSelection { get; } void PreResetTree (); void PostResetTree (); } public class TreeController : ITreeGridStore<ITreeGridItem>, IList, INotifyCollectionChanged { readonly Dictionary<int, ITreeGridItem> cache = new Dictionary<int, ITreeGridItem> (); int? countCache; List<TreeController> sections; TreeController parent; protected int StartRow { get; private set; } List<TreeController> Sections { get { if (sections == null) sections = new List<TreeController> (); return sections; } } public ITreeGridStore<ITreeGridItem> Store { get; private set; } public ITreeHandler Handler { get; set; } public event EventHandler<TreeGridViewItemCancelEventArgs> Expanding; public event EventHandler<TreeGridViewItemCancelEventArgs> Collapsing; public event EventHandler<TreeGridViewItemEventArgs> Expanded; public event EventHandler<TreeGridViewItemEventArgs> Collapsed; protected virtual void OnExpanding (TreeGridViewItemCancelEventArgs e) { if (Expanding != null) Expanding (this, e); } protected virtual void OnCollapsing (TreeGridViewItemCancelEventArgs e) { if (Collapsing != null) Collapsing (this, e); } protected virtual void OnExpanded (TreeGridViewItemEventArgs e) { if (Expanded != null) Expanded (this, e); } protected virtual void OnCollapsed (TreeGridViewItemEventArgs e) { if (Collapsed != null) Collapsed (this, e); } public void InitializeItems (ITreeGridStore<ITreeGridItem> store) { ClearCache (); if (sections != null) sections.Clear (); Store = store; if (Store != null) { for (int row = 0; row < Store.Count; row++) { var item = Store[row]; if (item.Expanded) { var children = (ITreeGridStore<ITreeGridItem>)item; var section = new TreeController { StartRow = row, Handler = Handler, parent = this }; section.InitializeItems (children); Sections.Add (section); } } } ResetCollection (); } void ClearCache () { countCache = null; cache.Clear (); } public int IndexOf (ITreeGridItem item) { if (cache.ContainsValue(item)) { var found = cache.First(r => object.ReferenceEquals(item, r.Value)); return found.Key; } for (int i = 0; i < Count; i++) { if (object.ReferenceEquals(this[i], item)) return i; } return -1; } public int LevelAtRow (int row) { if (sections == null || sections.Count == 0) return 0; foreach (var section in sections) { if (row <= section.StartRow) { return 0; } else { var count = section.Count; if (row <= section.StartRow + count) { return section.LevelAtRow(row - section.StartRow - 1) + 1; } row -= count; } } return 0; } public ITreeGridItem this[int row] { get { ITreeGridItem item; if (!cache.TryGetValue (row, out item)) { item = GetItemAtRow (row); cache[row] = item; } return item; } } public class TreeNode { public ITreeGridItem Item { get; set; } public int RowIndex { get; set; } public int Count { get; set; } public int Index { get; set; } public int Level { get; set; } public TreeNode Parent { get; set; } public bool IsFirstNode { get { return Index == 0; } } public bool IsLastNode { get { return Index == Count-1; } } } public TreeNode GetNodeAtRow (int row) { return GetNodeAtRow (row, null, 0); } TreeNode GetNodeAtRow (int row, TreeNode parent, int level) { var node = new TreeNode { RowIndex = row, Parent = parent, Count = Store.Count, Level = level }; if (sections == null || sections.Count == 0) { node.Item = Store[row]; node.Index = row; } else { foreach (var section in sections) { if (row <= section.StartRow) { node.Item = Store[row]; node.Index = row; break; } if (row <= section.StartRow + section.Count) { node.Index = section.StartRow; node.Item = section.Store as ITreeGridItem; return section.GetNodeAtRow(row - section.StartRow - 1, node, level + 1); } row -= section.Count; } } if (node.Item == null && row < Store.Count) { node.Item = Store[row]; node.Index = row; } return node; } ITreeGridItem GetItemAtRow (int row) { if (Store == null) return null; ITreeGridItem item = null; if (sections == null || sections.Count == 0) item = Store[row]; if (item == null) { foreach (var section in sections) { if (row <= section.StartRow) { item = Store[row]; break; } if (row <= section.StartRow + section.Count) { item = section.GetItemAtRow(row - section.StartRow - 1); break; } row -= section.Count; } } if (item == null && row < Store.Count) item = Store[row]; return item; } public bool IsExpanded (int row) { if (sections == null) return false; foreach (var section in sections) { if (row < section.StartRow) return false; if (row == section.StartRow) { return true; } if (row <= section.StartRow + section.Count) { return section.IsExpanded(row - section.StartRow - 1); } row -= section.Count; } return false; } public bool ExpandRow (int row) { var args = new TreeGridViewItemCancelEventArgs(GetItemAtRow(row)); OnExpanding (args); if (args.Cancel) return false; args.Item.Expanded = true; ExpandRowInternal (row); OnExpanded (new TreeGridViewItemEventArgs (args.Item)); return true; } ITreeGridStore<ITreeGridItem> ExpandRowInternal (int row) { ITreeGridStore<ITreeGridItem> children = null; if (sections == null || sections.Count == 0) { children = (ITreeGridStore<ITreeGridItem>)Store [row]; var childController = new TreeController { StartRow = row, Store = children, Handler = Handler, parent = this }; Sections.Add (childController); } else { bool addTop = true; foreach (var section in sections) { if (row <= section.StartRow) { break; } if (row <= section.StartRow + section.Count) { children = section.ExpandRowInternal(row - section.StartRow - 1); addTop = false; break; } row -= section.Count; } if (addTop && row < Store.Count) { children = (ITreeGridStore<ITreeGridItem>)Store [row]; var childController = new TreeController { StartRow = row, Store = children, Handler = Handler, parent = this }; Sections.Add (childController); } } Sections.Sort ((x, y) => x.StartRow.CompareTo (y.StartRow)); if (children != null) { ClearCache (); ResetCollection (); } return children; } bool ChildIsSelected (ITreeGridItem item) { var node = Handler.SelectedItem; while (node != null) { node = node.Parent; if (object.ReferenceEquals (node, item)) return true; } return false; } void ResetCollection () { if (parent == null) Handler.PreResetTree (); OnTriggerCollectionChanged (new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Reset)); if (parent == null) Handler.PostResetTree (); } public bool CollapseRow (int row) { var args = new TreeGridViewItemCancelEventArgs (GetItemAtRow (row)); OnCollapsing (args); if (args.Cancel) return false; var shouldSelect = !Handler.AllowMultipleSelection && ChildIsSelected (args.Item); args.Item.Expanded = false; OnCollapsed (new TreeGridViewItemEventArgs (args.Item)); CollapseSection (row); ResetCollection (); if (shouldSelect) Handler.SelectRow (row); return true; } void CollapseSection (int row) { if (sections != null && sections.Count > 0) { bool addTop = true; foreach (var section in sections) { if (row <= section.StartRow) { break; } if (row <= section.StartRow + section.Count) { addTop = false; section.CollapseSection(row - section.StartRow - 1); break; } row -= section.Count; } if (addTop && row < Store.Count) Sections.RemoveAll (r => r.StartRow == row); } ClearCache (); } public int Count { get { if (countCache != null) return countCache.Value; if (sections != null) countCache = Store.Count + sections.Sum (r => r.Count); else countCache = Store.Count; return countCache.Value; } } public int Add (object value) { return 0; } public void Clear () { } public bool Contains (object value) { return true; } int IList.IndexOf (object value) { return IndexOf (value as ITreeGridItem); } public void Insert (int index, object value) { } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return false; } } public void Remove (object value) { } public void RemoveAt (int index) { } object IList.this[int index] { get { return this[index]; } set { } } public void CopyTo (Array array, int index) { throw new NotImplementedException (); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } public IEnumerator GetEnumerator () { for (int i = 0; i < Count; i++) { yield return this[i]; } } public event NotifyCollectionChangedEventHandler CollectionChanged; protected virtual void OnTriggerCollectionChanged (NotifyCollectionChangedEventArgs args) { if (CollectionChanged != null) CollectionChanged (this, args); } static IEnumerable<ITreeGridItem> GetParents (ITreeGridItem value) { ITreeGridItem parent = value.Parent; while (parent != null) { yield return parent; parent = parent.Parent; } } public void ExpandToItem (ITreeGridItem value) { var parents = GetParents (value).Reverse (); foreach (var item in parents) { var row = IndexOf (item); if (row >= 0 && !IsExpanded(row)) ExpandRow (row); } } } }
using System; using System.Collections; using System.Text; using DAQ.HAL; using DAQ.Environment; namespace DAQ.Pattern { /// <summary> /// A class for building patterns that can be output by a NI pattern generator. /// To use this class, subclass it, and add your own structure. This class provides /// the primitives edge and pulse. Everything else is up to you. /// </summary> /// [Serializable] public class PatternBuilder32 : IPatternSource { [NonSerialized] private bool timeOrdered = true; [NonSerialized] private Layout layout; private UInt32[] pattern; private Int16[] patternInt16; private byte[] bytePattern; [NonSerialized] private int[] latestTimes; // Build a table of bit -> int conversions private UInt32[] bitValues = new UInt32[32]; public PatternBuilder32() { for (int i = 0 ; i < 32 ; i++) { UInt32 tmp = 1; bitValues[i] = tmp << i; } Clear(); } /** Add an edge to a pattern. All pattern trees must have addEdges as their terminals * (either directly or through <code>pulse</code> which is just two <code>addEdge</code>s */ public void AddEdge( int channel, int time, bool sense ) { if (timeOrdered) { // check the time ordering if ( time > latestTimes[channel] ) latestTimes[channel] = time; else throw new TimeOrderException(); } // add the edge layout.AddEdge(channel, time, sense); } public void AddEdge(string channel, int time, bool sense) { AddEdge(((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[channel]).BitNumber , time, sense); } /** Convenience method to add two edges. */ public int Pulse(int startTime, int delay, int duration, int channel ) { AddEdge(channel, startTime + delay, true ); AddEdge(channel, startTime + delay + duration, false ); return delay + duration; } public int Pulse(int startTime, int delay, int duration, string channel) { return Pulse(startTime,delay,duration, ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[channel]).BitNumber); } /** Adds a downward going pulse **/ public int DownPulse(int startTime, int delay, int duration, int channel ) { //AddEdge(channel, startTime, true); AddEdge(channel, startTime + delay, false ); AddEdge(channel, startTime + delay + duration, true ); return delay + duration; } public int DownPulse(int startTime, int delay, int duration, string channel) { return DownPulse(startTime, delay, duration, ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[channel]).BitNumber); } /** Convenience method to determine the channel number from a NI port/line spec. */ public static int ChannelFromNIPort(int port, int line) { return line + (8 * port); } /** Clear the pattern. */ public void Clear() { layout = new Layout(32); latestTimes = new int[32]; for (int i = 0 ; i < 32 ; i++) latestTimes[i] = -1; pattern = null; } /** Get the layout for this pattern. */ public Layout Layout { get { return layout; } } // Methods for controlling the level of error checking /** Used to enable or disable time order checks when pattern building. If time * order checking is enabled, adding an edge to a channel at a time earlier than * the latest edge on that channel will throw a <code>TimeOrderException</code> */ public bool EnforceTimeOrdering { set { timeOrdered = value; } } // Methods for building the pattern from its layout, and getting the // resulting pattern /** Return the minimum length array that this pattern can fit into. */ public int GetMinimumLength() { return layout.LastEventTime + 1; } /** Generate the pattern. */ public void BuildPattern( int length ) { // Are there any events ? if (layout.EventTimes.Count == 0) throw new PatternBuildException("No events to build pattern for."); // Is that big enough ? if ( length < layout.LastEventTime + 1 ) throw new PatternBuildException("Pattern will not fit in array of requested length.\n" + "Pattern length is " + layout.LastEventTime + ". Array length is " + length); // make the pattern array pattern = new UInt32[length]; // Get the event times and fill in the gaps ArrayList times = layout.EventTimes; int numberOfEvents = times.Count; // first the time before the first event, if there is any for (int i = 0 ; i < (int)times[0] ; i++ ) { pattern[i] = 0; } int endTime = 0; for (int j = 1 ; j < numberOfEvents ; j++ ) { int startTime = (int)times[j-1]; endTime = (int)times[j]; EdgeSet es = layout.GetEdgeSet(startTime); UInt32 nextInt; if (startTime != 0) { // middle of a pattern UInt32 previousInt = pattern[startTime - 1]; nextInt = GenerateNextInt( previousInt, es, true, startTime ); } else { // start of a pattern, special case UInt32 previousInt = 0; nextInt = GenerateNextInt( previousInt, es, false, startTime ); } // fill in the pattern for ( int i = startTime ; i < endTime ; i++ ) { pattern[i] = nextInt; } } // pad up to the end UInt32 padInt; if (endTime == 0) padInt = 0; else padInt = GenerateNextInt( pattern[endTime-1], layout.GetEdgeSet(endTime), true, endTime ); for (int i = endTime ; i < length ; i++ ) { pattern[i] = padInt; } GenerateInt16Pattern(); GenerateBytePattern(); } private UInt32 GenerateNextInt( UInt32 previousInt, EdgeSet es, bool throwError, int time) { // build a bit mask for the upwards edges UInt32 upMask = 0; for (int i = 0 ; i < 32 ; i++) if (es.GetEdge(i) == EdgeSense.UP) upMask = upMask | bitValues[i]; // and the downwards edges UInt32 downMask = 0; for (int i = 0 ; i < 32 ; i++) if (es.GetEdge(i) == EdgeSense.DOWN) downMask = downMask | bitValues[i]; // error checking if (throwError) { if ( (upMask & previousInt) != 0 ) throw new PatternBuildException("Edge conflict on upward edge at time " + time); if ( (downMask & ~previousInt) != 0 ) throw new PatternBuildException("Edge conflict on downward edge at time " + time); } UInt32 returnInt = previousInt | upMask; returnInt = ~(~returnInt | downMask); return returnInt; } /** Get the pattern - you must call <code>generatePattern()</code> first. */ public UInt32[] Pattern { get { return pattern; } } public Int16[] PatternAsInt16s { get { return patternInt16; } } public byte[] PatternAsBytes { get { return bytePattern; } } // gets the low word of the pattern so that you can run the pattern generator in half-width mode public Int16[] LowHalfPatternAsInt16 { get { Int16[] patternInt16 = new Int16[pattern.Length]; for (int i = 0 ; i < pattern.Length ; i++) { Int16 lowWord = (Int16)(pattern[i] & 0x0000ffff); patternInt16[i] = lowWord; } return patternInt16; } } // gets the high word of the pattern so that you can run the pattern generator in half-width mode public Int16[] HighHalfPatternAsInt16 { get { Int16[] patternInt16 = new Int16[pattern.Length]; for (int i = 0 ; i < pattern.Length ; i++) { Int16 highWord = (Int16)((pattern[i] & 0xffff0000) >> 16); patternInt16[i] = highWord; } return patternInt16; } } public byte[] LowHalfPatternAsByte { get { byte[] bytePattern = new byte[2 * pattern.Length]; for (int i = 0; i < pattern.Length; i++) { byte one = (byte) (pattern[i] & 0x000000ff); byte two = (byte) ((pattern[i] & 0x0000ff00) >> 8); bytePattern[2*i] = one; bytePattern[2*i + 1] = two; } return bytePattern; } } public byte[] HighHalfPatternAsByte { get { byte[] bytePattern = new byte[2 * pattern.Length]; for (int i = 0; i < pattern.Length; i++) { byte three = (byte) ((pattern[i] & 0x00ff0000) >> 16); byte four = (byte) ((pattern[i] & 0xff000000) >> 24); bytePattern[2*i] = three; bytePattern[2*i + 1] = four; } return bytePattern; } } private void GenerateInt16Pattern() { // TODO: I learn that there's a BitConverter class that can do this a bit more nicely patternInt16 = new Int16[pattern.Length * 2]; for (int i = 0 ; i < pattern.Length ; i++) { Int16 lowWord = (Int16)(pattern[i] & 0x0000ffff); Int16 highWord = (Int16)((pattern[i] & 0xffff0000) >> 16); // the order of these bytes is not obvious !!! By swapping these, // the word endianism can be changed patternInt16[2*i] = lowWord; patternInt16[2*i + 1] = highWord; } } private void GenerateBytePattern() { bytePattern = new byte[pattern.Length * 4]; for (int i = 0; i < pattern.Length; i++) { byte one = (byte) (pattern[i] & 0x000000ff); byte two = (byte) ((pattern[i] & 0x0000ff00) >> 8); byte three = (byte) ((pattern[i] & 0x00ff0000) >> 16); byte four = (byte) ((pattern[i] & 0xff000000) >> 24); bytePattern[4*i] = one; bytePattern[4*i + 1] = two; bytePattern[4*i + 2] = three; bytePattern[4*i + 3] = four; } } // Methods for displaying the pattern and layout /** Display the binary representation of the pattern. */ public String ArrayToString() { StringBuilder sb = new StringBuilder(pattern.Length * 33); for (int i = 0 ; i < pattern.Length ; i++) { for (int j = 0 ; j < 32 ; j++) { bool bit = ((pattern[i] & bitValues[j]) != 0); if (bit) sb.Append("1"); else sb.Append("0"); } sb.Append("\n"); } return sb.ToString(); } /** Display the pattern's layout as a list of edge events. */ public String LayoutToString() { return layout.ToString(); } } public class TimeOrderException : ApplicationException {} public class PatternBuildException : ApplicationException { public PatternBuildException(String message) : base(message) {} } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.Remoting { using System.Globalization; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Messaging; using System.Runtime.ConstrainedExecution; using System.Reflection; using System; // IdentityHolder maintains a lookup service for remoting identities. The methods // provided by it are used during calls to Wrap, UnWrap, Marshal, Unmarshal etc. // using System.Collections; using System.Diagnostics.Contracts; // This is just a internal struct to hold the various flags // that get passed for different flavors of idtable operations // just so that we do not have too many separate boolean parameters // all over the place (eg. xxxIdentity(id,uri, true, false, true);) internal struct IdOps { internal const int None = 0x00000000; internal const int GenerateURI = 0x00000001; internal const int StrongIdentity = 0x00000002; internal const int IsInitializing = 0x00000004; // Identity has not been fully initialized yet internal static bool bStrongIdentity(int flags) { return (flags&StrongIdentity)!=0; } internal static bool bIsInitializing(int flags) { return (flags & IsInitializing) != 0; } } // Internal enum to specify options for SetIdentity [Serializable] internal enum DuplicateIdentityOption { Unique, // -throw an exception if there is already an identity in the table UseExisting, // -if there is already an identity in the table, then use that one. // (could happen in a Connect ----, but we don't care which identity we get) } // enum DuplicateIdentityOption internal sealed class IdentityHolder { // private static Timer CleanupTimer = null; // private const int CleanupInterval = 60000; // 1 minute. // private static Object staticSyncObject = new Object(); private static volatile int SetIDCount=0; private const int CleanUpCountInterval = 0x40; private const int INFINITE = 0x7fffffff; private static Hashtable _URITable = new Hashtable(); private static volatile Context _cachedDefaultContext = null; internal static Hashtable URITable { get { return _URITable; } } internal static Context DefaultContext { [System.Security.SecurityCritical] // auto-generated get { if (_cachedDefaultContext == null) { _cachedDefaultContext = Thread.GetDomain().GetDefaultContext(); } return _cachedDefaultContext; } } // NOTE!!!: This must be used to convert any uri into something that can // be used as a key in the URITable!!! private static String MakeURIKey(String uri) { return Identity.RemoveAppNameOrAppGuidIfNecessary( uri.ToLower(CultureInfo.InvariantCulture)); } private static String MakeURIKeyNoLower(String uri) { return Identity.RemoveAppNameOrAppGuidIfNecessary(uri); } internal static ReaderWriterLock TableLock { get { return Thread.GetDomain().RemotingData.IDTableLock;} } // Cycles through the table periodically and cleans up expired entries. // private static void CleanupIdentities(Object state) { // < Contract.Assert( Thread.GetDomain().RemotingData.IDTableLock.IsWriterLockHeld, "ID Table being cleaned up without taking a lock!"); IDictionaryEnumerator e = URITable.GetEnumerator(); ArrayList removeList = new ArrayList(); while (e.MoveNext()) { Object o = e.Value; WeakReference wr = o as WeakReference; if ((null != wr) && (null == wr.Target)) { removeList.Add(e.Key); } } foreach (String key in removeList) { URITable.Remove(key); } } [System.Security.SecurityCritical] // auto-generated internal static void FlushIdentityTable() { // We need to guarantee that finally is not interrupted so that the lock is released. // TableLock has a long path without reliability contract. To avoid adding contract on // the path, we will use ReaderWriterLock directly. ReaderWriterLock rwlock = TableLock; bool takeAndRelease = !rwlock.IsWriterLockHeld; RuntimeHelpers.PrepareConstrainedRegions(); try{ if (takeAndRelease) rwlock.AcquireWriterLock(INFINITE); CleanupIdentities(null); } finally{ if(takeAndRelease && rwlock.IsWriterLockHeld){ rwlock.ReleaseWriterLock(); } } } private IdentityHolder() { // this is a singleton object. Can't construct it. } // Looks up the identity corresponding to a URI. // [System.Security.SecurityCritical] // auto-generated internal static Identity ResolveIdentity(String URI) { if (URI == null) throw new ArgumentNullException("URI"); Contract.EndContractBlock(); Identity id; // We need to guarantee that finally is not interrupted so that the lock is released. // TableLock has a long path without reliability contract. To avoid adding contract on // the path, we will use ReaderWriterLock directly. ReaderWriterLock rwlock = TableLock; bool takeAndRelease = !rwlock.IsReaderLockHeld; RuntimeHelpers.PrepareConstrainedRegions(); try { if (takeAndRelease) rwlock.AcquireReaderLock(INFINITE); Message.DebugOut("ResolveIdentity:: URI: " + URI + "\n"); Message.DebugOut("ResolveIdentity:: table.count: " + URITable.Count + "\n"); //Console.WriteLine("\n ResolveID: URI = " + URI); // This may be called both in the client process and the server process (loopback case). id = ResolveReference(URITable[MakeURIKey(URI)]); } finally { if (takeAndRelease && rwlock.IsReaderLockHeld){ rwlock.ReleaseReaderLock(); } } return id; } // ResolveIdentity // If the identity isn't found, this version will just return // null instead of asserting (this version doesn't need to // take a lock). [System.Security.SecurityCritical] // auto-generated internal static Identity CasualResolveIdentity(String uri) { if (uri == null) return null; Identity id = CasualResolveReference(URITable[MakeURIKeyNoLower(uri)]); if (id == null) { id = CasualResolveReference(URITable[MakeURIKey(uri)]); // DevDiv 720951 and 911924: // CreateWellKnownObject inserts the Identity into the URITable before // it is fully initialized. This can cause a race condition if another // concurrent operation re-enters this code and attempts to use it. // If we discover this situation, behave as if it is not in the URITable. // This falls into the code below to call CreateWellKnownObject again. // That method operates under a lock and will not return until it // has been fully initialized. It will not create or initialize twice. if (id == null || id.IsInitializing) { // Check if this a well-known object which needs to be faulted in id = RemotingConfigHandler.CreateWellKnownObject(uri); } } return id; } // CasualResolveIdentity private static Identity ResolveReference(Object o) { Contract.Assert( TableLock.IsReaderLockHeld || TableLock.IsWriterLockHeld , "Should have locked the ID Table!"); WeakReference wr = o as WeakReference; if (null != wr) { return((Identity) wr.Target); } else { return((Identity) o); } } // ResolveReference private static Identity CasualResolveReference(Object o) { WeakReference wr = o as WeakReference; if (null != wr) { return((Identity) wr.Target); } else { return((Identity) o); } } // CasualResolveReference // // // This is typically called when we need to create/establish // an identity for a serverObject. [System.Security.SecurityCritical] // auto-generated internal static ServerIdentity FindOrCreateServerIdentity( MarshalByRefObject obj, String objURI, int flags) { Message.DebugOut("Entered FindOrCreateServerIdentity \n"); ServerIdentity srvID = null; bool fServer; srvID = (ServerIdentity) MarshalByRefObject.GetIdentity(obj, out fServer); if (srvID == null) { // Create a new server identity and add it to the // table. IdentityHolder will take care of ----s Context serverCtx = null; if (obj is ContextBoundObject) { serverCtx = Thread.CurrentContext; } else { serverCtx = DefaultContext; } Contract.Assert(null != serverCtx, "null != serverCtx"); ServerIdentity serverID = new ServerIdentity(obj, serverCtx); // Set the identity depending on whether we have the server or proxy if(fServer) { srvID = obj.__RaceSetServerIdentity(serverID); Contract.Assert(srvID == MarshalByRefObject.GetIdentity(obj), "Bad ID state!" ); } else { RealProxy rp = null; rp = RemotingServices.GetRealProxy(obj); Contract.Assert(null != rp, "null != rp"); rp.IdentityObject = serverID; srvID = (ServerIdentity) rp.IdentityObject; } // DevDiv 720951 and 911924: // CreateWellKnownObject creates a ServerIdentity and places it in URITable // before it is fully initialized. This transient flag is set to to prevent // other concurrent operations from using it. CreateWellKnownObject is the // only code path that sets this flag, and by default it is false. if (IdOps.bIsInitializing(flags)) { srvID.IsInitializing = true; } Message.DebugOut("Created ServerIdentity \n"); } #if false // Check that we are asked to create the identity for the same // URI as the one already associated with the server object. // It is an error to associate two URIs with the same server // object // GopalK: Try eliminating the test because it is also done by GetOrCreateIdentity if ((null != objURI) && (null != srvID.ObjURI)) { if (string.Compare(objURI, srvID.ObjURI, StringComparison.OrdinalIgnoreCase) == 0) // case-insensitive compare { Message.DebugOut("Trying to associate a URI with identity again .. throwing execption \n"); throw new RemotingException( String.Format( Environment.GetResourceString( "Remoting_ResetURI"), srvID.ObjURI, objURI)); } } #endif // NOTE: for purely x-context cases we never execute this ... // the server ID is not put in the ID table. if ( IdOps.bStrongIdentity(flags) ) { // We need to guarantee that finally is not interrupted so that the lock is released. // TableLock has a long path without reliability contract. To avoid adding contract on // the path, we will use ReaderWriterLock directly. ReaderWriterLock rwlock = TableLock; bool takeAndRelease = !rwlock.IsWriterLockHeld; RuntimeHelpers.PrepareConstrainedRegions(); try { if (takeAndRelease) rwlock.AcquireWriterLock(INFINITE); // It is possible that we are marshaling out of this app-domain // for the first time. We need to do two things // (1) If there is no URI associated with the identity then go ahead // and generate one. // (2) Add the identity to the URI -> Identity map if not already present // (For purely x-context cases we don't need the URI) // (3) If the object ref is null, then this object hasn't been // marshalled yet. // (4) if id was created through SetObjectUriForMarshal, it would be // in the ID table if ((srvID.ObjURI == null) || (srvID.IsInIDTable() == false)) { // we are marshalling a server object, so there should not be a // a different identity at this location. SetIdentity(srvID, objURI, DuplicateIdentityOption.Unique); } // If the object is marked as disconnect, mark it as connected if(srvID.IsDisconnected()) srvID.SetFullyConnected(); } finally { if (takeAndRelease && rwlock.IsWriterLockHeld) { rwlock.ReleaseWriterLock(); } } } Message.DebugOut("Leaving FindOrCreateServerIdentity \n"); Contract.Assert(null != srvID,"null != srvID"); return srvID; } // // // This is typically called when we are unmarshaling an objectref // in order to create a client side identity for a remote server // object. [System.Security.SecurityCritical] // auto-generated internal static Identity FindOrCreateIdentity( String objURI, String URL, ObjRef objectRef) { Identity idObj = null; Contract.Assert(null != objURI,"null != objURI"); bool bWellKnown = (URL != null); // Lookup the object in the identity table // for well-known objects we user the URL // as the hash-key (instead of just the objUri) idObj = ResolveIdentity(bWellKnown ? URL : objURI); if (bWellKnown && (idObj != null) && (idObj is ServerIdentity)) { // We are trying to do a connect to a server wellknown object. throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Remoting_WellKnown_CantDirectlyConnect"), URL)); } if (null == idObj) { // There is no entry for this uri in the IdTable. Message.DebugOut("RemotingService::FindOrCreateIdentity: Creating Identity\n"); // This identity is being encountered for the first time. // We have to do the following things // (1) Create an identity object for the proxy // (2) Add the identity to the identity table // (3) Create a proxy for the object represented by the objref // Create a new identity // <EMAIL>GopalK:</EMAIL> Identity should get only one string that is used for everything idObj = new Identity(objURI, URL); // We need to guarantee that finally is not interrupted so that the lock is released. // TableLock has a long path without reliability contract. To avoid adding contract on // the path, we will use ReaderWriterLock directly. ReaderWriterLock rwlock = TableLock; bool takeAndRelease = !rwlock.IsWriterLockHeld; RuntimeHelpers.PrepareConstrainedRegions(); try { // Add it to the identity table if (takeAndRelease) rwlock.AcquireWriterLock(INFINITE); // SetIdentity will give the correct Id if we ----d // between the ResolveIdentity call above and now. // (we are unmarshaling, and the server should guarantee // that the uri is unique, so we will use an existing identity // in case of a ----) idObj = SetIdentity(idObj, null, DuplicateIdentityOption.UseExisting); idObj.RaceSetObjRef(objectRef); } finally { if (takeAndRelease && rwlock.IsWriterLockHeld) { rwlock.ReleaseWriterLock(); } } } else { Message.DebugOut("RemotingService::FindOrCreateIdentity: Found Identity!\n"); } Contract.Assert(null != idObj,"null != idObj"); return idObj; } // Creates an identity entry. // This is used by Unmarshal and Marshal to generate the URI to identity // mapping // // [System.Security.SecurityCritical] // auto-generated private static Identity SetIdentity( Identity idObj, String URI, DuplicateIdentityOption duplicateOption) { // NOTE: This function assumes that a lock has been taken // by the calling function // idObj could be for a transparent proxy or a server object Message.DebugOut("SetIdentity:: domainid: " + Thread.GetDomainID() + "\n"); Contract.Assert(null != idObj,"null != idObj"); // WriterLock must already be taken when SetIdentity is called! Contract.Assert( TableLock.IsWriterLockHeld, "Should have write-locked the ID Table!"); // flag to denote that the id being set is a ServerIdentity bool bServerIDSet = idObj is ServerIdentity; if (null == idObj.URI) { // No URI has been associated with this identity. It must be a // server identity getting marshaled out of the app domain for // the first time. Contract.Assert(bServerIDSet,"idObj should be ServerIdentity"); // Set the URI on the idObj (generating one if needed) idObj.SetOrCreateURI(URI); // If objectref is non-null make sure both have same URIs // (the URI in the objectRef could have potentially been reset // in a past external call to Disconnect() if (idObj.ObjectRef != null) { idObj.ObjectRef.URI = idObj.URI; } Message.DebugOut("SetIdentity: Generated URI " + URI + " for identity"); } // If we have come this far then there is no URI to identity // mapping present. Go ahead and create one. // ID should have a URI by now. Contract.Assert(null != idObj.URI,"null != idObj.URI"); // See if this identity is already present in the Uri table String uriKey = MakeURIKey(idObj.URI); Object o = URITable[uriKey]; // flag to denote that the id found in the table is a ServerIdentity bool bServerID; if (null != o) { // We found an identity (or a WeakRef to one) for the URI provided WeakReference wr = o as WeakReference; Identity idInTable = null; if (wr != null) { // The object we found is a weak referece to an identity // This could be an identity for a client side // proxy // OR // a server identity which has been weakened since its life // is over. idInTable = (Identity) wr.Target; bServerID = idInTable is ServerIdentity; // If we find a weakRef for a ServerId we will be converting // it to a strong one before releasing the IdTable lock. Contract.Assert( (idInTable == null)|| (!bServerID || idInTable.IsRemoteDisconnected()), "Expect to find WeakRef only for remotely disconnected ids"); // We could find a weakRef to a client ID that does not // match the idObj .. but that is a handled ---- case // during Unmarshaling .. SetIdentity() will return the ID // from the table to the caller. } else { // We found a non-weak (strong) Identity for the URI idInTable = (Identity) o; bServerID = idInTable is ServerIdentity; //We dont put strong refs to client "Identity"s in the table Contract.Assert( bServerID, "Found client side strong ID in the table"); } if ((idInTable != null) && (idInTable != idObj)) { // We are trying to add another identity for the same URI switch (duplicateOption) { case DuplicateIdentityOption.Unique: { String tempURI = idObj.URI; // Throw an exception to indicate the error since this could // be caused by a user trying to marshal two objects with the same // URI throw new RemotingException( Environment.GetResourceString("Remoting_URIClash", tempURI)); } // case DuplicateIdentityOption.Unique case DuplicateIdentityOption.UseExisting: { // This would be a case where our thread lost the ---- // we will return the one found in the table idObj = idInTable; break; } // case DuplicateIdentityOption.UseExisting: default: { Contract.Assert(false, "Invalid DuplicateIdentityOption"); break; } } // switch (duplicateOption) } else if (wr!=null) { // We come here if we found a weakRef in the table but // the target object had been cleaned up // OR // If there was a weakRef in the table and the target // object matches the idObj just passed in // Strengthen the entry if it a ServerIdentity. if (bServerID) { URITable[uriKey] = idObj; } else { // For client IDs associate the table entry // with the one passed in. // (If target was null we would set it ... // if was non-null then it matches idObj anyway) wr.Target = idObj; } } } else { // We did not find an identity entry for the URI Object addMe = null; if (bServerIDSet) { addMe = idObj; ((ServerIdentity)idObj).SetHandle(); } else { addMe = new WeakReference(idObj); } // Add the entry into the table URITable.Add(uriKey, addMe); idObj.SetInIDTable(); // After every fixed number of set-id calls we run through // the table and cleanup if needed. SetIDCount++; if (SetIDCount % CleanUpCountInterval == 0) { // This should be called with the write lock held! // (which is why we assert that at the beginning of this // method) CleanupIdentities(null); } } Message.DebugOut("SetIdentity:: Identity::URI: " + idObj.URI + "\n"); return idObj; } #if false // Convert table entry to a weak reference // internal static void WeakenIdentity(String URI) { Contract.Assert(URI!=null, "Null URI"); BCLDebug.Trace("REMOTE", "IdentityHolder.WeakenIdentity ",URI, " for context ", Thread.CurrentContext); String uriKey = MakeURIKey(URI); // We need to guarantee that finally is not interrupted so that the lock is released. // TableLock has a long path without reliability contract. To avoid adding contract on // the path, we will use ReaderWriterLock directly. ReaderWriterLock rwlock = TableLock; bool takeAndRelease = !rwlock.IsWriterLockHeld; RuntimeHelpers.PrepareConstrainedRegions(); try { if (takeAndRelease) rwlock.AcquireWriterLock(INFINITE); Object oRef = URITable[uriKey]; WeakReference wr = oRef as WeakReference; if (null == wr) { // Make the id a weakRef if it isn't already. Contract.Assert( oRef != null && (oRef is ServerIdentity), "Invaild URI given to WeakenIdentity"); URITable[uriKey] = new WeakReference(oRef); } } finally { if (takeAndRelase && rwlock.IsWriterLockHeld){ rwlock.ReleaseWriterLock(); } } } #endif [System.Security.SecurityCritical] // auto-generated internal static void RemoveIdentity(String uri) { RemoveIdentity(uri, true); } [System.Security.SecurityCritical] // auto-generated internal static void RemoveIdentity(String uri, bool bResetURI) { Contract.Assert(uri!=null, "Null URI"); BCLDebug.Trace("REMOTE", "IdentityHolder.WeakenIdentity ",uri, " for context ", Thread.CurrentContext); Identity id; String uriKey = MakeURIKey(uri); // We need to guarantee that finally is not interrupted so that the lock is released. // TableLock has a long path without reliability contract. To avoid adding contract on // the path, we will use ReaderWriterLock directly. ReaderWriterLock rwlock = TableLock; bool takeAndRelease = !rwlock.IsWriterLockHeld; RuntimeHelpers.PrepareConstrainedRegions(); try { if (takeAndRelease) rwlock.AcquireWriterLock(INFINITE); Object oRef = URITable[uriKey]; WeakReference wr = oRef as WeakReference; if (null != wr) { id = (Identity) wr.Target; wr.Target = null; } else { id = (Identity) oRef; if (id != null) ((ServerIdentity)id).ResetHandle(); } if(id != null) { URITable.Remove(uriKey); // Mark the ID as not present in the ID Table // This will clear its URI & objRef fields id.ResetInIDTable(bResetURI); } } finally { if (takeAndRelease && rwlock.IsWriterLockHeld){ rwlock.ReleaseWriterLock(); } } } // RemoveIdentity // Support for dynamically registered property sinks [System.Security.SecurityCritical] // auto-generated internal static bool AddDynamicProperty(MarshalByRefObject obj, IDynamicProperty prop) { if (RemotingServices.IsObjectOutOfContext(obj)) { // We have to add a proxy side property, get the identity RealProxy rp = RemotingServices.GetRealProxy(obj); return rp.IdentityObject.AddProxySideDynamicProperty(prop); } else { MarshalByRefObject realObj = (MarshalByRefObject) RemotingServices.AlwaysUnwrap((ContextBoundObject)obj); // This is a real object. See if we have an identity for it ServerIdentity srvID = (ServerIdentity)MarshalByRefObject.GetIdentity(realObj); if (srvID != null) { return srvID.AddServerSideDynamicProperty(prop); } else { // identity not found, we can't set a sink for this object. throw new RemotingException( Environment.GetResourceString("Remoting_NoIdentityEntry")); } } } [System.Security.SecurityCritical] // auto-generated internal static bool RemoveDynamicProperty(MarshalByRefObject obj, String name) { if (RemotingServices.IsObjectOutOfContext(obj)) { // We have to add a proxy side property, get the identity RealProxy rp = RemotingServices.GetRealProxy(obj); return rp.IdentityObject.RemoveProxySideDynamicProperty(name); } else { MarshalByRefObject realObj = (MarshalByRefObject) RemotingServices.AlwaysUnwrap((ContextBoundObject)obj); // This is a real object. See if we have an identity for it ServerIdentity srvID = (ServerIdentity)MarshalByRefObject.GetIdentity(realObj); if (srvID != null) { return srvID.RemoveServerSideDynamicProperty(name); } else { // identity not found, we can't set a sink for this object. throw new RemotingException( Environment.GetResourceString("Remoting_NoIdentityEntry")); } } } } // class IdentityHolder }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // 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 OpenTK.Input { /// <summary> /// Encapsulates the state of a mouse device. /// </summary> public struct MouseState : IEquatable<MouseState> { internal const int MaxButtons = 16; // we are storing in an ushort private Vector2 position; private MouseScroll scroll; private ushort buttons; /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the specified /// <see cref="OpenTK.Input.MouseButton"/> is pressed. /// </summary> /// <param name="button">The <see cref="OpenTK.Input.MouseButton"/> to check.</param> /// <returns>True if key is pressed; false otherwise.</returns> public bool this[MouseButton button] { get { return IsButtonDown(button); } internal set { if (value) { EnableBit((int)button); } else { DisableBit((int)button); } } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this button is down. /// </summary> /// <param name="button">The <see cref="OpenTK.Input.MouseButton"/> to check.</param> public bool IsButtonDown(MouseButton button) { return ReadBit((int)button); } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether this button is up. /// </summary> /// <param name="button">The <see cref="OpenTK.Input.MouseButton"/> to check.</param> public bool IsButtonUp(MouseButton button) { return !ReadBit((int)button); } /// <summary> /// Gets the absolute wheel position in integer units. /// To support high-precision mice, it is recommended to use <see cref="WheelPrecise"/> instead. /// </summary> public int Wheel { get { return (int)Math.Round(scroll.Y, MidpointRounding.AwayFromZero); } } /// <summary> /// Gets the absolute wheel position in floating-point units. /// </summary> public float WheelPrecise { get { return scroll.Y; } } /// <summary> /// Gets a <see cref="OpenTK.Input.MouseScroll"/> instance, /// representing the current state of the mouse scroll wheel. /// </summary> public MouseScroll Scroll { get { return scroll; } } /// <summary> /// Gets an integer representing the absolute x position of the pointer, in window pixel coordinates. /// </summary> public int X { get { return (int)Math.Round(position.X); } internal set { position.X = value; } } /// <summary> /// Gets an integer representing the absolute y position of the pointer, in window pixel coordinates. /// </summary> public int Y { get { return (int)Math.Round(position.Y); } internal set { position.Y = value; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the left mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState LeftButton { get { return IsButtonDown(MouseButton.Left) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the middle mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState MiddleButton { get { return IsButtonDown(MouseButton.Middle) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the right mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState RightButton { get { return IsButtonDown(MouseButton.Right) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the first extra mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState XButton1 { get { return IsButtonDown(MouseButton.Button1) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a <see cref="System.Boolean"/> indicating whether the second extra mouse button is pressed. /// This property is intended for XNA compatibility. /// </summary> public ButtonState XButton2 { get { return IsButtonDown(MouseButton.Button2) ? ButtonState.Pressed : ButtonState.Released; } } /// <summary> /// Gets a value indicating whether any button is down. /// </summary> /// <value><c>true</c> if any button is down; otherwise, <c>false</c>.</value> public bool IsAnyButtonDown { get { // If any bit is set then a button is down. return buttons != 0; } } /// <summary> /// Gets the absolute wheel position in integer units. This property is intended for XNA compatibility. /// To support high-precision mice, it is recommended to use <see cref="WheelPrecise"/> instead. /// </summary> public int ScrollWheelValue { get { return Wheel; } } /// <summary> /// Gets a value indicating whether this instance is connected. /// </summary> /// <value><c>true</c> if this instance is connected; otherwise, <c>false</c>.</value> public bool IsConnected { get; internal set; } /// <summary> /// Checks whether two <see cref="MouseState" /> instances are equal. /// </summary> /// <param name="left"> /// A <see cref="MouseState"/> instance. /// </param> /// <param name="right"> /// A <see cref="MouseState"/> instance. /// </param> /// <returns> /// True if both left is equal to right; false otherwise. /// </returns> public static bool operator ==(MouseState left, MouseState right) { return left.Equals(right); } /// <summary> /// Checks whether two <see cref="MouseState" /> instances are not equal. /// </summary> /// <param name="left"> /// A <see cref="MouseState"/> instance. /// </param> /// <param name="right"> /// A <see cref="MouseState"/> instance. /// </param> /// <returns> /// True if both left is not equal to right; false otherwise. /// </returns> public static bool operator !=(MouseState left, MouseState right) { return !left.Equals(right); } /// <summary> /// Compares to an object instance for equality. /// </summary> /// <param name="obj"> /// The <see cref="System.Object"/> to compare to. /// </param> /// <returns> /// True if this instance is equal to obj; false otherwise. /// </returns> public override bool Equals(object obj) { if (obj is MouseState) { return this == (MouseState)obj; } else { return false; } } /// <summary> /// Generates a hashcode for the current instance. /// </summary> /// <returns> /// A <see cref="System.Int32"/> represting the hashcode for this instance. /// </returns> public override int GetHashCode() { return buttons.GetHashCode() ^ X.GetHashCode() ^ Y.GetHashCode() ^ scroll.GetHashCode(); } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="OpenTK.Input.MouseState"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="OpenTK.Input.MouseState"/>.</returns> public override string ToString() { string b = Convert.ToString(buttons, 2).PadLeft(10, '0'); return String.Format("[X={0}, Y={1}, Scroll={2}, Buttons={3}, IsConnected={4}]", X, Y, Scroll, b, IsConnected); } internal Vector2 Position { get { return position; } set { position = value; } } internal bool ReadBit(int offset) { ValidateOffset(offset); return (buttons & (1 << offset)) != 0; } internal void EnableBit(int offset) { ValidateOffset(offset); buttons |= unchecked((ushort)(1 << offset)); } internal void DisableBit(int offset) { ValidateOffset(offset); buttons &= unchecked((ushort)(~(1 << offset))); } internal void MergeBits(MouseState other) { buttons |= other.buttons; SetScrollRelative(other.scroll.X, other.scroll.Y); X += other.X; Y += other.Y; IsConnected |= other.IsConnected; } internal void SetIsConnected(bool value) { IsConnected = value; } internal void SetScrollAbsolute(float x, float y) { scroll.X = x; scroll.Y = y; } internal void SetScrollRelative(float x, float y) { scroll.X += x; scroll.Y += y; } private static void ValidateOffset(int offset) { if (offset < 0 || offset >= 16) { throw new ArgumentOutOfRangeException("offset"); } } /// <summary> /// Compares two MouseState instances. /// </summary> /// <param name="other">The instance to compare two.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public bool Equals(MouseState other) { return buttons == other.buttons && X == other.X && Y == other.Y && Scroll == other.Scroll; } } }
namespace Attest.Fake.Setup.Contracts { /// <summary> /// Represents visitor for different callbacks without return value and no parameters. /// </summary> public interface IMethodCallbackVisitor { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> void Visit(OnErrorCallback onErrorCallback); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> void Visit(OnCompleteCallback onCompleteCallback); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback</param> void Visit(ProgressCallback progressCallback); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> void Visit(OnCancelCallback onCancelCallback); /// <summary> /// Visits never-ending callback. /// </summary> /// <param name="withoutCallback">Callback</param> void Visit(OnWithoutCallback withoutCallback); } /// <summary> /// Represents visitor for different callbacks without return value and one parameter. /// </summary> /// <typeparam name="T">The type of the parameter.</typeparam> public interface IMethodCallbackVisitor<T> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg">Parameter</param> void Visit(OnErrorCallback<T> onErrorCallback, T arg); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg">Parameter</param> void Visit(OnCompleteCallback<T> onCompleteCallback, T arg); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg">Parameter.</param> void Visit(ProgressCallback<T> progressCallback, T arg); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg">Parameter.</param> void Visit(OnCancelCallback<T> onCancelCallback, T arg); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg">Parameter.</param> void Visit(OnWithoutCallback<T> withoutCallback, T arg); } /// <summary> /// Represents visitor for different callbacks without return value and two parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> public interface IMethodCallbackVisitor<T1, T2> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> void Visit(OnErrorCallback<T1, T2> onErrorCallback, T1 arg1, T2 arg2); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> void Visit(OnCompleteCallback<T1, T2> onCompleteCallback, T1 arg1, T2 arg2); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> void Visit(ProgressCallback<T1, T2> progressCallback, T1 arg1, T2 arg2); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> void Visit(OnCancelCallback<T1, T2> onCancelCallback, T1 arg1, T2 arg2); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> void Visit(OnWithoutCallback<T1, T2> withoutCallback, T1 arg1, T2 arg2); } /// <summary> /// Represents visitor for different callbacks without return value and three parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> public interface IMethodCallbackVisitor<T1, T2, T3> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> void Visit(OnErrorCallback<T1, T2, T3> onErrorCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> void Visit(OnCompleteCallback<T1, T2, T3> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> void Visit(ProgressCallback<T1, T2, T3> progressCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> void Visit(OnCancelCallback<T1, T2, T3> onCancelCallback, T1 arg1, T2 arg2, T3 arg3); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> void Visit(OnWithoutCallback<T1, T2, T3> withoutCallback, T1 arg1, T2 arg2, T3 arg3); } /// <summary> /// Represents visitor for different callbacks without return value and four parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> public interface IMethodCallbackVisitor<T1, T2, T3, T4> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> void Visit(OnErrorCallback<T1, T2, T3, T4> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> void Visit(OnCompleteCallback<T1, T2, T3, T4> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> void Visit(ProgressCallback<T1, T2, T3, T4> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> void Visit(OnCancelCallback<T1, T2, T3, T4> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> void Visit(OnWithoutCallback<T1, T2, T3, T4> withoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4); } /// <summary> /// Represents visitor for different callbacks without return value and five parameters. /// </summary> /// <typeparam name="T1">The type of the first parameter.</typeparam> /// <typeparam name="T2">The type of the second parameter.</typeparam> /// <typeparam name="T3">The type of the third parameter.</typeparam> /// <typeparam name="T4">The type of the fourth parameter.</typeparam> /// <typeparam name="T5">The type of the fifth parameter.</typeparam> public interface IMethodCallbackVisitor<T1, T2, T3, T4, T5> { /// <summary> /// Visits exception throwing callback /// </summary> /// <param name="onErrorCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> void Visit(OnErrorCallback<T1, T2, T3, T4, T5> onErrorCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits successful completion callback /// </summary> /// <param name="onCompleteCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> void Visit(OnCompleteCallback<T1, T2, T3, T4, T5> onCompleteCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits progress callback /// </summary> /// <param name="progressCallback">Callback.</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> void Visit(ProgressCallback<T1, T2, T3, T4, T5> progressCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits cancellation callback /// </summary> /// <param name="onCancelCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> void Visit(OnCancelCallback<T1, T2, T3, T4, T5> onCancelCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); /// <summary> /// Visits never-ending callback /// </summary> /// <param name="withoutCallback">Callback</param> /// <param name="arg1">First parameter</param> /// <param name="arg2">Second parameter</param> /// <param name="arg3">Third parameter</param> /// <param name="arg4">Fourth parameter</param> /// <param name="arg5">Fifth parameter</param> void Visit(OnWithoutCallback<T1, T2, T3, T4, T5> withoutCallback, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Xml.Serialization; using System.Text; namespace DBTM.Domain.Entities { public class DatabaseVersion : IEntitySavedStateMonitor, INotifyPropertyChanged { private IDictionary<SqlStatementType, SqlStatementCollection> _statements = new Dictionary<SqlStatementType, SqlStatementCollection>() { {SqlStatementType.PreDeployment, new SqlStatementCollection()}, {SqlStatementType.PostDeployment, new SqlStatementCollection()}, }; [XmlIgnore] private bool _isSaved = true; private int _versionNumber; private DateTime _created; private string _cardNumber; private string _description; private bool _isEditable; private bool _isBaseline; [Obsolete("This Exists for Serialization only", true)] public DatabaseVersion() { HookupEvents(); IsEditable = false; } public DatabaseVersion(int versionId, DateTime created) { VersionNumber = versionId; Created = created; _isSaved = false; IsEditable = false; HookupEvents(); } private void HookupEvents() { _statements[SqlStatementType.PreDeployment].PropertyChanged += SqlStatementPropertyChanged; _statements[SqlStatementType.PostDeployment].PropertyChanged += SqlStatementPropertyChanged; } [XmlAttribute("Id")] public int VersionNumber { get { return _versionNumber; } set { if (_versionNumber != value) { _versionNumber = value; FirePropertyChangedEvent(x => x.VersionNumber, true); } } } [XmlAttribute("Created")] public DateTime Created { get { return _created; } set { if (_created != value) { _created = value; FirePropertyChangedEvent(x => x.Created, true); } } } [XmlAttribute("CardNumber")] public string CardNumber { get { return _cardNumber; } set { if (_cardNumber != value) { _cardNumber = value; FirePropertyChangedEvent(x => x.CardNumber, true); } } } [XmlAttribute("Description")] public string Description { get { return _description; } set { if (_description != value) { _description = value; FirePropertyChangedEvent(x => x.Description, true); } } } [XmlElement("PreDeploymentSqlStatement")] public virtual SqlStatementCollection PreDeploymentStatements { get { return _statements[SqlStatementType.PreDeployment]; } set { if (_statements[SqlStatementType.PreDeployment] != value) { _statements[SqlStatementType.PreDeployment].PropertyChanged -= SqlStatementPropertyChanged; _statements[SqlStatementType.PreDeployment] = value; _statements[SqlStatementType.PreDeployment].PropertyChanged += SqlStatementPropertyChanged; FirePropertyChangedEvent(x => x.PreDeploymentStatements, true); } } } #region Used for Serialization Only /// <summary> /// DO NOT USE. Used for backwards compatiblity only /// </summary> [XmlElement("SqlStatement")] public virtual SqlStatementCollection Statements { get { return _statements[SqlStatementType.PreDeployment]; } set { if (_statements[SqlStatementType.PreDeployment] != value) { _statements[SqlStatementType.PreDeployment].PropertyChanged -= SqlStatementPropertyChanged; _statements[SqlStatementType.PreDeployment] = value; _statements[SqlStatementType.PreDeployment].PropertyChanged += SqlStatementPropertyChanged; FirePropertyChangedEvent(x => x.Statements, true); } } } public virtual bool ShouldSerializeStatements() { return false; } #endregion [XmlElement("PostDeploymentSqlStatement")] public virtual SqlStatementCollection PostDeploymentStatements { get { return _statements[SqlStatementType.PostDeployment]; } set { if (_statements[SqlStatementType.PostDeployment] != value) { _statements[SqlStatementType.PostDeployment].PropertyChanged -= SqlStatementPropertyChanged; _statements[SqlStatementType.PostDeployment] = value; _statements[SqlStatementType.PostDeployment].PropertyChanged += SqlStatementPropertyChanged; FirePropertyChangedEvent(x => x.PostDeploymentStatements, true); } } } [XmlAttribute("IsBaseline")] public virtual bool IsBaseline { get { return _isBaseline; } set { _isBaseline = value; if (_isBaseline != value) { _isBaseline = value; FirePropertyChangedEvent(x => x.IsBaseline, true); } } } [XmlIgnore] public virtual bool IsEditable { get { return _isEditable; } set { if (_isEditable != value) { _isEditable = value; PreDeploymentStatements.ForEach(s => s.IsEditable = value); PostDeploymentStatements.ForEach(s => s.IsEditable = value); FirePropertyChangedEvent(x => x.IsEditable, true); } } } [XmlIgnore] public bool IsSaved { get { return _isSaved; } private set { if (_isSaved != value) { _isSaved = value; FirePropertyChangedEvent(x => x.IsSaved, false); } } } public virtual CompiledVersionSql CompileSql(string databasePrefix, SqlStatementType sqlStatementType,bool includeHistoryStatements) { var compiledSql = new CompiledVersionSql(VersionNumber, sqlStatementType); foreach (var statement in _statements[sqlStatementType]) { var compiledUpgradeSql = new CompiledUpgradeSql(statement.UpgradeSQL, databasePrefix, statement.Id, sqlStatementType, VersionNumber, includeHistoryStatements); compiledSql.AddUpgrade(compiledUpgradeSql); } foreach (var statement in _statements[sqlStatementType].Reverse()) { var compiledRollbackSql = new CompiledRollbackSql(statement.RollbackSQL, databasePrefix, statement.Id, sqlStatementType, VersionNumber, includeHistoryStatements); compiledSql.AddRollback(compiledRollbackSql); } return compiledSql; } public static DatabaseVersion Coalesce(DatabaseVersion databaseVersion) { return databaseVersion ?? new EmptyDatabaseVersion(); } public virtual bool CanBeBuilt() { return true; } public void MarkAsSaved() { IsSaved = true; PreDeploymentStatements.MarkAsSaved(); PostDeploymentStatements.MarkAsSaved(); } public virtual bool HasStatements { get { return PreDeploymentStatements.Count > 0 || PostDeploymentStatements.Count > 0; } } public event PropertyChangedEventHandler PropertyChanged; private void SqlStatementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == GetIsSavedPropertyName() && !((ISqlStatementCollection)sender).IsSaved) { IsSaved = false; } } private string GetIsSavedPropertyName() { return ((Expression<Func<ISqlStatementCollection, object>>)(x => x.IsSaved)).GetMemberName(); } private void FirePropertyChangedEvent(Expression<Func<DatabaseVersion, object>> propertyNameFunc, bool makeNotSaved) { if (makeNotSaved) { IsSaved = false; } if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyNameFunc.GetMemberName())); } } } }
// ---------------------------------------------------------------------------------- // // FXMaker // Created by ismoon - 2012 - ismoonto@gmail.com // // ---------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------- using UnityEditor; using UnityEngine; using System.Collections.Generic; using System.Collections; using System.IO; [CustomEditor(typeof(NcParticleSystem))] public class NcParticleSystemEditor : FXMakerEditor { // Attribute ------------------------------------------------------------------------ protected NcParticleSystem m_Sel; protected FxmPopupManager m_FxmPopupManager; // Property ------------------------------------------------------------------------- // Event Function ------------------------------------------------------------------- void OnEnable() { m_Sel = target as NcParticleSystem; m_UndoManager = new FXMakerUndoManager(m_Sel, "NcParticleSystem"); } void OnDisable() { if (m_FxmPopupManager != null && m_FxmPopupManager.IsShowByInspector()) m_FxmPopupManager.CloseNcPrefabPopup(); } public override void OnInspectorGUI() { AddScriptNameField(m_Sel); m_UndoManager.CheckUndo(); m_FxmPopupManager = GetFxmPopupManager(); bool bClickButton = false; EditorGUI.BeginChangeCheck(); { m_Sel.m_fUserTag = EditorGUILayout.FloatField(GetCommonContent("m_fUserTag"), m_Sel.m_fUserTag); m_Sel.m_fStartDelayTime = EditorGUILayout.FloatField(GetHelpContent("m_fStartDelayTime") , m_Sel.m_fStartDelayTime); // -------------------------------------------------------------------------------------------------------------------------------------------- if (IsParticleEmitterOneShot()) { Rect butRect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight)); { if (FXMakerLayout.GUIButton(butRect, GetHelpContent("Convert: OneShot To FXMakerBurst"), true)) { ConvertOneShotToFXMakerBurst(); return; } GUILayout.Label(""); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } // -------------------------------------------------------------------------------------------------------------------------------------------- m_Sel.m_bBurst = EditorGUILayout.Toggle(GetHelpContent("m_bBurst") , m_Sel.m_bBurst); if (m_Sel.m_bBurst) { m_Sel.m_fBurstRepeatTime = EditorGUILayout.FloatField(GetHelpContent("m_fBurstRepeatTime") , m_Sel.m_fBurstRepeatTime); m_Sel.m_nBurstRepeatCount = EditorGUILayout.IntField (GetHelpContent("m_nBurstRepeatCount") , m_Sel.m_nBurstRepeatCount); m_Sel.m_fBurstEmissionCount = EditorGUILayout.IntField (GetHelpContent("m_fBurstEmissionCount") , m_Sel.m_fBurstEmissionCount); SetMinValue(ref m_Sel.m_fBurstRepeatTime, 0.01f); } else { m_Sel.m_fEmitTime = EditorGUILayout.FloatField(GetHelpContent("m_fEmitTime") , m_Sel.m_fEmitTime); m_Sel.m_fSleepTime = EditorGUILayout.FloatField(GetHelpContent("m_fSleepTime") , m_Sel.m_fSleepTime); } m_Sel.m_bScaleWithTransform = EditorGUILayout.Toggle (GetHelpContent("m_bScaleWithTransform") , m_Sel.m_bScaleWithTransform); // -------------------------------------------------------------------------------------------------------------------------------------------- if (m_Sel.GetComponent<ParticleEmitter>() != null && m_Sel.m_bScaleWithTransform) // && m_Sel.transform.lossyScale != Vector3.one { Rect butRect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight)); { if (FXMakerLayout.GUIButton(butRect, GetHelpContent("Convert To Static Scale"), true)) { ConvertToStaticScale(m_Sel.GetComponent<ParticleEmitter>(), m_Sel.GetComponent<ParticleAnimator>()); m_Sel.m_bScaleWithTransform = false; return; } GUILayout.Label(""); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } // -------------------------------------------------------------------------------------------------------------------------------------------- bool bWorldSpace = EditorGUILayout.Toggle (GetHelpContent("m_bWorldSpace") , m_Sel.m_bWorldSpace); // Set bWorldSpace if (m_Sel.m_bWorldSpace != bWorldSpace) { m_Sel.m_bWorldSpace = bWorldSpace; NgSerialized.SetSimulationSpaceWorld(m_Sel.transform, bWorldSpace); } // Update bWorldSpace if (m_Sel.m_bWorldSpace != NgSerialized.GetSimulationSpaceWorld(m_Sel.transform)) m_Sel.m_bWorldSpace = !m_Sel.m_bWorldSpace; // -------------------------------------------------------------------------------------------------------------------------------------------- m_Sel.m_fStartSizeRate = EditorGUILayout.FloatField(GetHelpContent("m_fStartSizeRate") , m_Sel.m_fStartSizeRate); m_Sel.m_fStartLifeTimeRate = EditorGUILayout.FloatField(GetHelpContent("m_fStartLifeTimeRate") , m_Sel.m_fStartLifeTimeRate); m_Sel.m_fStartEmissionRate = EditorGUILayout.FloatField(GetHelpContent("m_fStartEmissionRate") , m_Sel.m_fStartEmissionRate); m_Sel.m_fStartSpeedRate = EditorGUILayout.FloatField(GetHelpContent("m_fStartSpeedRate") , m_Sel.m_fStartSpeedRate); m_Sel.m_fRenderLengthRate = EditorGUILayout.FloatField(GetHelpContent("m_fRenderLengthRate") , m_Sel.m_fRenderLengthRate); if (m_Sel.GetComponent<ParticleEmitter>() != null && NgSerialized.IsMeshParticleEmitter(m_Sel.GetComponent<ParticleEmitter>())) { m_Sel.m_fLegacyMinMeshNormalVelocity= EditorGUILayout.FloatField(GetHelpContent("m_fLegacyMinMeshNormalVelocity") , m_Sel.m_fLegacyMinMeshNormalVelocity); m_Sel.m_fLegacyMaxMeshNormalVelocity= EditorGUILayout.FloatField(GetHelpContent("m_fLegacyMaxMeshNormalVelocity") , m_Sel.m_fLegacyMaxMeshNormalVelocity); } if (m_Sel.GetComponent<ParticleSystem>() != null) { float fShurikenSpeedRate = EditorGUILayout.FloatField(GetHelpContent("m_fShurikenSpeedRate") , m_Sel.m_fShurikenSpeedRate); // Set particleSystem.speed if (m_Sel.m_fShurikenSpeedRate != fShurikenSpeedRate) { m_Sel.m_fShurikenSpeedRate = fShurikenSpeedRate; m_Sel.SaveShurikenSpeed(); } } // m_ParticleDestruct m_Sel.m_ParticleDestruct = (NcParticleSystem.ParticleDestruct)EditorGUILayout.EnumPopup(GetHelpContent("m_ParticleDestruct"), m_Sel.m_ParticleDestruct, GUILayout.MaxWidth(Screen.width)); if (m_Sel.m_ParticleDestruct != NcParticleSystem.ParticleDestruct.NONE) { if (m_Sel.m_ParticleDestruct == NcParticleSystem.ParticleDestruct.COLLISION) { m_Sel.m_CollisionLayer = LayerMaskField (GetHelpContent("m_CollisionLayer") , m_Sel.m_CollisionLayer); m_Sel.m_fCollisionRadius = EditorGUILayout.FloatField (GetHelpContent("m_fCollisionRadius") , m_Sel.m_fCollisionRadius); } if (m_Sel.m_ParticleDestruct == NcParticleSystem.ParticleDestruct.WORLD_Y) { m_Sel.m_fDestructPosY = EditorGUILayout.FloatField (GetHelpContent("m_fDestructPosY") , m_Sel.m_fDestructPosY); } m_Sel.m_AttachPrefab = (GameObject)EditorGUILayout.ObjectField(GetHelpContent("m_AttachPrefab") , m_Sel.m_AttachPrefab, typeof(GameObject), false, null); m_Sel.m_fPrefabScale = EditorGUILayout.FloatField (GetHelpContent("m_fPrefabScale") , m_Sel.m_fPrefabScale); m_Sel.m_fPrefabSpeed = EditorGUILayout.FloatField (GetHelpContent("m_fPrefabSpeed") , m_Sel.m_fPrefabSpeed); m_Sel.m_fPrefabLifeTime = EditorGUILayout.FloatField (GetHelpContent("m_fPrefabLifeTime") , m_Sel.m_fPrefabLifeTime); SetMinValue(ref m_Sel.m_fCollisionRadius, 0.01f); SetMinValue(ref m_Sel.m_fPrefabScale, 0.01f); SetMinValue(ref m_Sel.m_fPrefabSpeed, 0.01f); SetMinValue(ref m_Sel.m_fPrefabLifeTime, 0); // -------------------------------------------------------------- EditorGUILayout.Space(); Rect attRect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight)); { if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(attRect, 3, 0, 1), GetHelpContent("Select Prefab"), (m_FxmPopupManager != null))) m_FxmPopupManager.ShowSelectPrefabPopup(m_Sel, true, 0); if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(attRect, 3, 1, 1), GetHelpContent("Clear Prefab"), (m_Sel.m_AttachPrefab != null))) { bClickButton = true; m_Sel.m_AttachPrefab = null; } if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerHorizontalRect(attRect, 3, 2, 1), GetHelpContent("Open Prefab"), (m_FxmPopupManager != null) && (m_Sel.m_AttachPrefab != null))) { bClickButton = true; GetFXMakerMain().OpenPrefab(m_Sel.m_AttachPrefab); return; } GUILayout.Label(""); } EditorGUILayout.EndHorizontal(); } // --------------------------------------------------------------------- // current ParticleSystem EditorGUILayout.Space(); Component currentParticle = null; Rect rect = EditorGUILayout.BeginHorizontal(GUILayout.Height(m_fButtonHeight * 3)); { if ((currentParticle = m_Sel.gameObject.GetComponent<ParticleSystem>()) != null) { ParticleSystemRenderer psr = m_Sel.gameObject.GetComponent<ParticleSystemRenderer>(); if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 0, 2), GetHelpContent("Delete Shuriken Components"), true)) { bClickButton = true; Object.DestroyImmediate(currentParticle); if (psr != null) Object.DestroyImmediate(psr); } if (psr == null) { FXMakerLayout.GUIColorBackup(FXMakerLayout.m_ColorHelpBox); if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 2, 1), GetHelpContent("Add ParticleSystemRenderer"), true)) { bClickButton = true; m_Sel.gameObject.AddComponent<ParticleSystemRenderer>(); } FXMakerLayout.GUIColorRestore(); } else FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 2, 1),"ParticleSystemRenderer", false); } else { if ((currentParticle = m_Sel.gameObject.GetComponent<ParticleEmitter>()) != null) { ParticleAnimator pa = m_Sel.gameObject.GetComponent<ParticleAnimator>(); ParticleRenderer pr = m_Sel.gameObject.GetComponent<ParticleRenderer>(); if (currentParticle.ToString().Contains("EllipsoidParticleEmitter")) { if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 0, 1), GetHelpContent("Delete Legacy(Ellipsoid) Components"), true)) { bClickButton = true; Object.DestroyImmediate(currentParticle); if (pa != null) Object.DestroyImmediate(pa); if (pr != null) Object.DestroyImmediate(pr); } } else { if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 0, 1), GetHelpContent("Delete Legacy(Mesh) Components"), true)) { bClickButton = true; Object.DestroyImmediate(currentParticle); if (pa != null) Object.DestroyImmediate(pa); if (pr != null) Object.DestroyImmediate(pr); } } if (pa == null) { FXMakerLayout.GUIColorBackup(FXMakerLayout.m_ColorHelpBox); if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 1, 1), GetHelpContent("Add ParticleAnimator"), true)) { bClickButton = true; m_Sel.gameObject.AddComponent<ParticleAnimator>(); } FXMakerLayout.GUIColorRestore(); } else FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 1, 1),"ParticleAnimator", false); if (pr == null) { FXMakerLayout.GUIColorBackup(FXMakerLayout.m_ColorHelpBox); if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 2, 1), GetHelpContent("Add ParticleRenderer"), true)) { bClickButton = true; m_Sel.gameObject.AddComponent<ParticleRenderer>(); } FXMakerLayout.GUIColorRestore(); } else FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 2, 1),"ParticleRenderer", false); } } // --------------------------------------------------------------------- // Create ParticleSystem if (currentParticle == null) { if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 0, 1), GetHelpContent("Add Shuriken Components"), true)) { bClickButton = true; m_Sel.gameObject.AddComponent<ParticleSystem>(); if (m_Sel.gameObject.GetComponent<ParticleSystemRenderer>() == null) m_Sel.gameObject.AddComponent<ParticleSystemRenderer>(); } if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 1, 1), GetHelpContent("Add Legacy(Ellipsoid) Components"), true)) { bClickButton = true; m_Sel.gameObject.AddComponent<EllipsoidParticleEmitter>(); if (m_Sel.gameObject.GetComponent<ParticleAnimator>() == null) m_Sel.gameObject.AddComponent<ParticleAnimator>(); if (m_Sel.gameObject.GetComponent<ParticleRenderer>() == null) m_Sel.gameObject.AddComponent<ParticleRenderer>(); } if (FXMakerLayout.GUIButton(FXMakerLayout.GetInnerVerticalRect(rect, 3, 2, 1), GetHelpContent("Add Legacy(Mesh) Components"), true)) { bClickButton = true; m_Sel.gameObject.AddComponent<MeshParticleEmitter>(); if (m_Sel.gameObject.GetComponent<ParticleAnimator>() == null) m_Sel.gameObject.AddComponent<ParticleAnimator>(); if (m_Sel.gameObject.GetComponent<ParticleRenderer>() == null) m_Sel.gameObject.AddComponent<ParticleRenderer>(); } } GUILayout.Label(""); } EditorGUILayout.EndHorizontal(); } m_UndoManager.CheckDirty(); // --------------------------------------------------------------------- if ((EditorGUI.EndChangeCheck() || bClickButton) && GetFXMakerMain()) OnEditComponent(); // --------------------------------------------------------------------- if (GUI.tooltip != "") m_LastTooltip = GUI.tooltip; HelpBox(m_LastTooltip); } // -------------------------------------------------------------------------------------- // Legacy Only... public static void ConvertToStaticScale(ParticleEmitter pe, ParticleAnimator pa) { if (pe == null) return; Vector3 vecVelScale = (pe.transform.lossyScale); float fVelScale = (NcTransformTool.GetTransformScaleMeanValue(pe.transform)); float fScale = (NcTransformTool.GetTransformScaleMeanValue(pe.transform)); pe.minSize *= fScale; pe.maxSize *= fScale; pe.worldVelocity = Vector3.Scale(pe.worldVelocity, vecVelScale); pe.localVelocity = Vector3.Scale(pe.localVelocity, vecVelScale); pe.rndVelocity = Vector3.Scale(pe.rndVelocity, vecVelScale); pe.angularVelocity *= fVelScale; pe.rndAngularVelocity *= fVelScale; pe.emitterVelocityScale *= fVelScale; if (pa != null) { pa.rndForce = Vector3.Scale(pa.rndForce, vecVelScale); pa.force = Vector3.Scale(pa.force, vecVelScale); // pa.damping *= fScale; } Vector3 ellipsoid; float minEmitterRange; NgSerialized.GetEllipsoidSize(pe, out ellipsoid, out minEmitterRange); NgSerialized.SetEllipsoidSize(pe, ellipsoid * fScale, minEmitterRange * fScale); // NgAssembly.LogFieldsPropertis(pe); } protected bool IsParticleEmitterOneShot() { ParticleEmitter pe = m_Sel.GetComponent<ParticleEmitter>(); if (pe == null) return false; bool bOneShot = (bool)NgSerialized.GetPropertyValue(new SerializedObject(pe as ParticleEmitter), "m_OneShot"); return (bOneShot && m_Sel.m_bBurst == false); } protected void ConvertOneShotToFXMakerBurst() { ParticleEmitter pe = m_Sel.GetComponent<ParticleEmitter>(); ParticleAnimator pa = m_Sel.GetComponent<ParticleAnimator>(); bool bOneShot = (bool)NgSerialized.GetPropertyValue(new SerializedObject(pe as ParticleEmitter), "m_OneShot"); if (bOneShot && m_Sel.m_bBurst == false) { m_Sel.m_bBurst = true; m_Sel.m_fBurstRepeatTime = pe.maxEnergy; m_Sel.m_nBurstRepeatCount = 1; m_Sel.m_fBurstEmissionCount = (int)Random.Range(pe.minEmission, pe.maxEmission+1); pe.emit = false; NgSerialized.SetPropertyValue(new SerializedObject(pe as ParticleEmitter), "m_OneShot", false, true); if (pa != null) pa.autodestruct = false; } } // ---------------------------------------------------------------------------------- protected GUIContent GetHelpContent(string tooltip) { string caption = tooltip; string text = FXMakerTooltip.GetHsEditor_NcParticleSystem(tooltip); return GetHelpContent(caption, text); } protected override void HelpBox(string caption) { string str = caption; if (caption == "" || caption == "Script") str = FXMakerTooltip.GetHsEditor_NcParticleSystem(""); base.HelpBox(str); } }
// 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 Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace ArcGISRuntime.Samples.SpatialRelationships { [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Spatial relationships", category: "Geometry", description: "Determine spatial relationships between two geometries.", instructions: "Select one of the three graphics. The tree view will list the relationships the selected graphic has to the other graphic geometries.", tags: new[] { "geometries", "relationship", "spatial analysis" })] public class SpatialRelationships : Activity { private TextView _resultTextView; private MapView _myMapView; // References to the graphics and graphics overlay private GraphicsOverlay _graphicsOverlay; private Graphic _polygonGraphic; private Graphic _polylineGraphic; private Graphic _pointGraphic; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Spatial relationships"; CreateLayout(); Initialize(); } private void Initialize() { // Configure the basemap _myMapView.Map = new Map(BasemapStyle.ArcGISTopographic); // Create the graphics overlay _graphicsOverlay = new GraphicsOverlay(); // Add the overlay to the MapView _myMapView.GraphicsOverlays.Add(_graphicsOverlay); // Update the selection color _myMapView.SelectionProperties.Color = Color.Yellow; // Create the point collection that defines the polygon PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator) { new MapPoint(-5991501.677830, 5599295.131468), new MapPoint(-6928550.398185, 2087936.739807), new MapPoint(-3149463.800709, 1840803.011362), new MapPoint(-1563689.043184, 3714900.452072), new MapPoint(-3180355.516764, 5619889.608838) }; // Create the polygon Polygon polygonGeometry = new Polygon(polygonPoints); // Define the symbology of the polygon SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Green, 2); SimpleFillSymbol polygonFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Green, polygonOutlineSymbol); // Create the polygon graphic and add it to the graphics overlay _polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol); _graphicsOverlay.Graphics.Add(_polygonGraphic); // Create the point collection that defines the polyline PointCollection polylinePoints = new PointCollection(SpatialReferences.WebMercator) { new MapPoint(-4354240.726880, -609939.795721), new MapPoint(-3427489.245210, 2139422.933233), new MapPoint(-2109442.693501, 4301843.057130), new MapPoint(-1810822.771630, 7205664.366363) }; // Create the polyline Polyline polylineGeometry = new Polyline(polylinePoints); // Create the polyline graphic and add it to the graphics overlay _polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Red, 4)); _graphicsOverlay.Graphics.Add(_polylineGraphic); // Create the point geometry that defines the point graphic MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator); // Define the symbology for the point SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Blue, 10); // Create the point graphic and add it to the graphics overlay _pointGraphic = new Graphic(pointGeometry, locationMarker); _graphicsOverlay.Graphics.Add(_pointGraphic); // Listen for taps; the spatial relationships will be updated in the handler _myMapView.GeoViewTapped += myMapView_GeoViewTapped; // Set the viewpoint to center on the point _myMapView.SetViewpointGeometryAsync(GeometryEngine.Union(polygonGeometry, polylineGeometry), 50); } private async void myMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Identify the tapped graphics IdentifyGraphicsOverlayResult result = null; try { result = await _myMapView.IdentifyGraphicsOverlayAsync(_graphicsOverlay, e.Position, 1, false); } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show(); } // Return if there are no results if (result == null || result.Graphics.Count < 1) { return; } // Get the first identified graphic Graphic identifiedGraphic = result.Graphics.First(); // Clear any existing selection, then select the tapped graphic _graphicsOverlay.ClearSelection(); identifiedGraphic.IsSelected = true; // Get the selected graphic's geometry Geometry selectedGeometry = identifiedGraphic.Geometry; // Perform the calculation and show the results _resultTextView.Text = GetOutputText(selectedGeometry); } private string GetOutputText(Geometry selectedGeometry) { string output = $"Selected: {selectedGeometry.GeometryType}\n"; // Get the relationships List<SpatialRelationship> polygonRelationships = GetSpatialRelationships(selectedGeometry, _polygonGraphic.Geometry); List<SpatialRelationship> polylineRelationships = GetSpatialRelationships(selectedGeometry, _polylineGraphic.Geometry); List<SpatialRelationship> pointRelationships = GetSpatialRelationships(selectedGeometry, _pointGraphic.Geometry); // Add the point relationships to the output if (selectedGeometry.GeometryType != GeometryType.Point) { output += " Relationship(s) with Point:\n"; foreach (SpatialRelationship relationship in pointRelationships) { output += $" {relationship}\n"; } } // Add the polygon relationships to the output if (selectedGeometry.GeometryType != GeometryType.Polygon) { output += " Relationship(s) with Polygon:\n"; foreach (SpatialRelationship relationship in polygonRelationships) { output += $" {relationship}\n"; } } // Add the polyline relationships to the output if (selectedGeometry.GeometryType != GeometryType.Polyline) { output += " Relationship(s) with Polyline:\n"; foreach (SpatialRelationship relationship in polylineRelationships) { output += $" {relationship}\n"; } } return output.TrimEnd('\n'); } /// <summary> /// Returns a list of spatial relationships between two geometries /// </summary> /// <param name="a">The 'a' in "a contains b"</param> /// <param name="b">The 'b' in "a contains b"</param> /// <returns>A list of spatial relationships that are true for a and b.</returns> private static List<SpatialRelationship> GetSpatialRelationships(Geometry a, Geometry b) { List<SpatialRelationship> relationships = new List<SpatialRelationship>(); if (GeometryEngine.Crosses(a, b)) { relationships.Add(SpatialRelationship.Crosses); } if (GeometryEngine.Contains(a, b)) { relationships.Add(SpatialRelationship.Contains); } if (GeometryEngine.Disjoint(a, b)) { relationships.Add(SpatialRelationship.Disjoint); } if (GeometryEngine.Intersects(a, b)) { relationships.Add(SpatialRelationship.Intersects); } if (GeometryEngine.Overlaps(a, b)) { relationships.Add(SpatialRelationship.Overlaps); } if (GeometryEngine.Touches(a, b)) { relationships.Add(SpatialRelationship.Touches); } if (GeometryEngine.Within(a, b)) { relationships.Add(SpatialRelationship.Within); } return relationships; } private void CreateLayout() { // Create a new vertical layout for the app LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Create a help label for the sample. TextView helpLabel = new TextView(this) { Gravity = GravityFlags.Center }; helpLabel.Text = "Tap a graphic to select it. The display will update to show the relationships with the other graphics."; // Create a Textview for the results. _resultTextView = new TextView(this); _resultTextView.SetMinLines(7); //Add the labels to the layout. layout.AddView(helpLabel); layout.AddView(_resultTextView); _myMapView = new MapView(this); layout.AddView(_myMapView); // Show the layout in the app. SetContentView(layout); } } }
// 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 SubtractSaturateInt16() { var test = new SimpleBinaryOpTest__SubtractSaturateInt16(); 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 SimpleBinaryOpTest__SubtractSaturateInt16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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 Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractSaturateInt16 testClass) { var result = Sse2.SubtractSaturate(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractSaturateInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractSaturateInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__SubtractSaturateInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.SubtractSaturate( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_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 = Sse2.SubtractSaturate( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_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 = Sse2.SubtractSaturate( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_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(Sse2).GetMethod(nameof(Sse2.SubtractSaturate), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractSaturate), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SubtractSaturate), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.SubtractSaturate( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Int16*)(pClsVar1)), Sse2.LoadVector128((Int16*)(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<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse2.SubtractSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.SubtractSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.SubtractSaturate(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractSaturateInt16(); var result = Sse2.SubtractSaturate(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__SubtractSaturateInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.SubtractSaturate(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.SubtractSaturate( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(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 = Sse2.SubtractSaturate(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 = Sse2.SubtractSaturate( Sse2.LoadVector128((Int16*)(&test._fld1)), Sse2.LoadVector128((Int16*)(&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(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Sse2Verify.SubtractSaturate(left[0], right[0], result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (Sse2Verify.SubtractSaturate(left[i], right[i], result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.SubtractSaturate)}<Int16>(Vector128<Int16>, Vector128<Int16>): {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; } } } }
using DotVVM.Framework.Binding; using DotVVM.Framework.Controls; using DotVVM.Framework.Runtime; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotVVM.Framework.Compilation; using DotVVM.Framework.Compilation.Binding; using DotVVM.Framework.Compilation.ControlTree; using DotVVM.Framework.Compilation.Javascript; using DotVVM.Framework.Compilation.Javascript.Ast; using DotVVM.Framework.Testing; using DotVVM.Framework.Configuration; using System.Linq.Expressions; using Microsoft.Extensions.DependencyInjection; using DotVVM.Framework.Utils; using DotVVM.Framework.ViewModel; namespace DotVVM.Framework.Tests.Binding { [TestClass] public class JavascriptCompilationTests { private static readonly DotvvmConfiguration configuration; private static readonly BindingTestHelper bindingHelper; static JavascriptCompilationTests() { configuration = DotvvmTestHelper.CreateConfiguration(); configuration.RegisterApiClient(typeof(TestApiClient), "http://server/api", "./apiscript.js", "_testApi"); bindingHelper = new BindingTestHelper(configuration); } public string CompileBinding(string expression, params Type[] contexts) => CompileBinding(expression, contexts, expectedType: typeof(object)); public string CompileBinding(string expression, NamespaceImport[] imports, params Type[] contexts) => CompileBinding(expression, contexts, expectedType: typeof(object), imports); public string CompileBinding(string expression, Type[] contexts, Type expectedType, NamespaceImport[] imports = null) { return bindingHelper.ValueBindingToJs(expression, contexts, expectedType, imports, niceMode: false); } public static string FormatKnockoutScript(ParametrizedCode code) => JavascriptTranslator.FormatKnockoutScript(code); public string CompileBinding(Func<Dictionary<string, Expression>, Expression> expr, Type[] contexts) { var context = DataContextStack.Create(contexts.FirstOrDefault() ?? typeof(object), extensionParameters: new BindingExtensionParameter[]{ new BindingPageInfoExtensionParameter() }); for (int i = 1; i < contexts.Length; i++) { context = DataContextStack.Create(contexts[i], context); } var expressionTree = expr(BindingExpressionBuilder.GetParameters(context).ToDictionary(e => e.Name, e => (Expression)e)); var configuration = DotvvmTestHelper.DefaultConfig; var jsExpression = new JsParenthesizedExpression(configuration.ServiceProvider.GetRequiredService<JavascriptTranslator>().CompileToJavascript(expressionTree, context)); jsExpression.AcceptVisitor(new KnockoutObservableHandlingVisitor(true)); JsTemporaryVariableResolver.ResolveVariables(jsExpression); return JavascriptTranslator.FormatKnockoutScript(jsExpression); } [TestMethod] public void JavascriptCompilation_EnumComparison() { var js = CompileBinding($"_this == 'Local'", typeof(DateTimeKind)); Assert.AreEqual("$data==\"Local\"", js); } [TestMethod] public void JavascriptCompilation_ConstantToString() { var js = CompileBinding("5", Type.EmptyTypes, typeof(string)); Assert.AreEqual("\"5\"", js); } [TestMethod] public void JavascriptCompilation_ToString() { var js = CompileBinding("MyProperty", new[] { typeof(TestViewModel2) }, typeof(string)); Assert.AreEqual("dotvvm.globalize.bindingNumberToString(MyProperty)", js); } [TestMethod] public void JavascriptCompilation_ToString_Invalid() { Assert.ThrowsException<NotSupportedException>(() => { var js = CompileBinding("TestViewModel2", new[] { typeof(TestViewModel) }, typeof(string)); }); } [TestMethod] [DataRow(@"$""Interpolated {StringProp} {StringProp}""")] [DataRow(@"$'Interpolated {StringProp} {StringProp}'")] public void JavascriptCompilation_InterpolatedString(string expression) { var js = CompileBinding(expression, new[] { typeof(TestViewModel) }, typeof(string)); Assert.AreEqual("dotvvm.translations.string.format(\"Interpolated {0} {1}\",[StringProp(),StringProp()])", js); } [TestMethod] public void JavascriptCompilation_InterpolatedString_NoExpressions() { var js = CompileBinding("$'Non-Interpolated {{ no-expr }}'", new[] { typeof(TestViewModel) }); Assert.AreEqual("\"Non-Interpolated { no-expr }\"", js); } [TestMethod] public void JavascriptCompilation_UnwrappedObservables() { var js = CompileBinding("TestViewModel2.Collection[0].StringValue.Length + TestViewModel2.Collection[8].StringValue", new[] { typeof(TestViewModel) }); Assert.AreEqual("(TestViewModel2().Collection()[0]().StringValue().length??\"\")+(TestViewModel2().Collection()[8]().StringValue()??\"\")", js); } [TestMethod] public void JavascriptCompilation_Parent() { var js = CompileBinding("_parent + _parent2 + _parent0 + _parent1 + _parent3", typeof(string), typeof(string), typeof(string), typeof(string), typeof(string)) .Replace("(", "").Replace(")", ""); Assert.AreEqual("$parent+$parents[1]+$data+$parent+$parents[2]", js); } [TestMethod] public void JavascriptCompilation_BindingPageInfo_IsPostbackRunning() { var js = CompileBinding("_page.IsPostbackRunning"); Assert.AreEqual("dotvvm.isPostbackRunning()", js); } [TestMethod] public void JavascriptCompilation_BindingPageInfo_EvaluatingOnClient() { var js = CompileBinding("_page.EvaluatingOnClient"); Assert.AreEqual("true", js); } [TestMethod] public void JavascriptCompilation_BindingPageInfo_EvaluatingOnServer() { var js = CompileBinding("_page.EvaluatingOnServer"); Assert.AreEqual("false", js); } [TestMethod] public void JavascriptCompilation_NullableDateExpression() { var result = CompileBinding("DateFrom == null || DateTo == null || DateFrom.Value <= DateTo.Value", typeof(TestViewModel)); Assert.AreEqual("DateFrom()==null||DateTo()==null||DateFrom()<=DateTo()", result); var result2 = CompileBinding("DateFrom == null || DateTo == null || DateFrom <= DateTo", typeof(TestViewModel)); Assert.AreEqual("DateFrom()==null||DateTo()==null||DateFrom()<=DateTo()", result2); } [TestMethod] public void JavascriptCompilation_LambdaExpression() { var funcP = Expression.Parameter(typeof(string), "parameter"); var blockLocal = Expression.Parameter(typeof(int), "local"); var result = CompileBinding(p => Expression.Lambda( Expression.Block( new [] { blockLocal }, Expression.Assign(blockLocal, Expression.Add(Expression.Constant(6), p["_this"])), blockLocal ), new [] { funcP } ), new [] { typeof(int) } ); Assert.AreEqual("((parameter)=>(local=6+$data,local))", result); } [TestMethod] public void JavascriptCompilation_BlockExpression() { var funcP = Expression.Parameter(typeof(string), "parameter"); var blockLocal = Expression.Parameter(typeof(int), "local"); var result = CompileBinding(p => Expression.Block( new [] { blockLocal }, Expression.Assign(blockLocal, Expression.Add(Expression.Constant(6), p["_this"])), blockLocal ), new [] { typeof(int) } ); Assert.AreEqual("(local=6+$data,local)", result); } [TestMethod] public void JavascriptCompilation_Api_GetFunction() { var result = CompileBinding("_testApi.GetString()"); Assert.AreEqual("dotvvm.api.invoke(dotvvm.api._testApi,\"getString\",function(){return [];},function(args){return [dotvvm.eventHub.get(\"DotVVM.Framework.Tests.Binding.TestApiClient/\")];},function(args){return [];},null,function(args){return \"\";})", result); var assignment = CompileBinding("StringProp = _testApi.GetString()", typeof(TestViewModel)); Assert.AreEqual("StringProp(dotvvm.api.invoke(dotvvm.api._testApi,\"getString\",function(){return [];},function(args){return [dotvvm.eventHub.get(\"DotVVM.Framework.Tests.Binding.TestApiClient/\")];},function(args){return [];},null,function(args){return \"\";})()).StringProp", assignment); } [TestMethod] public void JavascriptCompilation_Api_GetDate() { var result = CompileBinding("_testApi.GetCurrentTime('test')"); Assert.AreEqual("dotvvm.api.invoke(dotvvm.api._testApi,\"getCurrentTime\",function(){return [\"test\"];},function(args){return [dotvvm.eventHub.get(\"DotVVM.Framework.Tests.Binding.TestApiClient/\")];},function(args){return [];},null,function(args){return \"\";})", result); var assignment = CompileBinding("DateFrom = _testApi.GetCurrentTime('test')", typeof(TestViewModel)); Assert.AreEqual("DateFrom(dotvvm.serialization.serializeDate(dotvvm.api.invoke(dotvvm.api._testApi,\"getCurrentTime\",function(){return [\"test\"];},function(args){return [dotvvm.eventHub.get(\"DotVVM.Framework.Tests.Binding.TestApiClient/\")];},function(args){return [];},null,function(args){return \"\";})(),false)).DateFrom", assignment); } [TestMethod] public void JavascriptCompilation_Api_DateParameter() { var result = CompileBinding("_testApi.PostDateToString(DateFrom.Value)", typeof(TestViewModel)); Assert.IsTrue(result.StartsWith("dotvvm.api.invoke(dotvvm.api._testApi,\"postDateToString\",function(){return [dotvvm.serialization.parseDate(DateFrom(),true)];},function(args){return [];},function(args){return [\"DotVVM.Framework.Tests.Binding.TestApiClient/\"];},$element,function(args){return \"")); Assert.IsTrue(result.EndsWith("\";})")); } [TestMethod] public void JavascriptCompilation_WrappedIdentifierExpression() { var result = bindingHelper.ValueBinding<object>("_this", new [] {typeof(TestViewModel) }); Assert.AreEqual("$data", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("$rawData", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("$rawData", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JavascriptCompilation_WrappedPropertyAccessExpression() { var result = bindingHelper.ValueBinding<object>("StringProp", new [] {typeof(TestViewModel) }); Assert.AreEqual("StringProp()", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("StringProp", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("StringProp", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JavascriptCompilation_WrappedNestedPropertyAccessExpression() { var result = bindingHelper.ValueBinding<object>("TestViewModel2.SomeString", new[] { typeof(TestViewModel) }); Assert.AreEqual("TestViewModel2()?.SomeString()", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("TestViewModel2()?.SomeString", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("dotvvm.evaluator.wrapObservable(()=>TestViewModel2()?.SomeString)", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JavascriptCompilation_WrappedNestedListAccessExpression() { var result = bindingHelper.ValueBinding<object>("TestViewModel2.Collection", new[] { typeof(TestViewModel) }); Assert.AreEqual("TestViewModel2()?.Collection()", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("TestViewModel2()?.Collection", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("dotvvm.evaluator.wrapObservable(()=>TestViewModel2()?.Collection,true)", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JavascriptCompilation_WrappedNegatedBooleanAccessExpression() { var result = bindingHelper.ValueBinding<object>("!Value", new[] { typeof(Something) }); Assert.AreEqual("!Value()", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("!Value()", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("ko.pureComputed(()=>!Value())", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JavascriptCompilation_WrappedExpression() { var result = bindingHelper.ValueBinding<object>("StringProp.Length + 43", new [] {typeof(TestViewModel) }); Assert.AreEqual("StringProp()?.length+43", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("StringProp()?.length+43", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("ko.pureComputed(()=>StringProp()?.length+43)", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JavascriptCompilation_FormatStringExpression() { var result = bindingHelper.ValueBinding<object>("LongProperty.ToString('0000')", new [] {typeof(TestViewModel) }); Assert.AreEqual("dotvvm.globalize.bindingNumberToString(LongProperty,\"0000\")()", FormatKnockoutScript(result.UnwrappedKnockoutExpression)); Assert.AreEqual("dotvvm.globalize.bindingNumberToString(LongProperty,\"0000\")", FormatKnockoutScript(result.KnockoutExpression)); Assert.AreEqual("dotvvm.globalize.bindingNumberToString(LongProperty,\"0000\")", FormatKnockoutScript(result.WrappedKnockoutExpression)); } [TestMethod] public void JsTranslator_SimpleCSharpExpression() { Expression<Func<string, string>> expr = abc => abc + "def"; var tree = configuration.ServiceProvider.GetRequiredService<JavascriptTranslator>().CompileToJavascript(expr, DataContextStack.Create(typeof(object))); Assert.AreEqual("(abc)=>abc+\"def\"", tree.ToString()); } [TestMethod] public void JsTranslator_StaticFieldInCSharpExpression() { Expression<Func<string, string>> expr = _ => string.Empty; var tree = configuration.ServiceProvider.GetRequiredService<JavascriptTranslator>().CompileToJavascript(expr, DataContextStack.Create(typeof(object))); Assert.AreEqual("(_)=>\"\"", tree.ToString()); } [TestMethod] public void JsTranslator_LambdaWithParameter() { var result = this.CompileBinding("_this + arg", new [] { typeof(string) }, typeof(Func<string, string>)); Assert.AreEqual("(arg)=>$data+ko.unwrap(arg)", result); } [TestMethod] public void JsTranslator_LambdaWithDelegateInvocation() { var result = this.CompileBinding("arg(12) + _this", new [] { typeof(string) }, typeof(Func<Func<int, string>, string>)); Assert.AreEqual("(arg)=>(ko.unwrap(arg)(12)??\"\")+$data", result); } [TestMethod] public void JsTranslator_EnumToString() { var result = CompileBinding("EnumProperty.ToString()", typeof(TestViewModel)); var resultImplicit = CompileBinding("EnumProperty", new [] { typeof(TestViewModel) }, typeof(string)); Assert.AreEqual(result, resultImplicit); Assert.AreEqual("EnumProperty", result); } [TestMethod] public void JsTranslator_DataContextShift() { var result = bindingHelper.ValueBinding<object>("_this.StringProp", new [] { typeof(TestViewModel) }); var expr0 = JavascriptTranslator.FormatKnockoutScript(result.KnockoutExpression, dataContextLevel: 0); var expr0_explicit = JavascriptTranslator.FormatKnockoutScript(result.KnockoutExpression, allowDataGlobal: false, dataContextLevel: 0); var expr1 = JavascriptTranslator.FormatKnockoutScript(result.KnockoutExpression, dataContextLevel: 1); var expr2 = JavascriptTranslator.FormatKnockoutScript(result.KnockoutExpression, dataContextLevel: 2); Assert.AreEqual("StringProp", expr0); Assert.AreEqual("$data.StringProp", expr0_explicit); Assert.AreEqual("$parent.StringProp", expr1); Assert.AreEqual("$parents[1].StringProp", expr2); } [TestMethod] public void JsTranslator_IntegerArithmetic() { var result = CompileBinding("IntProp / 2 + (IntProp + 1) / (IntProp - 1)", typeof(TestViewModel)); Assert.AreEqual("(IntProp()/2|0)+((IntProp()+1)/(IntProp()-1)|0)", result); } [TestMethod] public void JsTranslator_ArrayIndexer() { var result = CompileBinding("LongArray[1] == 3 && VmArray[0].MyProperty == 1 && VmArray.Length > 1", new [] { typeof(TestViewModel)}); Assert.AreEqual("LongArray()[1]()==3&&(VmArray()[0]().MyProperty()==1&&VmArray().length>1)", result); } [TestMethod] public void JsTranslator_ArrayElement_Get() { var result = CompileBinding("Array[1]", typeof(TestViewModel5)); Assert.AreEqual("Array()[1]", result); } [TestMethod] public void JsTranslator_ReadOnlyArrayElement_Get() { var result = CompileBinding("ReadOnlyArray[1]", typeof(TestViewModel5)); Assert.AreEqual("ReadOnlyArray()[1]", result); } [TestMethod] public void JsTranslator_ArrayElement_Set() { var result = CompileBinding("Array[1] = 123", new[] { typeof(TestViewModel5) }, typeof(void)); Assert.AreEqual("dotvvm.translations.array.setItem(Array,1,123)", result); } [TestMethod] public void JsTranslator_ListIndexer_Get() { var result = CompileBinding("List[1]", typeof(TestViewModel5)); Assert.AreEqual("List()[1]", result); } [TestMethod] public void JsTranslator_ReadOnlyListIndexer_Get() { var result = CompileBinding("List.AsReadOnly()[1]", typeof(TestViewModel5)); Assert.AreEqual("List()[1]", result); } [TestMethod] public void JsTranslator_ListIndexer_Set() { var result = CompileBinding("List[1] = 123", new[] { typeof(TestViewModel5) }, typeof(void)); Assert.AreEqual("dotvvm.translations.array.setItem(List,1,123)", result); } [TestMethod] public void JsTranslator_DictionaryIndexer_Get() { var result = CompileBinding("Dictionary[1]", typeof(TestViewModel5)); Assert.AreEqual("dotvvm.translations.dictionary.getItem(Dictionary(),1)", result); } [TestMethod] public void JsTranslator_ReadOnlyDictionaryIndexer_Get() { var result = CompileBinding("ReadOnlyDictionary[1]", typeof(TestViewModel5)); Assert.AreEqual("dotvvm.translations.dictionary.getItem(ReadOnlyDictionary(),1)", result); } [TestMethod] public void JsTranslator_DictionaryIndexer_Set() { var result = CompileBinding("Dictionary[1] = 123", new[] { typeof(TestViewModel5) }, typeof(void)); Assert.AreEqual("dotvvm.translations.dictionary.setItem(Dictionary,1,123)", result); } [TestMethod] public void JsTranslator_DictionaryClear() { var result = CompileBinding("Dictionary.Clear()", new[] { typeof(TestViewModel5) }, typeof(void)); Assert.AreEqual("dotvvm.translations.dictionary.clear(Dictionary)", result); } [TestMethod] public void JsTranslator_DictionaryContainsKey() { var result = CompileBinding("Dictionary.ContainsKey(123)", new[] { typeof(TestViewModel5) }, typeof(bool)); Assert.AreEqual("dotvvm.translations.dictionary.containsKey(Dictionary(),123)", result); } [TestMethod] public void JsTranslator_DictionaryRemove() { var result = CompileBinding("Dictionary.Remove(123)", new[] { typeof(TestViewModel5) }, typeof(bool)); Assert.AreEqual("dotvvm.translations.dictionary.remove(Dictionary,123)", result); } [TestMethod] [DataRow("Enumerable.Where(LongArray, (long item) => item % 2 == 0)", DisplayName = "Regular call of Enumerable.Where")] [DataRow("LongArray.Where((long item) => item % 2 == 0)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableWhere(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().filter((item)=>ko.unwrap(item)%2==0)", result); } [TestMethod] public void JsTranslator_NestedEnumerableMethods() { var result = CompileBinding("Enumerable.Where(Enumerable.Where(LongArray, (long item) => item % 2 == 0), (long item) => item % 3 == 0)", new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().filter((item)=>ko.unwrap(item)%2==0).filter((item)=>ko.unwrap(item)%3==0)", result); } [TestMethod] [DataRow("Enumerable.Select(LongArray, (long item) => -item)", DisplayName = "Regular call of Enumerable.Select")] [DataRow("LongArray.Select((long item) => -item)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableSelect(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().map((item)=>-ko.unwrap(item))", result); } [TestMethod] [DataRow("Enumerable.Concat(LongArray, LongArray)", DisplayName = "Regular call of Enumerable.Concat")] [DataRow("LongArray.Concat(LongArray)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableConcat(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().concat(LongArray())", result); } [TestMethod] [DataRow("Enumerable.Take(LongArray, 2)", DisplayName = "Regular call of Enumerable.Take")] [DataRow("LongArray.Take(2)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableTake(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().slice(0,2)", result); } [TestMethod] [DataRow("Enumerable.Skip(LongArray, 2)", DisplayName = "Regular call of Enumerable.Skip")] [DataRow("LongArray.Skip(2)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableSkip(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().slice(2)", result); } [TestMethod] public void JsTranslator_ListAdd() { var result = CompileBinding("LongList.Add(11)", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.add(LongList,11)", result); } [TestMethod] public void JsTranslator_ListAddOrUpdate() { var result = CompileBinding("LongList.AddOrUpdate(12345L, item => item == 12345, item => 54321L)", new[] { typeof(TestViewModel) }, typeof(void), new[] { new NamespaceImport("DotVVM.Framework.Binding.HelperNamespace") }); Assert.AreEqual("dotvvm.translations.array.addOrUpdate(LongList,12345,(item)=>ko.unwrap(item)==12345,(item)=>54321)", result); } [TestMethod] public void JsTranslator_ListAddRange() { var result = CompileBinding("LongList.AddRange(LongArray)", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.addRange(LongList,LongArray())", result); } [TestMethod] [DataRow("Enumerable.All(LongArray, (long item) => item > 0)", DisplayName = "Regular call of Enumerable.All")] [DataRow("LongArray.All((long item) => item > 0)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableAll(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().every((item)=>ko.unwrap(item)>0)", result); } [TestMethod] [DataRow("Enumerable.Any(LongArray, (long item) => item > 0)", DisplayName = "Regular call of Enumerable.Any")] [DataRow("LongArray.Any((long item) => item > 0)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableAny(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray().some((item)=>ko.unwrap(item)>0)", result); } [TestMethod] public void JsTranslator_ListClear() { var result = CompileBinding("LongList.Clear()", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.clear(LongList)", result); } [TestMethod] [DataRow("Enumerable.FirstOrDefault(LongArray)", DisplayName = "Regular call of Enumerable.FirstOrDefault")] [DataRow("LongArray.FirstOrDefault()", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableFirstOrDefault(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("LongArray()[0]", result); } [TestMethod] [DataRow("Enumerable.FirstOrDefault(LongArray, (long item) => item > 0)", DisplayName = "Regular call of Enumerable.FirstOrDefault")] [DataRow("LongArray.FirstOrDefault((long item) => item > 0)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableFirstOrDefaultParametrized(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("dotvvm.translations.array.firstOrDefault(LongArray(),(item)=>ko.unwrap(item)>0)", result); } [TestMethod] public void JsTranslator_ListInsert() { var result = CompileBinding("LongList.Insert(1, 12345)", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.insert(LongList,1,12345)", result); } [TestMethod] public void JsTranslator_ListInsertRange() { var result = CompileBinding("LongList.InsertRange(1, LongArray)", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.insertRange(LongList,1,LongArray())", result); } [TestMethod] [DataRow("Enumerable.LastOrDefault(LongArray)", DisplayName = "Regular call of Enumerable.LastOrDefault")] [DataRow("LongArray.LastOrDefault()", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableLastOrDefault(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("dotvvm.translations.array.lastOrDefault(LongArray(),()=>true)", result); } [TestMethod] [DataRow("Enumerable.LastOrDefault(LongArray, (long item) => item > 0)", DisplayName = "Regular call of Enumerable.LastOrDefault")] [DataRow("LongArray.LastOrDefault((long item) => item > 0)", DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableLastOrDefaultParametrized(string binding) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual("dotvvm.translations.array.lastOrDefault(LongArray(),(item)=>ko.unwrap(item)>0)", result); } [TestMethod] [DataRow("Enumerable.Distinct(VmArray)", DisplayName = "Regular call of Enumerable.Distinct")] [DataRow("VmArray.Distinct()", DisplayName = "Syntax sugar - extension method")] [ExpectedException(typeof(DotvvmCompilationException))] public void JsTranslator_EnumerableDistinct_NonPrimitiveTypesThrows(string binding) { CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); } [TestMethod] [DataRow("Enumerable.Max(Int32Array)", "Int32Array", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(Int64Array)", "Int64Array", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(SingleArray)", "SingleArray",false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(DoubleArray)", "DoubleArray", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(DecimalArray)", "DecimalArray", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableInt32Array)", "NullableInt32Array", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableInt64Array)", "NullableInt64Array", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableDecimalArray)", "NullableDecimalArray", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableSingleArray)", "NullableSingleArray", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableDoubleArray)", "NullableDoubleArray", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Int32Array.Max()", "Int32Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("Int64Array.Max()", "Int64Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("SingleArray.Max()", "SingleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DoubleArray.Max()", "DoubleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DecimalArray.Max()", "DecimalArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt32Array.Max()", "NullableInt32Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt64Array.Max()", "NullableInt64Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDecimalArray.Max()", "NullableDecimalArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableSingleArray.Max()", "NullableSingleArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDoubleArray.Max()", "NullableDoubleArray", true, DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableMax(string binding, string property, bool nullable) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); Assert.AreEqual($"dotvvm.translations.array.max({property}(),(arg)=>ko.unwrap(arg),{(!nullable).ToString().ToLowerInvariant()})", result); } [TestMethod] [DataRow("Enumerable.Max(Int32Array, (int item) => -item)", "Int32Array", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(Int64Array, (long item) => -item)", "Int64Array", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(SingleArray, (float item) => -item)", "SingleArray", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(DoubleArray, (double item) => -item)", "DoubleArray", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(DecimalArray, (decimal item) => -item)", "DecimalArray", false, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableInt32Array, item => -item)", "NullableInt32Array", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableInt64Array, item => -item)", "NullableInt64Array", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableDecimalArray, item => -item)", "NullableDecimalArray", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableSingleArray, item => -item)", "NullableSingleArray", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Enumerable.Max(NullableDoubleArray, item => -item)", "NullableDoubleArray", true, DisplayName = "Regular call of Enumerable.Max")] [DataRow("Int32Array.Max(item => -item)", "Int32Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("Int64Array.Max(item => -item)", "Int64Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("SingleArray.Max(item => -item)", "SingleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DoubleArray.Max(item => -item)", "DoubleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DecimalArray.Max(item => -item)", "DecimalArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt32Array.Max(item => -item)", "NullableInt32Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt64Array.Max(item => -item)", "NullableInt64Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDecimalArray.Max(item => -item)", "NullableDecimalArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableSingleArray.Max(item => -item)", "NullableSingleArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDoubleArray.Max(item => -item)", "NullableDoubleArray", true, DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableMax_WithSelector(string binding, string property, bool nullable) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); Assert.AreEqual($"dotvvm.translations.array.max({property}(),(item)=>-ko.unwrap(item),{(!nullable).ToString().ToLowerInvariant()})", result); } [TestMethod] [DataRow("Enumerable.Min(Int32Array)", "Int32Array", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(Int64Array)", "Int64Array", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(SingleArray)", "SingleArray", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(DoubleArray)", "DoubleArray", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(DecimalArray)", "DecimalArray", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableInt32Array)", "NullableInt32Array", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableInt64Array)", "NullableInt64Array", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableDecimalArray)", "NullableDecimalArray", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableSingleArray)", "NullableSingleArray", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableDoubleArray)", "NullableDoubleArray", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Int32Array.Min()", "Int32Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("Int64Array.Min()", "Int64Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("SingleArray.Min()", "SingleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DoubleArray.Min()", "DoubleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DecimalArray.Min()", "DecimalArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt32Array.Min()", "NullableInt32Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt64Array.Min()", "NullableInt64Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDecimalArray.Min()", "NullableDecimalArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableSingleArray.Min()", "NullableSingleArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDoubleArray.Min()", "NullableDoubleArray", true, DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableMin(string binding, string property, bool nullable) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); Assert.AreEqual($"dotvvm.translations.array.min({property}(),(arg)=>ko.unwrap(arg),{(!nullable).ToString().ToLowerInvariant()})", result); } [TestMethod] [DataRow("Enumerable.Min(Int32Array, item => -item)", "Int32Array", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(Int64Array, item => -item)", "Int64Array", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(SingleArray, item => -item)", "SingleArray", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(DoubleArray, item => -item)", "DoubleArray", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(DecimalArray, item => -item)", "DecimalArray", false, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableInt32Array, item => -item)", "NullableInt32Array", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableInt64Array, item => -item)", "NullableInt64Array", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableDecimalArray, item => -item)", "NullableDecimalArray", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableSingleArray, item => -item)", "NullableSingleArray", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Enumerable.Min(NullableDoubleArray, item => -item)", "NullableDoubleArray", true, DisplayName = "Regular call of Enumerable.Min")] [DataRow("Int32Array.Min(item => -item)", "Int32Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("Int64Array.Min(item => -item)", "Int64Array", false, DisplayName = "Syntax sugar - extension method")] [DataRow("SingleArray.Min(item => -item)", "SingleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DoubleArray.Min(item => -item)", "DoubleArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("DecimalArray.Min(item => -item)", "DecimalArray", false, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt32Array.Min(item => -item)", "NullableInt32Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableInt64Array.Min(item => -item)", "NullableInt64Array", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDecimalArray.Min(item => -item)", "NullableDecimalArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableSingleArray.Min(item => -item)", "NullableSingleArray", true, DisplayName = "Syntax sugar - extension method")] [DataRow("NullableDoubleArray.Min(item => -item)", "NullableDoubleArray", true, DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableMin_WithSelector(string binding, string property, bool nullable) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); Assert.AreEqual($"dotvvm.translations.array.min({property}(),(item)=>-ko.unwrap(item),{(!nullable).ToString().ToLowerInvariant()})", result); } [TestMethod] [DataRow("Enumerable.OrderBy(ObjectArray, (TestComparisonType item) => item.Int)", "Int", typeof(int), DisplayName = "Regular call of Enumerable.OrderBy")] [DataRow("Enumerable.OrderBy(ObjectArray, (TestComparisonType item) => item.Bool)", "Bool", typeof(bool), DisplayName = "Regular call of Enumerable.OrderBy")] [DataRow("Enumerable.OrderBy(ObjectArray, (TestComparisonType item) => item.String)", "String", typeof(string), DisplayName = "Regular call of Enumerable.OrderBy")] [DataRow("Enumerable.OrderBy(ObjectArray, (TestComparisonType item) => item.Enum)", "Enum", typeof(TestComparisonType.TestEnum), DisplayName = "Regular call of Enumerable.OrderBy")] [DataRow("ObjectArray.OrderBy((TestComparisonType item) => item.Int)", "Int", typeof(int), DisplayName = "Syntax sugar - extension method")] [DataRow("ObjectArray.OrderBy((TestComparisonType item) => item.Bool)", "Bool", typeof(bool), DisplayName = "Syntax sugar - extension method")] [DataRow("ObjectArray.OrderBy((TestComparisonType item) => item.String)", "String", typeof(string), DisplayName = "Syntax sugar - extension method")] [DataRow("ObjectArray.OrderBy((TestComparisonType item) => item.Enum)", "Enum", typeof(TestComparisonType.TestEnum), DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableOrderBy(string binding, string key, Type comparedType) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); var typeHash = (comparedType.IsEnum) ? $"\"{comparedType.GetTypeHash()}\"" : "null"; Assert.AreEqual($"dotvvm.translations.array.orderBy(ObjectArray(),(item)=>ko.unwrap(item).{key}(),{typeHash})", result); } [TestMethod] [DataRow("Enumerable.OrderBy(ObjectArray, (TestComparisonType item) => item.Obj)")] [DataRow("ObjectArray.OrderBy((TestComparisonType item) => item.Obj)")] [ExpectedException(typeof(DotvvmCompilationException))] public void JsTranslator_EnumerableOrderBy_NonPrimitiveTypesThrows(string binding) { CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); } [TestMethod] [DataRow("Enumerable.OrderByDescending(ObjectArray, (TestComparisonType item) => item.Int)", "Int", typeof(int), DisplayName = "Regular call of Enumerable.OrderByDescending")] [DataRow("Enumerable.OrderByDescending(ObjectArray, (TestComparisonType item) => item.Bool)", "Bool", typeof(bool), DisplayName = "Regular call of Enumerable.OrderByDescending")] [DataRow("Enumerable.OrderByDescending(ObjectArray, (TestComparisonType item) => item.String)", "String", typeof(string), DisplayName = "Regular call of Enumerable.OrderByDescending")] [DataRow("Enumerable.OrderByDescending(ObjectArray, (TestComparisonType item) => item.Enum)", "Enum", typeof(TestComparisonType.TestEnum), DisplayName = "Regular call of Enumerable.OrderByDescending")] [DataRow("ObjectArray.OrderByDescending((TestComparisonType item) => item.Int)", "Int", typeof(int), DisplayName = "Syntax sugar - extension method")] [DataRow("ObjectArray.OrderByDescending((TestComparisonType item) => item.Bool)", "Bool", typeof(bool), DisplayName = "Syntax sugar - extension method")] [DataRow("ObjectArray.OrderByDescending((TestComparisonType item) => item.String)", "String", typeof(string), DisplayName = "Syntax sugar - extension method")] [DataRow("ObjectArray.OrderByDescending((TestComparisonType item) => item.Enum)", "Enum", typeof(TestComparisonType.TestEnum), DisplayName = "Syntax sugar - extension method")] public void JsTranslator_EnumerableOrderByDescending(string binding, string key, Type comparedType) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); var typeHash = (comparedType.IsEnum) ? $"\"{comparedType.GetTypeHash()}\"" : "null"; Assert.AreEqual($"dotvvm.translations.array.orderByDesc(ObjectArray(),(item)=>ko.unwrap(item).{key}(),{typeHash})", result); } [TestMethod] [DataRow("Enumerable.OrderByDescending(ObjectArray, (TestComparisonType item) => item.Obj)")] [DataRow("ObjectArray.OrderByDescending((TestComparisonType item) => item.Obj)")] [ExpectedException(typeof(DotvvmCompilationException))] public void JsTranslator_EnumerableOrderByDescending_NonPrimitiveTypesThrows(string binding) { CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestArraysViewModel) }); } [TestMethod] public void JsTranslator_ListRemoveAt() { var result = CompileBinding("LongList.RemoveAt(1)", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.removeAt(LongList,1)", result); } [TestMethod] public void JsTranslator_ListRemoveFirst() { var result = CompileBinding("LongList.RemoveFirst((long item) => item == 2)", new[] { typeof(TestViewModel) }, typeof(void), new[] { new NamespaceImport("DotVVM.Framework.Binding.HelperNamespace") }); Assert.AreEqual("dotvvm.translations.array.removeFirst(LongList,(item)=>ko.unwrap(item)==2)", result); } [TestMethod] public void JsTranslator_ListRemoveLast() { var result = CompileBinding("LongList.RemoveLast((long item) => item == 2)", new[] { typeof(TestViewModel) }, typeof(void), new[] { new NamespaceImport("DotVVM.Framework.Binding.HelperNamespace") }); Assert.AreEqual("dotvvm.translations.array.removeLast(LongList,(item)=>ko.unwrap(item)==2)", result); } [TestMethod] public void JsTranslator_ListRemoveRange() { var result = CompileBinding("LongList.RemoveRange(1, 5)", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.removeRange(LongList,1,5)", result); } [TestMethod] public void JsTranslator_ListReverse() { var result = CompileBinding("LongList.Reverse()", new[] { typeof(TestViewModel) }, typeof(void), null); Assert.AreEqual("dotvvm.translations.array.reverse(LongList)", result); } [TestMethod] [DataRow("Math.Abs(IntProp)", "Math.abs(IntProp())")] [DataRow("Math.Abs(DoubleProp)", "Math.abs(DoubleProp())")] [DataRow("Math.Acos(DoubleProp)", "Math.acos(DoubleProp())")] [DataRow("Math.Asin(DoubleProp)", "Math.asin(DoubleProp())")] [DataRow("Math.Atan(DoubleProp)", "Math.atan(DoubleProp())")] [DataRow("Math.Atan2(DoubleProp, 15)", "Math.atan2(DoubleProp(),15)")] [DataRow("Math.Ceiling(DoubleProp)", "Math.ceil(DoubleProp())")] [DataRow("Math.Cos(DoubleProp)", "Math.cos(DoubleProp())")] [DataRow("Math.Cosh(DoubleProp)", "Math.cosh(DoubleProp())")] [DataRow("Math.Exp(DoubleProp)", "Math.exp(DoubleProp())")] [DataRow("Math.Floor(DoubleProp)", "Math.floor(DoubleProp())")] [DataRow("Math.Log(DoubleProp)", "Math.log(DoubleProp())")] [DataRow("Math.Log10(DoubleProp)", "Math.log10(DoubleProp())")] [DataRow("Math.Max(IntProp, DoubleProp)", "Math.max(IntProp(),DoubleProp())")] [DataRow("Math.Min(IntProp, DoubleProp)", "Math.min(IntProp(),DoubleProp())")] [DataRow("Math.Pow(IntProp, 3)", "Math.pow(IntProp(),3)")] [DataRow("Math.Round(DoubleProp)", "Math.round(DoubleProp())")] [DataRow("Math.Round(DoubleProp, 2)", "DoubleProp().toFixed(2)")] [DataRow("Math.Sign(IntProp)", "Math.sign(IntProp())")] [DataRow("Math.Sign(DoubleProp)", "Math.sign(DoubleProp())")] [DataRow("Math.Sqrt(DoubleProp)", "Math.sqrt(DoubleProp())")] [DataRow("Math.Tan(DoubleProp)", "Math.tan(DoubleProp())")] [DataRow("Math.Tanh(DoubleProp)", "Math.tanh(DoubleProp())")] [DataRow("Math.Truncate(DoubleProp)", "Math.trunc(DoubleProp())")] public void JsTranslator_MathMethods(string binding, string expected) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual(expected, result); } [TestMethod] [DataRow("Convert.ToBoolean(IntProp)", "Boolean(IntProp())")] [DataRow("Convert.ToBoolean(DoubleProp)", "Boolean(DoubleProp())")] [DataRow("Convert.ToDecimal(DoubleProp)", "DoubleProp")] [DataRow("Convert.ToInt32(DoubleProp)", "Math.round(DoubleProp())")] [DataRow("Convert.ToByte(DoubleProp)", "Math.round(DoubleProp())")] [DataRow("Convert.ToDouble(IntProp)", "IntProp")] [DataRow("Convert.ToDouble(DecimalProp)", "DecimalProp")] public void JsTranslator_ConvertNumeric(string binding, string expected) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual(expected, result); } [TestMethod] [DataRow("StringProp.Split('c')", "c", "None")] [DataRow("StringProp.Split(\"str\")", "str", "None")] [DataRow("StringProp.Split('c', StringSplitOptions.None)", "c", "None")] [DataRow("StringProp.Split('c', StringSplitOptions.RemoveEmptyEntries)", "c", "RemoveEmptyEntries")] public void JsTranslator_StringSplit_WithOptions(string binding, string delimiter, string options) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual($"dotvvm.translations.string.split(StringProp(),\"{delimiter}\",\"{options}\")", result); } [TestMethod] [DataRow("StringProp.Split('c', 'b')", "[\"c\",\"b\"]")] [DataRow("StringProp.Split('c', 'b', 'a')", "[\"c\",\"b\",\"a\"]")] public void JsTranslator_StringSplit_ArrayDelimiters_NoOptions(string binding, string delimiters) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual($"StringProp().split({delimiters})", result); } [TestMethod] [DataRow("string.Join('c', StringArray)", "c")] [DataRow("string.Join(\"str\", StringArray)", "str")] public void JsTranslator_StringArrayJoin(string binding, string delimiter) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual($"dotvvm.translations.string.join(StringArray(),\"{delimiter}\")", result); } [TestMethod] [DataRow("string.Join('c', StringArray.Where((string item) => item.Length > 2))", "c")] [DataRow("string.Join(\"str\", StringArray.Where((string item) => item.Length > 2))", "str")] public void JsTranslator_StringEnumerableJoin(string binding, string delimiter) { var result = CompileBinding(binding, new[] { new NamespaceImport("System.Linq") }, new[] { typeof(TestViewModel) }); Assert.AreEqual($"dotvvm.translations.string.join(StringArray().filter((item)=>ko.unwrap(item).length>2),\"{delimiter}\")", result); } [TestMethod] [DataRow("StringProp.Replace('c', 'a')", "c", "a")] [DataRow("StringProp.Replace(\"str\", \"rts\")", "str", "rts")] public void JsTranslator_StringReplace(string binding, string original, string replacement) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual($"StringProp().split(\"{original}\").join(\"{replacement}\")", result); } [TestMethod] [DataRow("DateTime.Year", "getFullYear", false)] [DataRow("DateTime.Month", "getMonth", true)] [DataRow("DateTime.Day", "getDate", false)] [DataRow("DateTime.Hour", "getHours", false)] [DataRow("DateTime.Minute", "getMinutes", false)] [DataRow("DateTime.Second", "getSeconds", false)] [DataRow("DateTime.Millisecond", "getMilliseconds", false)] public void JsTranslator_DateTime_Property_Getters(string binding, string jsFunction, bool increment = false) { var result = CompileBinding(binding, new[] { typeof(TestViewModel) }); Assert.AreEqual($"dotvvm.serialization.parseDate(DateTime()).{jsFunction}(){(increment ? "+1" : string.Empty)}", result); } [TestMethod] public void JsTranslator_WebUtility_UrlEncode() { var result = CompileBinding("WebUtility.UrlEncode(\"Hello World!\")", new[] { new NamespaceImport("System.Net") }, new[] { typeof(TestViewModel) }); Assert.AreEqual($"encodeURIComponent(\"Hello World!\")", result); } [TestMethod] public void JsTranslator_WebUtility_UrlDecode() { var result = CompileBinding("WebUtility.UrlDecode(\"Hello%20World!\")", new[] { new NamespaceImport("System.Net") }, new[] { typeof(TestViewModel) }); Assert.AreEqual($"decodeURIComponent(\"Hello%20World!\")", result); } [TestMethod] public void JavascriptCompilation_GuidToString() { var result = CompileBinding("GuidProp != Guid.Empty ? GuidProp.ToString() : ''", typeof(TestViewModel)); Assert.AreEqual("GuidProp()!=\"00000000-0000-0000-0000-000000000000\"?GuidProp:\"\"", result); } [TestMethod] [DataRow("_collection.IsEven", "$index()%2==0")] [DataRow("_this._collection.IsEven", "$index()%2==0")] [DataRow("_root._index", "$index()")] [DataRow("_index", "$index()")] [DataRow("_root._page.EvaluatingOnClient", "true")] [DataRow("_page.EvaluatingOnClient", "true")] public void StaticCommandCompilation_Parameters(string expr, string expectedResult) { var result = CompileBinding(expr, new [] { typeof(TestViewModel) }); Assert.AreEqual(expectedResult, result); } [TestMethod] [DataRow("_index", "$parentContext.$parentContext.$index()")] [DataRow("_parent2._index", "$parentContext.$parentContext.$index()")] [DataRow("_root._index", "$parentContext.$parentContext.$index()")] [DataRow("_collection.IsEven", "$parentContext.$parentContext.$index()%2==0")] public void StaticCommandCompilation_ParametersInHierarchy(string expr, string expectedResult) { var result = CompileBinding(expr, new [] { typeof(TestViewModel), typeof(object), typeof(string) }); Assert.AreEqual(expectedResult, result); } [TestMethod] [DataRow("_this._index", "IndexProperty")] [DataRow("_root._index", "IndexProperty")] [DataRow("_index", "IndexProperty")] [DataRow("_collection.Index", "$index()")] public void StaticCommandCompilation_ParameterPropertyConflict(string expr, string expectedResult) { var result = CompileBinding(expr, new [] { typeof(TestExtensionParameterConflictViewModel) }); Assert.AreEqual(expectedResult, result); } [TestMethod] public void StaticCommandCompilation_ParameterPropertyNotExists() { // _index exists on parent, but not on _this var e = Assert.ThrowsException<Exception>(() => CompileBinding("_this._index", new [] { typeof(object), typeof(string) })); Assert.AreEqual("Could not find instance member _index on type System.String.", e.Message); } [TestMethod] public void StaticCommandCompilation_MultipleExplicitIndexParameters() { var dc1 = DataContextStack.Create( typeof(TestViewModel), extensionParameters: new [] { new CurrentCollectionIndexExtensionParameter() }); var dc2 = DataContextStack.Create( typeof(int), parent: dc1, extensionParameters: new [] { new CurrentCollectionIndexExtensionParameter() }); var result = bindingHelper.ValueBindingToJs("_index + _this._index + _parent._index + _root._index", dc2); Assert.AreEqual("$index() + $index() + $parentContext.$index() + $parentContext.$index()", result); } [TestMethod] public void StaticCommandCompilation_ExplicitIndexParameterInThis() { var result = CompileBinding("_this._index", new [] { typeof(TestViewModel) }); Assert.AreEqual("$index()", result); } [TestMethod] public void JavascriptCompilation_Variable() { var result = CompileBinding("var a = 1; var b = 2; var c = 3; a + b + c", typeof(TestViewModel)); Assert.AreEqual("(()=>{let a=1;let b=2;let c=3;return a+b+c;})()", result); } [TestMethod] public void JavascriptCompilation_Variable_Nested() { var result = CompileBinding("var a = 1; var b = (var a = 5; a + 1); a + b", typeof(TestViewModel)); Assert.AreEqual("(()=>{let a0=1;let a=5;let b=a+1;return a0+b;})()", result); } [TestMethod] public void JavascriptCompilation_Variable_Property() { var result = CompileBinding("var a = _this.StringProp; var b = _this.StringProp2; StringProp2 = a + b", typeof(TestViewModel)); Assert.AreEqual("(()=>{let a=StringProp();let b=StringProp2();return StringProp2(a+b).StringProp2;})()", result); } [TestMethod] public void JavascriptCompilation_Variable_VM() { var result = CompileBinding("var a = _parent; var b = _this.StringProp2; StringProp2 = a + b", new [] { typeof(string), typeof(TestViewModel) }); Assert.AreEqual("(()=>{let a=$parent;let b=StringProp2();return StringProp2(a+b).StringProp2;})()", result); } [TestMethod] public void JavascriptCompilation_AssignAndUse() { var result = CompileBinding("StringProp2 = (_this.StringProp = _this.StringProp2 = 'lol') + 'hmm'", typeof(TestViewModel)); Assert.AreEqual("StringProp2((StringProp(StringProp2(\"lol\").StringProp2()).StringProp()??\"\")+\"hmm\").StringProp2", result); } [TestMethod] public void JavascriptCompilation_AssignAndUseObject() { var result = CompileBinding("StringProp2 = (_this.TestViewModel2B = _this.TestViewModel2 = _this.VmArray[3]).SomeString", typeof(TestViewModel)); Assert.AreEqual("StringProp2(dotvvm.serialization.deserialize(dotvvm.serialization.deserialize(VmArray()[3](),TestViewModel2,true)(),TestViewModel2B,true)().SomeString()).StringProp2", result); } [TestMethod, Ignore] // ignored because https://github.com/dotnet/corefx/issues/33074 public void JavascriptCompilation_AssignAndUseObjectArray() { var result = CompileBinding("StringProp2 = (_this.VmArray[1] = (_this.VmArray[0] = _this.VmArray[3])).SomeString", typeof(TestViewModel)); Assert.AreEqual("function(abc){return abc+\"def\";}", result); } [TestMethod] public void JavascriptCompilation_AssignmentExpectsObservable() { var result = CompileBinding("_api.RefreshOnChange(StringProp = StringProp2, StringProp + StringProp2)", typeof(TestViewModel)); Assert.AreEqual("dotvvm.api.refreshOn(StringProp(StringProp2()).StringProp,ko.pureComputed(()=>(StringProp()??\"\")+(StringProp2()??\"\")))", result); } [TestMethod] public void JavascriptCompilation_ApiRefreshOn() { var result = CompileBinding("_api.RefreshOnChange('here would be the API invocation', StringProp + StringProp2)", typeof(TestViewModel)); Assert.AreEqual("dotvvm.api.refreshOn(\"here would be the API invocation\",ko.pureComputed(()=>(StringProp()??\"\")+(StringProp2()??\"\")))", result); } [DataTestMethod] [DataRow("StringProp.ToUpper()", "StringProp().toLocaleUpperCase()")] [DataRow("StringProp.ToLower()", "StringProp().toLocaleLowerCase()")] [DataRow("StringProp.ToUpperInvariant()", "StringProp().toUpperCase()")] [DataRow("StringProp.ToLowerInvariant()", "StringProp().toLowerCase()")] [DataRow("StringProp.IndexOf('test')", "StringProp().indexOf(\"test\")")] [DataRow("StringProp.IndexOf('test',StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.indexOf(StringProp(),0,\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.IndexOf('test',1)", "StringProp().indexOf(\"test\",1)")] [DataRow("StringProp.IndexOf('test',1,StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.indexOf(StringProp(),1,\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.LastIndexOf('test')", "StringProp().lastIndexOf(\"test\")")] [DataRow("StringProp.LastIndexOf('test',StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.lastIndexOf(StringProp(),0,\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.LastIndexOf('test',2)", "StringProp().lastIndexOf(\"test\",2)")] [DataRow("StringProp.LastIndexOf('test',2,StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.lastIndexOf(StringProp(),2,\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.Contains('test')", "StringProp().includes(\"test\")")] [DataRow("StringProp.Contains('test',StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.contains(StringProp(),\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.StartsWith('test')", "StringProp().startsWith(\"test\")")] [DataRow("StringProp.StartsWith('test',StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.startsWith(StringProp(),\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.EndsWith('test')", "StringProp().endsWith(\"test\")")] [DataRow("StringProp.EndsWith('test',StringComparison.InvariantCultureIgnoreCase)", "dotvvm.translations.string.endsWith(StringProp(),\"test\",\"InvariantCultureIgnoreCase\")")] [DataRow("StringProp.Trim()", "StringProp().trim()")] [DataRow("StringProp.Trim('0')", "dotvvm.translations.string.trimEnd(dotvvm.translations.string.trimStart(StringProp(),\"0\"),\"0\")")] [DataRow("StringProp.TrimStart()", "StringProp().trimStart()")] [DataRow("StringProp.TrimStart('0')", "dotvvm.translations.string.trimStart(StringProp(),\"0\")")] [DataRow("StringProp.TrimEnd()", "StringProp().trimEnd()")] [DataRow("StringProp.TrimEnd('0')", "dotvvm.translations.string.trimEnd(StringProp(),\"0\")")] [DataRow("StringProp.PadLeft(1)", "StringProp().padStart(1)")] [DataRow("StringProp.PadRight(2)", "StringProp().padEnd(2)")] [DataRow("StringProp.PadLeft(1,'#')", "StringProp().padStart(1,\"#\")")] [DataRow("StringProp.PadRight(2,'#')", "StringProp().padEnd(2,\"#\")")] [DataRow("string.IsNullOrEmpty(StringProp)", "!(StringProp()?.length>0)")] [DataRow("string.IsNullOrWhiteSpace(StringProp)", "!(StringProp()?.trim().length>0)")] public void JavascriptCompilation_StringFunctions(string input, string expected) { var result = CompileBinding(input, typeof(TestViewModel)); Assert.AreEqual(expected, result); } } public class TestExtensionParameterConflictViewModel { [Bind(Name = "IndexProperty")] public int _index { get; } } public class TestApiClient { public string GetString() => ""; public string PostDateToString(DateTime date) => date.ToShortDateString(); public DateTime GetCurrentTime(string name) => DateTime.UtcNow; } public class TestArraysViewModel { public int[] Int32Array { get; set; } = new[] { 1, 2, 3 }; public long[] Int64Array { get; set; } = new[] { 1L, 2L, 3L }; public decimal[] DecimalArray { get; set; } = new[] { 1m, 2m, 3m }; public float[] SingleArray { get; set; } = new[] { 1f, 2f, 3f }; public double[] DoubleArray { get; set; } = new[] { 1d, 2d, 3d }; public int?[] NullableInt32Array { get; set; } = new int?[] { 1, 2, 3 }; public long?[] NullableInt64Array { get; set; } = new long?[] { 1, 2, 3 }; public decimal?[] NullableDecimalArray { get; set; } = new decimal?[] { 1, 2, 3 }; public float?[] NullableSingleArray { get; set; } = new float?[] { 1, 2, 3 }; public double?[] NullableDoubleArray { get; set; } = new double?[] { 1, 2, 3 }; public TestComparisonType[] ObjectArray { get; set; } = new[] { new TestComparisonType() }; } public class TestComparisonType { public enum TestEnum { Value1, Value2 } public int Int { get; set; } public object Obj { get; set; } public bool Bool { get; set; } public TestEnum Enum { get; set; } public string String { get; set; } } }
// 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; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Diagnostics; namespace System.ServiceModel.Channels { internal abstract class RequestContextBase : RequestContext { private TimeSpan _defaultSendTimeout; private TimeSpan _defaultCloseTimeout; private CommunicationState _state = CommunicationState.Opened; private Message _requestMessage; private Exception _requestMessageException; private bool _replySent; private bool _replyInitiated; private bool _aborted; private object _thisLock = new object(); protected RequestContextBase(Message requestMessage, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) { _defaultSendTimeout = defaultSendTimeout; _defaultCloseTimeout = defaultCloseTimeout; _requestMessage = requestMessage; } public void ReInitialize(Message requestMessage) { _state = CommunicationState.Opened; _requestMessageException = null; _replySent = false; _replyInitiated = false; _aborted = false; _requestMessage = requestMessage; } public override Message RequestMessage { get { if (_requestMessageException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_requestMessageException); } return _requestMessage; } } protected void SetRequestMessage(Message requestMessage) { Fx.Assert(_requestMessageException == null, "Cannot have both a requestMessage and a requestException."); _requestMessage = requestMessage; } protected void SetRequestMessage(Exception requestMessageException) { Fx.Assert(_requestMessage == null, "Cannot have both a requestMessage and a requestException."); _requestMessageException = requestMessageException; } protected bool ReplyInitiated { get { return _replyInitiated; } } protected object ThisLock { get { return _thisLock; } } public bool Aborted { get { return _aborted; } } public TimeSpan DefaultCloseTimeout { get { return _defaultCloseTimeout; } } public TimeSpan DefaultSendTimeout { get { return _defaultSendTimeout; } } public override void Abort() { lock (ThisLock) { if (_state == CommunicationState.Closed) return; _state = CommunicationState.Closing; _aborted = true; } try { this.OnAbort(); } finally { _state = CommunicationState.Closed; } } public override void Close() { this.Close(_defaultCloseTimeout); } public override void Close(TimeSpan timeout) { if (timeout < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", timeout, SR.ValueMustBeNonNegative)); } bool sendAck = false; lock (ThisLock) { if (_state != CommunicationState.Opened) return; if (TryInitiateReply()) { sendAck = true; } _state = CommunicationState.Closing; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); bool throwing = true; try { if (sendAck) { OnReply(null, timeoutHelper.RemainingTime()); } OnClose(timeoutHelper.RemainingTime()); _state = CommunicationState.Closed; throwing = false; } finally { if (throwing) this.Abort(); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (!disposing) return; if (_replySent) { this.Close(); } else { this.Abort(); } } protected abstract void OnAbort(); protected abstract void OnClose(TimeSpan timeout); protected abstract void OnReply(Message message, TimeSpan timeout); protected abstract IAsyncResult OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state); protected abstract void OnEndReply(IAsyncResult result); protected void ThrowIfInvalidReply() { if (_state == CommunicationState.Closed || _state == CommunicationState.Closing) { if (_aborted) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.RequestContextAborted)); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName)); } if (_replyInitiated) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ReplyAlreadySent)); } /// <summary> /// Attempts to initiate the reply. If a reply is not initiated already (and the object is opened), /// then it initiates the reply and returns true. Otherwise, it returns false. /// </summary> protected bool TryInitiateReply() { lock (_thisLock) { if ((_state != CommunicationState.Opened) || _replyInitiated) { return false; } else { _replyInitiated = true; return true; } } } public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state) { return this.BeginReply(message, _defaultSendTimeout, callback, state); } public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state) { // "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here lock (_thisLock) { this.ThrowIfInvalidReply(); _replyInitiated = true; } return OnBeginReply(message, timeout, callback, state); } public override void EndReply(IAsyncResult result) { OnEndReply(result); _replySent = true; } public override void Reply(Message message) { this.Reply(message, _defaultSendTimeout); } public override void Reply(Message message, TimeSpan timeout) { // "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here lock (_thisLock) { this.ThrowIfInvalidReply(); _replyInitiated = true; } this.OnReply(message, timeout); _replySent = true; } // This method is designed for WebSocket only, and will only be used once the WebSocket response was sent. // For WebSocket, we never call HttpRequestContext.Reply to send the response back. // Instead we call AcceptWebSocket directly. So we need to set the replyInitiated and // replySent boolean to be true once the response was sent successfully. Otherwise when we // are disposing the HttpRequestContext, we will see a bunch of warnings in trace log. protected void SetReplySent() { lock (_thisLock) { this.ThrowIfInvalidReply(); _replyInitiated = true; } _replySent = true; } } internal class RequestContextMessageProperty : IDisposable { private RequestContext _context; private object _thisLock = new object(); public RequestContextMessageProperty(RequestContext context) { _context = context; } public static string Name { get { return "requestContext"; } } void IDisposable.Dispose() { bool success = false; RequestContext thisContext; lock (_thisLock) { if (_context == null) return; thisContext = _context; _context = null; } try { thisContext.Close(); success = true; } catch (CommunicationException) { } catch (TimeoutException e) { if (WcfEventSource.Instance.CloseTimeoutIsEnabled()) { WcfEventSource.Instance.CloseTimeout(e.Message); } } finally { if (!success) { thisContext.Abort(); } } } } }
// $Id$ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using System.Threading; using NUnit.Framework; namespace Org.Apache.Etch.Bindings.Csharp.Support { [TestFixture] public class TestFreePool { private const int Q1 = 30; // 1 quanta of reliable clock tick private const int Q2 = 60; // 2 quanta of reliable clock tick private const int Q3 = 90; // 3 quanta of reliable clock tick [Test] public void close1() { FreePool p = new FreePool(2); p.Close(); } [Test] [ExpectedException(typeof(Exception))] public void close2() { // free pool thread count exceeded or pool closed FreePool p = new FreePool(2); p.Close(); MyPoolRunnable r = new MyPoolRunnable(0, false); p.Run(r.run, r.exception); } [Test] public void close3() { FreePool p = new FreePool(2); p.Close(); p.Close(); } [Test] [ExpectedException(typeof(Exception))] public void join1() { // free pool thread count exceeded or pool closed FreePool p = new FreePool(2); p.Join(); MyPoolRunnable r = new MyPoolRunnable(0, false); p.Run(r.run, r.exception); } [Test] public void join2() { FreePool p = new FreePool(2); MyPoolRunnable r = new MyPoolRunnable(0, false); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Run(r.run, r.exception); Thread.Sleep(Q2); Assert.IsTrue(r.done); Assert.IsNull(r.ex); p.Join(); } [Test] public void join3() { FreePool p = new FreePool(2); MyPoolRunnable r = new MyPoolRunnable(Q1, false); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Run(r.run, r.exception); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Join(); Assert.IsTrue(r.done); Assert.IsNull(r.ex); } [Test] public void run1() { FreePool p = new FreePool(2); MyPoolRunnable r = new MyPoolRunnable(0, false); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Run(r.run, r.exception); Thread.Sleep(Q1); Assert.IsTrue(r.done); Assert.IsNull(r.ex); } [Test] public void run2() { FreePool p = new FreePool(2); for (int i = 0; i < 100; i++) { MyPoolRunnable r = new MyPoolRunnable(0, false); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Run(r.run, r.exception); Thread.Sleep(Q1); Assert.IsTrue(r.done); Assert.IsNull(r.ex); } } [Test] public void run3() { FreePool p = new FreePool(2); MyPoolRunnable r = new MyPoolRunnable(0, true); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Run(r.run, r.exception); Thread.Sleep(Q1); Assert.IsFalse(r.done); Assert.IsNotNull(r.ex); } [Test] public void run4() { FreePool p = new FreePool(2); MyPoolRunnable r = new MyPoolRunnable(Q2, false); Assert.IsFalse(r.done); Assert.IsNull(r.ex); p.Run(r.run, r.exception); Thread.Sleep(Q1); Assert.IsFalse(r.done); Assert.IsNull(r.ex); Thread.Sleep(Q3); Assert.IsTrue(r.done); Assert.IsNull(r.ex); } [Test] public void run5() { FreePool p = new FreePool(2); MyPoolRunnable r1 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r1.done); Assert.IsNull(r1.ex); MyPoolRunnable r2 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r2.done); Assert.IsNull(r2.ex); p.Run(r1.run, r1.exception); p.Run(r2.run, r2.exception); Thread.Sleep(Q1); Assert.IsFalse(r1.done); Assert.IsNull(r1.ex); Assert.IsFalse(r2.done); Assert.IsNull(r2.ex); Thread.Sleep(Q3); Assert.IsTrue(r1.done); Assert.IsNull(r1.ex); Assert.IsTrue(r2.done); Assert.IsNull(r2.ex); } [Test] [ExpectedException(typeof(Exception))] public void run6() { // free pool thread count exceeded FreePool p = new FreePool(2); MyPoolRunnable r1 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r1.done); Assert.IsNull(r1.ex); MyPoolRunnable r2 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r2.done); Assert.IsNull(r2.ex); MyPoolRunnable r3 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r3.done); Assert.IsNull(r3.ex); p.Run(r1.run, r1.exception); p.Run(r2.run, r2.exception); p.Run(r3.run, r3.exception); } [Test] public void run7() { FreePool p = new FreePool(2); MyPoolRunnable r1 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r1.done); Assert.IsNull(r1.ex); MyPoolRunnable r2 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r2.done); Assert.IsNull(r2.ex); MyPoolRunnable r3 = new MyPoolRunnable(Q2, false); Assert.IsFalse(r3.done); Assert.IsNull(r3.ex); p.Run(r1.run, r1.exception); p.Run(r2.run, r2.exception); try { p.Run(r3.run, r3.exception); } catch (Exception) { } Thread.Sleep(Q1); Assert.IsFalse(r1.done); Assert.IsNull(r1.ex); Assert.IsFalse(r2.done); Assert.IsNull(r2.ex); Assert.IsFalse(r3.done); Assert.IsNull(r3.ex); Thread.Sleep(Q3); Assert.IsTrue(r1.done); Assert.IsNull(r1.ex); Assert.IsTrue(r2.done); Assert.IsNull(r2.ex); Assert.IsFalse(r3.done); Assert.IsNull(r3.ex); } } class MyPoolRunnable { public MyPoolRunnable( int delay, bool excp ) { this.delay = delay; this.excp = excp; } private readonly int delay; private readonly bool excp; public bool done; public Exception ex; public void run() { if (delay > 0) Thread.Sleep(delay); if (excp) throw new Exception(); done = true; } public void exception( Exception e ) { ex = e; } } }
using System; using System.Collections.Generic; using System.Composition.Hosting; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyModel; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.PlatformAbstractions; using OmniSharp.Mef; using OmniSharp.Middleware; using OmniSharp.Options; using OmniSharp.Roslyn; using OmniSharp.Services; using OmniSharp.Stdio.Logging; using OmniSharp.Stdio.Services; namespace OmniSharp { public class Startup { public Startup() { var appEnv = PlatformServices.Default.Application; var configBuilder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddJsonFile("config.json", optional: true) .AddEnvironmentVariables(); if (Program.Environment.OtherArgs != null) { configBuilder.AddCommandLine(Program.Environment.OtherArgs); } // Use the local omnisharp config if there's any in the root path configBuilder.AddJsonFile( new PhysicalFileProvider(Program.Environment.Path), "omnisharp.json", optional: true, reloadOnChange: false); Configuration = configBuilder.Build(); } public IConfiguration Configuration { get; } public OmnisharpWorkspace Workspace { get; set; } public CompositionHost PluginHost { get; private set; } public void ConfigureServices(IServiceCollection services) { // Add the omnisharp workspace to the container services.AddSingleton(typeof(OmnisharpWorkspace), (x) => Workspace); services.AddSingleton(typeof(CompositionHost), (x) => PluginHost); // Caching services.AddSingleton<IMemoryCache, MemoryCache>(); services.AddOptions(); // Setup the options from configuration services.Configure<OmniSharpOptions>(Configuration); } public static CompositionHost ConfigureMef(IServiceProvider serviceProvider, OmniSharpOptions options, IEnumerable<Assembly> assemblies, Func<ContainerConfiguration, ContainerConfiguration> configure = null) { var config = new ContainerConfiguration(); assemblies = assemblies .Concat(new[] { typeof(OmnisharpWorkspace).GetTypeInfo().Assembly, typeof(IRequest).GetTypeInfo().Assembly }) .Distinct(); foreach (var assembly in assemblies) { config = config.WithAssembly(assembly); } var memoryCache = serviceProvider.GetService<IMemoryCache>(); var loggerFactory = serviceProvider.GetService<ILoggerFactory>(); var env = serviceProvider.GetService<IOmnisharpEnvironment>(); var writer = serviceProvider.GetService<ISharedTextWriter>(); var applicationLifetime = serviceProvider.GetService<IApplicationLifetime>(); var loader = serviceProvider.GetService<IOmnisharpAssemblyLoader>(); config = config .WithProvider(MefValueProvider.From(serviceProvider)) .WithProvider(MefValueProvider.From<IFileSystemWatcher>(new ManualFileSystemWatcher())) .WithProvider(MefValueProvider.From(memoryCache)) .WithProvider(MefValueProvider.From(loggerFactory)) .WithProvider(MefValueProvider.From(env)) .WithProvider(MefValueProvider.From(writer)) .WithProvider(MefValueProvider.From(applicationLifetime)) .WithProvider(MefValueProvider.From(options)) .WithProvider(MefValueProvider.From(options.FormattingOptions)) .WithProvider(MefValueProvider.From(loader)) .WithProvider(MefValueProvider.From(new MetadataHelper(loader))); // other way to do singleton and autowire? if (env.TransportType == TransportType.Stdio) { config = config .WithProvider(MefValueProvider.From<IEventEmitter>(new StdioEventEmitter(writer))); } else { config = config .WithProvider(MefValueProvider.From<IEventEmitter>(new NullEventEmitter())); } if (configure != null) config = configure(config); var container = config.CreateContainer(); return container; } public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider, IOmnisharpEnvironment env, ILoggerFactory loggerFactory, ISharedTextWriter writer, IOmnisharpAssemblyLoader loader, IOptions<OmniSharpOptions> optionsAccessor) { Func<RuntimeLibrary, bool> shouldLoad = lib => lib.Dependencies.Any(dep => dep.Name == "OmniSharp.Abstractions" || dep.Name == "OmniSharp.Roslyn"); var dependencyContext = DependencyContext.Default; var assemblies = dependencyContext.RuntimeLibraries .Where(shouldLoad) .SelectMany(lib => lib.GetDefaultAssemblyNames(dependencyContext)) .Select(each => loader.Load(each.Name)) .ToList(); PluginHost = ConfigureMef(serviceProvider, optionsAccessor.Value, assemblies); Workspace = PluginHost.GetExport<OmnisharpWorkspace>(); if (env.TransportType == TransportType.Stdio) { loggerFactory.AddStdio(writer, (category, level) => LogFilter(category, level, env)); } else { loggerFactory.AddConsole((category, level) => LogFilter(category, level, env)); } var logger = loggerFactory.CreateLogger<Startup>(); foreach (var assembly in assemblies) { logger.LogDebug($"Loaded {assembly.FullName}"); } app.UseRequestLogging(); app.UseExceptionHandler("/error"); app.UseMiddleware<EndpointMiddleware>(); app.UseMiddleware<StatusMiddleware>(); app.UseMiddleware<StopServerMiddleware>(); if (env.TransportType == TransportType.Stdio) { logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{env.Path}' on host {env.HostPID}."); } else { logger.LogInformation($"Omnisharp server running on port '{env.Port}' at location '{env.Path}' on host {env.HostPID}."); } // ProjectEventForwarder register event to OmnisharpWorkspace during instantiation PluginHost.GetExport<ProjectEventForwarder>(); // Initialize all the project systems foreach (var projectSystem in PluginHost.GetExports<IProjectSystem>()) { try { projectSystem.Initalize(Configuration.GetSection(projectSystem.Key)); } catch (Exception e) { var message = $"The project system '{projectSystem.GetType().Name}' threw exception during initialization.\n{e.Message}\n{e.StackTrace}"; // if a project system throws an unhandled exception it should not crash the entire server logger.LogError(message); } } // Mark the workspace as initialized Workspace.Initialized = true; logger.LogInformation("Configuration finished."); } private static bool LogFilter(string category, LogLevel level, IOmnisharpEnvironment environment) { if (environment.TraceType > level) { return false; } if (string.Equals(category, typeof(ExceptionHandlerMiddleware).FullName, StringComparison.OrdinalIgnoreCase)) { return true; } if (!category.StartsWith("OmniSharp", StringComparison.OrdinalIgnoreCase)) { return false; } if (string.Equals(category, typeof(WorkspaceInformationService).FullName, StringComparison.OrdinalIgnoreCase)) { return false; } if (string.Equals(category, typeof(ProjectEventForwarder).FullName, StringComparison.OrdinalIgnoreCase)) { return false; } return true; } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Internal.PropertyEditing.Selection { using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Runtime; using System.Activities.Presentation.Internal.PropertyEditing.Selection; using System.Activities.Presentation; // <summary> // This is a container for attached properties used by PropertyInspector to track and manage // property selection. It is public because WPF requires that attached properties used in XAML // be declared by public classes. // </summary> [EditorBrowsable(EditorBrowsableState.Never)] static class PropertySelection { private static readonly DependencyPropertyKey IsSelectedPropertyKey = DependencyProperty.RegisterAttachedReadOnly( "IsSelected", typeof(bool), typeof(PropertySelection), new PropertyMetadata(false)); // <summary> // Attached, ReadOnly DP that we use to mark objects as selected. If they care, they can then render // themselves differently. // </summary> internal static readonly DependencyProperty IsSelectedProperty = IsSelectedPropertyKey.DependencyProperty; // <summary> // Attached DP that we use in XAML to mark elements that can be selected. // </summary> internal static readonly DependencyProperty SelectionStopProperty = DependencyProperty.RegisterAttached( "SelectionStop", typeof(ISelectionStop), typeof(PropertySelection), new PropertyMetadata(null)); // <summary> // Attached DP used in conjunction with SelectionStop DP. It specifies the FrameworkElement to hook into // in order to handle double-click events to control the expanded / collapsed state of its parent SelectionStop. // </summary> internal static readonly DependencyProperty IsSelectionStopDoubleClickTargetProperty = DependencyProperty.RegisterAttached( "IsSelectionStopDoubleClickTarget", typeof(bool), typeof(PropertySelection), new PropertyMetadata(false, new PropertyChangedCallback(OnIsSelectionStopDoubleClickTargetChanged))); // <summary> // Attached DP that we use in XAML to mark elements as selection scopes - meaning selection // won't spill beyond the scope of the marked element. // </summary> internal static readonly DependencyProperty IsSelectionScopeProperty = DependencyProperty.RegisterAttached( "IsSelectionScope", typeof(bool), typeof(PropertySelection), new PropertyMetadata(false)); // <summary> // Attached property we use to route non-navigational key strokes from one FrameworkElement to // another. When this property is set on a FrameworkElement, we hook into its KeyDown event // and send any unhandled, non-navigational key strokes to the FrameworkElement specified // by this property. The target FrameworkElement must be focusable or have a focusable child. // When the first eligible key stroke is detected, the focus will be shifted to the focusable // element and the key stroke will be sent to it. // </summary> internal static readonly DependencyProperty KeyDownTargetProperty = DependencyProperty.RegisterAttached( "KeyDownTarget", typeof(FrameworkElement), typeof(PropertySelection), new PropertyMetadata(null, new PropertyChangedCallback(OnKeyDownTargetChanged))); // Constant that determines how deep in the visual tree we search for SelectionStops that // are children or neighbors of a given element (usually one that the user clicked on) before // giving up. This constant is UI-dependent. private const int MaxSearchDepth = 11; // <summary> // Gets PropertySelection.IsSelected property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to examine</param> // <returns>Value of the IsSelected property</returns> internal static bool GetIsSelected(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } return (bool)obj.GetValue(IsSelectedProperty); } // Private (internal) setter that we use to mark objects as selected from within CategoryList class // internal static void SetIsSelected(DependencyObject obj, bool value) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.SetValue(IsSelectedPropertyKey, value); } // SelectionStop Attached DP // <summary> // Gets PropertySelection.SelectionStop property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to examine</param> // <returns>Value of the SelectionStop property.</returns> internal static ISelectionStop GetSelectionStop(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } return (ISelectionStop)obj.GetValue(SelectionStopProperty); } // <summary> // Sets PropertySelection.SelectionStop property on the specified DependencyObject // </summary> // <param name="obj">DependencyObject to modify</param> // <param name="value">New value of SelectionStop</param> internal static void SetSelectionStop(DependencyObject obj, ISelectionStop value) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.SetValue(SelectionStopProperty, value); } // <summary> // Clears PropertySelection.SelectionStop property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to clear</param> internal static void ClearSelectionStop(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.ClearValue(SelectionStopProperty); } // IsSelectionStopDoubleClickTarget Attached DP // <summary> // Gets PropertySelection.IsSelectionStopDoubleClickTarget property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to examine</param> // <returns>Value of the IsSelectionStopDoubleClickTarget property.</returns> internal static bool GetIsSelectionStopDoubleClickTarget(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } return (bool)obj.GetValue(IsSelectionStopDoubleClickTargetProperty); } // <summary> // Sets PropertySelection.IsSelectionStopDoubleClickTarget property on the specified DependencyObject // </summary> // <param name="obj">DependencyObject to modify</param> // <param name="value">New value of IsSelectionStopDoubleClickTarget</param> internal static void SetIsSelectionStopDoubleClickTarget(DependencyObject obj, bool value) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.SetValue(IsSelectionStopDoubleClickTargetProperty, value); } // <summary> // Clears PropertySelection.IsSelectionStopDoubleClickTarget property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to modify</param> internal static void ClearIsSelectionStopDoubleClickTarget(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.ClearValue(IsSelectionStopDoubleClickTargetProperty); } // Called when some object gets specified as the SelectionStop double-click target: // // * Hook into the MouseDown event so that we can detect double-clicks and automatically // expand or collapse the corresponding SelectionStop, if possible // private static void OnIsSelectionStopDoubleClickTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { FrameworkElement target = sender as FrameworkElement; if (target == null) { return; } if (bool.Equals(e.OldValue, false) && bool.Equals(e.NewValue, true)) { AddDoubleClickHandler(target); } else if (bool.Equals(e.OldValue, true) && bool.Equals(e.NewValue, false)) { RemoveDoubleClickHandler(target); } } // Called when some SelectionStop double-click target gets unloaded: // // * Unhook from events so that we don't prevent garbage collection // private static void OnSelectionStopDoubleClickTargetUnloaded(object sender, RoutedEventArgs e) { FrameworkElement target = sender as FrameworkElement; Fx.Assert(target != null, "sender parameter should not be null"); if (target == null) { return; } RemoveDoubleClickHandler(target); } // Called when the UI object representing a SelectionStop gets clicked: // // * If this is a double-click and the SelectionStop can be expanded / collapsed, // expand / collapse the SelectionStop // private static void OnSelectionStopDoubleClickTargetMouseDown(object sender, MouseButtonEventArgs e) { DependencyObject target = e.OriginalSource as DependencyObject; if (target == null) { return; } if (e.ClickCount > 1) { FrameworkElement parentSelectionStopVisual = PropertySelection.FindParentSelectionStop<FrameworkElement>(target); if (parentSelectionStopVisual != null) { ISelectionStop parentSelectionStop = PropertySelection.GetSelectionStop(parentSelectionStopVisual); if (parentSelectionStop != null && parentSelectionStop.IsExpandable) { parentSelectionStop.IsExpanded = !parentSelectionStop.IsExpanded; } } } } private static void AddDoubleClickHandler(FrameworkElement target) { target.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(OnSelectionStopDoubleClickTargetMouseDown), false); target.Unloaded += new RoutedEventHandler(OnSelectionStopDoubleClickTargetUnloaded); } private static void RemoveDoubleClickHandler(FrameworkElement target) { target.Unloaded -= new RoutedEventHandler(OnSelectionStopDoubleClickTargetUnloaded); target.RemoveHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(OnSelectionStopDoubleClickTargetMouseDown)); } // IsSelectionScope Attached DP // <summary> // Gets PropertySelection.IsSelectionScope property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to examine</param> // <returns>Value of the IsSelectionScope property.</returns> internal static bool GetIsSelectionScope(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } return (bool)obj.GetValue(IsSelectionScopeProperty); } // <summary> // Sets PropertySelection.IsSelectionScope property on the specified DependencyObject // </summary> // <param name="obj">DependencyObject to modify</param> // <param name="value">New value of IsSelectionScope</param> internal static void SetIsSelectionScope(DependencyObject obj, bool value) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.SetValue(IsSelectionScopeProperty, value); } // KeyDownTarget Attached DP // <summary> // Gets PropertySelection.KeyDownTarget property from the specified DependencyObject // </summary> // <param name="obj">DependencyObject to examine</param> // <returns>Value of the KeyDownTarget property.</returns> internal static FrameworkElement GetKeyDownTarget(DependencyObject obj) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } return (FrameworkElement)obj.GetValue(KeyDownTargetProperty); } // <summary> // Sets PropertySelection.KeyDownTarget property on the specified DependencyObject // </summary> // <param name="obj">DependencyObject to modify</param> // <param name="value">New value of KeyDownTarget</param> internal static void SetKeyDownTarget(DependencyObject obj, FrameworkElement value) { if (obj == null) { throw FxTrace.Exception.ArgumentNull("obj"); } obj.SetValue(KeyDownTargetProperty, value); } // Called when some FrameworkElement gets specified as the target for KeyDown RoutedEvents - // hook into / unhook from the KeyDown event of the source private static void OnKeyDownTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { FrameworkElement target = sender as FrameworkElement; if (target == null) { return; } if (e.OldValue != null && e.NewValue == null) { RemoveKeyStrokeHandlers(target); } else if (e.NewValue != null && e.OldValue == null) { AddKeyStrokeHandlers(target); } } // Called when a KeyDownTarget gets unloaded - // unhook from events so that we don't prevent garbage collection private static void OnKeyDownTargetUnloaded(object sender, RoutedEventArgs e) { FrameworkElement target = sender as FrameworkElement; Fx.Assert(target != null, "sender parameter should not be null"); if (target == null) { return; } RemoveKeyStrokeHandlers(target); } // Called when a KeyDownTarget is specified and a KeyDown event is detected on the source private static void OnKeyDownTargetKeyDown(object sender, KeyEventArgs e) { // Ignore handled events if (e.Handled) { return; } // Ignore navigation keys if (e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Tab || e.Key == Key.Escape || e.Key == Key.Return || e.Key == Key.Enter || e.Key == Key.PageUp || e.Key == Key.PageDown || e.Key == Key.Home || e.Key == Key.End || e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl) { return; } if (Keyboard.Modifiers == ModifierKeys.Control) { return; } DependencyObject keySender = sender as DependencyObject; Fx.Assert(keySender != null, "keySender should not be null"); if (keySender == null) { return; } FrameworkElement keyTarget = GetKeyDownTarget(keySender); Fx.Assert(keyTarget != null, "keyTarget should not be null"); if (keyTarget == null) { return; } // Find a focusable element on the target, set focus to it, and send the keys over FrameworkElement focusable = VisualTreeUtils.FindFocusableElement<FrameworkElement>(keyTarget); if (focusable != null && focusable == Keyboard.Focus(focusable)) { focusable.RaiseEvent(e); } } private static void AddKeyStrokeHandlers(FrameworkElement target) { target.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(OnKeyDownTargetKeyDown), false); target.Unloaded += new RoutedEventHandler(OnKeyDownTargetUnloaded); } private static void RemoveKeyStrokeHandlers(FrameworkElement target) { target.Unloaded -= new RoutedEventHandler(OnKeyDownTargetUnloaded); target.RemoveHandler(UIElement.KeyDownEvent, new KeyEventHandler(OnKeyDownTargetKeyDown)); } // <summary> // Returns the closest parent (or the element itself) marked as a SelectionStop. // </summary> // <typeparam name="T">Type of element to look for</typeparam> // <param name="element">Element to examine</param> // <returns>The closest parent (or the element itself) marked as a SelectionStop; // null if not found.</returns> internal static T FindParentSelectionStop<T>(DependencyObject element) where T : DependencyObject { if (element == null) { return null; } do { // IsEligibleSelectionStop already checks for visibility, so we don't need to // to do a specific check somewhere else in this loop if (IsEligibleSelectionStop<T>(element)) { return (T)element; } element = VisualTreeHelper.GetParent(element); } while (element != null); return null; } // <summary> // Returns the closest neighbor in the given direction marked as a SelectionStop. // </summary> // <typeparam name="T">Type of element to look for</typeparam> // <param name="element">Element to examine</param> // <param name="direction">Direction to search in</param> // <returns>The closest neighboring element in the given direction marked as a IsSelectionStop, // if found, null otherwise.</returns> internal static T FindNeighborSelectionStop<T>(DependencyObject element, SearchDirection direction) where T : DependencyObject { if (element == null) { throw FxTrace.Exception.ArgumentNull("element"); } T neighbor; int maxSearchDepth = MaxSearchDepth; // If we are looking for the NEXT element and we can dig deeper, start by digging deeper // before trying to look for any siblings. // if (direction == SearchDirection.Next && IsExpanded(element)) { neighbor = FindChildSelectionStop<T>(element, 0, VisualTreeHelper.GetChildrenCount(element) - 1, direction, maxSearchDepth, MatchDirection.Down); if (neighbor != null) { return neighbor; } } int childIndex, childrenCount, childDepth; bool isParentSelectionStop, isParentSelectionScope = false; DependencyObject parent = element; while (true) { while (true) { // If we reached the selection scope, don't try to go beyond it if (isParentSelectionScope) { return null; } parent = GetEligibleParent(parent, out childIndex, out childrenCount, out childDepth, out isParentSelectionStop, out isParentSelectionScope); maxSearchDepth += childDepth; if (parent == null) { return null; } if (direction == SearchDirection.Next && (childIndex + 1) >= childrenCount) { continue; } if (direction == SearchDirection.Previous && isParentSelectionStop == false && (childIndex < 1)) { continue; } break; } // If we get here, that means we found a SelectionStop on which we need to look for children that are // SelectionStops themselves. The first such child found should be returned. Otherwise, if no such child // is found, we potentially look at the node itself and return it OR we repeat the process and keep looking // for a better parent. int leftIndex, rightIndex; MatchDirection matchDirection; if (direction == SearchDirection.Previous) { leftIndex = 0; rightIndex = childIndex - 1; matchDirection = MatchDirection.Up; } else { leftIndex = childIndex + 1; rightIndex = childrenCount - 1; matchDirection = MatchDirection.Down; } neighbor = FindChildSelectionStop<T>(parent, leftIndex, rightIndex, direction, maxSearchDepth, matchDirection); if (neighbor != null) { return neighbor; } if (direction == SearchDirection.Previous && IsEligibleSelectionStop<T>(parent)) { return (T)parent; } } } // Helper method used from GetNeighborSelectionStop() // Returns a parent DependencyObject of the specified element that is // // * Visible AND // * ( Marked with a SelectionStop OR // * Marked with IsSelectionScope = true OR // * Has more than one child ) // private static DependencyObject GetEligibleParent(DependencyObject element, out int childIndex, out int childrenCount, out int childDepth, out bool isSelectionStop, out bool isSelectionScope) { childDepth = 0; isSelectionStop = false; isSelectionScope = false; bool isVisible; do { element = VisualTreeUtils.GetIndexedVisualParent(element, out childrenCount, out childIndex); isSelectionStop = element == null ? false : (GetSelectionStop(element) != null); isSelectionScope = element == null ? false : GetIsSelectionScope(element); isVisible = VisualTreeUtils.IsVisible(element as UIElement); childDepth++; } while ( element != null && (isVisible == false || (isSelectionStop == false && isSelectionScope == false && childrenCount < 2))); return element; } // Helper method that performs a recursive, depth-first search of children starting at the specified parent, // looking for any children that conform to the specified Type and are marked with a SelectionStop // private static T FindChildSelectionStop<T>(DependencyObject parent, int leftIndex, int rightIndex, SearchDirection iterationDirection, int maxDepth, MatchDirection matchDirection) where T : DependencyObject { if (parent == null || maxDepth <= 0) { return null; } int step = iterationDirection == SearchDirection.Next ? 1 : -1; int index = iterationDirection == SearchDirection.Next ? leftIndex : rightIndex; for (; index >= leftIndex && index <= rightIndex; index = index + step) { DependencyObject child = VisualTreeHelper.GetChild(parent, index); // If MatchDirection is set to Down, do an eligibility match BEFORE we dive down into // more children. // if (matchDirection == MatchDirection.Down && IsEligibleSelectionStop<T>(child)) { return (T)child; } // If this child is not an eligible SelectionStop because it is not visible, // there is no point digging down to get to more children. // if (!VisualTreeUtils.IsVisible(child as UIElement)) { continue; } int grandChildrenCount = VisualTreeHelper.GetChildrenCount(child); if (grandChildrenCount > 0 && IsExpanded(child)) { T element = FindChildSelectionStop<T>(child, 0, grandChildrenCount - 1, iterationDirection, maxDepth - 1, matchDirection); if (element != null) { return element; } } // If MatchDirection is set to Up, do an eligibility match AFTER we tried diving into // more children and failed to find something we could return. // if (matchDirection == MatchDirection.Up && IsEligibleSelectionStop<T>(child)) { return (T)child; } } return null; } // Helper method that returns false if the given element is a collapsed SelectionStop, // true otherwise. // private static bool IsExpanded(DependencyObject element) { ISelectionStop selectionStop = PropertySelection.GetSelectionStop(element); return selectionStop == null || selectionStop.IsExpanded; } // Helper method that return true if the given element is marked with a SelectionStop, // if it derives from the specified Type, and if it is Visible (assuming it derives from UIElement) // private static bool IsEligibleSelectionStop<T>(DependencyObject element) where T : DependencyObject { return (GetSelectionStop(element) != null) && typeof(T).IsAssignableFrom(element.GetType()) && VisualTreeUtils.IsVisible(element as UIElement); } // <summary> // Private enum we use to specify whether FindSelectionStopChild() should return any matches // as it drills down into the visual tree (Down) or whether it should wait on looking at // matches until it's bubbling back up again (Up). // </summary> private enum MatchDirection { Down, Up } // IsSelected ReadOnly, Attached DP } }
using System; using System.Threading.Tasks; using EasyNetQ.Consumer; using EasyNetQ.FluentConfiguration; using EasyNetQ.Producer; using EasyNetQ.Rpc; using EasyNetQ.Topology; namespace EasyNetQ { public class RabbitBus : IBus { private readonly IEasyNetQLogger logger; private readonly IConventions conventions; private readonly IAdvancedBus advancedBus; private readonly IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy; private readonly IMessageDeliveryModeStrategy messageDeliveryModeStrategy; private readonly IRpc rpc; private readonly ISendReceive sendReceive; private readonly IConnectionConfiguration connectionConfiguration; public IEasyNetQLogger Logger { get { return logger; } } public IConventions Conventions { get { return conventions; } } public RabbitBus( IEasyNetQLogger logger, IConventions conventions, IAdvancedBus advancedBus, IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy, IMessageDeliveryModeStrategy messageDeliveryModeStrategy, IRpc rpc, ISendReceive sendReceive, IConnectionConfiguration connectionConfiguration) { Preconditions.CheckNotNull(logger, "logger"); Preconditions.CheckNotNull(conventions, "conventions"); Preconditions.CheckNotNull(advancedBus, "advancedBus"); Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "advancedPublishExchangeDeclareStrategy"); Preconditions.CheckNotNull(rpc, "rpc"); Preconditions.CheckNotNull(sendReceive, "sendReceive"); Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration"); this.logger = logger; this.conventions = conventions; this.advancedBus = advancedBus; this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy; this.messageDeliveryModeStrategy = messageDeliveryModeStrategy; this.rpc = rpc; this.sendReceive = sendReceive; this.connectionConfiguration = connectionConfiguration; advancedBus.Connected += OnConnected; advancedBus.Disconnected += OnDisconnected; } public virtual void Publish<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); PublishAsync(message).Wait(); } public virtual void Publish<T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); PublishAsync(message, topic).Wait(); } public virtual Task PublishAsync<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); return PublishAsync(message, conventions.TopicNamingConvention(typeof(T))); } public virtual Task PublishAsync<T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var messageType = typeof (T); return publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).Then(exchange => { var easyNetQMessage = new Message<T>(message) { Properties = { DeliveryMode = (byte)(messageDeliveryModeStrategy.IsPersistent(messageType) ? 2 : 1) } }; return advancedBus.PublishAsync(exchange, topic, false, false, easyNetQMessage); }); } public virtual IDisposable Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class { return Subscribe(subscriptionId, onMessage, x => { }); } public virtual IDisposable Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure) where T : class { Preconditions.CheckNotNull(subscriptionId, "subscriptionId"); Preconditions.CheckNotNull(onMessage, "onMessage"); Preconditions.CheckNotNull(configure, "configure"); return SubscribeAsync<T>(subscriptionId, msg => { var tcs = new TaskCompletionSource<object>(); try { onMessage(msg); tcs.SetResult(null); } catch (Exception exception) { tcs.SetException(exception); } return tcs.Task; }, configure); } public virtual IDisposable SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class { return SubscribeAsync(subscriptionId, onMessage, x => { }); } public virtual IDisposable SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure) where T : class { Preconditions.CheckNotNull(subscriptionId, "subscriptionId"); Preconditions.CheckNotNull(onMessage, "onMessage"); Preconditions.CheckNotNull(configure, "configure"); var configuration = new SubscriptionConfiguration(connectionConfiguration.PrefetchCount); configure(configuration); var queueName = conventions.QueueNamingConvention(typeof(T), subscriptionId); var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var queue = advancedBus.QueueDeclare(queueName, autoDelete: configuration.AutoDelete, expires: configuration.Expires); var exchange = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic); foreach (var topic in configuration.Topics.AtLeastOneWithDefault("#")) { advancedBus.Bind(exchange, queue, topic); } return advancedBus.Consume<T>( queue, (message, messageReceivedInfo) => onMessage(message.Body), x => x.WithPriority(configuration.Priority) .WithCancelOnHaFailover(configuration.CancelOnHaFailover) .WithPrefetchCount(configuration.PrefetchCount)); } public virtual TResponse Request<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); var task = RequestAsync<TRequest, TResponse>(request); task.Wait(); return task.Result; } public virtual Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); return rpc.Request<TRequest, TResponse>(request); } public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); Func<TRequest, Task<TResponse>> taskResponder = request => Task<TResponse>.Factory.StartNew(_ => responder(request), null); return RespondAsync(taskResponder); } public virtual IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); return rpc.Respond(responder); } public virtual void Send<T>(string queue, T message) where T : class { sendReceive.Send(queue, message); } public virtual IDisposable Receive<T>(string queue, Action<T> onMessage) where T : class { return sendReceive.Receive(queue, onMessage); } public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage) where T : class { return sendReceive.Receive(queue, onMessage); } public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers) { return sendReceive.Receive(queue, addHandlers); } public virtual event Action Connected; protected void OnConnected() { if (Connected != null) Connected(); } public virtual event Action Disconnected; protected void OnDisconnected() { if (Disconnected != null) Disconnected(); } public virtual bool IsConnected { get { return advancedBus.IsConnected; } } public virtual IAdvancedBus Advanced { get { return advancedBus; } } public virtual void Dispose() { advancedBus.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclassautoprop.regclassautoprop { public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass { public string Property_string { set; get; } public MyClass Property_MyClass { get; set; } public MyStruct Property_MyStruct { set; get; } public MyEnum Property_MyEnum { set; private get; } public short Property_short { set; protected get; } public ulong Property_ulong { set; protected internal get; } public char Property_char { private set; get; } public bool Property_bool { protected set; get; } public decimal Property_decimal { protected internal set; get; } public MyStruct? Property_MyStructNull { set; get; } public MyEnum? Property_MyEnumNull { set; private get; } public short? Property_shortNull { set; get; } public ulong? Property_ulongNull { set; protected internal get; } public char? Property_charNull { private set; get; } public bool? Property_boolNull { protected set; get; } public decimal? Property_decimalNull { protected internal set; get; } public string[] Property_stringArr { set; get; } public MyClass[] Property_MyClassArr { set; get; } public MyStruct[] Property_MyStructArr { get; set; } public MyEnum[] Property_MyEnumArr { set; private get; } public short[] Property_shortArr { set; protected get; } public ulong[] Property_ulongArr { set; protected internal get; } public char[] Property_charArr { private set; get; } public bool[] Property_boolArr { protected set; get; } public decimal[] Property_decimalArr { protected internal set; get; } public MyStruct?[] Property_MyStructNullArr { set; get; } public MyEnum?[] Property_MyEnumNullArr { set; private get; } public short?[] Property_shortNullArr { set; protected get; } public ulong?[] Property_ulongNullArr { set; protected internal get; } public char?[] Property_charNullArr { private set; get; } public bool?[] Property_boolNullArr { protected set; get; } public decimal?[] Property_decimalNullArr { protected internal set; get; } public float Property_Float { get; set; } public float?[] Property_FloatNullArr { get; set; } public dynamic Property_Dynamic { get; set; } public static string Property_stringStatic { set; get; } // Move declarations to the call site } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass001.regclass001 { // <Title> Tests regular class auto property used in generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t1 = new Test(); return t1.TestGetMethod<long>(1, new MemberClass()) + t1.TestSetMethod<Test, string>(string.Empty, new MemberClass()) == 0 ? 0 : 1; } public int TestGetMethod<T>(T t, MemberClass mc) { mc.Property_string = "Test"; dynamic dy = mc; if ((string)dy.Property_string != "Test") return 1; else return 0; } public int TestSetMethod<U, V>(V v, MemberClass mc) { dynamic dy = mc; dy.Property_string = "Test"; mc = dy; //because we might change the property on a boxed version of it if MemberClass is a struct if (mc.Property_string != "Test") return 1; else return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass003.regclass003 { // <Title> Tests regular class auto property used in variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { string[] bas = new string[] { "Test", string.Empty, null } ; MemberClass mc = new MemberClass(); mc.Property_stringArr = bas; dynamic dy = mc; string[] loc = dy.Property_stringArr; if (ReferenceEquals(bas, loc) && loc[0] == "Test" && loc[1] == string.Empty && loc[2] == null) { return 0; } else return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass004.regclass004 { // <Title> Tests regular class auto property used in implicitly-typed array initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc1 = new MemberClass(); MemberClass mc2 = new MemberClass(); mc1.Property_MyStructNull = null; mc2.Property_MyStructNull = new MyStruct() { Number = 1 } ; dynamic dy1 = mc1; dynamic dy2 = mc2; var loc = new MyStruct?[] { (MyStruct? )dy1.Property_MyStructNull, (MyStruct? )dy2.Property_MyStructNull } ; if (loc.Length == 2 && loc[0] == null && loc[1].Value.Number == 1) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass005.regclass005 { // <Title> Tests regular class auto property used in operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc1 = new MemberClass(); MemberClass mc2 = new MemberClass(); mc1.Property_string = "a"; mc2.Property_string = "b"; dynamic dy1 = mc1; dynamic dy2 = mc2; string s = (string)dy1.Property_string + (string)dy2.Property_string; if (s == "ab") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass006.regclass006 { // <Title> Tests regular class auto property used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_MyStructArr = new MyStruct[] { new MyStruct() { Number = 0 } , new MyStruct() { Number = 1 } } ; dynamic dy = mc; string s1 = ((string)dy.Property_string) ?? string.Empty; mc.Property_string = "Test"; dy = mc; MyStruct[] b1 = ((MyStruct[])dy.Property_MyStructArr) ?? (new MyStruct[1]); MyStruct[] b2 = ((MyStruct[])dy.Property_MyStructArr) ?? (new MyStruct[1]); string s2 = ((string)dy.Property_string) ?? string.Empty; if (b1.Length == 2 && s1 == string.Empty && b2.Length == 2 && s2 == "Test") return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass007.regclass007 { // <Title> Tests regular class auto property used in destructor.</Title> // <Description> // On IA64 the GC.WaitForPendingFinalizers() does not actually work... // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Runtime.CompilerServices; public class Test { private static string s_field; public static object locker = new object(); ~Test() { lock (locker) { MemberClass mc = new MemberClass(); mc.Property_string = "Test"; dynamic dy = mc; s_field = dy.Property_string; } } private static int Verify() { lock (Test.locker) { if (Test.s_field != "Test") { return 1; } } return 0; } [MethodImpl(MethodImplOptions.NoInlining)] private static void RequireLifetimesEnded() { Test t = new Test(); Test.s_field = "Field"; GC.KeepAlive(t); } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { RequireLifetimesEnded(); GC.Collect(); GC.WaitForPendingFinalizers(); // If move the code in Verify() to here, the finalizer will only be executed after exited Main return Verify(); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass008.regclass008 { // <Title> Tests regular class auto property used in extension method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int a1 = 10; MyStruct ms1 = a1.TestSetMyStruct(); MyStruct ms2 = a1.TestGetMyStruct(); if (ms1.Number == 10 && ms2.Number == 10) return 0; return 1; } } public static class Extension { public static MyStruct TestSetMyStruct(this int i) { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_MyStruct = new MyStruct() { Number = i } ; mc = dy; //because MC might be a struct return mc.Property_MyStruct; } public static MyStruct TestGetMyStruct(this int i) { MemberClass mc = new MemberClass(); mc.Property_MyStruct = new MyStruct() { Number = i } ; dynamic dy = mc; return (MyStruct)dy.Property_MyStruct; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass009.regclass009 { // <Title> Tests regular class auto property used in variable initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; char value = (char)dy.Property_char; if (value == default(char)) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass010.regclass010 { // <Title> Tests regular class auto property used in array initializer list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; bool[] array = new bool[] { (bool)dy.Property_bool, true } ; if (array.Length == 2 && array[0] == false && array[1] == true) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass014.regclass014 { // <Title> Tests regular class auto property used in for loop body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic mc = new MemberClass(); ulong[] array = new ulong[] { 1L, 2L, 3L, ulong.MinValue, ulong.MaxValue } ; for (int i = 0; i < array.Length; i++) { mc.Property_ulong = array[i]; } ulong x = (ulong)mc.Property_ulong; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass015.regclass015 { // <Title> Tests regular class auto property used in foreach expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_MyClassArr = new MyClass[] { null, new MyClass() { Field = -1 } } ; dynamic dy = mc; List<MyClass> list = new List<MyClass>(); foreach (MyClass myclass in dy.Property_MyClassArr) { list.Add(myclass); } if (list.Count == 2 && list[0] == null && list[1].Field == -1) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass016.regclass016 { // <Title> Tests regular class auto property used in while body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test : MemberClass { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test mc = new Test(); dynamic dy = mc; short a = 0; short v = 0; while (a < 10) { v = a; dy.Property_shortNull = a; a = (short)((short)dy.Property_shortNull + 1); if (a != v + 1) return 1; } return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass018.regclass018 { // <Title> Tests regular class auto property used in uncheck expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; ulong result = 1; dy.Property_ulongNull = ulong.MaxValue; result = unchecked(dy.Property_ulongNull + 1); //0 return (int)result; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass019.regclass019 { // <Title> Tests regular class auto property used in static constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static char? s_charValue = 'a'; static Test() { dynamic dy = new MemberClass(); s_charValue = dy.Property_charNull; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (Test.s_charValue == null) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass020.regclass020 { // <Title> Tests regular class auto property used in variable named dynamic.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dynamic = new MemberClass(); if (dynamic.Property_boolNull == null) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass022.regclass022 { // <Title> Tests regular class auto property used in field initailizer outside of constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static dynamic s_dy = new MemberClass(); private char[] _result = s_dy.Property_charArr; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); if (t._result == null) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass023.regclass023 { // <Title> Tests regular class auto property used in static generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { return TestMethod<Test>(); } private static int TestMethod<T>() { dynamic dy = new MemberClass(); dy.Property_MyEnumArr = new MyEnum[0]; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass024.regclass024 { // <Title> Tests regular class auto property used in static generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { return TestMethod<int>(); } private static int TestMethod<T>() { dynamic dy = new MemberClass(); dy.Property_shortArr = new short[2]; try { short[] result = dy.Property_shortArr; // protected } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortArr")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass025.regclass025 { // <Title> Tests regular class auto property used in inside#if, #else block.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); ulong[] array = null; dy.Property_ulongArr = new ulong[] { 0, 1 } ; #if MS array = new ulong[] { (ulong)dy.Property_ulong }; #else try { array = dy.Property_ulongArr; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_ulongArr")) return 0; else { System.Console.WriteLine(e); return 1; } } #endif // different case actually if (array.Length == 2 && array[0] == 0 && array[1] == 1) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass026.regclass026 { // <Title> Tests regular class auto property used in regular method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (new Test().TestMethod()) return 0; return 1; } private bool TestMethod() { dynamic dy = new MemberClass(); bool[] result = dy.Property_boolArr; return result == null; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass027.regclass027 { // <Title> Tests regular class auto property used in using block.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.IO; public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); mc.Property_decimalArr = new decimal[] { 1M, 1.1M } ; dynamic dy = mc; using (MemoryStream ms = new MemoryStream()) { if (((decimal[])dy.Property_decimalArr)[0] != 1M && ((decimal[])dy.Property_decimalArr)[1] != 1.1M) return 1; } using (MemoryStream ms = new MemoryStream()) { dy.Property_decimalArr = new decimal[] { 10M } ; ((decimal[])dy.Property_decimalArr)[0] = 10.01M; } if (mc.Property_decimalArr.Length == 1 && mc.Property_decimalArr[0] == 10.01M) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass028.regclass028 { // <Title> Tests regular class auto property used in ternary operator expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); return t.TestGet() + t.TestSet(); } public int TestGet() { MemberClass mc = new MemberClass(); mc.Property_MyStructNullArr = new MyStruct?[] { null, new MyStruct() { Number = 10 } } ; dynamic dy = mc; return (int)dy.Property_MyStructNullArr.Length == 2 ? 0 : 1; } public int TestSet() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_MyStructNullArr = new MyStruct?[] { null, new MyStruct() { Number = 10 } } ; mc = dy; return (int)dy.Property_MyStructNullArr.Length == 2 ? 0 : 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass029.regclass029 { // <Title> Tests regular class auto property used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic dy = new MemberClass(); try { MyEnum?[] result = dy.Property_MyEnumNullArr ?? new MyEnum?[1]; //private, should have exception } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_MyEnumNullArr")) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass030.regclass030 { // <Title> Tests regular class auto property used in constructor.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static int Return; public Test() { dynamic dy = new MemberClass(); try { // public for struct short?[] result = dy.Property_shortNullArr; //protected, should have exception } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleGetter, e.Message, "MemberClass.Property_shortNullArr")) Test.Return = 0; else Test.Return = 1; } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Test t = new Test(); return Test.Return; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass031.regclass031 { // <Title> Tests regular class auto property used in null coalescing operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; ulong?[] result1 = dy.Property_ulongNullArr ?? new ulong?[1]; if (result1.Length != 1 || dy.Property_ulongNullArr != null) return 1; dy.Property_ulongNullArr = dy.Property_ulongNullArr ?? new ulong?[0]; return 0; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass032.regclass032 { // <Title> Tests regular class auto property used in static variable.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { private static dynamic s_dy = new MemberClass(); private static char?[] s_result = s_dy.Property_charNullArr; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { if (s_result == null) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass034.regclass034 { // <Title> Tests regular class auto property used in switch section statement.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; int result = int.MaxValue; try { dy.Property_decimalNullArr = new decimal?[] { int.MinValue } ; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.InaccessibleSetter, e.Message, "MemberClass.Property_decimalNullArr")) result = int.MaxValue; } switch (result) { case int.MaxValue: try { result = (int)((decimal?[])dy.Property_decimalNullArr)[0]; } catch (System.NullReferenceException) { result = int.MinValue; } break; default: break; } if (result == int.MinValue) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass035.regclass035 { // <Title> Tests regular class auto property used in switch default section statement.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; int result = 4; dy.Property_Float = 4; switch (result) { case 4: dy.Property_Float = float.NaN; break; default: result = (int)dy.Property_Float; break; } if (result == 4) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass036.regclass036 { // <Title> Tests regular class auto property used in foreach body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass mc = new MemberClass(); dynamic dy = mc; dy.Property_FloatNullArr = new float?[] { float.Epsilon, float.MaxValue, float.MinValue, float.NaN, float.NegativeInfinity, float.PositiveInfinity } ; if (dy.Property_FloatNullArr.Length == 6 && dy.Property_FloatNullArr[0] == float.Epsilon && dy.Property_FloatNullArr[1] == float.MaxValue && dy.Property_FloatNullArr[2] == float.MinValue && float.IsNaN((float)dy.Property_FloatNullArr[3]) && float.IsNegativeInfinity((float)dy.Property_FloatNullArr[4]) && float.IsPositiveInfinity((float)dy.Property_FloatNullArr[5])) return 0; return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.autoproperty.regclass.regclass037.regclass037 { // <Title> Tests regular class auto property used in static method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MemberClass.Property_stringStatic = "Test"; dynamic dynamic = MemberClass.Property_stringStatic; if ((string)dynamic == "Test") return 0; return 1; } } //</Code> }
using System; using System.IO; using System.Reflection; using System.Windows.Forms; namespace SIL.Windows.Forms { public static class ReflectionHelper { /// ------------------------------------------------------------------------------------ /// <summary> /// Loads a DLL. /// </summary> /// ------------------------------------------------------------------------------------ public static Assembly LoadAssembly(string dllPath) { try { if (!File.Exists(dllPath)) { string dllFile = Path.GetFileName(dllPath); dllPath = Path.Combine(Application.StartupPath, dllFile); if (!File.Exists(dllPath)) return null; } return Assembly.LoadFrom(dllPath); } catch (Exception) { return null; } } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ public static object CreateClassInstance(Assembly assembly, string className) { return CreateClassInstance(assembly, className, null); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ public static object CreateClassInstance(Assembly assembly, string className, object[] args) { try { // First, take a stab at creating the instance with the specified name. object instance = assembly.CreateInstance(className, false, BindingFlags.CreateInstance, null, args, null, null); if (instance != null) return instance; Type[] types = assembly.GetTypes(); // At this point, we know we failed to instantiate a class with the // specified name, so try to find a type with that name and attempt // to instantiate the class using the full namespace. foreach (Type type in types) { if (type.Name == className) { return assembly.CreateInstance(type.FullName, false, BindingFlags.CreateInstance, null, args, null, null); } } } catch { } return null; } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a string value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An array of arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static string GetStrResult(object binding, string methodName, object[] args) { return (GetResult(binding, methodName, args) as string); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a string value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An single arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static string GetStrResult(object binding, string methodName, object args) { return (GetResult(binding, methodName, args) as string); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a integer value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An single arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static int GetIntResult(object binding, string methodName, object args) { return ((int)GetResult(binding, methodName, args)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a integer value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An array of arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static int GetIntResult(object binding, string methodName, object[] args) { return ((int)GetResult(binding, methodName, args)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a float value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An single arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static float GetFloatResult(object binding, string methodName, object args) { return ((float)GetResult(binding, methodName, args)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a float value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An array of arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static float GetFloatResult(object binding, string methodName, object[] args) { return ((float)GetResult(binding, methodName, args)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a boolean value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An single arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static bool GetBoolResult(object binding, string methodName, object args) { return ((bool)GetResult(binding, methodName, args)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns a boolean value returned from a call to a private method. /// </summary> /// <param name="binding">This is either the Type of the object on which the method /// is called or an instance of that type of object. When the method being called /// is static then binding should be a type.</param> /// <param name="methodName">Name of the method to call.</param> /// <param name="args">An array of arguments to pass to the method call.</param> /// ------------------------------------------------------------------------------------ public static bool GetBoolResult(object binding, string methodName, object[] args) { return ((bool)GetResult(binding, methodName, args)); } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void CallMethod(object binding, string methodName) { CallMethod(binding, methodName, null); } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void CallMethod(object binding, string methodName, object args) { GetResult(binding, methodName, args); } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void CallMethod(object binding, string methodName, object arg1, object arg2) { object[] args = new[] {arg1, arg2}; GetResult(binding, methodName, args); } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void CallMethod(object binding, string methodName, object arg1, object arg2, object arg3) { object[] args = new[] { arg1, arg2, arg3 }; GetResult(binding, methodName, args); } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void CallMethod(object binding, string methodName, object arg1, object arg2, object arg3, object arg4) { object[] args = new[] { arg1, arg2, arg3, arg4 }; GetResult(binding, methodName, args); } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void CallMethod(object binding, string methodName, object[] args) { GetResult(binding, methodName, args); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns the result of calling a method on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static object GetResult(object binding, string methodName, object args) { return Invoke(binding, methodName, new[] { args }, BindingFlags.InvokeMethod); } /// ------------------------------------------------------------------------------------ /// <summary> /// Returns the result of calling a method on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static object GetResult(object binding, string methodName, object[] args) { return Invoke(binding, methodName, args, BindingFlags.InvokeMethod); } /// ------------------------------------------------------------------------------------ /// <summary> /// Sets the specified property on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void SetProperty(object binding, string propertyName, object args) { Invoke(binding, propertyName, new[] { args }, BindingFlags.SetProperty); } /// ------------------------------------------------------------------------------------ /// <summary> /// Sets the specified field (i.e. member variable) on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static void SetField(object binding, string fieldName, object args) { Invoke(binding, fieldName, new[] { args }, BindingFlags.SetField); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the specified property on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static object GetProperty(object binding, string propertyName) { return Invoke(binding, propertyName, null, BindingFlags.GetProperty); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the specified field (i.e. member variable) on the specified binding. /// </summary> /// ------------------------------------------------------------------------------------ public static object GetField(object binding, string fieldName) { return Invoke(binding, fieldName, null, BindingFlags.GetField); } /// ------------------------------------------------------------------------------------ /// <summary> /// Sets the specified member variable or property (specified by name) on the /// specified binding. /// </summary> /// ------------------------------------------------------------------------------------ private static object Invoke(object binding, string name, object[] args, BindingFlags flags) { flags |= (BindingFlags.NonPublic | BindingFlags.Public); //if (CanInvoke(binding, name, flags)) { try { // If binding is a Type then assume invoke on a static method, property or field. // Otherwise invoke on an instance method, property or field. if (binding is Type) { return ((binding as Type).InvokeMember(name, flags | BindingFlags.Static, null, binding, args)); } return binding.GetType().InvokeMember(name, flags | BindingFlags.Instance, null, binding, args); } catch { } } return null; } /// ------------------------------------------------------------------------------------ /// <summary> /// Calls a method specified on the specified binding, throwing any exceptions that /// may occur. /// </summary> /// ------------------------------------------------------------------------------------ public static object CallMethodWithThrow(object binding, string name, object[] args) { const BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod); // If binding is a Type then assume invoke on a static method, property or field. // Otherwise invoke on an instance method, property or field. if (binding is Type) { return ((binding as Type).InvokeMember(name, flags | BindingFlags.Static, null, binding, args)); } return binding.GetType().InvokeMember(name, flags | BindingFlags.Instance, null, binding, args); } ///// ------------------------------------------------------------------------------------ ///// <summary> ///// Gets a value indicating whether or not the specified binding contains the field, ///// property or method indicated by name and having the specified flags. ///// </summary> ///// ------------------------------------------------------------------------------------ //private static bool CanInvoke(object binding, string name, BindingFlags flags) //{ // var srchFlags = (BindingFlags.Public | BindingFlags.NonPublic); // Type bindingType = null; // if (binding is Type) // { // bindingType = (Type)binding; // srchFlags |= BindingFlags.Static; // } // else // { // binding.GetType(); // srchFlags |= BindingFlags.Instance; // } // if (((flags & BindingFlags.GetProperty) == BindingFlags.GetProperty) || // ((flags & BindingFlags.SetProperty) == BindingFlags.SetProperty)) // { // return (bindingType.GetProperty(name, srchFlags) != null); // } // if (((flags & BindingFlags.GetField) == BindingFlags.GetField) || // ((flags & BindingFlags.SetField) == BindingFlags.SetField)) // { // return (bindingType.GetField(name, srchFlags) != null); // } // if ((flags & BindingFlags.InvokeMethod) == BindingFlags.InvokeMethod) // return (bindingType.GetMethod(name, srchFlags) != null); // return false; //} } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AspnetWebApi2Helpers.Sample.Web.Areas.HelpPage.ModelDescriptions; using AspnetWebApi2Helpers.Sample.Web.Areas.HelpPage.Models; namespace AspnetWebApi2Helpers.Sample.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Project Orleans Cloud Service SDK ver. 1.0 // // Copyright (c) .NET Foundation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.CodeDom; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading.Tasks; using Orleans.Runtime; namespace Orleans.CodeGeneration { /// <summary> /// C# code generator. It contains the C#-specific logic for code generation of /// state classes, factories, grain reference classes, and method invokers. /// </summary> internal class CSharpCodeGenerator : NamespaceGenerator { public CSharpCodeGenerator(Assembly grainAssembly, string nameSpace) : base(grainAssembly, nameSpace, Language.CSharp) {} protected override string GetGenericTypeName(Type type, Action<Type> referred, Func<Type, bool> noNamespace = null) { if (type == null) throw new ArgumentNullException("type"); if (noNamespace == null) noNamespace = t => true; referred(type); var name = (noNamespace(type) && !type.IsNested) ? type.Name : TypeUtils.GetFullName(type, Language.CSharp); if (!type.IsGenericType) { if (type.FullName == null) return type.Name; var result = GetNestedClassName(name); return result == "Void" ? "void" : result; } var builder = new StringBuilder(); int index = name.IndexOf("`", StringComparison.Ordinal); builder.Append(GetNestedClassName(name.Substring(0, index), noNamespace(type))); builder.Append('<'); bool isFirstArgument = true; foreach (Type argument in type.GetGenericArguments()) { if (!isFirstArgument) builder.Append(','); builder.Append(GetGenericTypeName(argument, referred, noNamespace)); isFirstArgument = false; } builder.Append('>'); return builder.ToString(); } /// <summary> /// Returns the C# name for the provided <paramref name="parameter"/>. /// </summary> /// <param name="parameter">The parameter.</param> /// <returns>The C# name for the provided <paramref name="parameter"/>.</returns> protected override string GetParameterName(ParameterInfo parameter) { return "@" + GrainInterfaceData.GetParameterName(parameter); } #region Grain Interfaces protected override void AddCreateObjectReferenceMethods(GrainInterfaceData grainInterfaceData, CodeTypeDeclaration factoryClass) { var fieldImpl = @" private static global::Orleans.CodeGeneration.IGrainMethodInvoker methodInvoker;"; var invokerField = new CodeSnippetTypeMember(fieldImpl); factoryClass.Members.Add(invokerField); var methodImpl = string.Format(@" public async static System.Threading.Tasks.Task<{0}> CreateObjectReference({0} obj) {{ if (methodInvoker == null) methodInvoker = new {2}(); return {1}.Cast(await global::Orleans.Runtime.GrainReference.CreateObjectReference(obj, methodInvoker)); }}", grainInterfaceData.TypeName, grainInterfaceData.FactoryClassName, grainInterfaceData.InvokerClassName); var createObjectReferenceMethod = new CodeSnippetTypeMember(methodImpl); factoryClass.Members.Add(createObjectReferenceMethod); methodImpl = string.Format(@" public static System.Threading.Tasks.Task DeleteObjectReference({0} reference) {{ return global::Orleans.Runtime.GrainReference.DeleteObjectReference(reference); }}", grainInterfaceData.TypeName); var deleteObjectReferenceMethod = new CodeSnippetTypeMember(methodImpl); factoryClass.Members.Add(deleteObjectReferenceMethod); } protected override string GetInvokerImpl( GrainInterfaceData si, CodeTypeDeclaration invokerClass, Type grainType, GrainInterfaceInfo grainInterfaceInfo, bool isClient) { //No public method is implemented in this grain type for orleans messages if (grainInterfaceInfo.Interfaces.Count == 0) { return string.Format(@" var t = new System.Threading.Tasks.TaskCompletionSource<object>(); t.SetException(new NotImplementedException(""No grain interfaces for type {0}"")); return t.Task; ", TypeUtils.GetFullName(grainType, Language.CSharp)); } var builder = new StringBuilder(); builder.AppendFormat(@" try {{"); var interfaceSwitchBody = string.Empty; foreach (int interfaceId in grainInterfaceInfo.Interfaces.Keys) { InterfaceInfo interfaceInfo = grainInterfaceInfo.Interfaces[interfaceId]; interfaceSwitchBody += GetMethodDispatchSwitchForInterface(interfaceId, interfaceInfo); } builder.AppendFormat( @" if (grain == null) throw new System.ArgumentNullException(""grain""); switch (interfaceId) {{ {0} default: {1}; }}", interfaceSwitchBody, "throw new System.InvalidCastException(\"interfaceId=\"+interfaceId)"); builder.AppendFormat(@" }} catch(Exception ex) {{ var t = new System.Threading.Tasks.TaskCompletionSource<object>(); t.SetException(ex); return t.Task; }}"); return builder.ToString(); } private string GetMethodDispatchSwitchForInterface(int interfaceId, InterfaceInfo interfaceInfo) { string methodSwitchBody = string.Empty; foreach (int methodId in interfaceInfo.Methods.Keys) { MethodInfo methodInfo = interfaceInfo.Methods[methodId]; var returnType = methodInfo.ReturnType; GetGenericTypeName(returnType); // Adds return type assembly and namespace to import / library lists if necessary var invokeGrainArgs = string.Empty; ParameterInfo[] paramInfoArray = methodInfo.GetParameters(); for (int count = 0; count < paramInfoArray.Length; count++) { invokeGrainArgs += string.Format("({0})arguments[{1}]", GetGenericTypeName(paramInfoArray[count].ParameterType), count); if (count < paramInfoArray.Length - 1) invokeGrainArgs += ", "; } // TODO: parameters for indexed properties string grainTypeName = GetGenericTypeName(interfaceInfo.InterfaceType); string methodName = methodInfo.Name; string invokeGrainMethod; if (!methodInfo.IsSpecialName) { invokeGrainMethod = string.Format("(({0})grain).{1}({2})", grainTypeName, methodName, invokeGrainArgs); } else if (methodInfo.Name.StartsWith("get_")) { invokeGrainMethod = string.Format("(({0})grain).{1}", grainTypeName, methodName.Substring(4)); } else if (methodInfo.Name.StartsWith("set_")) { invokeGrainMethod = string.Format("(({0})grain).{1} = {2}", grainTypeName, methodName.Substring(4), invokeGrainArgs); } else { // Should never happen throw new InvalidOperationException("Don't know how to handle method " + methodInfo); } string caseBodyStatements; if (returnType == typeof(void)) { caseBodyStatements = string.Format( @"{0}; return System.Threading.Tasks.Task.FromResult((object)true); ", invokeGrainMethod); } else if (GrainInterfaceData.IsTaskType(returnType)) { if (returnType != typeof(Task)) GetGenericTypeName(returnType.GetGenericArguments()[0]); if (returnType == typeof(Task)) { caseBodyStatements = string.Format( @"return {0}.ContinueWith(t => {{if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)null; }}); ", invokeGrainMethod); } else caseBodyStatements = string.Format( @"return {0}.ContinueWith(t => {{if (t.Status == System.Threading.Tasks.TaskStatus.Faulted) throw t.Exception; return (object)t.Result; }}); ", invokeGrainMethod); } else { // Should never happen throw new InvalidOperationException(string.Format( "Don't know how to create invoker for method {0} with Id={1} of returnType={2}", methodInfo, methodId, returnType)); } methodSwitchBody += string.Format(@" case {0}: {1}", methodId, caseBodyStatements); } const string defaultCase = @"default: throw new NotImplementedException(""interfaceId=""+interfaceId+"",methodId=""+methodId);"; return string.Format(@"case {0}: // {1} switch (methodId) {{ {2} {3} }}", interfaceId, interfaceInfo.InterfaceType.Name, methodSwitchBody, defaultCase); } protected override string GetOrleansGetMethodNameImpl(Type grainType, GrainInterfaceInfo grainInterfaceInfo) { if (grainInterfaceInfo.Interfaces.Keys.Count == 0) { // No public method is implemented in this grain type for orleans messages return @" throw new NotImplementedException(); "; } var interfaces = new Dictionary<int, InterfaceInfo>(grainInterfaceInfo.Interfaces); // Copy, as we may alter the original collection in the loop below var interfaceSwitchBody = string.Empty; foreach (var kv in interfaces) { var methodSwitchBody = string.Empty; int interfaceId = kv.Key; InterfaceInfo interfaceInfo = kv.Value; foreach (int methodId in interfaceInfo.Methods.Keys) { MethodInfo methodInfo = interfaceInfo.Methods[methodId]; //add return type assembly and namespace in GetGenericTypeName(methodInfo.ReturnType); var invokeGrainMethod = string.Format("return \"{0}\"", methodInfo.Name); methodSwitchBody += string.Format( @"case {0}: {1}; ", methodId, invokeGrainMethod); } interfaceSwitchBody += string.Format(@" case {0}: // {1} switch (methodId) {{ {2} default: throw new NotImplementedException(""interfaceId=""+interfaceId+"",methodId=""+methodId); }}", interfaceId, interfaceInfo.InterfaceType.Name, methodSwitchBody); } // End for each interface return string.Format(@" switch (interfaceId) {{ {0} default: throw new System.InvalidCastException(""interfaceId=""+interfaceId); }}", interfaceSwitchBody); } /// <summary> /// Generate Cast method in CodeDom and add it in reference class /// </summary> /// <param name="si">The service interface this grain reference type is being generated for</param> /// <param name="isFactory">whether the class being generated is a factory class rather than a grainref implementation</param> /// <param name="referenceClass">The class being generated for this grain reference type</param> protected override void AddCastMethods(GrainInterfaceData si, bool isFactory, CodeTypeDeclaration referenceClass) { string castImplCode; string checkCode = null; if (isFactory) { castImplCode = string.Format(@"{0}.Cast(grainRef)", si.ReferenceClassName); if (si.IsSystemTarget) checkCode = @"if(!((global::Orleans.Runtime.GrainReference)grainRef).IsInitializedSystemTarget) throw new InvalidOperationException(""InvalidCastException cast of a system target grain reference. Must have SystemTargetSilo set to the target silo address"");"; } else { castImplCode = string.Format( @"({0}) global::Orleans.Runtime.GrainReference.CastInternal(typeof({0}), (global::Orleans.Runtime.GrainReference gr) => {{ return new {1}(gr);}}, grainRef, {2})", si.InterfaceTypeName, // Interface type for references for this grain si.ReferenceClassName, // Concrete class for references for this grain GrainInterfaceData.GetGrainInterfaceId(si.Type)); } var methodImpl = string.Format(@" {3} static {0} Cast(global::Orleans.Runtime.IAddressable grainRef) {{ {1} return {2}; }}", si.InterfaceTypeName, checkCode, castImplCode, "public"); var castMethod = new CodeSnippetTypeMember(methodImpl); referenceClass.Members.Add(castMethod); } protected override string GetInvokeArguments(MethodInfo methodInfo) { var invokeArguments = string.Empty; int count = 1; var parameters = methodInfo.GetParameters(); foreach (var paramInfo in parameters) { if (paramInfo.ParameterType.GetInterface("Orleans.Runtime.IAddressable") != null && !typeof(GrainReference).IsAssignableFrom(paramInfo.ParameterType)) invokeArguments += string.Format("{0} is global::Orleans.Grain ? {0}.AsReference<{1}>() : {0}", GetParameterName(paramInfo), TypeUtils.GetTemplatedName(paramInfo.ParameterType, _ => true, Language.CSharp)); else invokeArguments += GetParameterName(paramInfo); if (count++ < parameters.Length) invokeArguments += ", "; } return invokeArguments; } protected override string GetBasicMethodImpl(MethodInfo methodInfo) { string invokeArguments = GetInvokeArguments(methodInfo); int methodId = GrainInterfaceData.ComputeMethodId(methodInfo); string methodImpl; string optional = null; if (GrainInterfaceData.IsReadOnly(methodInfo)) optional = ", options: global::Orleans.CodeGeneration.InvokeMethodOptions.ReadOnly"; if (GrainInterfaceData.IsUnordered(methodInfo)) { if (optional == null) optional = ", options: "; else optional += " | "; optional += " global::Orleans.CodeGeneration.InvokeMethodOptions.Unordered"; } if (GrainInterfaceData.IsAlwaysInterleave(methodInfo)) { if (optional == null) optional = ", options: "; else optional += " | "; optional += " global::Orleans.CodeGeneration.InvokeMethodOptions.AlwaysInterleave"; } if (methodInfo.ReturnType == typeof(void)) { methodImpl = string.Format(@" base.InvokeOneWayMethod({0}, {1} {2});", methodId, invokeArguments.Equals(string.Empty) ? "null" : string.Format("new object[] {{{0}}}", invokeArguments), optional); } else { if (methodInfo.ReturnType == typeof(Task)) { methodImpl = string.Format(@" return base.InvokeMethodAsync<object>({0}, {1} {2});", methodId, invokeArguments.Equals(string.Empty) ? "null" : string.Format("new object[] {{{0}}}", invokeArguments), optional); } else { methodImpl = string.Format(@" return base.InvokeMethodAsync<{0}>({1}, {2} {3});", GetActualMethodReturnType(methodInfo.ReturnType, SerializeFlag.NoSerialize), methodId, invokeArguments.Equals(string.Empty) ? "null" : string.Format("new object[] {{{0}}}", invokeArguments), optional); } } return GetParamGuardCheckStatements(methodInfo) + methodImpl; } /// <summary> /// Generate any safeguard check statements for the generated Invoke for the specified method /// </summary> /// <param name="methodInfo">The method for which the invoke is being generated for </param> /// <returns></returns> protected override string GetParamGuardCheckStatements(MethodInfo methodInfo) { var paramGuardStatements = new StringBuilder(); foreach (var parameterInfo in methodInfo.GetParameters()) { // For any parameters of type IGrainObjerver, the object passed at runtime must also be a GrainReference if (typeof (IGrainObserver).IsAssignableFrom(parameterInfo.ParameterType)) paramGuardStatements.AppendLine( string.Format( @"global::Orleans.CodeGeneration.GrainFactoryBase.CheckGrainObserverParamInternal({0});", GetParameterName(parameterInfo))); } return paramGuardStatements.ToString(); } #endregion } }
using System; using static OneOf.Functions; namespace OneOf { public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly T9 _value9; readonly T10 _value10; readonly T11 _value11; readonly T12 _value12; readonly T13 _value13; readonly T14 _value14; readonly T15 _value15; readonly T16 _value16; readonly T17 _value17; readonly T18 _value18; readonly T19 _value19; readonly T20 _value20; readonly T21 _value21; readonly int _index; protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> input) { _index = input.Index; switch (_index) { case 0: _value0 = input.AsT0; break; case 1: _value1 = input.AsT1; break; case 2: _value2 = input.AsT2; break; case 3: _value3 = input.AsT3; break; case 4: _value4 = input.AsT4; break; case 5: _value5 = input.AsT5; break; case 6: _value6 = input.AsT6; break; case 7: _value7 = input.AsT7; break; case 8: _value8 = input.AsT8; break; case 9: _value9 = input.AsT9; break; case 10: _value10 = input.AsT10; break; case 11: _value11 = input.AsT11; break; case 12: _value12 = input.AsT12; break; case 13: _value13 = input.AsT13; break; case 14: _value14 = input.AsT14; break; case 15: _value15 = input.AsT15; break; case 16: _value16 = input.AsT16; break; case 17: _value17 = input.AsT17; break; case 18: _value18 = input.AsT18; break; case 19: _value19 = input.AsT19; break; case 20: _value20 = input.AsT20; break; case 21: _value21 = input.AsT21; break; default: throw new InvalidOperationException(); } } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, 9 => _value9, 10 => _value10, 11 => _value11, 12 => _value12, 13 => _value13, 14 => _value14, 15 => _value15, 16 => _value16, 17 => _value17, 18 => _value18, 19 => _value19, 20 => _value20, 21 => _value21, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public bool IsT9 => _index == 9; public bool IsT10 => _index == 10; public bool IsT11 => _index == 11; public bool IsT12 => _index == 12; public bool IsT13 => _index == 13; public bool IsT14 => _index == 14; public bool IsT15 => _index == 15; public bool IsT16 => _index == 16; public bool IsT17 => _index == 17; public bool IsT18 => _index == 18; public bool IsT19 => _index == 19; public bool IsT20 => _index == 20; public bool IsT21 => _index == 21; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public T9 AsT9 => _index == 9 ? _value9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}"); public T10 AsT10 => _index == 10 ? _value10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}"); public T11 AsT11 => _index == 11 ? _value11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}"); public T12 AsT12 => _index == 12 ? _value12 : throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}"); public T13 AsT13 => _index == 13 ? _value13 : throw new InvalidOperationException($"Cannot return as T13 as result is T{_index}"); public T14 AsT14 => _index == 14 ? _value14 : throw new InvalidOperationException($"Cannot return as T14 as result is T{_index}"); public T15 AsT15 => _index == 15 ? _value15 : throw new InvalidOperationException($"Cannot return as T15 as result is T{_index}"); public T16 AsT16 => _index == 16 ? _value16 : throw new InvalidOperationException($"Cannot return as T16 as result is T{_index}"); public T17 AsT17 => _index == 17 ? _value17 : throw new InvalidOperationException($"Cannot return as T17 as result is T{_index}"); public T18 AsT18 => _index == 18 ? _value18 : throw new InvalidOperationException($"Cannot return as T18 as result is T{_index}"); public T19 AsT19 => _index == 19 ? _value19 : throw new InvalidOperationException($"Cannot return as T19 as result is T{_index}"); public T20 AsT20 => _index == 20 ? _value20 : throw new InvalidOperationException($"Cannot return as T20 as result is T{_index}"); public T21 AsT21 => _index == 21 ? _value21 : throw new InvalidOperationException($"Cannot return as T21 as result is T{_index}"); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13, Action<T14> f14, Action<T15> f15, Action<T16> f16, Action<T17> f17, Action<T18> f18, Action<T19> f19, Action<T20> f20, Action<T21> f21) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } if (_index == 9 && f9 != null) { f9(_value9); return; } if (_index == 10 && f10 != null) { f10(_value10); return; } if (_index == 11 && f11 != null) { f11(_value11); return; } if (_index == 12 && f12 != null) { f12(_value12); return; } if (_index == 13 && f13 != null) { f13(_value13); return; } if (_index == 14 && f14 != null) { f14(_value14); return; } if (_index == 15 && f15 != null) { f15(_value15); return; } if (_index == 16 && f16 != null) { f16(_value16); return; } if (_index == 17 && f17 != null) { f17(_value17); return; } if (_index == 18 && f18 != null) { f18(_value18); return; } if (_index == 19 && f19 != null) { f19(_value19); return; } if (_index == 20 && f20 != null) { f20(_value20); return; } if (_index == 21 && f21 != null) { f21(_value21); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13, Func<T14, TResult> f14, Func<T15, TResult> f15, Func<T16, TResult> f16, Func<T17, TResult> f17, Func<T18, TResult> f18, Func<T19, TResult> f19, Func<T20, TResult> f20, Func<T21, TResult> f21) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } if (_index == 9 && f9 != null) { return f9(_value9); } if (_index == 10 && f10 != null) { return f10(_value10); } if (_index == 11 && f11 != null) { return f11(_value11); } if (_index == 12 && f12 != null) { return f12(_value12); } if (_index == 13 && f13 != null) { return f13(_value13); } if (_index == 14 && f14 != null) { return f14(_value14); } if (_index == 15 && f15 != null) { return f15(_value15); } if (_index == 16 && f16 != null) { return f16(_value16); } if (_index == 17 && f17 != null) { return f17(_value17); } if (_index == 18 && f18 != null) { return f18(_value18); } if (_index == 19 && f19 != null) { return f19(_value19); } if (_index == 20 && f20 != null) { return f20(_value20); } if (_index == 21 && f21 != null) { return f21(_value21); } throw new InvalidOperationException(); } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT8; } public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT9 ? AsT9 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => default, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT9; } public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT10 ? AsT10 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => default, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT10; } public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT11 ? AsT11 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => default, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT11; } public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT12 ? AsT12 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => default, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT12; } public bool TryPickT13(out T13 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T14, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT13 ? AsT13 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => default, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT13; } public bool TryPickT14(out T14 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T15, T16, T17, T18, T19, T20, T21> remainder) { value = IsT14 ? AsT14 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => default, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT14; } public bool TryPickT15(out T15 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T16, T17, T18, T19, T20, T21> remainder) { value = IsT15 ? AsT15 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => default, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT15; } public bool TryPickT16(out T16 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T17, T18, T19, T20, T21> remainder) { value = IsT16 ? AsT16 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => default, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT16; } public bool TryPickT17(out T17 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T18, T19, T20, T21> remainder) { value = IsT17 ? AsT17 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => default, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT17; } public bool TryPickT18(out T18 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T19, T20, T21> remainder) { value = IsT18 ? AsT18 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => default, 19 => AsT19, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT18; } public bool TryPickT19(out T19 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T20, T21> remainder) { value = IsT19 ? AsT19 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => default, 20 => AsT20, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT19; } public bool TryPickT20(out T20 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T21> remainder) { value = IsT20 ? AsT20 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => default, 21 => AsT21, _ => throw new InvalidOperationException() }; return this.IsT20; } public bool TryPickT21(out T21 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> remainder) { value = IsT21 ? AsT21 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, 15 => AsT15, 16 => AsT16, 17 => AsT17, 18 => AsT18, 19 => AsT19, 20 => AsT20, 21 => default, _ => throw new InvalidOperationException() }; return this.IsT21; } bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), 9 => Equals(_value9, other._value9), 10 => Equals(_value10, other._value10), 11 => Equals(_value11, other._value11), 12 => Equals(_value12, other._value12), 13 => Equals(_value13, other._value13), 14 => Equals(_value14, other._value14), 15 => Equals(_value15, other._value15), 16 => Equals(_value16, other._value16), 17 => Equals(_value17, other._value17), 18 => Equals(_value18, other._value18), 19 => Equals(_value19, other._value19), 20 => Equals(_value20, other._value20), 21 => Equals(_value21, other._value21), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), 9 => FormatValue(_value9), 10 => FormatValue(_value10), 11 => FormatValue(_value11), 12 => FormatValue(_value12), 13 => FormatValue(_value13), 14 => FormatValue(_value14), 15 => FormatValue(_value15), 16 => FormatValue(_value16), 17 => FormatValue(_value17), 18 => FormatValue(_value18), 19 => FormatValue(_value19), 20 => FormatValue(_value20), 21 => FormatValue(_value21), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), 9 => _value9?.GetHashCode(), 10 => _value10?.GetHashCode(), 11 => _value11?.GetHashCode(), 12 => _value12?.GetHashCode(), 13 => _value13?.GetHashCode(), 14 => _value14?.GetHashCode(), 15 => _value15?.GetHashCode(), 16 => _value16?.GetHashCode(), 17 => _value17?.GetHashCode(), 18 => _value18?.GetHashCode(), 19 => _value19?.GetHashCode(), 20 => _value20?.GetHashCode(), 21 => _value21?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _index; } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXWSCORE { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario is designed to test operations related to creation, retrieving, updating, movement, copy, deletion and mark of contact items on the server. /// </summary> [TestClass] public class S02_ManageContactItems : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the test class. /// </summary> /// <param name="context">Context to initialize.</param> [ClassInitialize] public static void ClassInitialize(TestContext context) { TestClassBase.Initialize(context); } /// <summary> /// Clean up the test class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is intended to validate the successful response returned by CreateItem, GetItem and DeleteItem operations for contact item with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC01_CreateGetDeleteContactItemSuccessfully() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyCreateGetDeleteItem(item); } /// <summary> /// This test case is intended to validate the successful responses returned by CreateItem, CopyItem and GetItem operations for contact item with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC02_CopyContactItemSuccessfully() { #region Step 1: Create the contact item. ContactItemType item = new ContactItemType(); ItemIdType[] createdItemIds = this.CreateItemWithMinimumElements(item); #endregion #region Step 2:Copy the contact item // Call CopyItem operation. CopyItemResponseType copyItemResponse = this.CallCopyItemOperation(DistinguishedFolderIdNameType.drafts, createdItemIds); // Check the operation response. Common.CheckOperationSuccess(copyItemResponse, 1, this.Site); ItemIdType[] copiedItemIds = Common.GetItemIdsFromInfoResponse(copyItemResponse); // One copied contact item should be returned. Site.Assert.AreEqual<int>( 1, copiedItemIds.GetLength(0), "One copied contact item should be returned! Expected Item Count: {0}, Actual Item Count: {1}", 1, copiedItemIds.GetLength(0)); #endregion #region Step 3: Get the first created contact item success. // Call the GetItem operation. GetItemResponseType getItemResponse = this.CallGetItemOperation(createdItemIds); // Check the operation response. Common.CheckOperationSuccess(getItemResponse, 1, this.Site); ItemIdType[] getItemIds = Common.GetItemIdsFromInfoResponse(getItemResponse); ContactItemType[] getItems = Common.GetItemsFromInfoResponse<ContactItemType>(getItemResponse); // One contact item should be returned. Site.Assert.AreEqual<int>( 1, getItemIds.GetLength(0), "One contact item should be returned! Expected Item Count: {0}, Actual Item Count: {1}", 1, getItemIds.GetLength(0)); // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSCORE_R2018"); // Verify MS-OXWSCORE requirement: MS-OXWSCORE_R2018 this.Site.CaptureRequirementIfAreEqual<string>( "IPM.Contact", ((ItemInfoResponseMessageType)getItemResponse.ResponseMessages.Items[0]).Items.Items[0].ItemClass, 2018, @"[In t:ItemType Complex Type] This value is ""IPM.Contact"" for contact item."); #endregion #region Step 4: Get the second copied contact item success. // Call the GetItem operation. getItemResponse = this.CallGetItemOperation(copiedItemIds); // Check the operation response. Common.CheckOperationSuccess(getItemResponse, 1, this.Site); getItemIds = Common.GetItemIdsFromInfoResponse(getItemResponse); // One contact item should be returned. Site.Assert.AreEqual<int>( 1, getItemIds.GetLength(0), "One contact item should be returned! Expected Item Count: {0}, Actual Item Count: {1}", 1, getItemIds.GetLength(0)); #endregion } /// <summary> /// This test case is intended to validate the successful response returned by CreateItem, MoveItem and GetItem operations for contact item with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC03_MoveContactItemSuccessfully() { #region Step 1: Create the contact item. ContactItemType item = new ContactItemType(); ItemIdType[] createdItemIds = this.CreateItemWithMinimumElements(item); #endregion #region Step 2: Move the contact item. // Clear ExistItemIds for MoveItem. this.InitializeCollection(); // Call MoveItem operation. MoveItemResponseType moveItemResponse = this.CallMoveItemOperation(DistinguishedFolderIdNameType.inbox, createdItemIds); // Check the operation response. Common.CheckOperationSuccess(moveItemResponse, 1, this.Site); ItemIdType[] movedItemIds = Common.GetItemIdsFromInfoResponse(moveItemResponse); // One moved contact item should be returned. Site.Assert.AreEqual<int>( 1, movedItemIds.GetLength(0), "One moved contact item should be returned! Expected Item Count: {0}, Actual Item Count: {1}", 1, movedItemIds.GetLength(0)); #endregion #region Step 3: Get the created contact item failed. // Call the GetItem operation. GetItemResponseType getItemResponse = this.CallGetItemOperation(createdItemIds); Site.Assert.AreEqual<int>( 1, getItemResponse.ResponseMessages.Items.GetLength(0), "Expected Item Count: {0}, Actual Item Count: {1}", 1, getItemResponse.ResponseMessages.Items.GetLength(0)); Site.Assert.AreEqual<ResponseClassType>( ResponseClassType.Error, getItemResponse.ResponseMessages.Items[0].ResponseClass, string.Format( "Get contact item operation should be failed with error! Actual response code: {0}", getItemResponse.ResponseMessages.Items[0].ResponseCode)); #endregion #region Step 4: Get the moved contact item. // Call the GetItem operation. getItemResponse = this.CallGetItemOperation(movedItemIds); // Check the operation response. Common.CheckOperationSuccess(getItemResponse, 1, this.Site); ItemIdType[] getItemIds = Common.GetItemIdsFromInfoResponse(getItemResponse); // One contact item should be returned. Site.Assert.AreEqual<int>( 1, getItemIds.GetLength(0), "One contact item should be returned! Expected Item Count: {0}, Actual Item Count: {1}", 1, getItemIds.GetLength(0)); #endregion } /// <summary> /// This test case is intended to validate the successful response returned by CreateItem, UpdateItem and GetItem operations for contact item with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC04_UpdateContactItemSuccessfully() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyUpdateItemSuccessfulResponse(item); } /// <summary> /// This test case is intended to validate the successful response returned by CreateItem, MarkAllItemsAsRead and GetItem operations for contact items with required elements. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC05_MarkAllContactItemsAsReadSuccessfully() { Site.Assume.IsTrue(Common.IsRequirementEnabled(1290, this.Site), "Exchange 2007 and Exchange 2010 do not support the MarkAllItemsAsRead operation."); ContactItemType[] items = new ContactItemType[] { new ContactItemType(), new ContactItemType() }; this.TestSteps_VerifyMarkAllItemsAsRead<ContactItemType>(items); } /// <summary> /// This test case is intended to validate the failed response returned by UpdateItem operation with ErrorIncorrectUpdatePropertyCount response code for contact item. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC06_UpdateContactItemFailed() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyUpdateItemFailedResponse(item); } /// <summary> /// This test case is intended to validate the failed response returned by CreateItem operation with ErrorObjectTypeChanged response code for contact item. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC07_CreateContactItemFailed() { #region Step 1: Create the contact item with invalid item class. ContactItemType[] createdItems = new ContactItemType[] { new ContactItemType() { Subject = Common.GenerateResourceName( this.Site, TestSuiteHelper.SubjectForCreateItem), // Set an invalid ItemClass to contact item. ItemClass = TestSuiteHelper.InvalidItemClass } }; CreateItemResponseType createItemResponse = this.CallCreateItemOperation(DistinguishedFolderIdNameType.contacts, createdItems); #endregion // Get ResponseCode from CreateItem operation response. ResponseCodeType responseCode = createItemResponse.ResponseMessages.Items[0].ResponseCode; // Verify MS-OXWSCDATA_R619. this.VerifyErrorObjectTypeChanged(responseCode); } /// <summary> /// This test case is intended to validate the PathToExtendedFieldType complex type returned by CreateItem operation for contact item. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC08_VerifyExtendPropertyType() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyDistinguishedPropertySetIdConflictsWithPropertySetId(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyDistinguishedPropertySetIdConflictsWithPropertyTag(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyDistinguishedPropertySetIdWithPropertyTypeOrPropertyName(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertySetIdConflictsWithDistinguishedPropertySetId(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertySetIdConflictsWithPropertyTag(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertySetIdWithPropertyTypeOrPropertyName(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyTagRepresentation(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyTagConflictsWithDistinguishedPropertySetId(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyTagConflictsWithPropertySetId(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyTagConflictsWithPropertyName(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyTagConflictsWithPropertyId(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyNameWithDistinguishedPropertySetIdOrPropertySetId(DistinguishedFolderIdNameType.contacts, item); this.TestSteps_VerifyPropertyIdWithDistinguishedPropertySetIdOrPropertySetId(DistinguishedFolderIdNameType.contacts, item); } /// <summary> /// This test case is intended to create, update, move, get and copy the multiple contact items with successful responses. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC09_OperateMultipleContactItemsSuccessfully() { ContactItemType[] items = new ContactItemType[] { new ContactItemType(), new ContactItemType() }; this.TestSteps_VerifyOperateMultipleItems(items); } /// <summary> /// This case is intended to validate the response returned by GetItem operation with the ItemShape element. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC10_GetContactItemWithItemResponseShapeType() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType(item); } /// <summary> /// This case is intended to validate the response returned by GetItem operation with the ItemShape element in which ConvertHtmlCodePageToUTF8 element exists or is not specified. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC11_GetContactItemWithConvertHtmlCodePageToUTF8() { Site.Assume.IsTrue(Common.IsRequirementEnabled(21498, this.Site), "Exchange 2007 and Exchange 2010 do not include the ConvertHtmlCodePageToUTF8 element."); ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType_ConvertHtmlCodePageToUTF8Boolean(item); } /// <summary> /// This case is intended to validate the response returned by GetItem operation with the ItemShape element in which AddBlankTargetToLinks element exists. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC12_GetContactItemWithAddBlankTargetToLinks() { Site.Assume.IsTrue(Common.IsRequirementEnabled(2149908, this.Site), "Exchange 2007 and Exchange 2010 do not use the AddBlankTargetToLinks element."); ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType_AddBlankTargetToLinksBoolean(item); } /// <summary> /// This case is intended to validate the response returned by GetItem operation with the ItemShape element in which BlockExternalImages element exists. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC13_GetContactItemWithBlockExternalImages() { Site.Assume.IsTrue(Common.IsRequirementEnabled(2149905, this.Site), "Exchange 2007 and Exchange 2010 do not use the BlockExternalImages element."); ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType_BlockExternalImagesBoolean(item); } /// <summary> /// This case is intended to validate the responses returned by GetItem operation with different DefaultShapeNamesType enumeration values in ItemShape element. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC14_GetContactItemWithDefaultShapeNamesTypeEnum() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType_DefaultShapeNamesTypeEnum(item); } /// <summary> /// This case is intended to validate the responses returned by GetItem operation with different BodyTypeResponseType enumeration values in ItemShape element. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC15_GetContactItemWithBodyTypeResponseTypeEnum() { ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType_BodyTypeResponseTypeEnum(item); } /// <summary> /// This test case is intended to validate if invalid ItemClass values are set for contact items in the CreateItem request, /// an ErrorObjectTypeChanged response code will be returned in the CreateItem response. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC16_CreateContactItemWithInvalidItemClass() { #region Step 1: Create the contact item with ItemClass set to IPM.Appointment. CreateItemType createItemRequest = new CreateItemType(); createItemRequest.Items = new NonEmptyArrayOfAllItemsType(); ContactItemType item = new ContactItemType(); createItemRequest.Items.Items = new ItemType[] { item }; createItemRequest.Items.Items[0].Subject = Common.GenerateResourceName(this.Site, TestSuiteHelper.SubjectForCreateItem, 1); createItemRequest.Items.Items[0].ItemClass = "IPM.Appointment"; CreateItemResponseType createItemResponse = this.COREAdapter.CreateItem(createItemRequest); Site.Assert.AreEqual<ResponseCodeType>( ResponseCodeType.ErrorObjectTypeChanged, createItemResponse.ResponseMessages.Items[0].ResponseCode, "ErrorObjectTypeChanged should be returned if create a contact item with ItemClass IPM.Appointment."); #endregion #region Step 2: Create the contact item with ItemClass set to IPM.Post. createItemRequest.Items.Items[0].Subject = Common.GenerateResourceName(this.Site, TestSuiteHelper.SubjectForCreateItem, 2); createItemRequest.Items.Items[0].ItemClass = "IPM.Post"; createItemResponse = this.COREAdapter.CreateItem(createItemRequest); Site.Assert.AreEqual<ResponseCodeType>( ResponseCodeType.ErrorObjectTypeChanged, createItemResponse.ResponseMessages.Items[0].ResponseCode, "ErrorObjectTypeChanged should be returned if create a contact item with ItemClass IPM.Post."); #endregion #region Step 3: Create the contact item with ItemClass set to IPM.Task. createItemRequest.Items.Items[0].Subject = Common.GenerateResourceName(this.Site, TestSuiteHelper.SubjectForCreateItem, 3); createItemRequest.Items.Items[0].ItemClass = "IPM.Task"; createItemResponse = this.COREAdapter.CreateItem(createItemRequest); Site.Assert.AreEqual<ResponseCodeType>( ResponseCodeType.ErrorObjectTypeChanged, createItemResponse.ResponseMessages.Items[0].ResponseCode, "ErrorObjectTypeChanged should be returned if create a contact item with ItemClass IPM.Task."); #endregion #region Step 4: Create the contact item with ItemClass set to IPM.DistList. createItemRequest.Items.Items[0].Subject = Common.GenerateResourceName(this.Site, TestSuiteHelper.SubjectForCreateItem, 4); createItemRequest.Items.Items[0].ItemClass = "IPM.DistList"; createItemResponse = this.COREAdapter.CreateItem(createItemRequest); Site.Assert.AreEqual<ResponseCodeType>( ResponseCodeType.ErrorObjectTypeChanged, createItemResponse.ResponseMessages.Items[0].ResponseCode, "ErrorObjectTypeChanged should be returned if create a contact item with ItemClass IPM.DistList."); #endregion #region Step 5: Create the contact item with ItemClass set to random string. createItemRequest.Items.Items[0].Subject = Common.GenerateResourceName(this.Site, TestSuiteHelper.SubjectForCreateItem, 5); createItemRequest.Items.Items[0].ItemClass = Common.GenerateResourceName(this.Site, "ItemClass"); createItemResponse = this.COREAdapter.CreateItem(createItemRequest); Site.Assert.AreEqual<ResponseCodeType>( ResponseCodeType.ErrorObjectTypeChanged, createItemResponse.ResponseMessages.Items[0].ResponseCode, "ErrorObjectTypeChanged should be returned if create a contact item with ItemClass is set to a random string."); #endregion // Add the debug information this.Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXWSCORE_R2023"); // Verify MS-OXWSCORE requirement: MS-OXWSCORE_R2023 this.Site.CaptureRequirement( 2023, @"[In t:ItemType Complex Type] If invalid values are set for these items in the CreateItem request, an ErrorObjectTypeChanged ([MS-OXWSCDATA] section 2.2.5.24) response code will be returned in the CreateItem response."); } /// <summary> /// This case is intended to validate the response returned by GetItem operation with the ItemShape element in which IncludeMimeContent element exists. /// </summary> [TestCategory("MSOXWSCORE"), TestMethod()] public void MSOXWSCORE_S02_TC17_VerifyGetItemWithItemResponseShapeType_IncludeMimeContentBoolean() { Site.Assume.IsTrue(Common.IsRequirementEnabled(23091, this.Site), "E2010SP3 version below do not support the MimeContent element for ContactType, TaskType and DistributionListType item when retrieving MIME content."); ContactItemType item = new ContactItemType(); this.TestSteps_VerifyGetItemWithItemResponseShapeType_IncludeMimeContentBoolean(item); } #endregion } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; namespace Community.CsharpSqlite { using sqlite3_int64 = System.Int64; using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2005 July 8 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code associated with the ANALYZE command. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ #if !SQLITE_OMIT_ANALYZE //#include "sqliteInt.h" /* ** This routine generates code that opens the sqlite_stat1 table for ** writing with cursor iStatCur. If the library was built with the ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is ** opened for writing using cursor (iStatCur+1) ** ** If the sqlite_stat1 tables does not previously exist, it is created. ** Similarly, if the sqlite_stat2 table does not exist and the library ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. ** ** Argument zWhere may be a pointer to a buffer containing a table name, ** or it may be a NULL pointer. If it is not NULL, then all entries in ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated ** with the named table are deleted. If zWhere==0, then code is generated ** to delete all stat table entries. */ public struct _aTable { public string zName; public string zCols; public _aTable( string zName, string zCols ) { this.zName = zName; this.zCols = zCols; } }; static _aTable[] aTable = new _aTable[]{ new _aTable( "sqlite_stat1", "tbl,idx,stat" ), #if SQLITE_ENABLE_STAT2 new _aTable( "sqlite_stat2", "tbl,idx,sampleno,sample" ), #endif }; static void openStatTable( Parse pParse, /* Parsing context */ int iDb, /* The database we are looking in */ int iStatCur, /* Open the sqlite_stat1 table on this cursor */ string zWhere, /* Delete entries for this table or index */ string zWhereType /* Either "tbl" or "idx" */ ) { int[] aRoot = new int[] { 0, 0 }; u8[] aCreateTbl = new u8[] { 0, 0 }; int i; sqlite3 db = pParse.db; Db pDb; Vdbe v = sqlite3GetVdbe( pParse ); if ( v == null ) return; Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); Debug.Assert( sqlite3VdbeDb( v ) == db ); pDb = db.aDb[iDb]; for ( i = 0; i < ArraySize( aTable ); i++ ) { string zTab = aTable[i].zName; Table pStat; if ( ( pStat = sqlite3FindTable( db, zTab, pDb.zName ) ) == null ) { /* The sqlite_stat[12] table does not exist. Create it. Note that a ** side-effect of the CREATE TABLE statement is to leave the rootpage ** of the new table in register pParse.regRoot. This is important ** because the OpenWrite opcode below will be needing it. */ sqlite3NestedParse( pParse, "CREATE TABLE %Q.%s(%s)", pDb.zName, zTab, aTable[i].zCols ); aRoot[i] = pParse.regRoot; aCreateTbl[i] = 1; } else { /* The table already exists. If zWhere is not NULL, delete all entries ** associated with the table zWhere. If zWhere is NULL, delete the ** entire contents of the table. */ aRoot[i] = pStat.tnum; sqlite3TableLock( pParse, iDb, aRoot[i], 1, zTab ); if ( !String.IsNullOrEmpty( zWhere ) ) { sqlite3NestedParse( pParse, "DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere ); } else { /* The sqlite_stat[12] table already exists. Delete all rows. */ sqlite3VdbeAddOp2( v, OP_Clear, aRoot[i], iDb ); } } } /* Open the sqlite_stat[12] tables for writing. */ for ( i = 0; i < ArraySize( aTable ); i++ ) { sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb ); sqlite3VdbeChangeP4( v, -1, 3, P4_INT32 ); sqlite3VdbeChangeP5( v, aCreateTbl[i] ); } } /* ** Generate code to do an analysis of all indices associated with ** a single table. */ static void analyzeOneTable( Parse pParse, /* Parser context */ Table pTab, /* Table whose indices are to be analyzed */ Index pOnlyIdx, /* If not NULL, only analyze this one index */ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */ int iMem /* Available memory locations begin here */ ) { sqlite3 db = pParse.db; /* Database handle */ Index pIdx; /* An index to being analyzed */ int iIdxCur; /* Cursor open on index being analyzed */ Vdbe v; /* The virtual machine being built up */ int i; /* Loop counter */ int topOfLoop; /* The top of the loop */ int endOfLoop; /* The end of the loop */ int jZeroRows = -1; /* Jump from here if number of rows is zero */ int iDb; /* Index of database containing pTab */ int regTabname = iMem++; /* Register containing table name */ int regIdxname = iMem++; /* Register containing index name */ int regSampleno = iMem++; /* Register containing next sample number */ int regCol = iMem++; /* Content of a column analyzed table */ int regRec = iMem++; /* Register holding completed record */ int regTemp = iMem++; /* Temporary use register */ int regRowid = iMem++; /* Rowid for the inserted record */ #if SQLITE_ENABLE_STAT2 int addr = 0; /* Instruction address */ int regTemp2 = iMem++; /* Temporary use register */ int regSamplerecno = iMem++; /* Index of next sample to record */ int regRecno = iMem++; /* Current sample index */ int regLast = iMem++; /* Index of last sample to record */ int regFirst = iMem++; /* Index of first sample to record */ #endif v = sqlite3GetVdbe( pParse ); if ( v == null || NEVER( pTab == null ) ) { return; } if ( pTab.tnum == 0 ) { /* Do not gather statistics on views or virtual tables */ return; } if ( pTab.zName.StartsWith( "sqlite_", StringComparison.OrdinalIgnoreCase ) ) { /* Do not gather statistics on system tables */ return; } Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); iDb = sqlite3SchemaToIndex( db, pTab.pSchema ); Debug.Assert( iDb >= 0 ); Debug.Assert( sqlite3SchemaMutexHeld(db, iDb, null) ); #if !SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0, db.aDb[iDb].zName ) ){ return; } #endif /* Establish a read-lock on the table at the shared-cache level. */ sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName ); iIdxCur = pParse.nTab++; sqlite3VdbeAddOp4( v, OP_String8, 0, regTabname, 0, pTab.zName, 0 ); for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext ) { int nCol; KeyInfo pKey; if ( pOnlyIdx != null && pOnlyIdx != pIdx ) continue; nCol = pIdx.nColumn; pKey = sqlite3IndexKeyinfo( pParse, pIdx ); if ( iMem + 1 + ( nCol * 2 ) > pParse.nMem ) { pParse.nMem = iMem + 1 + ( nCol * 2 ); } /* Open a cursor to the index to be analyzed. */ Debug.Assert( iDb == sqlite3SchemaToIndex( db, pIdx.pSchema ) ); sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb, pKey, P4_KEYINFO_HANDOFF ); VdbeComment( v, "%s", pIdx.zName ); /* Populate the registers containing the index names. */ sqlite3VdbeAddOp4( v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0 ); #if SQLITE_ENABLE_STAT2 /* If this iteration of the loop is generating code to analyze the ** first index in the pTab.pIndex list, then register regLast has ** not been populated. In this case populate it now. */ if ( pTab.pIndex == pIdx ) { sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno ); sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2 - 1, regTemp ); sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES * 2, regTemp2 ); sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regLast ); sqlite3VdbeAddOp2( v, OP_Null, 0, regFirst ); addr = sqlite3VdbeAddOp3( v, OP_Lt, regSamplerecno, 0, regLast ); sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regFirst ); sqlite3VdbeAddOp3( v, OP_Multiply, regLast, regTemp, regLast ); sqlite3VdbeAddOp2( v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES * 2 - 2 ); sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regLast, regLast ); sqlite3VdbeJumpHere( v, addr ); } /* Zero the regSampleno and regRecno registers. */ sqlite3VdbeAddOp2( v, OP_Integer, 0, regSampleno ); sqlite3VdbeAddOp2( v, OP_Integer, 0, regRecno ); sqlite3VdbeAddOp2( v, OP_Copy, regFirst, regSamplerecno ); #endif /* The block of memory cells initialized here is used as follows. ** ** iMem: ** The total number of rows in the table. ** ** iMem+1 .. iMem+nCol: ** Number of distinct entries in index considering the ** left-most N columns only, where N is between 1 and nCol, ** inclusive. ** ** iMem+nCol+1 .. Mem+2*nCol: ** Previous value of indexed columns, from left to right. ** ** Cells iMem through iMem+nCol are initialized to 0. The others are ** initialized to contain an SQL NULL. */ for ( i = 0; i <= nCol; i++ ) { sqlite3VdbeAddOp2( v, OP_Integer, 0, iMem + i ); } for ( i = 0; i < nCol; i++ ) { sqlite3VdbeAddOp2( v, OP_Null, 0, iMem + nCol + i + 1 ); } /* Start the analysis loop. This loop runs through all the entries in ** the index b-tree. */ endOfLoop = sqlite3VdbeMakeLabel( v ); sqlite3VdbeAddOp2( v, OP_Rewind, iIdxCur, endOfLoop ); topOfLoop = sqlite3VdbeCurrentAddr( v ); sqlite3VdbeAddOp2( v, OP_AddImm, iMem, 1 ); for ( i = 0; i < nCol; i++ ) { sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, regCol ); CollSeq pColl; if ( i == 0 ) { #if SQLITE_ENABLE_STAT2 /* Check if the record that cursor iIdxCur points to contains a ** value that should be stored in the sqlite_stat2 table. If so, ** store it. */ int ne = sqlite3VdbeAddOp3( v, OP_Ne, regRecno, 0, regSamplerecno ); Debug.Assert( regTabname + 1 == regIdxname && regTabname + 2 == regSampleno && regTabname + 3 == regCol ); sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL ); sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur + 1, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur + 1, regRec, regRowid ); /* Calculate new values for regSamplerecno and regSampleno. ** ** sampleno = sampleno + 1 ** samplerecno = samplerecno+(remaining records)/(remaining samples) */ sqlite3VdbeAddOp2( v, OP_AddImm, regSampleno, 1 ); sqlite3VdbeAddOp3( v, OP_Subtract, regRecno, regLast, regTemp ); sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); sqlite3VdbeAddOp2( v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2 ); sqlite3VdbeAddOp3( v, OP_Subtract, regSampleno, regTemp2, regTemp2 ); sqlite3VdbeAddOp3( v, OP_Divide, regTemp2, regTemp, regTemp ); sqlite3VdbeAddOp3( v, OP_Add, regSamplerecno, regTemp, regSamplerecno ); sqlite3VdbeJumpHere( v, ne ); sqlite3VdbeAddOp2( v, OP_AddImm, regRecno, 1 ); #endif /* Always record the very first row */ sqlite3VdbeAddOp1( v, OP_IfNot, iMem + 1 ); } Debug.Assert( pIdx.azColl != null ); Debug.Assert( pIdx.azColl[i] != null ); pColl = sqlite3LocateCollSeq( pParse, pIdx.azColl[i] ); sqlite3VdbeAddOp4( v, OP_Ne, regCol, 0, iMem + nCol + i + 1, pColl, P4_COLLSEQ ); sqlite3VdbeChangeP5( v, SQLITE_NULLEQ ); } //if( db.mallocFailed ){ // /* If a malloc failure has occurred, then the result of the expression // ** passed as the second argument to the call to sqlite3VdbeJumpHere() // ** below may be negative. Which causes an Debug.Assert() to fail (or an // ** out-of-bounds write if SQLITE_DEBUG is not defined). */ // return; //} sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop ); for ( i = 0; i < nCol; i++ ) { int addr2 = sqlite3VdbeCurrentAddr( v ) - ( nCol * 2 ); if ( i == 0 ) { sqlite3VdbeJumpHere( v, addr2 - 1 ); /* Set jump dest for the OP_IfNot */ } sqlite3VdbeJumpHere( v, addr2 ); /* Set jump dest for the OP_Ne */ sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 ); sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 ); } /* End of the analysis loop. */ sqlite3VdbeResolveLabel( v, endOfLoop ); sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop ); sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); /* Store the results in sqlite_stat1. ** ** The result is a single row of the sqlite_stat1 table. The first ** two columns are the names of the table and index. The third column ** is a string composed of a list of integer statistics about the ** index. The first integer in the list is the total number of entries ** in the index. There is one additional integer in the list for each ** column of the table. This additional integer is a guess of how many ** rows of the table the index will select. If D is the count of distinct ** values and K is the total number of rows, then the integer is computed ** as: ** ** I = (K+D-1)/D ** ** If K==0 then no entry is made into the sqlite_stat1 table. ** If K>0 then it is always the case the D>0 so division by zero ** is never possible. */ sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regSampleno ); if ( jZeroRows < 0 ) { jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, iMem ); } for ( i = 0; i < nCol; i++ ) { sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, " ", 0 ); sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno ); sqlite3VdbeAddOp3( v, OP_Add, iMem, iMem + i + 1, regTemp ); sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 ); sqlite3VdbeAddOp3( v, OP_Divide, iMem + i + 1, regTemp, regTemp ); sqlite3VdbeAddOp1( v, OP_ToInt, regTemp ); sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno ); } sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); } /* If the table has no indices, create a single sqlite_stat1 entry ** containing NULL as the index name and the row count as the content. */ if ( pTab.pIndex == null ) { sqlite3VdbeAddOp3( v, OP_OpenRead, iIdxCur, pTab.tnum, iDb ); VdbeComment( v, "%s", pTab.zName ); sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regSampleno ); sqlite3VdbeAddOp1( v, OP_Close, iIdxCur ); jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, regSampleno ); } else { sqlite3VdbeJumpHere( v, jZeroRows ); jZeroRows = sqlite3VdbeAddOp0( v, OP_Goto ); } sqlite3VdbeAddOp2( v, OP_Null, 0, regIdxname ); sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 ); sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid ); sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid ); sqlite3VdbeChangeP5( v, OPFLAG_APPEND ); if ( pParse.nMem < regRec ) pParse.nMem = regRec; sqlite3VdbeJumpHere( v, jZeroRows ); } /* ** Generate code that will cause the most recent index analysis to ** be loaded into internal hash tables where is can be used. */ static void loadAnalysis( Parse pParse, int iDb ) { Vdbe v = sqlite3GetVdbe( pParse ); if ( v != null ) { sqlite3VdbeAddOp1( v, OP_LoadAnalysis, iDb ); } } /* ** Generate code that will do an analysis of an entire database */ static void analyzeDatabase( Parse pParse, int iDb ) { sqlite3 db = pParse.db; Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */ HashElem k; int iStatCur; int iMem; sqlite3BeginWriteOperation( pParse, 0, iDb ); iStatCur = pParse.nTab; pParse.nTab += 2; openStatTable( pParse, iDb, iStatCur, null, null ); iMem = pParse.nMem + 1; Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); //for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){ for ( k = pSchema.tblHash.first; k != null; k = k.next ) { Table pTab = (Table)k.data;// sqliteHashData( k ); analyzeOneTable( pParse, pTab, null, iStatCur, iMem ); } loadAnalysis( pParse, iDb ); } /* ** Generate code that will do an analysis of a single table in ** a database. If pOnlyIdx is not NULL then it is a single index ** in pTab that should be analyzed. */ static void analyzeTable( Parse pParse, Table pTab, Index pOnlyIdx) { int iDb; int iStatCur; Debug.Assert( pTab != null ); Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema ); sqlite3BeginWriteOperation( pParse, 0, iDb ); iStatCur = pParse.nTab; pParse.nTab += 2; if ( pOnlyIdx != null ) { openStatTable( pParse, iDb, iStatCur, pOnlyIdx.zName, "idx" ); } else { openStatTable( pParse, iDb, iStatCur, pTab.zName, "tbl" ); } analyzeOneTable( pParse, pTab, pOnlyIdx, iStatCur, pParse.nMem + 1 ); loadAnalysis( pParse, iDb ); } /* ** Generate code for the ANALYZE command. The parser calls this routine ** when it recognizes an ANALYZE command. ** ** ANALYZE -- 1 ** ANALYZE <database> -- 2 ** ANALYZE ?<database>.?<tablename> -- 3 ** ** Form 1 causes all indices in all attached databases to be analyzed. ** Form 2 analyzes all indices the single database named. ** Form 3 analyzes all indices associated with the named table. */ // OVERLOADS, so I don't need to rewrite parse.c static void sqlite3Analyze( Parse pParse, int null_2, int null_3 ) { sqlite3Analyze( pParse, null, null ); } static void sqlite3Analyze( Parse pParse, Token pName1, Token pName2 ) { sqlite3 db = pParse.db; int iDb; int i; string z, zDb; Table pTab; Index pIdx; Token pTableName = null; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) ); if ( SQLITE_OK != sqlite3ReadSchema( pParse ) ) { return; } Debug.Assert( pName2 != null || pName1 == null ); if ( pName1 == null ) { /* Form 1: Analyze everything */ for ( i = 0; i < db.nDb; i++ ) { if ( i == 1 ) continue; /* Do not analyze the TEMP database */ analyzeDatabase( pParse, i ); } } else if ( pName2.n == 0 ) { /* Form 2: Analyze the database or table named */ iDb = sqlite3FindDb( db, pName1 ); if ( iDb >= 0 ) { analyzeDatabase( pParse, iDb ); } else { z = sqlite3NameFromToken( db, pName1 ); if ( z != null ) { if ( ( pIdx = sqlite3FindIndex( db, z, null ) ) != null ) { analyzeTable( pParse, pIdx.pTable, pIdx ); } else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, null ) ) != null ) { analyzeTable( pParse, pTab, null ); } z = null;//sqlite3DbFree( db, z ); } } } else { /* Form 3: Analyze the fully qualified table name */ iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pTableName ); if ( iDb >= 0 ) { zDb = db.aDb[iDb].zName; z = sqlite3NameFromToken( db, pTableName ); if ( z != null ) { if ( ( pIdx = sqlite3FindIndex( db, z, zDb ) ) != null ) { analyzeTable( pParse, pIdx.pTable, pIdx ); } else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, zDb ) ) != null ) { analyzeTable( pParse, pTab, null ); } z = null; //sqlite3DbFree( db, z ); } } } } /* ** Used to pass information from the analyzer reader through to the ** callback routine. */ //typedef struct analysisInfo analysisInfo; public struct analysisInfo { public sqlite3 db; public string zDatabase; }; /* ** This callback is invoked once for each index when reading the ** sqlite_stat1 table. ** ** argv[0] = name of the table ** argv[1] = name of the index (might be NULL) ** argv[2] = results of analysis - on integer for each column ** ** Entries for which argv[1]==NULL simply record the number of rows in ** the table. */ static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed ) { string[] argv = (string[])Oargv; analysisInfo pInfo = (analysisInfo)pData; Index pIndex; Table pTable; int i, c, n; int v; string z; Debug.Assert( argc == 3 ); UNUSED_PARAMETER2( NotUsed, argc ); if ( argv == null || argv[0] == null || argv[2] == null ) { return 0; } pTable = sqlite3FindTable( pInfo.db, argv[0], pInfo.zDatabase ); if ( pTable == null ) { return 0; } if ( !String.IsNullOrEmpty( argv[1] ) ) { pIndex = sqlite3FindIndex( pInfo.db, argv[1], pInfo.zDatabase ); } else { pIndex = null; } n = pIndex != null ? pIndex.nColumn : 0; z = argv[2]; int zIndex = 0; for ( i = 0; z != null && i <= n; i++ ) { v = 0; while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' ) { v = v * 10 + c - '0'; zIndex++; } if ( i == 0 ) pTable.nRowEst = (uint)v; if ( pIndex == null ) break; pIndex.aiRowEst[i] = v; if ( zIndex < z.Length && z[zIndex] == ' ' ) zIndex++; if ( z.Substring(zIndex).CompareTo("unordered")==0)//memcmp( z, "unordered", 10 ) == 0 ) { pIndex.bUnordered = 1; break; } } return 0; } /* ** If the Index.aSample variable is not NULL, delete the aSample[] array ** and its contents. */ static void sqlite3DeleteIndexSamples( sqlite3 db, Index pIdx ) { #if SQLITE_ENABLE_STAT2 if ( pIdx.aSample != null ) { int j; for ( j = 0; j < SQLITE_INDEX_SAMPLES; j++ ) { IndexSample p = pIdx.aSample[j]; if ( p.eType == SQLITE_TEXT || p.eType == SQLITE_BLOB ) { p.u.z = null;//sqlite3DbFree(db, p.u.z); p.u.zBLOB = null; } } sqlite3DbFree( db, ref pIdx.aSample ); } #else UNUSED_PARAMETER(db); UNUSED_PARAMETER( pIdx ); #endif } /* ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[] ** arrays. The contents of sqlite_stat2 are used to populate the ** Index.aSample[] arrays. ** ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined ** during compilation and the sqlite_stat2 table is present, no data is ** read from it. ** ** If SQLITE_ENABLE_STAT2 was defined during compilation and the ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is ** returned. However, in this case, data is read from the sqlite_stat1 ** table (if it is present) before returning. ** ** If an OOM error occurs, this function always sets db.mallocFailed. ** This means if the caller does not care about other errors, the return ** code may be ignored. */ static int sqlite3AnalysisLoad( sqlite3 db, int iDb ) { analysisInfo sInfo; HashElem i; string zSql; int rc; Debug.Assert( iDb >= 0 && iDb < db.nDb ); Debug.Assert( db.aDb[iDb].pBt != null ); /* Clear any prior statistics */ Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) ); //for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){ for ( i = db.aDb[iDb].pSchema.idxHash.first; i != null; i = i.next ) { Index pIdx = (Index)i.data;// sqliteHashData( i ); sqlite3DefaultRowEst( pIdx ); sqlite3DeleteIndexSamples( db, pIdx ); pIdx.aSample = null; } /* Check to make sure the sqlite_stat1 table exists */ sInfo.db = db; sInfo.zDatabase = db.aDb[iDb].zName; if ( sqlite3FindTable( db, "sqlite_stat1", sInfo.zDatabase ) == null ) { return SQLITE_ERROR; } /* Load new statistics out of the sqlite_stat1 table */ zSql = sqlite3MPrintf( db, "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase ); //if ( zSql == null ) //{ // rc = SQLITE_NOMEM; //} //else { rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 ); sqlite3DbFree( db, ref zSql ); } /* Load the statistics from the sqlite_stat2 table. */ #if SQLITE_ENABLE_STAT2 if ( rc == SQLITE_OK && null == sqlite3FindTable( db, "sqlite_stat2", sInfo.zDatabase ) ) { rc = SQLITE_ERROR; } if ( rc == SQLITE_OK ) { sqlite3_stmt pStmt = null; zSql = sqlite3MPrintf( db, "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase ); //if( null==zSql ){ //rc = SQLITE_NOMEM; //}else{ rc = sqlite3_prepare( db, zSql, -1, ref pStmt, 0 ); sqlite3DbFree( db, ref zSql ); //} if ( rc == SQLITE_OK ) { while ( sqlite3_step( pStmt ) == SQLITE_ROW ) { string zIndex; /* Index name */ Index pIdx; /* Pointer to the index object */ zIndex = sqlite3_column_text( pStmt, 0 ); pIdx = !String.IsNullOrEmpty( zIndex ) ? sqlite3FindIndex( db, zIndex, sInfo.zDatabase ) : null; if ( pIdx != null ) { int iSample = sqlite3_column_int( pStmt, 1 ); if ( iSample < SQLITE_INDEX_SAMPLES && iSample >= 0 ) { int eType = sqlite3_column_type( pStmt, 2 ); if ( pIdx.aSample == null ) { //static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES; //pIdx->aSample = (IndexSample )sqlite3DbMallocRaw(0, sz); //if( pIdx.aSample==0 ){ //db.mallocFailed = 1; //break; //} pIdx.aSample = new IndexSample[SQLITE_INDEX_SAMPLES];//memset(pIdx->aSample, 0, sz); } //Debug.Assert( pIdx.aSample != null ); if ( pIdx.aSample[iSample] == null ) pIdx.aSample[iSample] = new IndexSample(); IndexSample pSample = pIdx.aSample[iSample]; { pSample.eType = (u8)eType; if ( eType == SQLITE_INTEGER || eType == SQLITE_FLOAT ) { pSample.u.r = sqlite3_column_double( pStmt, 2 ); } else if ( eType == SQLITE_TEXT || eType == SQLITE_BLOB ) { string z = null; byte[] zBLOB = null; //string z = (string )( //(eType==SQLITE_BLOB) ? //sqlite3_column_blob(pStmt, 2): //sqlite3_column_text(pStmt, 2) //); if ( eType == SQLITE_BLOB ) zBLOB = sqlite3_column_blob( pStmt, 2 ); else z = sqlite3_column_text( pStmt, 2 ); int n = sqlite3_column_bytes( pStmt, 2 ); if ( n > 24 ) { n = 24; } pSample.nByte = (u8)n; if ( n < 1 ) { pSample.u.z = null; pSample.u.zBLOB = null; } else { pSample.u.z = z; pSample.u.zBLOB = zBLOB; //pSample->u.z = sqlite3DbMallocRaw(dbMem, n); //if( pSample->u.z ){ // memcpy(pSample->u.z, z, n); //}else{ // db->mallocFailed = 1; // break; //} } } } } } } rc = sqlite3_finalize( pStmt ); } } #endif //if( rc==SQLITE_NOMEM ){ // db.mallocFailed = 1; //} return rc; } #endif // * SQLITE_OMIT_ANALYZE */ } }
#region Using using System; using System.Collections.Generic; using FlatRedBall; using FlatRedBall.Graphics; #if !SILVERLIGHT using FlatRedBall.Graphics.Model; #endif using FlatRedBall.ManagedSpriteGroups; using FlatRedBall.Math; using FlatRedBall.Math.Geometry; using FlatRedBall.Gui; using FlatRedBall.Utilities; using FlatRedBall.IO; #if WINDOWS_PHONE using System.IO.IsolatedStorage; using Microsoft.Phone.Shell; #endif #endregion namespace PlatformerSample.Screens { public static partial class ScreenManager { #region Fields private static Screen mCurrentScreen; private static bool mSuppressStatePush = false; #if !MONODROID && !FRB_MDX && !SILVERLIGHT private static BackStack<StackItem?> mBackStack = new BackStack<StackItem?>(); #endif private static bool mWarnIfNotEmptyBetweenScreens = true; private static int mNumberOfFramesSinceLastScreenLoad = 0; private static Layer mNextScreenLayer; // The ScreenManager can be told to ignore certain objects which // we recognize will persist from screen to screen. This should // NOT be used as a solution to get around the ScreenManager's check. private static PositionedObjectList<Camera> mPersistentCameras = new PositionedObjectList<Camera>(); private static PositionedObjectList<SpriteFrame> mPersistentSpriteFrames = new PositionedObjectList<SpriteFrame>(); private static PositionedObjectList<Text> mPersistentTexts = new PositionedObjectList<Text>(); #endregion #region Properties public static Screen CurrentScreen { get { return mCurrentScreen; } } public static Layer NextScreenLayer { get { return mNextScreenLayer; } } public static PositionedObjectList<Camera> PersistentCameras { get { return mPersistentCameras; } } public static PositionedObjectList<SpriteFrame> PersistentSpriteFrames { get { return mPersistentSpriteFrames; } } public static PositionedObjectList<Text> PersistentTexts { get { return mPersistentTexts; } } public static bool WarnIfNotEmptyBetweenScreens { get { return mWarnIfNotEmptyBetweenScreens; } set { mWarnIfNotEmptyBetweenScreens = value; } } public static bool ShouldActivateScreen { get; set; } public static Action<string> RehydrateAction { get; set; } #endregion #region Methods #region Public Methods #if !MONODROID && !FRB_MDX && !SILVERLIGHT public static void PushStateToStack(int state) { if (!mSuppressStatePush && PlatformServices.BackStackEnabled) { mBackStack.MoveTo(new StackItem { State = state }); } } public static void NavigateBack() { if (!PlatformServices.BackStackEnabled) { return; } StackItem? stackResult = null; // screens are added when moving to a new screen, while states are added as you move if (mBackStack.Current.HasValue && !string.IsNullOrEmpty(mBackStack.Current.Value.Screen)) { stackResult = mBackStack.Current.Value; mBackStack.Back(); } else { stackResult = mBackStack.Back(); } if (!stackResult.HasValue) { // if we've gone to the beginning of the back stack, we should exit the game FlatRedBallServices.Game.Exit(); return; } StackItem stackItem = stackResult.Value; if (!string.IsNullOrEmpty(stackItem.Screen)) { mCurrentScreen.NextScreen = stackItem.Screen; mCurrentScreen.IsActivityFinished = true; mCurrentScreen.IsMovingBack = true; } else if (stackItem.State > -1) { // states are set as they are moved to, so if this is the last state, we should exit if (mBackStack.Count == 0) { FlatRedBallServices.Game.Exit(); return; } mCurrentScreen.MoveToState(stackItem.State); } } #endif #region XML Docs /// <summary> /// Calls activity on the current screen and checks to see if screen /// activity is finished. If activity is finished, the current Screen's /// NextScreen is loaded. /// </summary> #endregion public static void Activity() { if (mCurrentScreen == null) return; mCurrentScreen.Activity(false); mCurrentScreen.ActivityCallCount++; if (mCurrentScreen.IsActivityFinished) { GuiManager.Cursor.IgnoreNextClick = true; string type = mCurrentScreen.NextScreen; Screen asyncLoadedScreen = mCurrentScreen.mNextScreenToLoadAsync; #if !MONODROID && !FRB_MDX && !SILVERLIGHT if (!mCurrentScreen.IsMovingBack && PlatformServices.BackStackEnabled) { StackItem item = new StackItem { Screen = mCurrentScreen.GetType().FullName, State = -1 }; mBackStack.MoveTo(item, mCurrentScreen.BackStackBehavior); } #endif mCurrentScreen.Destroy(); // check to see if there is any leftover data CheckAndWarnIfNotEmpty(); // Let's perform a GC here. GC.Collect(); GC.WaitForPendingFinalizers(); if (asyncLoadedScreen == null) { // Loads the Screen, suspends input for one frame, and // calls Activity on the Screen. // The Activity call is required for objects like SpriteGrids // which need to be managed internally. // No need to assign mCurrentScreen - this is done by the 4th argument "true" //mCurrentScreen = LoadScreen(type, null, true, true); mNumberOfFramesSinceLastScreenLoad = 0; } else { mCurrentScreen = asyncLoadedScreen; mCurrentScreen.AddToManagers(); mCurrentScreen.Activity(true); mCurrentScreen.ActivityCallCount++; mNumberOfFramesSinceLastScreenLoad = 0; } } else { mNumberOfFramesSinceLastScreenLoad++; } } public static Screen LoadScreen(string screen, bool createNewLayer) { if (createNewLayer) { return LoadScreen(screen, SpriteManager.AddLayer()); } else { return LoadScreen(screen, (Layer)null); } } public static T LoadScreen<T>(Layer layerToLoadScreenOn) where T : Screen { mNextScreenLayer = layerToLoadScreenOn; #if XBOX360 T newScreen = (T)Activator.CreateInstance(typeof(T)); #else T newScreen = (T)Activator.CreateInstance(typeof(T), new object[0]); #endif FlatRedBall.Input.InputManager.CurrentFrameInputSuspended = true; newScreen.Initialize(true); #if !MONODROID && !FRB_MDX && !SILVERLIGHT if (mBackStack.Current.HasValue && mBackStack.Current.Value.State > -1 && PlatformServices.BackStackEnabled) { newScreen.MoveToState(mBackStack.Current.Value.State); } #endif newScreen.Activity(true); newScreen.ActivityCallCount++; return newScreen; } public static Screen LoadScreen(string screen, Layer layerToLoadScreenOn) { return LoadScreen(screen, layerToLoadScreenOn, true, false); } public static Screen LoadScreen(string screen, Layer layerToLoadScreenOn, bool addToManagers, bool makeCurrentScreen) { mNextScreenLayer = layerToLoadScreenOn; Screen newScreen = null; Type typeOfScreen = Type.GetType(screen); if (typeOfScreen == null) { throw new System.ArgumentException("There is no " + screen + " class defined in your project or linked assemblies."); } if (screen != null && screen != "") { #if XBOX360 newScreen = (Screen)Activator.CreateInstance(typeOfScreen); #else newScreen = (Screen)Activator.CreateInstance(typeOfScreen, new object[0]); #endif } if (newScreen != null) { FlatRedBall.Input.InputManager.CurrentFrameInputSuspended = true; #if !MONODROID && !FRB_MDX && !SILVERLIGHT mSuppressStatePush = mBackStack.Current.HasValue && mBackStack.Current.Value.State > -1; #endif newScreen.Initialize(addToManagers); #if !MONODROID && !FRB_MDX && !SILVERLIGHT if (mSuppressStatePush) { newScreen.MoveToState(mBackStack.Current.Value.State); } #endif mSuppressStatePush = false; if (addToManagers) { // We do this so that new Screens are the CurrentScreen in Activity. // This is useful in custom logic. if (makeCurrentScreen) { mCurrentScreen = newScreen; } newScreen.Activity(true); newScreen.ActivityCallCount++; } } return newScreen; } public static void Start<T>() where T : Screen, new() { mCurrentScreen = LoadScreen<T>(null); } #region XML Docs /// <summary> /// Loads a screen. Should only be called once during initialization. /// </summary> /// <param name="screenToStartWith">Qualified name of the class to load.</param> #endregion public static void Start(string screenToStartWith) { if (mCurrentScreen != null) { throw new InvalidOperationException("You can't call Start if there is already a Screen. Did you call Start twice?"); } else { #if !FRB_MDX StateManager.Current.Activating += new Action(OnStateActivating); StateManager.Current.Deactivating += new Action(OnStateDeactivating); StateManager.Current.Initialize(); #if !MONODROID && !SILVERLIGHT //if the state manager overwrote the backstack from tombstone (WP7), it will have a different current, //otherwise, it will be the same value as screenToStartWith. if (mBackStack.Count > 0) { System.Diagnostics.Debug.WriteLine("resuming with backstack containing " + mBackStack.Count + " items with current being " + mBackStack.Current.Value.Screen); screenToStartWith = mBackStack.Current.Value.Screen; mBackStack.Back(); } #endif #endif if (ShouldActivateScreen && RehydrateAction != null) { RehydrateAction(screenToStartWith); } else { mCurrentScreen = LoadScreen(screenToStartWith, null, true, true); ShouldActivateScreen = false; } } } /// <summary>Do all state deactivation work here.</summary> private static void OnStateDeactivating() { #if !MONODROID && !FRB_MDX && !SILVERLIGHT mBackStack.MoveTo(new StackItem { Screen = mCurrentScreen.GetType().FullName, State = -1 }); StateManager.Current["backstack"] = mBackStack; #endif } /// <summary>Do all state activation work here</summary> private static void OnStateActivating() { #if !MONODROID && !FRB_MDX && !SILVERLIGHT mBackStack = StateManager.Current.Get<BackStack<StackItem?>>("backstack"); ShouldActivateScreen = true; #endif } public static new string ToString() { if (mCurrentScreen != null) return mCurrentScreen.ToString(); else return "No Current Screen"; } #endregion #region Private Methods public static void CheckAndWarnIfNotEmpty() { if (WarnIfNotEmptyBetweenScreens) { List<string> messages = new List<string>(); // the user wants to make sure that the Screens have cleaned up everything // after being destroyed. Check the data to make sure it's all empty. #region Make sure there's only 1 non-persistent Camera left if (SpriteManager.Cameras.Count > 1) { int count = SpriteManager.Cameras.Count; foreach (Camera camera in mPersistentCameras) { if (SpriteManager.Cameras.Contains(camera)) { count--; } } if (count > 1) { messages.Add("There are " + count + " Cameras in the SpriteManager (excluding ignored Cameras). There should only be 1."); } } #endregion #region Make sure that the Camera doesn't have any extra layers if (SpriteManager.Camera.Layers.Count > 1) { messages.Add("There are " + SpriteManager.Camera.Layers.Count + " Layers on the default Camera. There should only be 1"); } #endregion #region Automatically updated Sprites if (SpriteManager.AutomaticallyUpdatedSprites.Count != 0) { int spriteCount = SpriteManager.AutomaticallyUpdatedSprites.Count; foreach (SpriteFrame spriteFrame in mPersistentSpriteFrames) { foreach (Sprite sprite in SpriteManager.AutomaticallyUpdatedSprites) { if (spriteFrame.IsSpriteComponentOfThis(sprite)) { spriteCount--; } } } if (spriteCount != 0) { messages.Add("There are " + spriteCount + " AutomaticallyUpdatedSprites in the SpriteManager."); } } #endregion #region Manually updated Sprites if (SpriteManager.ManuallyUpdatedSpriteCount != 0) messages.Add("There are " + SpriteManager.ManuallyUpdatedSpriteCount + " ManuallyUpdatedSprites in the SpriteManager."); #endregion #region Ordered by distance Sprites if (SpriteManager.OrderedSprites.Count != 0) { int spriteCount = SpriteManager.OrderedSprites.Count; foreach (SpriteFrame spriteFrame in mPersistentSpriteFrames) { foreach (Sprite sprite in SpriteManager.OrderedSprites) { if (spriteFrame.IsSpriteComponentOfThis(sprite)) { spriteCount--; } } } if (spriteCount != 0) { messages.Add("There are " + spriteCount + " Ordered (Drawn) Sprites in the SpriteManager."); } } #endregion #region Managed Positionedobjects if (SpriteManager.ManagedPositionedObjects.Count != 0) messages.Add("There are " + SpriteManager.ManagedPositionedObjects.Count + " Managed PositionedObjects in the SpriteManager."); #endregion #region Layers if (SpriteManager.LayerCount != 0) messages.Add("There are " + SpriteManager.LayerCount + " Layers in the SpriteManager."); #endregion #region TopLayer if (SpriteManager.TopLayer.Sprites.Count != 0) { messages.Add("There are " + SpriteManager.TopLayer.Sprites.Count + " Sprites in the SpriteManager's TopLayer."); } #endregion #region Particles if (SpriteManager.ParticleCount != 0) messages.Add("There are " + SpriteManager.ParticleCount + " Particle Sprites in the SpriteManager."); #endregion #region SpriteFrames if (SpriteManager.SpriteFrames.Count != 0) { int spriteFrameCount = SpriteManager.SpriteFrames.Count; foreach (SpriteFrame spriteFrame in mPersistentSpriteFrames) { if (SpriteManager.SpriteFrames.Contains(spriteFrame)) { spriteFrameCount--; } } if (spriteFrameCount != 0) { messages.Add("There are " + spriteFrameCount + " SpriteFrames in the SpriteManager."); } } #endregion #region Text objects if (TextManager.AutomaticallyUpdatedTexts.Count != 0) { int textCount = TextManager.AutomaticallyUpdatedTexts.Count; foreach (Text text in mPersistentTexts) { if (TextManager.AutomaticallyUpdatedTexts.Contains(text)) { textCount--; } } if (textCount != 0) { messages.Add("There are " + textCount + "automatically updated Texts in the TextManager."); } } #endregion #region Managed Shapes if (ShapeManager.AutomaticallyUpdatedShapes.Count != 0) messages.Add("There are " + ShapeManager.AutomaticallyUpdatedShapes.Count + " Automatically Updated Shapes in the ShapeManager."); #endregion #region Visible Circles if (ShapeManager.VisibleCircles.Count != 0) messages.Add("There are " + ShapeManager.VisibleCircles.Count + " visible Circles in the ShapeManager."); #endregion #region Visible Rectangles if (ShapeManager.VisibleRectangles.Count != 0) messages.Add("There are " + ShapeManager.VisibleRectangles.Count + " visible AxisAlignedRectangles in the VisibleRectangles."); #endregion #region Visible Polygons if (ShapeManager.VisiblePolygons.Count != 0) messages.Add("There are " + ShapeManager.VisiblePolygons.Count + " visible Polygons in the ShapeManager."); #endregion #region Visible Lines if (ShapeManager.VisibleLines.Count != 0) messages.Add("There are " + ShapeManager.VisibleLines.Count + " visible Lines in the ShapeManager."); #endregion #region Automatically Updated Positioned Models #if !SILVERLIGHT && !MONODROID && !WINDOWS_8 if (ModelManager.AutomaticallyUpdatedModels.Count != 0) { messages.Add("There are " + ModelManager.AutomaticallyUpdatedModels.Count + " managed PositionedModels in the ModelManager."); } #endif #endregion if (messages.Count != 0) { string errorString = "The Screen that was just unloaded did not clean up after itself:"; foreach (string s in messages) errorString += "\n" + s; throw new System.Exception(errorString); } } } #endregion #endregion } }
// XslCompiledTransform.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2005 Novell Inc. http://www.novell.com // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.CodeDom.Compiler; using System.Collections; using System.IO; using System.Text; using System.Runtime.InteropServices; using System.Security; using System.Security.Policy; using System.Xml.XPath; using Mono.Xml.Xsl; namespace System.Xml.Xsl { [MonoTODO] // FIXME: Of cource this is just a stub for now. public sealed class XslCompiledTransform { bool enable_debug; object debugger; CompiledStylesheet s; #if !TARGET_JVM && !MOBILE // TempFileCollection temporary_files; #endif XmlWriterSettings output_settings = new XmlWriterSettings (); public XslCompiledTransform () : this (false) { } public XslCompiledTransform (bool enableDebug) { enable_debug = enableDebug; if (enable_debug) debugger = new NoOperationDebugger (); output_settings.ConformanceLevel = ConformanceLevel.Fragment; } [MonoTODO] public XmlWriterSettings OutputSettings { get { return output_settings; } } #if !TARGET_JVM && !MOBILE [MonoTODO] public TempFileCollection TemporaryFiles { get { return null; /*temporary_files;*/ } } #endif #region Transform public void Transform (string inputUri, string resultsFile) { using (Stream outStream = File.Create (resultsFile)) { Transform (new XPathDocument (inputUri, XmlSpace.Preserve), null, outStream); } } public void Transform (string inputUri, XmlWriter results) { Transform (inputUri, null, results); } public void Transform (string inputUri, XsltArgumentList arguments, Stream results) { Transform (new XPathDocument (inputUri, XmlSpace.Preserve), arguments, results); } public void Transform (string inputUri, XsltArgumentList arguments, TextWriter results) { Transform (new XPathDocument (inputUri, XmlSpace.Preserve), arguments, results); } public void Transform (string inputUri, XsltArgumentList arguments, XmlWriter results) { Transform (new XPathDocument (inputUri, XmlSpace.Preserve), arguments, results); } public void Transform (XmlReader input, XmlWriter results) { Transform (input, null, results); } public void Transform (XmlReader input, XsltArgumentList arguments, Stream results) { Transform (new XPathDocument (input, XmlSpace.Preserve), arguments, results); } public void Transform (XmlReader input, XsltArgumentList arguments, TextWriter results) { Transform (new XPathDocument (input, XmlSpace.Preserve), arguments, results); } public void Transform (XmlReader input, XsltArgumentList arguments, XmlWriter results) { Transform (input, arguments, results, null); } public void Transform (IXPathNavigable input, XsltArgumentList arguments, TextWriter results) { Transform (input.CreateNavigator (), arguments, results); } public void Transform (IXPathNavigable input, XsltArgumentList arguments, Stream results) { Transform (input.CreateNavigator (), arguments, results); } public void Transform (IXPathNavigable input, XmlWriter results) { Transform (input, null, results); } public void Transform (IXPathNavigable input, XsltArgumentList arguments, XmlWriter results) { Transform (input.CreateNavigator (), arguments, results, null); } public void Transform (XmlReader input, XsltArgumentList arguments, XmlWriter results, XmlResolver documentResolver) { Transform (new XPathDocument (input, XmlSpace.Preserve).CreateNavigator (), arguments, results, documentResolver); } void Transform (XPathNavigator input, XsltArgumentList args, XmlWriter output, XmlResolver resolver) { if (s == null) throw new XsltException ("No stylesheet was loaded.", null); Outputter outputter = new GenericOutputter (output, s.Outputs, null); new XslTransformProcessor (s, debugger).Process (input, outputter, args, resolver); output.Flush (); } void Transform (XPathNavigator input, XsltArgumentList args, Stream output) { XslOutput xslOutput = (XslOutput)s.Outputs[String.Empty]; Transform (input, args, new StreamWriter (output, xslOutput.Encoding)); } void Transform (XPathNavigator input, XsltArgumentList args, TextWriter output) { if (s == null) throw new XsltException ("No stylesheet was loaded.", null); Outputter outputter = new GenericOutputter(output, s.Outputs, output.Encoding); new XslTransformProcessor (s, debugger).Process (input, outputter, args, null); outputter.Done (); output.Flush (); } #endregion #region Load private XmlReader GetXmlReader (string url) { XmlResolver res = new XmlUrlResolver (); Uri uri = res.ResolveUri (null, url); Stream s = res.GetEntity (uri, null, typeof (Stream)) as Stream; XmlTextReader xtr = new XmlTextReader (uri.ToString (), s); xtr.XmlResolver = res; XmlValidatingReader xvr = new XmlValidatingReader (xtr); xvr.XmlResolver = res; xvr.ValidationType = ValidationType.None; return xvr; } public void Load (string stylesheetUri) { using (XmlReader r = GetXmlReader (stylesheetUri)) { Load (r); } } public void Load (XmlReader stylesheet) { Load (stylesheet, null, null); } public void Load (IXPathNavigable stylesheet) { Load (stylesheet.CreateNavigator(), null, null); } public void Load (IXPathNavigable stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { Load (stylesheet.CreateNavigator(), settings, stylesheetResolver); } public void Load (XmlReader stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { Load (new XPathDocument (stylesheet, XmlSpace.Preserve).CreateNavigator (), settings, stylesheetResolver); } public void Load (string stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) { Load (new XPathDocument (stylesheetUri, XmlSpace.Preserve).CreateNavigator (), settings, stylesheetResolver); } private void Load (XPathNavigator stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) { s = new Compiler (debugger).Compile (stylesheet, stylesheetResolver, null); } #endregion } class NoOperationDebugger { protected void OnCompile (XPathNavigator input) { } protected void OnExecute (XPathNodeIterator currentNodeset, XPathNavigator style, XsltContext context) { //ShowLocationInTrace (style); } /* string ShowLocationInTrace (XPathNavigator style) { IXmlLineInfo li = style as IXmlLineInfo; return li != null ? String.Format ("at {0} ({1},{2})", style.BaseURI, li.LineNumber, li.LinePosition) : "(no debug info available)"; } */ } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage.Table; using Newtonsoft.Json; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.AzureStorage { public class AzureTableTransactionalStateStorage<TState> : ITransactionalStateStorage<TState> where TState : class, new() { private readonly CloudTable table; private readonly string partition; private readonly JsonSerializerSettings jsonSettings; private readonly ILogger logger; private KeyEntity key; private List<KeyValuePair<long, StateEntity>> states; public AzureTableTransactionalStateStorage(CloudTable table, string partition, JsonSerializerSettings JsonSettings, ILogger<AzureTableTransactionalStateStorage<TState>> logger) { this.table = table; this.partition = partition; this.jsonSettings = JsonSettings; this.logger = logger; // default values must be included // otherwise, we get errors for explicitly specified default values // (e.g. Orleans.Transactions.Azure.Tests.TestState.state) this.jsonSettings.DefaultValueHandling = DefaultValueHandling.Include; } public async Task<TransactionalStorageLoadResponse<TState>> Load() { try { var keyTask = ReadKey(); var statesTask = ReadStates(); key = await keyTask.ConfigureAwait(false); states = await statesTask.ConfigureAwait(false); if (string.IsNullOrEmpty(key.ETag)) { if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug($"{partition} Loaded v0, fresh"); // first time load return new TransactionalStorageLoadResponse<TState>(); } else { TState committedState; if (this.key.CommittedSequenceId == 0) { committedState = new TState(); } else { if (!FindState(this.key.CommittedSequenceId, out var pos)) { var error = $"Storage state corrupted: no record for committed state v{this.key.CommittedSequenceId}"; logger.LogCritical($"{partition} {error}"); throw new InvalidOperationException(error); } committedState = states[pos].Value.GetState<TState>(this.jsonSettings); } var PrepareRecordsToRecover = new List<PendingTransactionState<TState>>(); for (int i = 0; i < states.Count; i++) { var kvp = states[i]; // pending states for already committed transactions can be ignored if (kvp.Key <= key.CommittedSequenceId) continue; // upon recovery, local non-committed transactions are considered aborted if (kvp.Value.TransactionManager == null) break; ParticipantId tm = JsonConvert.DeserializeObject<ParticipantId>(kvp.Value.TransactionManager, this.jsonSettings); PrepareRecordsToRecover.Add(new PendingTransactionState<TState>() { SequenceId = kvp.Key, State = kvp.Value.GetState<TState>(this.jsonSettings), TimeStamp = kvp.Value.TransactionTimestamp, TransactionId = kvp.Value.TransactionId, TransactionManager = tm }); } // clear the state strings... no longer needed, ok to GC now for (int i = 0; i < states.Count; i++) { states[i].Value.StateJson = null; } if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug($"{partition} Loaded v{this.key.CommittedSequenceId} rows={string.Join(",", states.Select(s => s.Key.ToString("x16")))}"); TransactionalStateMetaData metadata = JsonConvert.DeserializeObject<TransactionalStateMetaData>(this.key.Metadata, this.jsonSettings); return new TransactionalStorageLoadResponse<TState>(this.key.ETag, committedState, this.key.CommittedSequenceId, metadata, PrepareRecordsToRecover); } } catch (Exception ex) { this.logger.LogError("Transactional state load failed {Exception}.", ex); throw; } } public async Task<string> Store(string expectedETag, TransactionalStateMetaData metadata, List<PendingTransactionState<TState>> statesToPrepare, long? commitUpTo, long? abortAfter) { if (this.key.ETag != expectedETag) throw new ArgumentException(nameof(expectedETag), "Etag does not match"); // assemble all storage operations into a single batch // these operations must commit in sequence, but not necessarily atomically // so we can split this up if needed var batchOperation = new BatchOperation(logger, key, table); // first, clean up aborted records if (abortAfter.HasValue && states.Count != 0) { while (states.Count > 0 && states[states.Count - 1].Key > abortAfter) { var entity = states[states.Count - 1].Value; await batchOperation.Add(TableOperation.Delete(entity)).ConfigureAwait(false); states.RemoveAt(states.Count - 1); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace($"{partition}.{entity.RowKey} Delete {entity.TransactionId}"); } } // second, persist non-obsolete prepare records var obsoleteBefore = commitUpTo.HasValue ? commitUpTo.Value : key.CommittedSequenceId; if (statesToPrepare != null) foreach (var s in statesToPrepare) if (s.SequenceId >= obsoleteBefore) { if (FindState(s.SequenceId, out var pos)) { // overwrite with new pending state StateEntity existing = states[pos].Value; existing.TransactionId = s.TransactionId; existing.TransactionTimestamp = s.TimeStamp; existing.TransactionManager = JsonConvert.SerializeObject(s.TransactionManager, this.jsonSettings); existing.SetState(s.State, this.jsonSettings); await batchOperation.Add(TableOperation.Replace(existing)).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace($"{partition}.{existing.RowKey} Update {existing.TransactionId}"); } else { var entity = StateEntity.Create(this.jsonSettings, this.partition, s); await batchOperation.Add(TableOperation.Insert(entity)).ConfigureAwait(false); states.Insert(pos, new KeyValuePair<long, StateEntity>(s.SequenceId, entity)); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace($"{partition}.{entity.RowKey} Insert {entity.TransactionId}"); } } // third, persist metadata and commit position key.Metadata = JsonConvert.SerializeObject(metadata, this.jsonSettings); if (commitUpTo.HasValue && commitUpTo.Value > key.CommittedSequenceId) { key.CommittedSequenceId = commitUpTo.Value; } if (string.IsNullOrEmpty(this.key.ETag)) { await batchOperation.Add(TableOperation.Insert(this.key)).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace($"{partition}.{KeyEntity.RK} Insert. v{this.key.CommittedSequenceId}, {metadata.CommitRecords.Count}c"); } else { await batchOperation.Add(TableOperation.Replace(this.key)).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace($"{partition}.{KeyEntity.RK} Update. v{this.key.CommittedSequenceId}, {metadata.CommitRecords.Count}c"); } // fourth, remove obsolete records if (states.Count > 0 && states[0].Key < obsoleteBefore) { FindState(obsoleteBefore, out var pos); for (int i = 0; i < pos; i++) { await batchOperation.Add(TableOperation.Delete(states[i].Value)).ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace($"{partition}.{states[i].Value.RowKey} Delete {states[i].Value.TransactionId}"); } states.RemoveRange(0, pos); } await batchOperation.Flush().ConfigureAwait(false); if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug($"{partition} Stored v{this.key.CommittedSequenceId} eTag={key.ETag}"); return key.ETag; } private bool FindState(long sequenceId, out int pos) { pos = 0; while (pos < states.Count) { switch (states[pos].Key.CompareTo(sequenceId)) { case 0: return true; case -1: pos++; continue; case 1: return false; } } return false; } private async Task<KeyEntity> ReadKey() { var query = new TableQuery<KeyEntity>() .Where(AzureStorageUtils.PointQuery(this.partition, KeyEntity.RK)); TableQuerySegment<KeyEntity> queryResult = await table.ExecuteQuerySegmentedAsync(query, null).ConfigureAwait(false); return queryResult.Results.Count == 0 ? new KeyEntity() { PartitionKey = this.partition } : queryResult.Results[0]; } private async Task<List<KeyValuePair<long, StateEntity>>> ReadStates() { var query = new TableQuery<StateEntity>() .Where(AzureStorageUtils.RangeQuery(this.partition, StateEntity.RK_MIN, StateEntity.RK_MAX)); TableContinuationToken continuationToken = null; var results = new List<KeyValuePair<long, StateEntity>>(); do { TableQuerySegment<StateEntity> queryResult = await table.ExecuteQuerySegmentedAsync(query, continuationToken).ConfigureAwait(false); foreach (var x in queryResult.Results) { results.Add(new KeyValuePair<long, StateEntity>(x.SequenceId, x)); }; continuationToken = queryResult.ContinuationToken; } while (continuationToken != null); return results; } private class BatchOperation { private readonly TableBatchOperation batchOperation; private readonly ILogger logger; private readonly KeyEntity key; private readonly CloudTable table; private bool batchContainsKey; public BatchOperation(ILogger logger, KeyEntity key, CloudTable table) { this.batchOperation = new TableBatchOperation(); this.logger = logger; this.key = key; this.table = table; } public async Task Add(TableOperation operation) { batchOperation.Add(operation); if (operation.Entity == key) { batchContainsKey = true; } if (batchOperation.Count == AzureTableConstants.MaxBatchSize - (batchContainsKey ? 0 : 1)) { // the key serves as a synchronizer, to prevent modification by multiple grains under edge conditions, // like duplicate activations or deployments.Every batch write needs to include the key, // even if the key values don't change. if (!batchContainsKey) { if (string.IsNullOrEmpty(key.ETag)) batchOperation.Insert(key); else batchOperation.Replace(key); } await Flush().ConfigureAwait(false); batchOperation.Clear(); batchContainsKey = false; } } public async Task Flush() { if (batchOperation.Count > 0) try { await table.ExecuteBatchAsync(batchOperation).ConfigureAwait(false); batchOperation.Clear(); batchContainsKey = false; if (logger.IsEnabled(LogLevel.Trace)) { for (int i = 0; i < batchOperation.Count; i++) logger.LogTrace($"{batchOperation[i].Entity.PartitionKey}.{batchOperation[i].Entity.RowKey} batch-op ok {i}"); } } catch (Exception ex) { if (logger.IsEnabled(LogLevel.Trace)) { for (int i = 0; i < batchOperation.Count; i++) logger.LogTrace($"{batchOperation[i].Entity.PartitionKey}.{batchOperation[i].Entity.RowKey} batch-op failed {i}"); } this.logger.LogError("Transactional state store failed {Exception}.", ex); throw; } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace iTrellis.ToDo.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Policy; using Prism.Properties; namespace Prism.Modularity { /// <summary> /// Represets a catalog created from a directory on disk. /// </summary> /// <remarks> /// The directory catalog will scan the contents of a directory, locating classes that implement /// <see cref="IModule"/> and add them to the catalog based on contents in their associated <see cref="ModuleAttribute"/>. /// Assemblies are loaded into a new application domain with ReflectionOnlyLoad. The application domain is destroyed /// once the assemblies have been discovered. /// /// The diretory catalog does not continue to monitor the directory after it has created the initialze catalog. /// </remarks> public class DirectoryModuleCatalog : ModuleCatalog { /// <summary> /// Directory containing modules to search for. /// </summary> public string ModulePath { get; set; } /// <summary> /// Drives the main logic of building the child domain and searching for the assemblies. /// </summary> protected override void InnerLoad() { if (string.IsNullOrEmpty(this.ModulePath)) throw new InvalidOperationException(Resources.ModulePathCannotBeNullOrEmpty); if (!Directory.Exists(this.ModulePath)) throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.DirectoryNotFound, this.ModulePath)); AppDomain childDomain = this.BuildChildDomain(AppDomain.CurrentDomain); try { List<string> loadedAssemblies = new List<string>(); var assemblies = ( from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() where !(assembly is System.Reflection.Emit.AssemblyBuilder) && assembly.GetType().FullName != "System.Reflection.Emit.InternalAssemblyBuilder" && !String.IsNullOrEmpty(assembly.Location) select assembly.Location ); loadedAssemblies.AddRange(assemblies); Type loaderType = typeof(InnerModuleInfoLoader); if (loaderType.Assembly != null) { var loader = (InnerModuleInfoLoader) childDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap(); loader.LoadAssemblies(loadedAssemblies); this.Items.AddRange(loader.GetModuleInfos(this.ModulePath)); } } finally { AppDomain.Unload(childDomain); } } /// <summary> /// Creates a new child domain and copies the evidence from a parent domain. /// </summary> /// <param name="parentDomain">The parent domain.</param> /// <returns>The new child domain.</returns> /// <remarks> /// Grabs the <paramref name="parentDomain"/> evidence and uses it to construct the new /// <see cref="AppDomain"/> because in a ClickOnce execution environment, creating an /// <see cref="AppDomain"/> will by default pick up the partial trust environment of /// the AppLaunch.exe, which was the root executable. The AppLaunch.exe does a /// create domain and applies the evidence from the ClickOnce manifests to /// create the domain that the application is actually executing in. This will /// need to be Full Trust for Prism applications. /// </remarks> /// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="parentDomain"/> is null.</exception> protected virtual AppDomain BuildChildDomain(AppDomain parentDomain) { if (parentDomain == null) throw new System.ArgumentNullException("parentDomain"); Evidence evidence = new Evidence(parentDomain.Evidence); AppDomainSetup setup = parentDomain.SetupInformation; return AppDomain.CreateDomain("DiscoveryRegion", evidence, setup); } private class InnerModuleInfoLoader : MarshalByRefObject { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal ModuleInfo[] GetModuleInfos(string path) { DirectoryInfo directory = new DirectoryInfo(path); ResolveEventHandler resolveEventHandler = delegate(object sender, ResolveEventArgs args) { return OnReflectionOnlyResolve(args, directory); }; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler; Assembly moduleReflectionOnlyAssembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().First( asm => asm.FullName == typeof(IModule).Assembly.FullName); Type IModuleType = moduleReflectionOnlyAssembly.GetType(typeof(IModule).FullName); IEnumerable<ModuleInfo> modules = GetNotAllreadyLoadedModuleInfos(directory, IModuleType); var array = modules.ToArray(); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler; return array; } private static IEnumerable<ModuleInfo> GetNotAllreadyLoadedModuleInfos(DirectoryInfo directory, Type IModuleType) { List<FileInfo> validAssemblies = new List<FileInfo>(); Assembly[] alreadyLoadedAssemblies = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies(); var fileInfos = directory.GetFiles("*.dll") .Where(file => alreadyLoadedAssemblies .FirstOrDefault( assembly => String.Compare(Path.GetFileName(assembly.Location), file.Name, StringComparison.OrdinalIgnoreCase) == 0) == null); foreach (FileInfo fileInfo in fileInfos) { try { Assembly.ReflectionOnlyLoadFrom(fileInfo.FullName); validAssemblies.Add(fileInfo); } catch (BadImageFormatException) { // skip non-.NET Dlls } } return validAssemblies.SelectMany(file => Assembly.ReflectionOnlyLoadFrom(file.FullName) .GetExportedTypes() .Where(IModuleType.IsAssignableFrom) .Where(t => t != IModuleType) .Where(t => !t.IsAbstract) .Select(type => CreateModuleInfo(type))); } private static Assembly OnReflectionOnlyResolve(ResolveEventArgs args, DirectoryInfo directory) { Assembly loadedAssembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault( asm => string.Equals(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase)); if (loadedAssembly != null) { return loadedAssembly; } AssemblyName assemblyName = new AssemblyName(args.Name); string dependentAssemblyFilename = Path.Combine(directory.FullName, assemblyName.Name + ".dll"); if (File.Exists(dependentAssemblyFilename)) { return Assembly.ReflectionOnlyLoadFrom(dependentAssemblyFilename); } return Assembly.ReflectionOnlyLoad(args.Name); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void LoadAssemblies(IEnumerable<string> assemblies) { foreach (string assemblyPath in assemblies) { try { Assembly.ReflectionOnlyLoadFrom(assemblyPath); } catch (FileNotFoundException) { // Continue loading assemblies even if an assembly can not be loaded in the new AppDomain } } } private static ModuleInfo CreateModuleInfo(Type type) { string moduleName = type.Name; List<string> dependsOn = new List<string>(); bool onDemand = false; var moduleAttribute = CustomAttributeData.GetCustomAttributes(type).FirstOrDefault( cad => cad.Constructor.DeclaringType.FullName == typeof(ModuleAttribute).FullName); if (moduleAttribute != null) { foreach (CustomAttributeNamedArgument argument in moduleAttribute.NamedArguments) { string argumentName = argument.MemberInfo.Name; switch (argumentName) { case "ModuleName": moduleName = (string) argument.TypedValue.Value; break; case "OnDemand": onDemand = (bool) argument.TypedValue.Value; break; case "StartupLoaded": onDemand = !((bool) argument.TypedValue.Value); break; } } } var moduleDependencyAttributes = CustomAttributeData.GetCustomAttributes(type).Where( cad => cad.Constructor.DeclaringType.FullName == typeof(ModuleDependencyAttribute).FullName); foreach (CustomAttributeData cad in moduleDependencyAttributes) { dependsOn.Add((string) cad.ConstructorArguments[0].Value); } ModuleInfo moduleInfo = new ModuleInfo(moduleName, type.AssemblyQualifiedName) { InitializationMode = onDemand ? InitializationMode.OnDemand : InitializationMode.WhenAvailable, Ref = type.Assembly.CodeBase, }; moduleInfo.DependsOn.AddRange(dependsOn); return moduleInfo; } } } }
#pragma warning disable IDE0051 #pragma warning disable IDE0060 using Neo.Cryptography.ECC; using Neo.IO; using Neo.Ledger; using Neo.Persistence; using Neo.VM; using Neo.VM.Types; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using VMArray = Neo.VM.Types.Array; namespace Neo.SmartContract.Native.Tokens { public sealed class NeoToken : Nep5Token<NeoToken.AccountState> { public override string ServiceName => "Neo.Native.Tokens.NEO"; public override string Name => "NEO"; public override string Symbol => "neo"; public override byte Decimals => 0; public BigInteger TotalAmount { get; } private const byte Prefix_Validator = 33; private const byte Prefix_ValidatorsCount = 15; private const byte Prefix_NextValidators = 14; internal NeoToken() { this.TotalAmount = 100000000 * Factor; } public override BigInteger TotalSupply(StoreView snapshot) { return TotalAmount; } protected override void OnBalanceChanging(ApplicationEngine engine, UInt160 account, AccountState state, BigInteger amount) { DistributeGas(engine, account, state); if (amount.IsZero) return; if (state.Votes.Length == 0) return; foreach (ECPoint pubkey in state.Votes) { StorageItem storage_validator = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_Validator, pubkey.ToArray())); ValidatorState state_validator = ValidatorState.FromByteArray(storage_validator.Value); state_validator.Votes += amount; storage_validator.Value = state_validator.ToByteArray(); } StorageItem storage_count = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_ValidatorsCount)); ValidatorsCountState state_count = ValidatorsCountState.FromByteArray(storage_count.Value); state_count.Votes[state.Votes.Length - 1] += amount; storage_count.Value = state_count.ToByteArray(); } private void DistributeGas(ApplicationEngine engine, UInt160 account, AccountState state) { BigInteger gas = CalculateBonus(engine.Snapshot, state.Balance, state.BalanceHeight, engine.Snapshot.PersistingBlock.Index); state.BalanceHeight = engine.Snapshot.PersistingBlock.Index; GAS.Mint(engine, account, gas); engine.Snapshot.Storages.GetAndChange(CreateAccountKey(account)).Value = state.ToByteArray(); } private BigInteger CalculateBonus(StoreView snapshot, BigInteger value, uint start, uint end) { if (value.IsZero || start >= end) return BigInteger.Zero; if (value.Sign < 0) throw new ArgumentOutOfRangeException(nameof(value)); BigInteger amount = BigInteger.Zero; uint ustart = start / Blockchain.DecrementInterval; if (ustart < Blockchain.GenerationAmount.Length) { uint istart = start % Blockchain.DecrementInterval; uint uend = end / Blockchain.DecrementInterval; uint iend = end % Blockchain.DecrementInterval; if (uend >= Blockchain.GenerationAmount.Length) { uend = (uint)Blockchain.GenerationAmount.Length; iend = 0; } if (iend == 0) { uend--; iend = Blockchain.DecrementInterval; } while (ustart < uend) { amount += (Blockchain.DecrementInterval - istart) * Blockchain.GenerationAmount[ustart]; ustart++; istart = 0; } amount += (iend - istart) * Blockchain.GenerationAmount[ustart]; } amount += (GAS.GetSysFeeAmount(snapshot, end - 1) - (start == 0 ? 0 : GAS.GetSysFeeAmount(snapshot, start - 1))) / GAS.Factor; return value * amount * GAS.Factor / TotalAmount; } internal override bool Initialize(ApplicationEngine engine) { if (!base.Initialize(engine)) return false; if (base.TotalSupply(engine.Snapshot) != BigInteger.Zero) return false; UInt160 account = Contract.CreateMultiSigRedeemScript(Blockchain.StandbyValidators.Length / 2 + 1, Blockchain.StandbyValidators).ToScriptHash(); Mint(engine, account, TotalAmount); foreach (ECPoint pubkey in Blockchain.StandbyValidators) RegisterValidator(engine.Snapshot, pubkey); return true; } protected override bool OnPersist(ApplicationEngine engine) { if (!base.OnPersist(engine)) return false; StorageItem storage = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_NextValidators), () => new StorageItem()); storage.Value = GetValidators(engine.Snapshot).ToByteArray(); return true; } [ContractMethod(0_03000000, ContractParameterType.Integer, ParameterTypes = new[] { ContractParameterType.Hash160, ContractParameterType.Integer }, ParameterNames = new[] { "account", "end" }, SafeMethod = true)] private StackItem UnclaimedGas(ApplicationEngine engine, VMArray args) { UInt160 account = new UInt160(args[0].GetSpan().ToArray()); uint end = (uint)args[1].GetBigInteger(); return UnclaimedGas(engine.Snapshot, account, end); } public BigInteger UnclaimedGas(StoreView snapshot, UInt160 account, uint end) { StorageItem storage = snapshot.Storages.TryGet(CreateAccountKey(account)); if (storage is null) return BigInteger.Zero; AccountState state = new AccountState(storage.Value); return CalculateBonus(snapshot, state.Balance, state.BalanceHeight, end); } [ContractMethod(0_05000000, ContractParameterType.Boolean, ParameterTypes = new[] { ContractParameterType.PublicKey }, ParameterNames = new[] { "pubkey" })] private StackItem RegisterValidator(ApplicationEngine engine, VMArray args) { ECPoint pubkey = args[0].GetSpan().AsSerializable<ECPoint>(); return RegisterValidator(engine.Snapshot, pubkey); } private bool RegisterValidator(StoreView snapshot, ECPoint pubkey) { StorageKey key = CreateStorageKey(Prefix_Validator, pubkey); if (snapshot.Storages.TryGet(key) != null) return false; snapshot.Storages.Add(key, new StorageItem { Value = new ValidatorState().ToByteArray() }); return true; } [ContractMethod(5_00000000, ContractParameterType.Boolean, ParameterTypes = new[] { ContractParameterType.Hash160, ContractParameterType.Array }, ParameterNames = new[] { "account", "pubkeys" })] private StackItem Vote(ApplicationEngine engine, VMArray args) { UInt160 account = new UInt160(args[0].GetSpan().ToArray()); ECPoint[] pubkeys = ((VMArray)args[1]).Select(p => p.GetSpan().AsSerializable<ECPoint>()).ToArray(); if (!InteropService.CheckWitness(engine, account)) return false; StorageKey key_account = CreateAccountKey(account); if (engine.Snapshot.Storages.TryGet(key_account) is null) return false; StorageItem storage_account = engine.Snapshot.Storages.GetAndChange(key_account); AccountState state_account = new AccountState(storage_account.Value); foreach (ECPoint pubkey in state_account.Votes) { StorageItem storage_validator = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_Validator, pubkey.ToArray())); ValidatorState state_validator = ValidatorState.FromByteArray(storage_validator.Value); state_validator.Votes -= state_account.Balance; storage_validator.Value = state_validator.ToByteArray(); } pubkeys = pubkeys.Distinct().Where(p => engine.Snapshot.Storages.TryGet(CreateStorageKey(Prefix_Validator, p.ToArray())) != null).ToArray(); if (pubkeys.Length != state_account.Votes.Length) { StorageItem storage_count = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_ValidatorsCount), () => new StorageItem { Value = new ValidatorsCountState().ToByteArray() }); ValidatorsCountState state_count = ValidatorsCountState.FromByteArray(storage_count.Value); if (state_account.Votes.Length > 0) state_count.Votes[state_account.Votes.Length - 1] -= state_account.Balance; if (pubkeys.Length > 0) state_count.Votes[pubkeys.Length - 1] += state_account.Balance; storage_count.Value = state_count.ToByteArray(); } state_account.Votes = pubkeys; storage_account.Value = state_account.ToByteArray(); foreach (ECPoint pubkey in state_account.Votes) { StorageItem storage_validator = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_Validator, pubkey.ToArray())); ValidatorState state_validator = ValidatorState.FromByteArray(storage_validator.Value); state_validator.Votes += state_account.Balance; storage_validator.Value = state_validator.ToByteArray(); } return true; } [ContractMethod(1_00000000, ContractParameterType.Array, SafeMethod = true)] private StackItem GetRegisteredValidators(ApplicationEngine engine, VMArray args) { return GetRegisteredValidators(engine.Snapshot).Select(p => new Struct(new StackItem[] { p.PublicKey.ToArray(), p.Votes })).ToArray(); } public IEnumerable<(ECPoint PublicKey, BigInteger Votes)> GetRegisteredValidators(StoreView snapshot) { byte[] prefix_key = StorageKey.CreateSearchPrefix(Hash, new[] { Prefix_Validator }); return snapshot.Storages.Find(prefix_key).Select(p => ( p.Key.Key.Skip(1).ToArray().AsSerializable<ECPoint>(), ValidatorState.FromByteArray(p.Value.Value).Votes )); } [ContractMethod(1_00000000, ContractParameterType.Array, SafeMethod = true)] private StackItem GetValidators(ApplicationEngine engine, VMArray args) { return GetValidators(engine.Snapshot).Select(p => (StackItem)p.ToArray()).ToList(); } public ECPoint[] GetValidators(StoreView snapshot) { StorageItem storage_count = snapshot.Storages.TryGet(CreateStorageKey(Prefix_ValidatorsCount)); if (storage_count is null) return Blockchain.StandbyValidators; ValidatorsCountState state_count = ValidatorsCountState.FromByteArray(storage_count.Value); int count = (int)state_count.Votes.Select((p, i) => new { Count = i, Votes = p }).Where(p => p.Votes.Sign > 0).ToArray().WeightedFilter(0.25, 0.75, p => p.Votes, (p, w) => new { p.Count, Weight = w }).WeightedAverage(p => p.Count, p => p.Weight); count = Math.Max(count, Blockchain.StandbyValidators.Length); HashSet<ECPoint> sv = new HashSet<ECPoint>(Blockchain.StandbyValidators); return GetRegisteredValidators(snapshot).Where(p => (p.Votes.Sign > 0) || sv.Contains(p.PublicKey)).OrderByDescending(p => p.Votes).ThenBy(p => p.PublicKey).Select(p => p.PublicKey).Take(count).OrderBy(p => p).ToArray(); } [ContractMethod(1_00000000, ContractParameterType.Array, SafeMethod = true)] private StackItem GetNextBlockValidators(ApplicationEngine engine, VMArray args) { return GetNextBlockValidators(engine.Snapshot).Select(p => (StackItem)p.ToArray()).ToList(); } public ECPoint[] GetNextBlockValidators(StoreView snapshot) { StorageItem storage = snapshot.Storages.TryGet(CreateStorageKey(Prefix_NextValidators)); if (storage is null) return Blockchain.StandbyValidators; return storage.Value.AsSerializableArray<ECPoint>(); } public class AccountState : Nep5AccountState { public uint BalanceHeight; public ECPoint[] Votes; public AccountState() { this.Votes = new ECPoint[0]; } public AccountState(byte[] data) : base(data) { } protected override void FromStruct(Struct @struct) { base.FromStruct(@struct); BalanceHeight = (uint)@struct[1].GetBigInteger(); Votes = @struct[2].GetSpan().AsSerializableArray<ECPoint>(Blockchain.MaxValidators); } protected override Struct ToStruct() { Struct @struct = base.ToStruct(); @struct.Add(BalanceHeight); @struct.Add(Votes.ToByteArray()); return @struct; } } internal class ValidatorState { public BigInteger Votes; public static ValidatorState FromByteArray(byte[] data) { return new ValidatorState { Votes = new BigInteger(data) }; } public byte[] ToByteArray() { return Votes.ToByteArray(); } } internal class ValidatorsCountState { public BigInteger[] Votes = new BigInteger[Blockchain.MaxValidators]; public static ValidatorsCountState FromByteArray(byte[] data) { using (MemoryStream ms = new MemoryStream(data, false)) using (BinaryReader r = new BinaryReader(ms)) { BigInteger[] votes = new BigInteger[(int)r.ReadVarInt(Blockchain.MaxValidators)]; for (int i = 0; i < votes.Length; i++) votes[i] = new BigInteger(r.ReadVarBytes()); return new ValidatorsCountState { Votes = votes }; } } public byte[] ToByteArray() { using (MemoryStream ms = new MemoryStream()) using (BinaryWriter w = new BinaryWriter(ms)) { w.WriteVarInt(Votes.Length); foreach (BigInteger vote in Votes) w.WriteVarBytes(vote.ToByteArray()); w.Flush(); return ms.ToArray(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Utility; using Microsoft.Extensions.Logging; namespace Foundatio.Lock { public interface ILockProvider { Task<ILock> AcquireAsync(string resource, TimeSpan? timeUntilExpires = null, bool releaseOnDispose = true, CancellationToken cancellationToken = default); Task<bool> IsLockedAsync(string resource); Task ReleaseAsync(string resource, string lockId); Task RenewAsync(string resource, string lockId, TimeSpan? timeUntilExpires = null); } public interface ILock : IAsyncDisposable { Task RenewAsync(TimeSpan? timeUntilExpires = null); Task ReleaseAsync(); string LockId { get; } string Resource { get; } DateTime AcquiredTimeUtc { get; } TimeSpan TimeWaitedForLock { get; } int RenewalCount { get; } } public static class LockProviderExtensions { public static Task ReleaseAsync(this ILockProvider provider, ILock @lock) { return provider.ReleaseAsync(@lock.Resource, @lock.LockId); } public static Task RenewAsync(this ILockProvider provider, ILock @lock, TimeSpan? timeUntilExpires = null) { return provider.RenewAsync(@lock.Resource, @lock.LockId, timeUntilExpires); } public static Task<ILock> AcquireAsync(this ILockProvider provider, string resource, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { return provider.AcquireAsync(resource, timeUntilExpires, true, cancellationToken); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, string resource, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource(TimeSpan.FromSeconds(30))) { return await provider.AcquireAsync(resource, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); } } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work(cancellationToken).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work(cancellationTokenSource.Token).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Func<Task> work, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resource, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static Task<bool> TryUsingAsync(this ILockProvider locker, string resource, Action work, TimeSpan? timeUntilExpires = null, TimeSpan? acquireTimeout = null) { return locker.TryUsingAsync(resource, () => { work(); return Task.CompletedTask; }, timeUntilExpires, acquireTimeout); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnumerable<string> resources, TimeSpan? timeUntilExpires = null, bool releaseOnDispose = true, CancellationToken cancellationToken = default) { if (resources == null) throw new ArgumentNullException(nameof(resources)); var resourceList = resources.Distinct().ToArray(); if (resourceList.Length == 0) return new EmptyLock(); var logger = provider.GetLogger(); if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Acquiring {LockCount} locks {Resource}", resourceList.Length, resourceList); var sw = Stopwatch.StartNew(); var locks = await Task.WhenAll(resourceList.Select(r => provider.AcquireAsync(r, timeUntilExpires, releaseOnDispose, cancellationToken))); sw.Stop(); // if any lock is null, release any acquired and return null (all or nothing) var acquiredLocks = locks.Where(l => l != null).ToArray(); var unacquiredResources = resourceList.Except(locks.Select(l => l?.Resource)).ToArray(); if (unacquiredResources.Length > 0) { if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Unable to acquire all {LockCount} locks {Resource} releasing acquired locks", unacquiredResources.Length, unacquiredResources); await Task.WhenAll(acquiredLocks.Select(l => l.ReleaseAsync())).AnyContext(); return null; } if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Acquired {LockCount} locks {Resource} after {Duration:g}", resourceList.Length, resourceList, sw.Elapsed); return new DisposableLockCollection(locks, String.Join("+", locks.Select(l => l.LockId)), sw.Elapsed, logger); } public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnumerable<string> resources, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource(TimeSpan.FromSeconds(30))) { return await provider.AcquireAsync(resources, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); } } public static async Task<ILock> AcquireAsync(this ILockProvider provider, IEnumerable<string> resources, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout, bool releaseOnDispose) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource(TimeSpan.FromSeconds(30))) { return await provider.AcquireAsync(resources, timeUntilExpires, releaseOnDispose, cancellationTokenSource.Token).AnyContext(); } } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work(cancellationToken).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<Task> work, TimeSpan? timeUntilExpires = null, CancellationToken cancellationToken = default) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationToken).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<CancellationToken, Task> work, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work(cancellationTokenSource.Token).AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static async Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Func<Task> work, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { using (var cancellationTokenSource = acquireTimeout.ToCancellationTokenSource()) { var l = await locker.AcquireAsync(resources, timeUntilExpires, true, cancellationTokenSource.Token).AnyContext(); if (l == null) return false; try { await work().AnyContext(); } finally { await l.ReleaseAsync().AnyContext(); } } return true; } public static Task<bool> TryUsingAsync(this ILockProvider locker, IEnumerable<string> resources, Action work, TimeSpan? timeUntilExpires, TimeSpan? acquireTimeout) { return locker.TryUsingAsync(resources, () => { work(); return Task.CompletedTask; }, timeUntilExpires, acquireTimeout); } } }
// 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 OLEDB.Test.ModuleCore; using Xunit; namespace System.Xml.Tests { public class XmlConvertTests : CTestModule { [Fact] [OuterLoop] public static void EncodeDecodeTests() { RunTestCase(new EncodeDecodeTests { Attribute = new TestCase { Name = "EncodeName/DecodeName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void MiscellaneousTests() { RunTestCase(new MiscellaneousTests { Attribute = new TestCase { Name = "Misc. Bug Regressions", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void SqlXmlConvertTests0() { RunTestCase(new SqlXmlConvertTests0 { Attribute = new TestCase { Name = "2. XmlConvert (SQL-XML EncodeName) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void SqlXmlConvertTests1() { RunTestCase(new SqlXmlConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (SQL-XML EncodeName) EncodeName-EncodeLocalName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void SqlXmlConvertTests2() { RunTestCase(new SqlXmlConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (SQL-XML EncodeName) EncodeName-DecodeName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void SqlXmlConvertTests3() { RunTestCase(new SqlXmlConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (SQL-XML EncodeName) EncodeLocalName only", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] [ActiveIssue(5462, PlatformID.AnyUnix)] [ActiveIssue(1303, PlatformID.Windows)] public static void ToTypeTests() { RunTestCase(new ToTypeTests { Attribute = new TestCase { Name = "XmlConvert type conversion functions", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void VerifyNameTests1() { RunTestCase(new VerifyNameTests1 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void VerifyNameTests2() { RunTestCase(new VerifyNameTests2 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void VerifyNameTests3() { RunTestCase(new VerifyNameTests3 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void VerifyNameTests4() { RunTestCase(new VerifyNameTests4 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void VerifyNameTests5() { RunTestCase(new VerifyNameTests5 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlBaseCharConvertTests1() { RunTestCase(new XmlBaseCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Base Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlBaseCharConvertTests2() { RunTestCase(new XmlBaseCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Base Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlBaseCharConvertTests3() { RunTestCase(new XmlBaseCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Base Char) EncodeName-DecodeName ", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlCombiningCharConvertTests1() { RunTestCase(new XmlCombiningCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Combining Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlCombiningCharConvertTests2() { RunTestCase(new XmlCombiningCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Combining Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlCombiningCharConvertTests3() { RunTestCase(new XmlCombiningCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Combining Char) EncodeName-DecodeName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlDigitCharConvertTests1() { RunTestCase(new XmlDigitCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Digit Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlDigitCharConvertTests2() { RunTestCase(new XmlDigitCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Digit Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlDigitCharConvertTests3() { RunTestCase(new XmlDigitCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Digit Char) EncodeName-DecodeName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlEmbeddedNullCharConvertTests1() { RunTestCase(new XmlEmbeddedNullCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (EmbeddedNull Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlEmbeddedNullCharConvertTests2() { RunTestCase(new XmlEmbeddedNullCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (EmbeddedNull Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlEmbeddedNullCharConvertTests3() { RunTestCase(new XmlEmbeddedNullCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (EmbeddedNull Char) EncodeName-DecodeName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlIdeographicCharConvertTests1() { RunTestCase(new XmlIdeographicCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Ideographic Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlIdeographicCharConvertTests2() { RunTestCase(new XmlIdeographicCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Ideographic Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } }); } [Fact] [OuterLoop] public static void XmlIdeographicCharConvertTests3() { RunTestCase(new XmlIdeographicCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Ideographic Char) EncodeName-DecodeName", Desc = "XmlConvert" } }); } private static void RunTestCase(CTestBase testCase) { var module = new XmlConvertTests(); module.Init(null); module.AddChild(testCase); module.Execute(); Assert.Equal(0, module.FailCount); } } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.GridUser { public class GridUserServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IGridUserService m_GridUserService; public GridUserServerPostHandler(IGridUserService service) : base("POST", "/griduser") { m_GridUserService = service; } public override byte[] Handle(string path, Stream requestData, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); string method = string.Empty; try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); method = request["METHOD"].ToString(); switch (method) { case "loggedin": return LoggedIn(request); case "loggedout": return LoggedOut(request); case "sethome": return SetHome(request); case "setposition": return SetPosition(request); case "getgriduserinfo": return GetGridUserInfo(request); } m_log.DebugFormat("[GRID USER HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[GRID USER HANDLER]: Exception in method {0}: {1}", method, e); } return FailureResult(); } byte[] LoggedIn(Dictionary<string, object> request) { string user = String.Empty; if (!request.ContainsKey("UserID")) return FailureResult(); user = request["UserID"].ToString(); GridUserInfo guinfo = m_GridUserService.LoggedIn(user); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = guinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] LoggedOut(Dictionary<string, object> request) { string userID = string.Empty; UUID regionID = UUID.Zero; Vector3 position = Vector3.Zero; Vector3 lookat = Vector3.Zero; if (!UnpackArgs(request, out userID, out regionID, out position, out lookat)) return FailureResult(); if (m_GridUserService.LoggedOut(userID, UUID.Zero, regionID, position, lookat)) return SuccessResult(); return FailureResult(); } byte[] SetHome(Dictionary<string, object> request) { string user = string.Empty; UUID region = UUID.Zero; Vector3 position = new Vector3(128, 128, 70); Vector3 look = Vector3.Zero; if (!UnpackArgs(request, out user, out region, out position, out look)) return FailureResult(); if (m_GridUserService.SetHome(user, region, position, look)) return SuccessResult(); return FailureResult(); } byte[] SetPosition(Dictionary<string, object> request) { string user = string.Empty; UUID region = UUID.Zero; Vector3 position = new Vector3(128, 128, 70); Vector3 look = Vector3.Zero; if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) return FailureResult(); if (!UnpackArgs(request, out user, out region, out position, out look)) return FailureResult(); if (m_GridUserService.SetLastPosition(user, UUID.Zero, region, position, look)) return SuccessResult(); return FailureResult(); } byte[] GetGridUserInfo(Dictionary<string, object> request) { string user = String.Empty; if (!request.ContainsKey("UserID")) return FailureResult(); user = request["UserID"].ToString(); GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(user); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = guinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } private bool UnpackArgs(Dictionary<string, object> request, out string user, out UUID region, out Vector3 position, out Vector3 lookAt) { user = string.Empty; region = UUID.Zero; position = new Vector3(128, 128, 70); lookAt = Vector3.Zero; if (!request.ContainsKey("UserID") || !request.ContainsKey("RegionID")) return false; user = request["UserID"].ToString(); if (!UUID.TryParse(request["RegionID"].ToString(), out region)) return false; if (request.ContainsKey("Position")) Vector3.TryParse(request["Position"].ToString(), out position); if (request.ContainsKey("LookAt")) Vector3.TryParse(request["LookAt"].ToString(), out lookAt); return true; } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.Composition; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.Setup; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Orders; using QuantConnect.Packets; using QuantConnect.Statistics; package com.quantconnect.lean.Lean.Engine.Results { /** * Handle the results of the backtest: where should we send the profit, portfolio updates: * Backtester or the Live trading platform: */ [InheritedExport(typeof(IResultHandler))] public interface IResultHandler { /** * Put messages to process into the queue so they are processed by this thread. */ ConcurrentQueue<Packet> Messages { get; set; } /** * Charts collection for storing the master copy of user charting data. */ ConcurrentMap<String, Chart> Charts { get; set; } /** * Sampling period for timespans between resamples of the charting equity. */ * Specifically critical for backtesting since with such long timeframes the sampled data can get extreme. Duration ResamplePeriod { get; } /** * How frequently the backtests push messages to the browser. */ * Update frequency of notification packets Duration NotificationPeriod { get; } /** * Boolean flag indicating the result hander thread is busy. * False means it has completely finished and ready to dispose. */ boolean IsActive { get; } /** * Initialize the result handler with this result packet. */ * @param job Algorithm job packet for this result handler * @param messagingHandler"> * @param api"> * @param dataFeed"> * @param setupHandler"> * @param transactionHandler"> void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler); /** * Primary result thread entry point to process the result message queue and send it to whatever endpoint is set. */ void Run(); /** * Process debug messages with the preconfigured settings. */ * @param message String debug message void DebugMessage( String message); /** * Send a list of security types to the browser */ * @param types Security types list inside algorithm void SecurityType(List<SecurityType> types); /** * Send a logging message to the log list for storage. */ * @param message Message we'd in the log. void LogMessage( String message); /** * Send an error message back to the browser highlighted in red with a stacktrace. */ * @param error Error message we'd like shown in console. * @param stacktrace Stacktrace information string void ErrorMessage( String error, String stacktrace = ""); /** * Send a runtime error message back to the browser highlighted with in red */ * @param message Error message. * @param stacktrace Stacktrace information string void RuntimeError( String message, String stacktrace = ""); /** * Add a sample to the chart specified by the chartName, and seriesName. */ * @param chartName String chart name to place the sample. * @param seriesName Series name for the chart. * @param seriesType Series type for the chart. * @param time Time for the sample * @param value Value for the chart sample. * @param unit Unit for the sample chart * @param seriesIndex Index of the series we're sampling * Sample can be used to create new charts or sample equity - daily performance. void Sample( String chartName, String seriesName, int seriesIndex, SeriesType seriesType, DateTime time, BigDecimal value, String unit = "$"); /** * Wrapper methond on sample to create the equity chart. */ * @param time Time of the sample. * @param value Equity value at this moment in time. * <seealso cref="Sample( String,string,int,SeriesType,DateTime,decimal,string)"/> void SampleEquity(DateTime time, BigDecimal value); /** * Sample the current daily performance directly with a time-value pair. */ * @param time Current backtest date. * @param value Current daily performance value. * <seealso cref="Sample( String,string,int,SeriesType,DateTime,decimal,string)"/> void SamplePerformance(DateTime time, BigDecimal value); /** * Sample the current benchmark performance directly with a time-value pair. */ * @param time Current backtest date. * @param value Current benchmark value. * <seealso cref="Sample( String,string,int,SeriesType,DateTime,decimal,string)"/> void SampleBenchmark(DateTime time, BigDecimal value); /** * Sample the asset prices to generate plots. */ * @param symbol Symbol we're sampling. * @param time Time of sample * @param value Value of the asset price * <seealso cref="Sample( String,string,int,SeriesType,DateTime,decimal,string)"/> void SampleAssetPrices(Symbol symbol, DateTime time, BigDecimal value); /** * Add a range of samples from the users algorithms to the end of our current list. */ * @param samples Chart updates since the last request. * <seealso cref="Sample( String,string,int,SeriesType,DateTime,decimal,string)"/> void SampleRange(List<Chart> samples); /** * Set the algorithm of the result handler after its been initialized. */ * @param algorithm Algorithm object matching IAlgorithm interface void SetAlgorithm(IAlgorithm algorithm); /** * Save the snapshot of the total results to storage. */ * @param packet Packet to store. * @param async Store the packet asyncronously to speed up the thread. * Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now. void StoreResult(Packet packet, boolean async = false); /** * Post the final result back to the controller worker if backtesting, or to console if local. */ * @param job Lean AlgorithmJob task * @param orders Collection of orders from the algorithm * @param profitLoss Collection of time-profit values for the algorithm * @param holdings Current holdings state for the algorithm * @param statisticsResults Statistics information for the algorithm (empty if not finished) * @param banner Runtime statistics banner information void SendFinalResult(AlgorithmNodePacket job, Map<Integer, Order> orders, Map<DateTime, decimal> profitLoss, Map<String, Holding> holdings, StatisticsResults statisticsResults, Map<String,String> banner); /** * Send a algorithm status update to the user of the algorithms running state. */ * @param status Status enum of the algorithm. * @param message Optional String message describing reason for status change. void SendStatusUpdate(AlgorithmStatus status, String message = ""); /** * Set the chart name: */ * @param symbol Symbol of the chart we want. void SetChartSubscription( String symbol); /** * Set a dynamic runtime statistic to show in the (live) algorithm header */ * @param key Runtime headline statistic name * @param value Runtime headline statistic value void RuntimeStatistic( String key, String value); /** * Send a new order event. */ * @param newEvent Update, processing or cancellation of an order, update the IDE in live mode or ignore in backtesting. void OrderEvent(OrderEvent newEvent); /** * Terminate the result thread and apply any required exit proceedures. */ void Exit(); /** * Purge/clear any outstanding messages in message queue. */ void PurgeQueue(); /** * Process any synchronous events in here that are primarily triggered from the algorithm loop */ void ProcessSynchronousEvents( boolean forceProcess = false); } }
using J2N.Text; using YAF.Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using Directory = YAF.Lucene.Net.Store.Directory; namespace YAF.Lucene.Net.Codecs.Lucene3x { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using FieldInfos = YAF.Lucene.Net.Index.FieldInfos; using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames; using IOContext = YAF.Lucene.Net.Store.IOContext; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using Term = YAF.Lucene.Net.Index.Term; /// <summary> /// This stores a monotonically increasing set of <c>Term, TermInfo</c> pairs in a /// Directory. Pairs are accessed either by <see cref="Term"/> or by ordinal position the /// set. /// <para/> /// @lucene.experimental /// </summary> [Obsolete("(4.0) this class has been replaced by FormatPostingsTermsDictReader, except for reading old segments.")] internal sealed class TermInfosReader : IDisposable { private readonly Directory directory; private readonly string segment; private readonly FieldInfos fieldInfos; private readonly DisposableThreadLocal<ThreadResources> threadResources = new DisposableThreadLocal<ThreadResources>(); private readonly SegmentTermEnum origEnum; private readonly long size; private readonly TermInfosReaderIndex index; private readonly int indexLength; private readonly int totalIndexInterval; private const int DEFAULT_CACHE_SIZE = 1024; // Just adds term's ord to TermInfo public sealed class TermInfoAndOrd : TermInfo { internal readonly long termOrd; public TermInfoAndOrd(TermInfo ti, long termOrd) : base(ti) { Debug.Assert(termOrd >= 0); this.termOrd = termOrd; } } private class CloneableTerm : DoubleBarrelLRUCache.CloneableKey { internal Term term; public CloneableTerm(Term t) { this.term = t; } public override bool Equals(object other) { CloneableTerm t = (CloneableTerm)other; return this.term.Equals(t.term); } public override int GetHashCode() { return term.GetHashCode(); } public override object Clone() { return new CloneableTerm(term); } } private readonly DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd> termsCache = new DoubleBarrelLRUCache<CloneableTerm, TermInfoAndOrd>(DEFAULT_CACHE_SIZE); /// <summary> /// Per-thread resources managed by ThreadLocal. /// </summary> private sealed class ThreadResources { internal SegmentTermEnum termEnum; } internal TermInfosReader(Directory dir, string seg, FieldInfos fis, IOContext context, int indexDivisor) { bool success = false; if (indexDivisor < 1 && indexDivisor != -1) { throw new System.ArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor); } try { directory = dir; segment = seg; fieldInfos = fis; origEnum = new SegmentTermEnum(directory.OpenInput(IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION), context), fieldInfos, false); size = origEnum.size; if (indexDivisor != -1) { // Load terms index totalIndexInterval = origEnum.indexInterval * indexDivisor; string indexFileName = IndexFileNames.SegmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION); SegmentTermEnum indexEnum = new SegmentTermEnum(directory.OpenInput(indexFileName, context), fieldInfos, true); try { index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.FileLength(indexFileName), totalIndexInterval); indexLength = index.Length; } finally { indexEnum.Dispose(); } } else { // Do not load terms index: totalIndexInterval = -1; index = null; indexLength = -1; } success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { Dispose(); } } } public int SkipInterval { get { return origEnum.skipInterval; } } public int MaxSkipLevels { get { return origEnum.maxSkipLevels; } } public void Dispose() { IOUtils.Dispose(origEnum, threadResources); } /// <summary> /// Returns the number of term/value pairs in the set. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> internal long Count { get { return size; } } private ThreadResources GetThreadResources() { ThreadResources resources = threadResources.Get(); if (resources == null) { resources = new ThreadResources(); resources.termEnum = Terms(); threadResources.Set(resources); } return resources; } private static readonly IComparer<BytesRef> legacyComparer = BytesRef.UTF8SortedAsUTF16Comparer; private int CompareAsUTF16(Term term1, Term term2) { if (term1.Field.Equals(term2.Field, StringComparison.Ordinal)) { return legacyComparer.Compare(term1.Bytes, term2.Bytes); } else { return term1.Field.CompareToOrdinal(term2.Field); } } /// <summary> /// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary> internal TermInfo Get(Term term) { return Get(term, false); } /// <summary> /// Returns the <see cref="TermInfo"/> for a <see cref="Term"/> in the set, or <c>null</c>. </summary> private TermInfo Get(Term term, bool mustSeekEnum) { if (size == 0) { return null; } EnsureIndexIsRead(); TermInfoAndOrd tiOrd = termsCache.Get(new CloneableTerm(term)); ThreadResources resources = GetThreadResources(); if (!mustSeekEnum && tiOrd != null) { return tiOrd; } return SeekEnum(resources.termEnum, term, tiOrd, true); } public void CacheCurrentTerm(SegmentTermEnum enumerator) { termsCache.Put(new CloneableTerm(enumerator.Term()), new TermInfoAndOrd(enumerator.termInfo, enumerator.position)); } internal static Term DeepCopyOf(Term other) { return new Term(other.Field, BytesRef.DeepCopyOf(other.Bytes)); } internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, bool useCache) { if (useCache) { return SeekEnum(enumerator, term, termsCache.Get(new CloneableTerm(DeepCopyOf(term))), useCache); } else { return SeekEnum(enumerator, term, null, useCache); } } internal TermInfo SeekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, bool useCache) { if (size == 0) { return null; } // optimize sequential access: first try scanning cached enum w/o seeking if (enumerator.Term() != null && ((enumerator.Prev() != null && CompareAsUTF16(term, enumerator.Prev()) > 0) || CompareAsUTF16(term, enumerator.Term()) >= 0)) // term is at or past current { int enumOffset = (int)(enumerator.position / totalIndexInterval) + 1; if (indexLength == enumOffset || index.CompareTo(term, enumOffset) < 0) // but before end of block { // no need to seek TermInfo ti; int numScans = enumerator.ScanTo(term); if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0) { ti = enumerator.termInfo; if (numScans > 1) { // we only want to put this TermInfo into the cache if // scanEnum skipped more than one dictionary entry. // this prevents RangeQueries or WildcardQueries to // wipe out the cache when they iterate over a large numbers // of terms in order if (tiOrd == null) { if (useCache) { termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti, enumerator.position)); } } else { Debug.Assert(SameTermInfo(ti, tiOrd, enumerator)); Debug.Assert(enumerator.position == tiOrd.termOrd); } } } else { ti = null; } return ti; } } // random-access: must seek int indexPos; if (tiOrd != null) { indexPos = (int)(tiOrd.termOrd / totalIndexInterval); } else { // Must do binary search: indexPos = index.GetIndexOffset(term); } index.SeekEnum(enumerator, indexPos); enumerator.ScanTo(term); TermInfo ti_; if (enumerator.Term() != null && CompareAsUTF16(term, enumerator.Term()) == 0) { ti_ = enumerator.termInfo; if (tiOrd == null) { if (useCache) { termsCache.Put(new CloneableTerm(DeepCopyOf(term)), new TermInfoAndOrd(ti_, enumerator.position)); } } else { Debug.Assert(SameTermInfo(ti_, tiOrd, enumerator)); Debug.Assert(enumerator.position == tiOrd.termOrd); } } else { ti_ = null; } return ti_; } // called only from asserts private bool SameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator) { if (ti1.DocFreq != ti2.DocFreq) { return false; } if (ti1.FreqPointer != ti2.FreqPointer) { return false; } if (ti1.ProxPointer != ti2.ProxPointer) { return false; } // skipOffset is only valid when docFreq >= skipInterval: if (ti1.DocFreq >= enumerator.skipInterval && ti1.SkipOffset != ti2.SkipOffset) { return false; } return true; } private void EnsureIndexIsRead() { if (index == null) { throw new InvalidOperationException("terms index was not loaded when this reader was created"); } } /// <summary> /// Returns the position of a <see cref="Term"/> in the set or -1. </summary> internal long GetPosition(Term term) { if (size == 0) { return -1; } EnsureIndexIsRead(); int indexOffset = index.GetIndexOffset(term); SegmentTermEnum enumerator = GetThreadResources().termEnum; index.SeekEnum(enumerator, indexOffset); while (CompareAsUTF16(term, enumerator.Term()) > 0 && enumerator.Next()) { } if (CompareAsUTF16(term, enumerator.Term()) == 0) { return enumerator.position; } else { return -1; } } /// <summary> /// Returns an enumeration of all the <see cref="Term"/>s and <see cref="TermInfo"/>s in the set. </summary> public SegmentTermEnum Terms() { return (SegmentTermEnum)origEnum.Clone(); } /// <summary> /// Returns an enumeration of terms starting at or after the named term. </summary> public SegmentTermEnum Terms(Term term) { Get(term, true); return (SegmentTermEnum)GetThreadResources().termEnum.Clone(); } internal long RamBytesUsed() { return index == null ? 0 : index.RamBytesUsed(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.ComponentModel; using System.Collections.Generic; using System.Threading; namespace System.Data { internal struct IndexField { public readonly DataColumn Column; public readonly bool IsDescending; // false = Asc; true = Desc what is default value for this? internal IndexField(DataColumn column, bool isDescending) { Debug.Assert(column != null, "null column"); Column = column; IsDescending = isDescending; } public static bool operator ==(IndexField if1, IndexField if2) => if1.Column == if2.Column && if1.IsDescending == if2.IsDescending; public static bool operator !=(IndexField if1, IndexField if2) => !(if1 == if2); // must override Equals if == operator is defined public override bool Equals(object obj) => obj is IndexField ? this == (IndexField)obj : false; // must override GetHashCode if Equals is redefined public override int GetHashCode() => Column.GetHashCode() ^ IsDescending.GetHashCode(); } internal sealed class Index { private sealed class IndexTree : RBTree<int> { private readonly Index _index; internal IndexTree(Index index) : base(TreeAccessMethod.KEY_SEARCH_AND_INDEX) { _index = index; } protected override int CompareNode(int record1, int record2) => _index.CompareRecords(record1, record2); protected override int CompareSateliteTreeNode(int record1, int record2) => _index.CompareDuplicateRecords(record1, record2); } // these constants are used to update a DataRow when the record and Row are known, but don't match private const int DoNotReplaceCompareRecord = 0; private const int ReplaceNewRecordForCompare = 1; private const int ReplaceOldRecordForCompare = 2; private readonly DataTable _table; internal readonly IndexField[] _indexFields; /// <summary>Allow a user implemented comparison of two DataRow</summary> /// <remarks>User must use correct DataRowVersion in comparison or index corruption will happen</remarks> private readonly System.Comparison<DataRow> _comparison; private readonly DataViewRowState _recordStates; private WeakReference _rowFilter; private IndexTree _records; private int _recordCount; private int _refCount; private Listeners<DataViewListener> _listeners; private bool _suspendEvents; private readonly bool _isSharable; private readonly bool _hasRemoteAggregate; internal const int MaskBits = unchecked(0x7FFFFFFF); private static int s_objectTypeCount; // Bid counter private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount); public Index(DataTable table, IndexField[] indexFields, DataViewRowState recordStates, IFilter rowFilter) : this(table, indexFields, null, recordStates, rowFilter) { } public Index(DataTable table, System.Comparison<DataRow> comparison, DataViewRowState recordStates, IFilter rowFilter) : this(table, GetAllFields(table.Columns), comparison, recordStates, rowFilter) { } // for the delegate methods, we don't know what the dependent columns are - so all columns are dependent private static IndexField[] GetAllFields(DataColumnCollection columns) { IndexField[] fields = new IndexField[columns.Count]; for (int i = 0; i < fields.Length; ++i) { fields[i] = new IndexField(columns[i], false); } return fields; } private Index(DataTable table, IndexField[] indexFields, System.Comparison<DataRow> comparison, DataViewRowState recordStates, IFilter rowFilter) { DataCommonEventSource.Log.Trace("<ds.Index.Index|API> {0}, table={1}, recordStates={2}", ObjectID, (table != null) ? table.ObjectID : 0, recordStates); Debug.Assert(indexFields != null); Debug.Assert(null != table, "null table"); if ((recordStates & (~(DataViewRowState.CurrentRows | DataViewRowState.OriginalRows))) != 0) { throw ExceptionBuilder.RecordStateRange(); } _table = table; _listeners = new Listeners<DataViewListener>(ObjectID, listener => null != listener); _indexFields = indexFields; _recordStates = recordStates; _comparison = comparison; DataColumnCollection columns = table.Columns; _isSharable = (rowFilter == null) && (comparison == null); // a filter or comparison make an index unsharable if (null != rowFilter) { _rowFilter = new WeakReference(rowFilter); DataExpression expr = (rowFilter as DataExpression); if (null != expr) { _hasRemoteAggregate = expr.HasRemoteAggregate(); } } InitRecords(rowFilter); // do not AddRef in ctor, every caller should be responsible to AddRef it // if caller does not AddRef, it is expected to be a one-time read operation because the index won't be maintained on writes } public bool Equal(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) { if (!_isSharable || _indexFields.Length != indexDesc.Length || _recordStates != recordStates || null != rowFilter) { return false; } for (int loop = 0; loop < _indexFields.Length; loop++) { if (_indexFields[loop].Column != indexDesc[loop].Column || _indexFields[loop].IsDescending != indexDesc[loop].IsDescending) { return false; } } return true; } internal bool HasRemoteAggregate => _hasRemoteAggregate; internal int ObjectID => _objectID; public DataViewRowState RecordStates => _recordStates; public IFilter RowFilter => (IFilter)((null != _rowFilter) ? _rowFilter.Target : null); public int GetRecord(int recordIndex) { Debug.Assert(recordIndex >= 0 && recordIndex < _recordCount, "recordIndex out of range"); return _records[recordIndex]; } public bool HasDuplicates => _records.HasDuplicates; public int RecordCount => _recordCount; public bool IsSharable => _isSharable; private bool AcceptRecord(int record) => AcceptRecord(record, RowFilter); private bool AcceptRecord(int record, IFilter filter) { DataCommonEventSource.Log.Trace("<ds.Index.AcceptRecord|API> {0}, record={1}", ObjectID, record); if (filter == null) { return true; } DataRow row = _table._recordManager[record]; if (row == null) { return true; } DataRowVersion version = DataRowVersion.Default; if (row._oldRecord == record) { version = DataRowVersion.Original; } else if (row._newRecord == record) { version = DataRowVersion.Current; } else if (row._tempRecord == record) { version = DataRowVersion.Proposed; } return filter.Invoke(row, version); } /// <remarks>Only call from inside a lock(this)</remarks> internal void ListChangedAdd(DataViewListener listener) => _listeners.Add(listener); /// <remarks>Only call from inside a lock(this)</remarks> internal void ListChangedRemove(DataViewListener listener) => _listeners.Remove(listener); public int RefCount => _refCount; public void AddRef() { DataCommonEventSource.Log.Trace("<ds.Index.AddRef|API> {0}", ObjectID); _table._indexesLock.EnterWriteLock(); try { Debug.Assert(0 <= _refCount, "AddRef on disposed index"); Debug.Assert(null != _records, "null records"); if (_refCount == 0) { _table.ShadowIndexCopy(); _table._indexes.Add(this); } _refCount++; } finally { _table._indexesLock.ExitWriteLock(); } } public int RemoveRef() { DataCommonEventSource.Log.Trace("<ds.Index.RemoveRef|API> {0}", ObjectID); int count; _table._indexesLock.EnterWriteLock(); try { count = --_refCount; if (_refCount <= 0) { _table.ShadowIndexCopy(); _table._indexes.Remove(this); } } finally { _table._indexesLock.ExitWriteLock(); } return count; } private void ApplyChangeAction(int record, int action, int changeRecord) { if (action != 0) { if (action > 0) { if (AcceptRecord(record)) { InsertRecord(record, true); } } else if ((null != _comparison) && (-1 != record)) { // when removing a record, the DataRow has already been updated to the newer record // depending on changeRecord, either the new or old record needs be backdated to record // for Comparison<DataRow> to operate correctly DeleteRecord(GetIndex(record, changeRecord)); } else { // unnecessary codepath other than keeping original code path for redbits DeleteRecord(GetIndex(record)); } } } public bool CheckUnique() { #if DEBUG Debug.Assert(_records.CheckUnique(_records.root) != HasDuplicates, "CheckUnique difference"); #endif return !HasDuplicates; } // only used for main tree compare, not satalite tree private int CompareRecords(int record1, int record2) { if (null != _comparison) { return CompareDataRows(record1, record2); } if (0 < _indexFields.Length) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.Compare(record1, record2); if (c != 0) { return (_indexFields[i].IsDescending ? -c : c); } } return 0; } else { Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. return _table.Rows.IndexOf(_table._recordManager[record1]).CompareTo(_table.Rows.IndexOf(_table._recordManager[record2])); } } private int CompareDataRows(int record1, int record2) { _table._recordManager.VerifyRecord(record1, _table._recordManager[record1]); _table._recordManager.VerifyRecord(record2, _table._recordManager[record2]); return _comparison(_table._recordManager[record1], _table._recordManager[record2]); } // PS: same as previous CompareRecords, except it compares row state if needed // only used for satalite tree compare private int CompareDuplicateRecords(int record1, int record2) { #if DEBUG if (null != _comparison) { Debug.Assert(0 == CompareDataRows(record1, record2), "duplicate record not a duplicate by user function"); } else if (record1 != record2) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.Compare(record1, record2); Debug.Assert(0 == c, "duplicate record not a duplicate"); } } #endif Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); if (null == _table._recordManager[record1]) { return ((null == _table._recordManager[record2]) ? 0 : -1); } else if (null == _table._recordManager[record2]) { return 1; } // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. int diff = _table._recordManager[record1].rowID.CompareTo(_table._recordManager[record2].rowID); // if they're two records in the same row, we need to be able to distinguish them. if ((diff == 0) && (record1 != record2)) { diff = ((int)_table._recordManager[record1].GetRecordState(record1)).CompareTo((int)_table._recordManager[record2].GetRecordState(record2)); } return diff; } private int CompareRecordToKey(int record1, object[] vals) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.CompareValueTo(record1, vals[i]); if (c != 0) { return (_indexFields[i].IsDescending ? -c : c); } } return 0; } // DeleteRecordFromIndex deletes the given record from index and does not fire any Event. IT SHOULD NOT FIRE EVENT public void DeleteRecordFromIndex(int recordIndex) { // this is for expression use, to maintain expression columns's sort , filter etc. do not fire event DeleteRecord(recordIndex, false); } // old and existing DeleteRecord behavior, we can not use this for silently deleting private void DeleteRecord(int recordIndex) { DeleteRecord(recordIndex, true); } private void DeleteRecord(int recordIndex, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.Index.DeleteRecord|INFO> {0}, recordIndex={1}, fireEvent={2}", ObjectID, recordIndex, fireEvent); if (recordIndex >= 0) { _recordCount--; int record = _records.DeleteByIndex(recordIndex); MaintainDataView(ListChangedType.ItemDeleted, record, !fireEvent); if (fireEvent) { OnListChanged(ListChangedType.ItemDeleted, recordIndex); } } } // this improves performance by allowing DataView to iterating instead of computing for records over index // this will also allow Linq over DataSet to enumerate over the index // avoid boxing by returning RBTreeEnumerator (a struct) instead of IEnumerator<int> public RBTree<int>.RBTreeEnumerator GetEnumerator(int startIndex) => new IndexTree.RBTreeEnumerator(_records, startIndex); // What it actually does is find the index in the records[] that // this record inhabits, and if it doesn't, suggests what index it would // inhabit while setting the high bit. public int GetIndex(int record) => _records.GetIndexByKey(record); /// <summary> /// When searching by value for a specific record, the DataRow may require backdating to reflect the appropriate state /// otherwise on Delete of a DataRow in the Added state, would result in the <see cref="System.Comparison&lt;DataRow&gt;"/> where the row /// reflection record would be in the Detached instead of Added state. /// </summary> private int GetIndex(int record, int changeRecord) { Debug.Assert(null != _comparison, "missing comparison"); int index; DataRow row = _table._recordManager[record]; int a = row._newRecord; int b = row._oldRecord; try { switch (changeRecord) { case ReplaceNewRecordForCompare: row._newRecord = record; break; case ReplaceOldRecordForCompare: row._oldRecord = record; break; } _table._recordManager.VerifyRecord(record, row); index = _records.GetIndexByKey(record); } finally { switch (changeRecord) { case ReplaceNewRecordForCompare: Debug.Assert(record == row._newRecord, "newRecord has change during GetIndex"); row._newRecord = a; break; case ReplaceOldRecordForCompare: Debug.Assert(record == row._oldRecord, "oldRecord has change during GetIndex"); row._oldRecord = b; break; } #if DEBUG if (-1 != a) { _table._recordManager.VerifyRecord(a, row); } #endif } return index; } public object[] GetUniqueKeyValues() { if (_indexFields == null || _indexFields.Length == 0) { return Array.Empty<object>(); } List<object[]> list = new List<object[]>(); GetUniqueKeyValues(list, _records.root); return list.ToArray(); } /// <summary> /// Find index of maintree node that matches key in record /// </summary> public int FindRecord(int record) { int nodeId = _records.Search(record); if (nodeId != IndexTree.NIL) return _records.GetIndexByNode(nodeId); //always returns the First record index else return -1; } public int FindRecordByKey(object key) { int nodeId = FindNodeByKey(key); if (IndexTree.NIL != nodeId) { return _records.GetIndexByNode(nodeId); } return -1; // return -1 to user indicating record not found } public int FindRecordByKey(object[] key) { int nodeId = FindNodeByKeys(key); if (IndexTree.NIL != nodeId) { return _records.GetIndexByNode(nodeId); } return -1; // return -1 to user indicating record not found } private int FindNodeByKey(object originalKey) { int x, c; if (_indexFields.Length != 1) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, 1); } x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist DataColumn column = _indexFields[0].Column; object key = column.ConvertValue(originalKey); x = _records.root; if (_indexFields[0].IsDescending) { while (IndexTree.NIL != x) { c = column.CompareValueTo(_records.Key(x), key); if (c == 0) { break; } if (c < 0) { x = _records.Left(x); } // < for decsending else { x = _records.Right(x); } } } else { while (IndexTree.NIL != x) { c = column.CompareValueTo(_records.Key(x), key); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } // > for ascending else { x = _records.Right(x); } } } } return x; } private int FindNodeByKeys(object[] originalKey) { int x, c; c = ((null != originalKey) ? originalKey.Length : 0); if ((0 == c) || (_indexFields.Length != c)) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, c); } x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist // copy array to avoid changing original object[] key = new object[originalKey.Length]; for (int i = 0; i < originalKey.Length; ++i) { key[i] = _indexFields[i].Column.ConvertValue(originalKey[i]); } x = _records.root; while (IndexTree.NIL != x) { c = CompareRecordToKey(_records.Key(x), key); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } else { x = _records.Right(x); } } } return x; } private int FindNodeByKeyRecord(int record) { int x, c; x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist x = _records.root; while (IndexTree.NIL != x) { c = CompareRecords(_records.Key(x), record); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } else { x = _records.Right(x); } } } return x; } private Range GetRangeFromNode(int nodeId) { // fill range with the min and max indexes of matching record (i.e min and max of satelite tree) // min index is the index of the node in main tree, and max is the min + size of satelite tree-1 if (IndexTree.NIL == nodeId) { return new Range(); } int recordIndex = _records.GetIndexByNode(nodeId); if (_records.Next(nodeId) == IndexTree.NIL) return new Range(recordIndex, recordIndex); int span = _records.SubTreeSize(_records.Next(nodeId)); return new Range(recordIndex, recordIndex + span - 1); } public Range FindRecords(object key) { int nodeId = FindNodeByKey(key); // main tree node associated with key return GetRangeFromNode(nodeId); } public Range FindRecords(object[] key) { int nodeId = FindNodeByKeys(key); // main tree node associated with key return GetRangeFromNode(nodeId); } internal void FireResetEvent() { DataCommonEventSource.Log.Trace("<ds.Index.FireResetEvent|API> {0}", ObjectID); if (DoListChanged) { OnListChanged(DataView.s_resetEventArgs); } } private int GetChangeAction(DataViewRowState oldState, DataViewRowState newState) { int oldIncluded = ((int)_recordStates & (int)oldState) == 0 ? 0 : 1; int newIncluded = ((int)_recordStates & (int)newState) == 0 ? 0 : 1; return newIncluded - oldIncluded; } /// <summary>Determine if the record that needs backdating is the newRecord or oldRecord or neither</summary> private static int GetReplaceAction(DataViewRowState oldState) { return ((0 != (DataViewRowState.CurrentRows & oldState)) ? ReplaceNewRecordForCompare : // Added/ModifiedCurrent/Unchanged ((0 != (DataViewRowState.OriginalRows & oldState)) ? ReplaceOldRecordForCompare : // Deleted/ModififedOriginal DoNotReplaceCompareRecord)); // None } public DataRow GetRow(int i) => _table._recordManager[GetRecord(i)]; public DataRow[] GetRows(object[] values) => GetRows(FindRecords(values)); public DataRow[] GetRows(Range range) { DataRow[] newRows = _table.NewRowArray(range.Count); if (0 < newRows.Length) { RBTree<int>.RBTreeEnumerator iterator = GetEnumerator(range.Min); for (int i = 0; i < newRows.Length && iterator.MoveNext(); i++) { newRows[i] = _table._recordManager[iterator.Current]; } } return newRows; } private void InitRecords(IFilter filter) { DataViewRowState states = _recordStates; // this improves performance when the is no filter, like with the default view (creating after rows added) // we know the records are in the correct order, just append to end, duplicates not possible bool append = (0 == _indexFields.Length); _records = new IndexTree(this); _recordCount = 0; // this improves performance by iterating of the index instead of computing record by index foreach (DataRow b in _table.Rows) { int record = -1; if (b._oldRecord == b._newRecord) { if ((states & DataViewRowState.Unchanged) != 0) { record = b._oldRecord; } } else if (b._oldRecord == -1) { if ((states & DataViewRowState.Added) != 0) { record = b._newRecord; } } else if (b._newRecord == -1) { if ((states & DataViewRowState.Deleted) != 0) { record = b._oldRecord; } } else { if ((states & DataViewRowState.ModifiedCurrent) != 0) { record = b._newRecord; } else if ((states & DataViewRowState.ModifiedOriginal) != 0) { record = b._oldRecord; } } if (record != -1 && AcceptRecord(record, filter)) { _records.InsertAt(-1, record, append); _recordCount++; } } } // InsertRecordToIndex inserts the given record to index and does not fire any Event. IT SHOULD NOT FIRE EVENT // I added this since I can not use existing InsertRecord which is not silent operation // it returns the position that record is inserted public int InsertRecordToIndex(int record) { int pos = -1; if (AcceptRecord(record)) { pos = InsertRecord(record, false); } return pos; } // existing functionality, it calls the overlaod with fireEvent== true, so it still fires the event private int InsertRecord(int record, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.Index.InsertRecord|INFO> {0}, record={1}, fireEvent={2}", ObjectID, record, fireEvent); // this improves performance when the is no filter, like with the default view (creating before rows added) // we know can append when the new record is the last row in table, normal insertion pattern bool append = false; if ((0 == _indexFields.Length) && (null != _table)) { DataRow row = _table._recordManager[record]; append = (_table.Rows.IndexOf(row) + 1 == _table.Rows.Count); } int nodeId = _records.InsertAt(-1, record, append); _recordCount++; MaintainDataView(ListChangedType.ItemAdded, record, !fireEvent); if (fireEvent) { if (DoListChanged) { OnListChanged(ListChangedType.ItemAdded, _records.GetIndexByNode(nodeId)); } return 0; } else { return _records.GetIndexByNode(nodeId); } } // Search for specified key public bool IsKeyInIndex(object key) { int x_id = FindNodeByKey(key); return (IndexTree.NIL != x_id); } public bool IsKeyInIndex(object[] key) { int x_id = FindNodeByKeys(key); return (IndexTree.NIL != x_id); } public bool IsKeyRecordInIndex(int record) { int x_id = FindNodeByKeyRecord(record); return (IndexTree.NIL != x_id); } private bool DoListChanged => (!_suspendEvents && _listeners.HasListeners && !_table.AreIndexEventsSuspended); private void OnListChanged(ListChangedType changedType, int newIndex, int oldIndex) { if (DoListChanged) { OnListChanged(new ListChangedEventArgs(changedType, newIndex, oldIndex)); } } private void OnListChanged(ListChangedType changedType, int index) { if (DoListChanged) { OnListChanged(new ListChangedEventArgs(changedType, index)); } } private void OnListChanged(ListChangedEventArgs e) { DataCommonEventSource.Log.Trace("<ds.Index.OnListChanged|INFO> {0}", ObjectID); Debug.Assert(DoListChanged, "supposed to check DoListChanged before calling to delay create ListChangedEventArgs"); _listeners.Notify(e, false, false, delegate (DataViewListener listener, ListChangedEventArgs args, bool arg2, bool arg3) { listener.IndexListChanged(args); }); } private void MaintainDataView(ListChangedType changedType, int record, bool trackAddRemove) { Debug.Assert(-1 <= record, "bad record#"); _listeners.Notify(changedType, ((0 <= record) ? _table._recordManager[record] : null), trackAddRemove, delegate (DataViewListener listener, ListChangedType type, DataRow row, bool track) { listener.MaintainDataView(changedType, row, track); }); } public void Reset() { DataCommonEventSource.Log.Trace("<ds.Index.Reset|API> {0}", ObjectID); InitRecords(RowFilter); MaintainDataView(ListChangedType.Reset, -1, false); FireResetEvent(); } public void RecordChanged(int record) { DataCommonEventSource.Log.Trace("<ds.Index.RecordChanged|API> {0}, record={1}", ObjectID, record); if (DoListChanged) { int index = GetIndex(record); if (index >= 0) { OnListChanged(ListChangedType.ItemChanged, index); } } } // new RecordChanged which takes oldIndex and newIndex and fires _onListChanged public void RecordChanged(int oldIndex, int newIndex) { DataCommonEventSource.Log.Trace("<ds.Index.RecordChanged|API> {0}, oldIndex={1}, newIndex={2}", ObjectID, oldIndex, newIndex); if (oldIndex > -1 || newIndex > -1) { // no need to fire if it was not and will not be in index: this check means at least one version should be in index if (oldIndex == newIndex) { OnListChanged(ListChangedType.ItemChanged, newIndex, oldIndex); } else if (oldIndex == -1) { // it is added OnListChanged(ListChangedType.ItemAdded, newIndex, oldIndex); } else if (newIndex == -1) { OnListChanged(ListChangedType.ItemDeleted, oldIndex); } else { OnListChanged(ListChangedType.ItemMoved, newIndex, oldIndex); } } } public void RecordStateChanged(int record, DataViewRowState oldState, DataViewRowState newState) { DataCommonEventSource.Log.Trace("<ds.Index.RecordStateChanged|API> {0}, record={1}, oldState={2}, newState={3}", ObjectID, record, oldState, newState); int action = GetChangeAction(oldState, newState); ApplyChangeAction(record, action, GetReplaceAction(oldState)); } public void RecordStateChanged(int oldRecord, DataViewRowState oldOldState, DataViewRowState oldNewState, int newRecord, DataViewRowState newOldState, DataViewRowState newNewState) { DataCommonEventSource.Log.Trace("<ds.Index.RecordStateChanged|API> {0}, oldRecord={1}, oldOldState={2}, oldNewState={3}, newRecord={4}, newOldState={5}, newNewState={6}", ObjectID, oldRecord, oldOldState, oldNewState, newRecord, newOldState, newNewState); Debug.Assert((-1 == oldRecord) || (-1 == newRecord) || _table._recordManager[oldRecord] == _table._recordManager[newRecord], "not the same DataRow when updating oldRecord and newRecord"); int oldAction = GetChangeAction(oldOldState, oldNewState); int newAction = GetChangeAction(newOldState, newNewState); if (oldAction == -1 && newAction == 1 && AcceptRecord(newRecord)) { int oldRecordIndex; if ((null != _comparison) && oldAction < 0) { // when oldRecord is being removed, allow GetIndexByKey updating the DataRow for Comparison<DataRow> oldRecordIndex = GetIndex(oldRecord, GetReplaceAction(oldOldState)); } else { oldRecordIndex = GetIndex(oldRecord); } if ((null == _comparison) && oldRecordIndex != -1 && CompareRecords(oldRecord, newRecord) == 0) { _records.UpdateNodeKey(oldRecord, newRecord); //change in place, as Both records have same key value int commonIndexLocation = GetIndex(newRecord); OnListChanged(ListChangedType.ItemChanged, commonIndexLocation, commonIndexLocation); } else { _suspendEvents = true; if (oldRecordIndex != -1) { _records.DeleteByIndex(oldRecordIndex); // DeleteByIndex doesn't require searching by key _recordCount--; } _records.Insert(newRecord); _recordCount++; _suspendEvents = false; int newRecordIndex = GetIndex(newRecord); if (oldRecordIndex == newRecordIndex) { // if the position is the same OnListChanged(ListChangedType.ItemChanged, newRecordIndex, oldRecordIndex); // be carefull remove oldrecord index if needed } else { if (oldRecordIndex == -1) { MaintainDataView(ListChangedType.ItemAdded, newRecord, false); OnListChanged(ListChangedType.ItemAdded, GetIndex(newRecord)); // oldLocation would be -1 } else { OnListChanged(ListChangedType.ItemMoved, newRecordIndex, oldRecordIndex); } } } } else { ApplyChangeAction(oldRecord, oldAction, GetReplaceAction(oldOldState)); ApplyChangeAction(newRecord, newAction, GetReplaceAction(newOldState)); } } internal DataTable Table => _table; private void GetUniqueKeyValues(List<object[]> list, int curNodeId) { if (curNodeId != IndexTree.NIL) { GetUniqueKeyValues(list, _records.Left(curNodeId)); int record = _records.Key(curNodeId); object[] element = new object[_indexFields.Length]; // number of columns in PK for (int j = 0; j < element.Length; ++j) { element[j] = _indexFields[j].Column[record]; } list.Add(element); GetUniqueKeyValues(list, _records.Right(curNodeId)); } } internal static int IndexOfReference<T>(List<T> list, T item) where T : class { if (null != list) { for (int i = 0; i < list.Count; ++i) { if (ReferenceEquals(list[i], item)) { return i; } } } return -1; } internal static bool ContainsReference<T>(List<T> list, T item) where T : class { return (0 <= IndexOfReference(list, item)); } } internal sealed class Listeners<TElem> where TElem : class { private readonly List<TElem> _listeners; private readonly Func<TElem, bool> _filter; private readonly int _objectID; private int _listenerReaderCount; /// <summary>Wish this was defined in mscorlib.dll instead of System.Core.dll</summary> internal delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary>Wish this was defined in mscorlib.dll instead of System.Core.dll</summary> internal delegate TResult Func<T1, TResult>(T1 arg1); internal Listeners(int ObjectID, Func<TElem, bool> notifyFilter) { _listeners = new List<TElem>(); _filter = notifyFilter; _objectID = ObjectID; _listenerReaderCount = 0; } internal bool HasListeners => (0 < _listeners.Count); /// <remarks>Only call from inside a lock</remarks> internal void Add(TElem listener) { Debug.Assert(null != listener, "null listener"); Debug.Assert(!Index.ContainsReference(_listeners, listener), "already contains reference"); _listeners.Add(listener); } internal int IndexOfReference(TElem listener) { return Index.IndexOfReference(_listeners, listener); } /// <remarks>Only call from inside a lock</remarks> internal void Remove(TElem listener) { Debug.Assert(null != listener, "null listener"); int index = IndexOfReference(listener); Debug.Assert(0 <= index, "listeners don't contain listener"); _listeners[index] = null; if (0 == _listenerReaderCount) { _listeners.RemoveAt(index); _listeners.TrimExcess(); } } /// <summary> /// Write operation which means user must control multi-thread and we can assume single thread /// </summary> internal void Notify<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3, Action<TElem, T1, T2, T3> action) { Debug.Assert(null != action, "no action"); Debug.Assert(0 <= _listenerReaderCount, "negative _listEventCount"); int count = _listeners.Count; if (0 < count) { int nullIndex = -1; // protect against listeners shrinking via Remove _listenerReaderCount++; try { // protect against listeners growing via Add since new listeners will already have the Notify in progress for (int i = 0; i < count; ++i) { // protect against listener being set to null (instead of being removed) TElem listener = _listeners[i]; if (_filter(listener)) { // perform the action on each listener // some actions may throw an exception blocking remaning listeners from being notified (just like events) action(listener, arg1, arg2, arg3); } else { _listeners[i] = null; nullIndex = i; } } } finally { _listenerReaderCount--; } if (0 == _listenerReaderCount) { RemoveNullListeners(nullIndex); } } } private void RemoveNullListeners(int nullIndex) { Debug.Assert((-1 == nullIndex) || (null == _listeners[nullIndex]), "non-null listener"); Debug.Assert(0 == _listenerReaderCount, "0 < _listenerReaderCount"); for (int i = nullIndex; 0 <= i; --i) { if (null == _listeners[i]) { _listeners.RemoveAt(i); } } } } }
namespace WarMachines.Engine { using System; using System.Collections.Generic; using System.Linq; using WarMachines.Interfaces; public class Command : ICommand { private const char SplitCommandSymbol = ' '; private string name; private IList<string> parameters; private Command(string input) { this.TranslateInput(input); } public string Name { get { return this.name; } private set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("Name cannot be null or empty."); } this.name = value; } } public IList<string> Parameters { get { return this.parameters; } private set { if (value == null) { throw new ArgumentNullException("List of strings cannot be null."); } this.parameters = value; } } public static Command Parse(string input) { return new Command(input); } private void TranslateInput(string input) { var indexOfFirstSeparator = input.IndexOf(SplitCommandSymbol); this.Name = input.Substring(0, indexOfFirstSeparator); this.Parameters = input.Substring(indexOfFirstSeparator + 1).Split(new[] { SplitCommandSymbol }, StringSplitOptions.RemoveEmptyEntries); } } } namespace WarMachines.Engine { using WarMachines.Interfaces; using WarMachines.Machines; public class MachineFactory : IMachineFactory { public IPilot HirePilot(string name) { return new Pilot(name); } public ITank ManufactureTank(string name, double attackPoints, double defensePoints) { return new Tank(name, attackPoints, defensePoints); } public IFighter ManufactureFighter(string name, double attackPoints, double defensePoints, bool stealthMode) { return new Fighter(name, attackPoints, defensePoints, stealthMode); } } } namespace WarMachines.Engine { using System; using System.Collections.Generic; using System.Text; using WarMachines.Interfaces; public sealed class WarMachineEngine : IWarMachineEngine { private const string InvalidCommand = "Invalid command name: {0}"; private const string PilotHired = "Pilot {0} hired"; private const string PilotExists = "Pilot {0} is hired already"; private const string TankManufactured = "Tank {0} manufactured - attack: {1}; defense: {2}"; private const string FighterManufactured = "Fighter {0} manufactured - attack: {1}; defense: {2}; stealth: {3}"; private const string MachineExists = "Machine {0} is manufactured already"; private const string MachineHasPilotAlready = "Machine {0} is already occupied"; private const string PilotNotFound = "Pilot {0} could not be found"; private const string MachineNotFound = "Machine {0} could not be found"; private const string MachineEngaged = "Pilot {0} engaged machine {1}"; private const string InvalidMachineOperation = "Machine {0} does not support this operation"; private const string FighterOperationSuccessful = "Fighter {0} toggled stealth mode"; private const string TankOperationSuccessful = "Tank {0} toggled defense mode"; private const string InvalidAttackTarget = "Tank {0} cannot attack stealth fighter {1}"; private const string AttackSuccessful = "Machine {0} was attacked by machine {1} - current health: {2}"; private static readonly WarMachineEngine SingleInstance = new WarMachineEngine(); private IMachineFactory factory; private IDictionary<string, IPilot> pilots; private IDictionary<string, IMachine> machines; private WarMachineEngine() { this.factory = new MachineFactory(); this.pilots = new Dictionary<string, IPilot>(); this.machines = new Dictionary<string, IMachine>(); } public static WarMachineEngine Instance { get { return SingleInstance; } } public void Start() { var commands = this.ReadCommands(); var commandResult = this.ProcessCommands(commands); this.PrintReports(commandResult); } private IList<ICommand> ReadCommands() { var commands = new List<ICommand>(); var currentLine = Console.ReadLine(); while (!string.IsNullOrEmpty(currentLine)) { var currentCommand = Command.Parse(currentLine); commands.Add(currentCommand); currentLine = Console.ReadLine(); } return commands; } private IList<string> ProcessCommands(IList<ICommand> commands) { var reports = new List<string>(); foreach (var command in commands) { string commandResult; switch (command.Name) { case "HirePilot": var pilotName = command.Parameters[0]; commandResult = this.HirePilot(pilotName); reports.Add(commandResult); break; case "Report": var pilotReporting = command.Parameters[0]; commandResult = this.PilotReport(pilotReporting); reports.Add(commandResult); break; case "ManufactureTank": var tankName = command.Parameters[0]; var tankAttackPoints = double.Parse(command.Parameters[1]); var tankDefensePoints = double.Parse(command.Parameters[2]); commandResult = this.ManufactureTank(tankName, tankAttackPoints, tankDefensePoints); reports.Add(commandResult); break; case "DefenseMode": var defenseModeTankName = command.Parameters[0]; commandResult = this.ToggleTankDefenseMode(defenseModeTankName); reports.Add(commandResult); break; case "ManufactureFighter": var fighterName = command.Parameters[0]; var fighterAttackPoints = double.Parse(command.Parameters[1]); var fighterDefensePoints = double.Parse(command.Parameters[2]); var fighterStealthMode = command.Parameters[3] == "StealthON" ? true : false; commandResult = this.ManufactureFighter(fighterName, fighterAttackPoints, fighterDefensePoints, fighterStealthMode); reports.Add(commandResult); break; case "StealthMode": var stealthModeFighterName = command.Parameters[0]; commandResult = this.ToggleFighterStealthMode(stealthModeFighterName); reports.Add(commandResult); break; case "Engage": var selectedPilotName = command.Parameters[0]; var selectedMachineName = command.Parameters[1]; commandResult = this.EngageMachine(selectedPilotName, selectedMachineName); reports.Add(commandResult); break; case "Attack": var attackingMachine = command.Parameters[0]; var defendingMachine = command.Parameters[1]; commandResult = this.AttackMachines(attackingMachine, defendingMachine); reports.Add(commandResult); break; default: reports.Add(string.Format(InvalidCommand, command.Name)); break; } } return reports; } private void PrintReports(IList<string> reports) { var output = new StringBuilder(); foreach (var report in reports) { output.AppendLine(report); } Console.Write(output.ToString()); } private string HirePilot(string name) { if (this.pilots.ContainsKey(name)) { return string.Format(PilotExists, name); } var pilot = this.factory.HirePilot(name); this.pilots.Add(name, pilot); return string.Format(PilotHired, name); } private string ManufactureTank(string name, double attackPoints, double defensePoints) { if (this.machines.ContainsKey(name)) { return string.Format(MachineExists, name); } var tank = this.factory.ManufactureTank(name, attackPoints, defensePoints); this.machines.Add(name, tank); return string.Format(TankManufactured, name, attackPoints, defensePoints); } private string ManufactureFighter(string name, double attackPoints, double defensePoints, bool stealthMode) { if (this.machines.ContainsKey(name)) { return string.Format(MachineExists, name); } var fighter = this.factory.ManufactureFighter(name, attackPoints, defensePoints, stealthMode); this.machines.Add(name, fighter); return string.Format(FighterManufactured, name, attackPoints, defensePoints, stealthMode == true ? "ON" : "OFF"); } private string EngageMachine(string selectedPilotName, string selectedMachineName) { if (!this.pilots.ContainsKey(selectedPilotName)) { return string.Format(PilotNotFound, selectedPilotName); } if (!this.machines.ContainsKey(selectedMachineName)) { return string.Format(MachineNotFound, selectedMachineName); } if (this.machines[selectedMachineName].Pilot != null) { return string.Format(MachineHasPilotAlready, selectedMachineName); } var pilot = this.pilots[selectedPilotName]; var machine = this.machines[selectedMachineName]; pilot.AddMachine(machine); machine.Pilot = pilot; return string.Format(MachineEngaged, selectedPilotName, selectedMachineName); } private string AttackMachines(string attackingMachineName, string defendingMachineName) { if (!this.machines.ContainsKey(attackingMachineName)) { return string.Format(MachineNotFound, attackingMachineName); } if (!this.machines.ContainsKey(defendingMachineName)) { return string.Format(MachineNotFound, defendingMachineName); } var attackingMachine = this.machines[attackingMachineName]; var defendingMachine = this.machines[defendingMachineName]; if (attackingMachine is ITank && defendingMachine is IFighter && (defendingMachine as IFighter).StealthMode) { return string.Format(InvalidAttackTarget, attackingMachineName, defendingMachineName); } attackingMachine.Targets.Add(defendingMachineName); var attackPoints = attackingMachine.AttackPoints; var defensePoints = defendingMachine.DefensePoints; var damage = attackPoints - defensePoints; if (damage > 0) { var newHeathPoints = defendingMachine.HealthPoints - damage; if (newHeathPoints < 0) { newHeathPoints = 0; } defendingMachine.HealthPoints = newHeathPoints; } return string.Format(AttackSuccessful, defendingMachineName, attackingMachineName, defendingMachine.HealthPoints); } private string PilotReport(string pilotReporting) { if (!this.pilots.ContainsKey(pilotReporting)) { return string.Format(PilotNotFound, pilotReporting); } return this.pilots[pilotReporting].Report(); } private string ToggleFighterStealthMode(string stealthModeFighterName) { if (!this.machines.ContainsKey(stealthModeFighterName)) { return string.Format(MachineNotFound, stealthModeFighterName); } if (this.machines[stealthModeFighterName] is ITank) { return string.Format(InvalidMachineOperation, stealthModeFighterName); } var machineAsFighter = this.machines[stealthModeFighterName] as IFighter; machineAsFighter.ToggleStealthMode(); return string.Format(FighterOperationSuccessful, stealthModeFighterName); } private string ToggleTankDefenseMode(string defenseModeTankName) { if (!this.machines.ContainsKey(defenseModeTankName)) { return string.Format(MachineNotFound, defenseModeTankName); } if (this.machines[defenseModeTankName] is IFighter) { return string.Format(InvalidMachineOperation, defenseModeTankName); } var machineAsFighter = this.machines[defenseModeTankName] as ITank; machineAsFighter.ToggleDefenseMode(); return string.Format(TankOperationSuccessful, defenseModeTankName); } } } namespace WarMachines.Interfaces { using System.Collections.Generic; public interface ICommand { string Name { get; } IList<string> Parameters { get; } } } namespace WarMachines.Interfaces { public interface IFighter : IMachine { bool StealthMode { get; } void ToggleStealthMode(); } } namespace WarMachines.Interfaces { using System.Collections.Generic; public interface IMachine { string Name { get; set; } IPilot Pilot { get; set; } double HealthPoints { get; set; } double AttackPoints { get; } double DefensePoints { get; } IList<string> Targets { get; } void Attack(string target); string ToString(); } } namespace WarMachines.Interfaces { public interface IMachineFactory { IPilot HirePilot(string name); ITank ManufactureTank(string name, double attackPoints, double defensePoints); IFighter ManufactureFighter(string name, double attackPoints, double defensePoints, bool stealthMode); } } namespace WarMachines.Interfaces { public interface IPilot { string Name { get; } void AddMachine(IMachine machine); string Report(); } } namespace WarMachines.Interfaces { public interface ITank : IMachine { bool DefenseMode { get; } void ToggleDefenseMode(); } } namespace WarMachines.Interfaces { using System.Collections.Generic; public interface IWarMachineEngine { void Start(); } } namespace WarMachines.Machines { using System; using System.Collections.Generic; using WarMachines; using WarMachines.Interfaces; public class DeleteMe { // TODO: Implement all machine classes in this namespace - WarMachines.Machines } public class Pilot : IPilot { public Pilot(string name) { this.Name = name; this.machines = new List<IMachine>(); } private string name; private IList<IMachine> machines; public string Name { get { return this.name; } private set { this.name = value; } } public void AddMachine(IMachine machine) { this.machines.Add(machine); } public string Report() { string report = string.Empty; report = this.ToString(); foreach (var machine in this.machines) { report += machine.ToString(); } return report; } public override string ToString() { string tostring = string.Empty; int machinesCnt = this.machines.Count; tostring += this.Name + " - "; if (machinesCnt == 0) { tostring += "no machines"; } else if (machinesCnt == 1) { tostring += "1 machine"; } else { tostring += machinesCnt + " " + "machines"; } return tostring; } } public abstract class Machine : IMachine { private string name; private IPilot pilot; private double healthPoints; private double attackPoints; private double defensePoints; private IList<string> targets = new List<string>(); public string Name { get { return this.name; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("Machine name can not be null or empty!"); this.name = value; } } public IPilot Pilot { get { return this.pilot; } set { if (null == value) throw new ArgumentNullException("Pilot can not be null!"); this.pilot = value; } } public double HealthPoints { get { return this.healthPoints; } set { this.healthPoints = value; } } public double AttackPoints { get { return this.attackPoints; } set { this.attackPoints = value; } } public double DefensePoints { get { return this.defensePoints; } set { this.defensePoints = value; } } public IList<string> Targets { get { return this.targets; } } public void Attack(string target) { this.Targets.Add(target); } public override string ToString() { //Targets string trgts = string.Empty; if (this.Targets.Count == 0) { trgts = "None"; } else { for (int indx = 0; indx < this.Targets.Count; indx++) { trgts += this.Targets[indx]; if (indx != this.Targets.Count - 1) { trgts += ", "; } } } //defense mode string defense = string.Empty; var hasDefense = this as Tank; if (hasDefense != null) { if (hasDefense.DefenseMode) { defense = "\n *Defense: ON"; } else { defense = "\n *Defense: OFF"; } } //stealth mode string stealth = string.Empty; var hasStealth = this as Fighter; if (hasStealth != null) { if (hasStealth.StealthMode) { stealth = "\n *Stealth: ON"; } else { stealth = "\n *Stealth: OFF"; } } string tostring = string.Format("\n- {0}\n *Type: {1}\n *Health: {2}\n *Attack: {3}\n *Defense: {4}\n *Targets: {5}{6}{7}", this.Name, this.GetType().Name, this.HealthPoints, this.AttackPoints, this.DefensePoints, trgts, defense, stealth); return tostring; } } public class Tank : Machine, ITank { public Tank(string name, double attackPoints, double defensePoints) { this.Name = name; this.AttackPoints = attackPoints; this.DefensePoints = defensePoints; this.HealthPoints = 100; ToggleDefenseMode(); } private bool defenseMode; public bool DefenseMode { get { return this.defenseMode; } set { this.defenseMode = value; } } public void ToggleDefenseMode() { if (this.defenseMode == false) { this.DefensePoints += 30; this.AttackPoints -= 40; this.defenseMode = true; } else { this.DefensePoints -= 30; this.AttackPoints += 40; this.defenseMode = false; } } } public class Fighter : Machine, IFighter { public Fighter(string name, double attackPoints, double defensePoints, bool stealthMode) { this.Name = name; this.AttackPoints = attackPoints; this.DefensePoints = defensePoints; this.StealthMode = stealthMode; this.HealthPoints = 200; } private bool stealthMode; public bool StealthMode { get { return this.stealthMode; } set { this.stealthMode = value; } } public void ToggleStealthMode() { this.StealthMode = !this.StealthMode; } } } namespace WarMachines { using WarMachines.Engine; public class WarMachinesProgram { public static void Main() { WarMachineEngine.Instance.Start(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Security.Authentication; namespace System.Net.Security { // Implements SSL session caching mechanism based on a static table of SSL credentials. internal static class SslSessionsCache { private const int CheckExpiredModulo = 32; private static Hashtable s_CachedCreds = new Hashtable(32); // // Uses certificate thumb-print comparison. // private struct SslCredKey { private byte[] _CertThumbPrint; private int _AllowedProtocols; private bool _isServerMode; private EncryptionPolicy _EncryptionPolicy; private readonly int _HashCode; // // SECURITY: X509Certificate.GetCertHash() is virtual hence before going here, // the caller of this ctor has to ensure that a user cert object was inspected and // optionally cloned. // internal SslCredKey(byte[] thumbPrint, int allowedProtocols, bool serverMode, EncryptionPolicy encryptionPolicy) { _CertThumbPrint = thumbPrint == null ? Array.Empty<byte>() : thumbPrint; _HashCode = 0; if (thumbPrint != null) { _HashCode ^= _CertThumbPrint[0]; if (1 < _CertThumbPrint.Length) { _HashCode ^= (_CertThumbPrint[1] << 8); } if (2 < _CertThumbPrint.Length) { _HashCode ^= (_CertThumbPrint[2] << 16); } if (3 < _CertThumbPrint.Length) { _HashCode ^= (_CertThumbPrint[3] << 24); } } _HashCode ^= allowedProtocols; _HashCode ^= (int)encryptionPolicy; _HashCode ^= serverMode ? 0x10000 : 0x20000; _AllowedProtocols = allowedProtocols; _EncryptionPolicy = encryptionPolicy; _isServerMode = serverMode; } public override int GetHashCode() { return _HashCode; } public static bool operator ==(SslCredKey sslCredKey1, SslCredKey sslCredKey2) { return sslCredKey1.Equals(sslCredKey2); } public static bool operator !=(SslCredKey sslCredKey1, SslCredKey sslCredKey2) { return !sslCredKey1.Equals(sslCredKey2); } public override bool Equals(Object y) { SslCredKey other = (SslCredKey)y; if (_CertThumbPrint.Length != other._CertThumbPrint.Length) { return false; } if (_HashCode != other._HashCode) { return false; } if (_EncryptionPolicy != other._EncryptionPolicy) { return false; } if (_AllowedProtocols != other._AllowedProtocols) { return false; } if (_isServerMode != other._isServerMode) { return false; } for (int i = 0; i < _CertThumbPrint.Length; ++i) { if (_CertThumbPrint[i] != other._CertThumbPrint[i]) { return false; } } return true; } } // // Returns null or previously cached cred handle. // // ATTN: The returned handle can be invalid, the callers of InitializeSecurityContext and AcceptSecurityContext // must be prepared to execute a back-out code if the call fails. // internal static SafeFreeCredentials TryCachedCredential(byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { if (s_CachedCreds.Count == 0) { GlobalLog.Print("TryCachedCredential() Not found, Current Cache Count = " + s_CachedCreds.Count); return null; } object key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); SafeCredentialReference cached = s_CachedCreds[key] as SafeCredentialReference; if (cached == null || cached.IsClosed || cached.Target.IsInvalid) { GlobalLog.Print("TryCachedCredential() Not found or invalid, Current Cache Count = " + s_CachedCreds.Count); return null; } GlobalLog.Print("TryCachedCredential() Found a cached Handle = " + cached.Target.ToString()); return cached.Target; } // // The app is calling this method after starting an SSL handshake. // // ATTN: The thumbPrint must be from inspected and possibly cloned user Cert object or we get a security hole in SslCredKey ctor. // internal static void CacheCredential(SafeFreeCredentials creds, byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { GlobalLog.Assert(creds != null, "CacheCredential|creds == null"); if (creds.IsInvalid) { GlobalLog.Print("CacheCredential() Refused to cache an Invalid Handle = " + creds.ToString() + ", Current Cache Count = " + s_CachedCreds.Count); return; } object key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); SafeCredentialReference cached = s_CachedCreds[key] as SafeCredentialReference; if (cached == null || cached.IsClosed || cached.Target.IsInvalid) { lock (s_CachedCreds) { cached = s_CachedCreds[key] as SafeCredentialReference; if (cached == null || cached.IsClosed) { cached = SafeCredentialReference.CreateReference(creds); if (cached == null) { // Means the handle got closed in between, return it back and let caller deal with the issue. return; } s_CachedCreds[key] = cached; GlobalLog.Print("CacheCredential() Caching New Handle = " + creds.ToString() + ", Current Cache Count = " + s_CachedCreds.Count); // // A simplest way of preventing infinite cache grows. // // Security relief (DoS): // A number of active creds is never greater than a number of _outstanding_ // security sessions, i.e. SSL connections. // So we will try to shrink cache to the number of active creds once in a while. // // We won't shrink cache in the case when NO new handles are coming to it. // if ((s_CachedCreds.Count % CheckExpiredModulo) == 0) { DictionaryEntry[] toRemoveAttempt = new DictionaryEntry[s_CachedCreds.Count]; s_CachedCreds.CopyTo(toRemoveAttempt, 0); for (int i = 0; i < toRemoveAttempt.Length; ++i) { cached = toRemoveAttempt[i].Value as SafeCredentialReference; if (cached != null) { creds = cached.Target; cached.Dispose(); if (!creds.IsClosed && !creds.IsInvalid && (cached = SafeCredentialReference.CreateReference(creds)) != null) { s_CachedCreds[toRemoveAttempt[i].Key] = cached; } else { s_CachedCreds.Remove(toRemoveAttempt[i].Key); } } } GlobalLog.Print("Scavenged cache, New Cache Count = " + s_CachedCreds.Count); } } else { GlobalLog.Print("CacheCredential() (locked retry) Found already cached Handle = " + cached.Target.ToString()); } } } else { GlobalLog.Print("CacheCredential() Ignoring incoming handle = " + creds.ToString() + " since found already cached Handle = " + cached.Target.ToString()); } } } }
// 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 files defines the following types: * - NativeOverlapped * - _IOCompletionCallback * - OverlappedData * - Overlapped * - OverlappedDataCache */ /*============================================================================= ** ** ** ** Purpose: Class for converting information to and from the native ** overlapped structure used in asynchronous file i/o ** ** =============================================================================*/ namespace System.Threading { using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; using System.Collections.Concurrent; #region struct NativeOverlapped // Valuetype that represents the (unmanaged) Win32 OVERLAPPED structure // the layout of this structure must be identical to OVERLAPPED. // The first five matches OVERLAPPED structure. // The remaining are reserved at the end [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct NativeOverlapped { public IntPtr InternalLow; public IntPtr InternalHigh; public int OffsetLow; public int OffsetHigh; public IntPtr EventHandle; } #endregion struct NativeOverlapped #region class _IOCompletionCallback unsafe internal class _IOCompletionCallback { [System.Security.SecurityCritical] // auto-generated IOCompletionCallback _ioCompletionCallback; ExecutionContext _executionContext; uint _errorCode; // Error code uint _numBytes; // No. of bytes transferred [SecurityCritical] NativeOverlapped* _pOVERLAP; [System.Security.SecuritySafeCritical] // auto-generated static _IOCompletionCallback() { } [System.Security.SecurityCritical] // auto-generated internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ref StackCrawlMark stackMark) { _ioCompletionCallback = ioCompletionCallback; // clone the exection context _executionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase); } // Context callback: same sig for SendOrPostCallback and ContextCallback #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context); [System.Security.SecurityCritical] static internal void IOCompletionCallback_Context(Object state) { _IOCompletionCallback helper = (_IOCompletionCallback)state; Contract.Assert(helper != null,"_IOCompletionCallback cannot be null"); helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP); } // call back helper [System.Security.SecurityCritical] // auto-generated static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code uint numBytes, // No. of bytes transferred NativeOverlapped* pOVERLAP // ptr to OVERLAP structure ) { Overlapped overlapped; _IOCompletionCallback helper; do { overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped; helper = overlapped.iocbHelper; if (helper == null || helper._executionContext == null || helper._executionContext.IsDefaultFTContext(true)) { // We got here because of UnsafePack (or) Pack with EC flow supressed IOCompletionCallback callback = overlapped.UserCallback; callback( errorCode, numBytes, pOVERLAP); } else { // We got here because of Pack helper._errorCode = errorCode; helper._numBytes = numBytes; helper._pOVERLAP = pOVERLAP; using (ExecutionContext executionContext = helper._executionContext.CreateCopy()) ExecutionContext.Run(executionContext, _ccb, helper, true); } //Quickly check the VM again, to see if a packet has arrived. OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); } while (pOVERLAP != null); } } #endregion class _IOCompletionCallback #region class OverlappedData sealed internal class OverlappedData { // ! If you make any change to the layout here, you need to make matching change // ! to OverlappedObject in vm\nativeoverlapped.h internal IAsyncResult m_asyncResult; [System.Security.SecurityCritical] // auto-generated internal IOCompletionCallback m_iocb; internal _IOCompletionCallback m_iocbHelper; internal Overlapped m_overlapped; private Object m_userObject; private IntPtr m_pinSelf; private IntPtr m_userObjectInternal; private int m_AppDomainId; #pragma warning disable 414 // Field is not used from managed. #pragma warning disable 169 private byte m_isArray; private byte m_toBeCleaned; #pragma warning restore 414 #pragma warning restore 169 internal NativeOverlapped m_nativeOverlapped; #if FEATURE_CORECLR // Adding an empty default ctor for annotation purposes [System.Security.SecuritySafeCritical] // auto-generated internal OverlappedData(){} #endif // FEATURE_CORECLR [System.Security.SecurityCritical] internal void ReInitialize() { m_asyncResult = null; m_iocb = null; m_iocbHelper = null; m_overlapped = null; m_userObject = null; Contract.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf"); m_pinSelf = (IntPtr)0; m_userObjectInternal = (IntPtr)0; Contract.Assert(m_AppDomainId == 0 || m_AppDomainId == AppDomain.CurrentDomain.Id, "OverlappedData is not in the current domain"); m_AppDomainId = 0; m_nativeOverlapped.EventHandle = (IntPtr)0; m_isArray = 0; m_nativeOverlapped.InternalLow = (IntPtr)0; m_nativeOverlapped.InternalHigh = (IntPtr)0; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { if (!m_pinSelf.IsNull()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack")); } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (iocb != null) { m_iocbHelper = new _IOCompletionCallback(iocb, ref stackMark); m_iocb = iocb; } else { m_iocbHelper = null; m_iocb = null; } m_userObject = userData; if (m_userObject != null) { if (m_userObject.GetType() == typeof(Object[])) { m_isArray = 1; } else { m_isArray = 0; } } return AllocateNativeOverlapped(); } [System.Security.SecurityCritical] // auto-generated_required unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) { if (!m_pinSelf.IsNull()) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack")); } m_userObject = userData; if (m_userObject != null) { if (m_userObject.GetType() == typeof(Object[])) { m_isArray = 1; } else { m_isArray = 0; } } m_iocb = iocb; m_iocbHelper = null; return AllocateNativeOverlapped(); } [ComVisible(false)] internal IntPtr UserHandle { get { return m_nativeOverlapped.EventHandle; } set { m_nativeOverlapped.EventHandle = value; } } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe private extern NativeOverlapped* AllocateNativeOverlapped(); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes); } #endregion class OverlappedData #region class Overlapped /// <internalonly/> [System.Runtime.InteropServices.ComVisible(true)] public class Overlapped { private OverlappedData m_overlappedData; private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData()); #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #endif public Overlapped() { m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; } public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) { m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo; m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi; m_overlappedData.UserHandle = hEvent; m_overlappedData.m_asyncResult = ar; } [Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")] public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar) { } public IAsyncResult AsyncResult { get { return m_overlappedData.m_asyncResult; } set { m_overlappedData.m_asyncResult = value; } } public int OffsetLow { get { return m_overlappedData.m_nativeOverlapped.OffsetLow; } set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; } } public int OffsetHigh { get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; } set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; } } [Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int EventHandle { get { return m_overlappedData.UserHandle.ToInt32(); } set { m_overlappedData.UserHandle = new IntPtr(value); } } [ComVisible(false)] public IntPtr EventHandleIntPtr { get { return m_overlappedData.UserHandle; } set { m_overlappedData.UserHandle = value; } } internal _IOCompletionCallback iocbHelper { get { return m_overlappedData.m_iocbHelper; } } internal IOCompletionCallback UserCallback { [System.Security.SecurityCritical] get { return m_overlappedData.m_iocb; } } /*==================================================================== * Packs a managed overlapped class into native Overlapped struct. * Roots the iocb and stores it in the ReservedCOR field of native Overlapped * Pins the native Overlapped struct and returns the pinned index. ====================================================================*/ [System.Security.SecurityCritical] // auto-generated [Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb) { return Pack (iocb, null); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false),ComVisible(false)] unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { return m_overlappedData.Pack(iocb, userData); } [System.Security.SecurityCritical] // auto-generated_required [Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb) { return UnsafePack (iocb, null); } [System.Security.SecurityCritical] // auto-generated_required [CLSCompliant(false), ComVisible(false)] unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) { return m_overlappedData.UnsafePack(iocb, userData); } /*==================================================================== * Unpacks an unmanaged native Overlapped struct. * Unpins the native Overlapped struct ====================================================================*/ [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] unsafe public static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; return overlapped; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] unsafe public static void Free(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); OverlappedData overlappedData = overlapped.m_overlappedData; overlapped.m_overlappedData = null; overlappedData.ReInitialize(); s_overlappedDataCache.Free(overlappedData); } } #endregion class Overlapped } // namespace
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedConversationProfilesClientTest { [xunit::FactAttribute] public void GetConversationProfileRequestObject() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); GetConversationProfileRequest request = new GetConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.GetConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.GetConversationProfile(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConversationProfileRequestObjectAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); GetConversationProfileRequest request = new GetConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.GetConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.GetConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.GetConversationProfileAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConversationProfile() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); GetConversationProfileRequest request = new GetConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.GetConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.GetConversationProfile(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConversationProfileAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); GetConversationProfileRequest request = new GetConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.GetConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.GetConversationProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.GetConversationProfileAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConversationProfileResourceNames() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); GetConversationProfileRequest request = new GetConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.GetConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.GetConversationProfile(request.ConversationProfileName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConversationProfileResourceNamesAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); GetConversationProfileRequest request = new GetConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.GetConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.GetConversationProfileAsync(request.ConversationProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.GetConversationProfileAsync(request.ConversationProfileName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateConversationProfileRequestObject() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.CreateConversationProfile(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateConversationProfileRequestObjectAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateConversationProfile() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.CreateConversationProfile(request.Parent, request.ConversationProfile); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateConversationProfileAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request.Parent, request.ConversationProfile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request.Parent, request.ConversationProfile, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateConversationProfileResourceNames1() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.CreateConversationProfile(request.ParentAsProjectName, request.ConversationProfile); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateConversationProfileResourceNames1Async() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request.ParentAsProjectName, request.ConversationProfile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request.ParentAsProjectName, request.ConversationProfile, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateConversationProfileResourceNames2() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.CreateConversationProfile(request.ParentAsLocationName, request.ConversationProfile); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateConversationProfileResourceNames2Async() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); CreateConversationProfileRequest request = new CreateConversationProfileRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), ConversationProfile = new ConversationProfile(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.CreateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.CreateConversationProfileAsync(request.ParentAsLocationName, request.ConversationProfile, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.CreateConversationProfileAsync(request.ParentAsLocationName, request.ConversationProfile, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateConversationProfileRequestObject() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); UpdateConversationProfileRequest request = new UpdateConversationProfileRequest { ConversationProfile = new ConversationProfile(), UpdateMask = new wkt::FieldMask(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.UpdateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.UpdateConversationProfile(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateConversationProfileRequestObjectAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); UpdateConversationProfileRequest request = new UpdateConversationProfileRequest { ConversationProfile = new ConversationProfile(), UpdateMask = new wkt::FieldMask(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.UpdateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.UpdateConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.UpdateConversationProfileAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateConversationProfile() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); UpdateConversationProfileRequest request = new UpdateConversationProfileRequest { ConversationProfile = new ConversationProfile(), UpdateMask = new wkt::FieldMask(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.UpdateConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile response = client.UpdateConversationProfile(request.ConversationProfile, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateConversationProfileAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); UpdateConversationProfileRequest request = new UpdateConversationProfileRequest { ConversationProfile = new ConversationProfile(), UpdateMask = new wkt::FieldMask(), }; ConversationProfile expectedResponse = new ConversationProfile { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), DisplayName = "display_name137f65c2", AutomatedAgentConfig = new AutomatedAgentConfig(), HumanAgentAssistantConfig = new HumanAgentAssistantConfig(), HumanAgentHandoffConfig = new HumanAgentHandoffConfig(), NotificationConfig = new NotificationConfig(), LoggingConfig = new LoggingConfig(), NewMessageEventNotificationConfig = new NotificationConfig(), SttConfig = new SpeechToTextConfig(), LanguageCode = "language_code2f6c7160", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), SecuritySettingsAsCXSecuritySettingsName = CXSecuritySettingsName.FromProjectLocationSecuritySettings("[PROJECT]", "[LOCATION]", "[SECURITY_SETTINGS]"), TimeZone = "time_zone73f23b20", }; mockGrpcClient.Setup(x => x.UpdateConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConversationProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); ConversationProfile responseCallSettings = await client.UpdateConversationProfileAsync(request.ConversationProfile, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ConversationProfile responseCancellationToken = await client.UpdateConversationProfileAsync(request.ConversationProfile, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteConversationProfileRequestObject() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); DeleteConversationProfileRequest request = new DeleteConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); client.DeleteConversationProfile(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteConversationProfileRequestObjectAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); DeleteConversationProfileRequest request = new DeleteConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); await client.DeleteConversationProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteConversationProfileAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteConversationProfile() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); DeleteConversationProfileRequest request = new DeleteConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); client.DeleteConversationProfile(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteConversationProfileAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); DeleteConversationProfileRequest request = new DeleteConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); await client.DeleteConversationProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteConversationProfileAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteConversationProfileResourceNames() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); DeleteConversationProfileRequest request = new DeleteConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteConversationProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); client.DeleteConversationProfile(request.ConversationProfileName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteConversationProfileResourceNamesAsync() { moq::Mock<ConversationProfiles.ConversationProfilesClient> mockGrpcClient = new moq::Mock<ConversationProfiles.ConversationProfilesClient>(moq::MockBehavior.Strict); DeleteConversationProfileRequest request = new DeleteConversationProfileRequest { ConversationProfileName = ConversationProfileName.FromProjectConversationProfile("[PROJECT]", "[CONVERSATION_PROFILE]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteConversationProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversationProfilesClient client = new ConversationProfilesClientImpl(mockGrpcClient.Object, null); await client.DeleteConversationProfileAsync(request.ConversationProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteConversationProfileAsync(request.ConversationProfileName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Modeling; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fscc; using System; namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter { /// <summary> /// A base interface that implements IAdapter /// </summary> public interface IFSAAdapter : IAdapter { #region Initialize /// <summary> /// FSA initialize, it contains the following operations: /// 1. The client connects to server. /// 2. The client sets up a session with server. /// 3. The client connects to a share on server. /// </summary> void FsaInitial(); #endregion #region 3.1.5 Higher-Layer Triggered Events #region 3.1.5.1 Server Requests an Open of a File #region 3.1.5.1.1 Creation of a New File /// <summary> /// Implement CreateFile Interface /// </summary> /// <param name="desiredFileAttribute">Desired file attribute</param> /// <param name="createOption">Specifies the options to be applied when creating or opening the file</param> /// <param name="streamTypeNameToOPen">The name of stream type to open</param> /// <param name="desiredAccess">A bitmask indicating desired access for the open, as specified in [MS-SMB2] section 2.2.13.1.</param> /// <param name="shareAccess">A bitmask indicating sharing access for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="createDisposition">The desired disposition for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="streamFoundType">Indicate if the stream is found or not.</param> /// <param name="symbolicLinkType">Indicate if it is symbolic link or not.</param> /// <param name="openFileType">Indicate Filetype of open file</param> /// <param name="fileNameStatus">File name status</param> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus CreateFile( FileAttribute desiredFileAttribute, CreateOptions createOption, StreamTypeNameToOPen streamTypeNameToOpen, FileAccess desiredAccess, ShareAccess shareAccess, CreateDisposition createDisposition, StreamFoundType streamFoundType, SymbolicLinkType symbolicLinkType, FileType openFileType, FileNameStatus fileNameStatus ); #endregion #region 3.1.5.1.2 Open of an Existing File /// <summary> /// Implement OpenExistingFile Interface /// </summary> /// <param name="shareAccess">A bitmask indicates sharing access for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="desiredAccess">A bitmask indicates desired access for the open, as specified in [MS-SMB2] section 2.2.13.1.</param> /// <param name="streamFoundType">Indicate if the stream is found or not.</param> /// <param name="symbolicLinkType">Indicate if it is symbolic link or not.</param> /// <param name="openFileType">Indicate file type of the file to be opened</param> /// <param name="fileNameStatus">File name status</param> /// <param name="existingOpenModeCreateOption">The option of existing file's create.</param> /// <param name="existOpenShareModeShareAccess">A bitmask indicates sharing access for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="existOpenDesiredAccess">A bitmask indicates desired access for the open, as specified in [MS-SMB2] section 2.2.13.1.</param> /// <param name="createOption">Create options</param> /// <param name="createDisposition">The desired disposition for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="streamTypeNameToOpen">The name of the stream type to be opened</param> /// <param name="fileAttribute">A bitmask of file attributes for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="desiredFileAttribute">A bitmask of desired file attributes for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus OpenExistingFile( ShareAccess shareAccess, FileAccess desiredAccess, StreamFoundType streamFoundType, SymbolicLinkType symbolicLinkType, FileType openFileType, FileNameStatus fileNameStatus, CreateOptions existingOpenModeCreateOption, ShareAccess existOpenShareModeShareAccess, FileAccess existOpenDesiredAccess, CreateOptions createOption, CreateDisposition createDisposition, StreamTypeNameToOPen streamTypeNameToOpen, FileAttribute fileAttribute, FileAttribute desiredFileAttribute); #endregion #region OpenFileinitial /// <summary> /// Implement OpenFileinitial Interface /// </summary> /// <param name="desiredAccess">A bitmask indicating desired access for the open, as specified in [MS-SMB2] section 2.2.13.1.</param> /// <param name="shareAccess">A bitmask indicating sharing access for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="createOption">Options of create</param> /// <param name="createDisposition">The desired disposition for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="fileAttribute">A bitmask of file attributes for the open, as specified in [MS-SMB2] section 2.2.13.</param> /// <param name="isVolumeReadOnly">True: if Open.File.Volume.IsReadOnly is true</param> /// <param name="isCreateNewFile">True: if create a new file</param> /// <param name="isCaseInsensitive">True: if is case-insensitive</param> /// <param name="isLinkIsDeleted">True: if Link is deleted</param> /// <param name="isSymbolicLink">True: if Link.File.IsSymbolicLink is true</param> /// <param name="streamTypeNameToOPen">The type name of stream to be opened</param> /// <param name="openFileType">Open.File.FileType</param> /// <param name="fileNameStatus">File name status</param> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus OpenFileinitial( FileAccess desiredAccess, ShareAccess shareAccess, CreateOptions createOption, CreateDisposition createDisposition, FileAttribute fileAttribute, bool isVolumeReadOnly, bool isCreateNewFile, bool isCaseInsensitive, bool isLinkIsDeleted, bool isSymbolicLink, StreamTypeNameToOPen streamTypeNameToOpen, FileType openFileType, FileNameStatus fileNameStatus); #endregion #endregion #region 3.1.5.2 Server Requests a Read /// <summary> /// Implement ReadFile Interface /// </summary> /// <param name="valueOffset">The absolute byte offset in the stream from which to read data.</param> /// <param name="valueCount">The desired number of bytes to read.</param> /// <param name="byteRead">The number of bytes that were read.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus ReadFile( long valueOffset, int valueCount, out long byteRead); #endregion #region 3.1.5.3 Server Requests a Write /// <summary> /// Implement WriteFile Interface /// </summary> /// <param name="valueOffset">The absolute byte offset in the stream where data should be written. </param> /// <param name="valueCount">The number of bytes in InputBuffer to write.</param> /// <param name="bytesWritten">The number of bytes that were written</param> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus WriteFile( long valueOffset, long valueCount, out long bytesWritten); #endregion #region 3.1.5.4 Server Requests Closing an Open /// <summary> /// Implement CloseOpen Interface /// </summary> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus CloseOpen(); #endregion #region 3.1.5.5 Server Requests Querying a Directory #region 3.1.5.5.1 FileObjectIdInformation /// <summary> /// Implement QueryFileObjectIdInfo Interface /// </summary> /// <param name="fileNamePattern"> A Unicode string containing the file name pattern to match. </param> /// <param name="queryDirectoryScanType">Indicate whether the enumeration should be restarted.</param> /// <param name="queryDirectoryFileNameMatchType">The object store MUST search the volume for Files having File.ObjectId matching FileNamePattern. /// This parameter indicates if matches the file by FileNamePattern.</param> /// <param name="queryDirectoryOutputBufferType">Indicate if OutputBuffer is large enough to hold the first matching entry.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QueryFileObjectIdInfo( FileNamePattern fileNamePattern, QueryDirectoryScanType queryDirectoryScanType, QueryDirectoryFileNameMatchType queryDirectoryFileNameMatchType, QueryDirectoryOutputBufferType queryDirectoryOutputBufferType); #endregion #region 3.1.5.5.2 FileReparsePointInformation /// <summary> /// Implement QueryFileReparsePointInformation Interface /// </summary> /// <param name="fileNamePattern"> A Unicode string containing the file name pattern to match. </param> /// <param name="queryDirectoryScanType">Indicate whether the enumeration should be restarted.</param> /// <param name="queryDirectoryFileNameMatchType">The object store MUST search the volume for Files having File.ObjectId matching FileNamePattern. /// This parameter indicates if matches the file by FileNamePattern.</param> /// <param name="queryDirectoryOutputBufferType">Indicate if OutputBuffer is large enough to hold the first matching entry.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QueryFileReparsePointInformation( FileNamePattern fileNamePattern, QueryDirectoryScanType queryDirectoryScanType, QueryDirectoryFileNameMatchType queryDirectoryFileNameMatchType, QueryDirectoryOutputBufferType queryDirectoryOutputBufferType); #endregion #region 3.1.5.5.3 Directory Information Queries /// <summary> /// Implement QueryDirectoryInfo Interface /// </summary> /// <param name="fileNamePattern">A Unicode string containing the file name pattern to match. </param> /// <param name="restartScan">A boolean value indicates whether the enumeration should be restarted.</param> /// <param name="isNoRecordsReturned">True if no record returned.</param> /// <param name="isOutBufferSizeLess">True if OutputBufferSize is less than the size needed to return a single entry</param> /// <param name="outBufferSize">The state of OutBufferSize in subsection of section 3.1.5.5.4</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QueryDirectoryInfo( FileNamePattern fileNamePattern, bool restartScan, bool isNoRecordsReturned, bool isOutBufferSizeLess, OutBufferSmall outBufferSize); #endregion #endregion #region 3.1.5.6 Server Requests Flushing Cached Data /// <summary> /// Implement FlushCachedData Interface /// </summary> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus FlushCachedData(); #endregion #region 3.1.5.7 Server Requests a Byte-Range Lock /// <summary> /// Implement ByteRangeLock Interface /// </summary> /// </summary> /// <param name="fileOffset">A 64-bit unsigned integer containing the starting offset, in bytes.</param> /// <param name="length">A 64-bit unsigned integer containing the length, in bytes.</param> /// <param name="exclusiveLock">A boolean value indicates whether the range is to be locked exclusively (true) or shared (false).</param> /// <param name="failImmediately">A boolean value indicates whether the lock request fails immediately. /// True: if the range is locked by another open. False: if it has to wait until the lock can be acquired.</param> /// <param name="isOpenNotEqual">True: if open is not equal</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus ByteRangeLock( long fileOffset, long length, bool exclusiveLock, bool failImmediately, bool isOpenNotEqual); #endregion #region 3.1.5.8 Server Requests an Unlock of a Byte-Range /// <summary> /// Implement ByteRangeUnlock Interface /// </summary> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus ByteRangeUnlock(); #endregion #region 3.1.5.9 Server Requests an FsControl Request #region 3.1.5.9.1 FSCTL_CREATE_OR_GET_OBJECT_ID /// <summary> /// Implement FsCtlCreateOrGetObjId Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="isBytesReturnedSet">True: if the return status is success.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlCreateOrGetObjId( BufferSize bufferSize, out bool isBytesReturnedSet ); #endregion #region 3.1.5.9.2 FSCTL_DELETE_OBJECT_ID /// <summary> /// Implement FsCtlDeleteObjId Interface /// </summary> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlDeleteObjId(); #endregion #region 3.1.5.9.3 FSCTL_DELETE_REPARSE_POINT /// <summary> /// Implement FsCtlDeleteReparsePoint Interface /// </summary> /// <param name="reparseTag">An identifier indicates the type of the reparse point to delete, /// as defined in [MS-FSCC] section 2.1.2.1.</param> /// <param name="reparseGuidEqualOpenGuid">True: if Open.File.ReparseGUID == ReparseGUID</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlDeleteReparsePoint( ReparseTag reparseTag, bool reparseGuidEqualOpenGuid ); #endregion #region 3.1.5.9.6 FSCTL_FIND_FILES_BY_SID /// <summary> /// Implement FsCtlFindFilesBySID Interface /// </summary> /// <param name="openFileVolQuoInfoEmpty">True: if Open.File.Volume.QuotaInformation is empty</param> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="linkOwnerSidEqualSID">True: if linkOwnerSid equals SID.</param> /// <param name="outputBufferLessLinkSize">True: if the outputbuffer is less than linksize.</param> /// <param name="isOutputBufferOffset">True: if the outputbuffer is offset</param> /// <param name="isBytesReturnedSet">True: if returned status is success.</param> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus FsCtlFindFilesBySID( bool openFileVolumeQuoInfoEmpty, BufferSize bufferSize, bool linkOwnerSidEqualSid, bool outputBufferLessLinkSize, bool isOutputBufferOffset, out bool isBytesReturnedSet); #endregion #region 3.1.5.9.11 FSCTL_GET_REPARSE_POINT /// <summary> /// Implement FsCtlGetReparsePoint Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="openFileReparseTag">Open.File.ReparseTag </param> /// <param name="isBytesReturnedSet">True: if the returned status is success.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlGetReparsePoint( BufferSize bufferSize, ReparseTag openFileReparseTag, out bool isBytesReturnedSet ); #endregion #region 3.1.5.9.12 FSCTL_GET_RETRIEVAL_POINTERS /// <summary> /// Implement FsCtlGetRetrivalPoints Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="isStartingNegative">True: if StartingVcnBuffer.StartingVcn is negative</param> /// <param name="isStartingGreatThanAllocationSize">True: if StartingVcnBuffer.StartingVcn is /// greater than or equal to Open.Stream.AllocationSize divided by Open.File.Volume.ClusterSize</param> /// <param name="isElementsNotAllocated">True: if not all the elements in Open.Stream.ExtentList /// were copied into OutputBuffer.Extents.</param> /// <param name="isBytesReturnedSet">True: if the returned status is success.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlGetRetrivalPoints( BufferSize bufferSize, bool isStartingNegative, bool isStartingGreatThanAllocationSize, bool isElementsNotAllocated, out bool isBytesReturnedSet ); #endregion #region 3.1.5.9.19 FSCTL_QUERY_ALLOCATED_RANGES /// <summary> /// Implement FsCtlQueryAllocatedRanges Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="inputBuffer">Indicate buffer length</param> /// <param name="isBytesReturnedSet">True: if the returned status is success.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlQueryAllocatedRanges( BufferSize bufferSize, BufferLength inputBuffer, out bool isBytesReturnedSet ); #endregion #region 3.1.5.9.22 FSCTL_READ_FILE_USN_DATA /// <summary> /// Implement FsCtlReadFileUSNData Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="isBytesReturnedSet">True: if the returned status is success.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlReadFileUSNData( BufferSize bufferSize, out bool isBytesReturnedSet ); #endregion #region 3.1.5.9.24 FSCTL_SET_COMPRESSION /// <summary> /// Implement FsCtlSetCompression Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="compressionState">This string value indicates the InputBuffer.CompressionState. /// <param name="isCompressionSupportEnable">True: if compression support is enabled</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlSetCompression( BufferSize bufferSize, InputBufferCompressionState compressionState, bool isCompressionSupportEnable ); #endregion #region 3.1.5.9.25 FSCTL_SET_DEFECT_MANAGEMENT /// <summary> /// Implement FsCtlSetDefectManagement Interface /// </summary> /// <param name="bufferSize">Indicate buffer size.</param> /// <param name="isOpenListContainMoreThanOneOpen">True: if openList contains more than one open</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlSetDefectManagement( BufferSize bufferSize, bool isOpenListContainMoreThanOneOpen ); #endregion #region FsCtlForEasyRequest /// <summary> /// Implement FsCtlForEasyRequest Interface /// </summary> /// <param name="requestType">Request type</param> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="isBytesReturnedSet">True: if the returned status is success.</param> /// <param name="isOutputBufferSizeReturn">True: if return OutputBufferSize</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlForEasyRequest( FsControlRequestType requestType, BufferSize bufferSize, out bool isBytesReturnedSet, out bool isOutputBufferSizeReturn ); #endregion #region 3.1.5.9.26 FSCTL_SET_ENCRYPTION /// <summary> /// Implement FsCtlSetEncryption Interface /// </summary> /// <param name="isIsCompressedTrue">True: if stream is compressed.</param> /// <param name="encryptionOperation">InputBuffer.EncryptionOperation </param> /// <param name="bufferSize">Indicate buffer size</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlSetEncryption( bool isIsCompressedTrue, EncryptionOperation encryptionOperation, BufferSize bufferSize ); #endregion #region 3.1.5.9.28 FSCTL_SET_OBJECT_ID /// <summary> /// Implement FsCtlSetObjID Interface /// </summary> /// <param name="requestType">FsControlRequestType is self-defined to indicate control type</param> /// <param name="bufferSize">Indicate buffer size</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlSetObjID( FsControlRequestType requestType, BufferSize bufferSize ); #endregion #region 3.1.5.9.32 FSCTL_SET_SPARSE /// <summary> /// Implement FsCtlSetReparsePoint Interface /// </summary> /// <param name="inputReparseTag">InputBuffer.ReparseTag</param> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="isReparseGuidNotEqual">True: if Open.File.ReparseGUID is not equal to InputBuffer.ReparseGUID</param> /// <param name="isFileReparseTagNotEqualInputBufferReparseTag">True: if Open.File.ReparseTag is not equal to /// InputBuffer.ReparseTag.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlSetReparsePoint( ReparseTag inputReparseTag, BufferSize bufferSize, bool isReparseGuidNotEqual, bool isFileReparseTagNotEqualInputBufferReparseTag ); #endregion #region 3.1.5.9.33 FSCTL_SET_ZERO_DATA /// <summary> /// Implement FsCtlSetZeroData Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="inputBuffer">InputBuffer_FSCTL_SET_ZERO_DATA</param> /// <param name="isDeletedTrue">True: if Open.Stream.IsDeleted</param> /// <param name="isConflictDetected">True: if a conflict is detected.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsCtlSetZeroData( BufferSize bufferSize, InputBuffer_FSCTL_SET_ZERO_DATA inputBuffer, bool isIsDeletedTrue, bool isConflictDetected ); #endregion #region 3.1.5.9.35 FSCTL_SIS_COPYFILE /// <summary> /// Implement FsctlSisCopyFile Interface /// </summary> /// <param name="bufferSize">Indicate buffer size</param> /// <param name="inputBuffer">InputBufferFSCTL_SIS_COPYFILE</param> /// <param name="isCopyFileSisLinkTrue">True: if InputBuffer.Flags.COPYFILE_SIS_LINK is true</param> /// <param name="isIsEncryptedTrue">Ture if encrypted</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus FsctlSisCopyFile( BufferSize bufferSize, InputBufferFSCTL_SIS_COPYFILE inputBuffer, bool isCopyFileSisLinkTrue, bool isIsEncryptedTrue ); #endregion #endregion #region 3.1.5.10 Server Requests Change Notifications for a Directory /// <summary> /// Implement ChangeNotificationForDir Interface /// </summary> /// <param name="changeNotifyEntryType">ChangeNotifyEntryType to indicate if all entries from ChangeNotifyEntry.NotifyEventList /// fit in OutputBufferSize bytes</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus ChangeNotificationForDir(ChangeNotifyEntryType changeNotifyEntryType); #endregion #region 3.1.5.11 Server Requests a Query of File Information /// <summary> /// Implement QueryFileInfoPart1 Interface /// </summary> /// <param name="fileInfoClass">The type of information being queried, as specified in [MS-FSCC] section 2.5.</param> /// <param name="outputBufferSize">Indicate output buffer size</param> /// <param name="byteCount">The desired number of bytes to query.</param> /// <param name="outputBuffer">Indicate output buffer</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QueryFileInfoPart1( FileInfoClass fileInfoClass, OutputBufferSize outputBufferSize, out ByteCount byteCount, out OutputBuffer outputBuffer ); #endregion #region 3.1.5.12 Server Requests a Query of File System Information /// <summary> /// Implement QueryFileSystemInfo Interface /// </summary> /// <param name="fileInfoClass">The type of information being queried, as specified in [MS-FSCC] section 2.5.</param> /// <param name="outputBufferSize">This value indicates size of output buffer. </param> /// <param name="byteCount">The number of bytes stored in OutputBuffer.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QueryFileSystemInfo( FileSystemInfoClass fileInfoClass, OutputBufferSize outputBufferSize, out FsInfoByteCount byteCount); #endregion #region 3.1.5.13 Server Requests a Query of Security Information /// <summary> /// Implement QuerySecurityInfo Interface /// </summary> /// <param name="securityInformation">A SECURITY_INFORMATION data type, as defined in [MS-DTYP] section 2.4.7.</param> /// <param name="isByteCountGreater">True: if ByteCount is greater than OutputBufferSize</param> /// <param name="outputBuffer">Indicate output buffer</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QuerySecurityInfo( SecurityInformation securityInformation, bool isByteCountGreater, out OutputBuffer outputBuffer ); #endregion #region 3.1.5.14 Server Requests Setting of File Information #region 3.1.5.14.1 FileAllocationInformation /// <summary> /// Implement SetFileAllocOrObjIdInfo Interface /// </summary> /// <param name="fileInfoClass">The type of information being applied, as specified in [MS-FSCC] section 2.4.</param> /// <param name="allocationSizeType">Indicates if InputBuffer.AllocationSize is greater than the maximum file size allowed by the object store.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileAllocOrObjIdInfo( FileInfoClass fileInfoClass, AllocationSizeType allocationSizeType ); #endregion #region 3.1.5.14.2 FileBasicInformation /// <summary> /// Implement SetFileBasicInfo Interface /// </summary> /// <param name="inputBufferSize">Indicate inputBuffer size</param> /// <param name="inputBufferTime">Indicate inputBuffer time</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileBasicInfo( InputBufferSize inputBufferSize, InputBufferTime inputBufferTime ); #endregion #region 3.1.5.14.3 FileDispositionInformation /// <summary> /// Implement SetFileDispositionInfo Interface /// </summary> /// <param name="fileDispositionType">Indicates if the file is set to delete pending.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileDispositionInfo( FileDispositionType fileDispositionType ); #endregion #region 3.1.5.14.4 FileEndOfFileInformation /// <summary> /// Implement SetFileEndOfFileInfo Interface /// </summary> /// <param name="isEndOfFileGreatThanMaxSize">True: if InputBuffer.EndOfFile is greater than the maximum file size</param> /// <param name="isSizeEqualEndOfFile">True: if Open.Stream.Size is equal to InputBuffer.EndOfFile</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileEndOfFileInfo( bool isEndOfFileGreatThanMaxSize, bool isSizeEqualEndOfFile ); #endregion #region 3.1.5.14.5 FileFullEaInformation /// <summary> /// Implement SetFileFullEaInfo Interface /// </summary> /// <param name="eAValidate">Indicate Ea Information</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileFullEaInfo( EainInputBuffer eAValidate ); #endregion #region 3.1.5.14.6 FileLinkInformation /// <summary> /// Implement SetFileLinkInfo Interface /// </summary> /// <param name="inputNameInvalid">True: if InputBuffer.FileName is not valid as specified in [MS-FSCC] section 2.1.5</param> /// <param name="replaceIfExist">InputBuffer.ReplaceIfExists </param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileLinkInfo( bool inputNameInvalid, bool replaceIfExist ); #endregion #region 3.1.5.14.7 FileModeInformation /// <summary> /// Implement SetFileModeInfo Interface /// </summary> /// <param name="inputMode">InputBuffer.Mode </param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileModeInfo( FileMode inputMode ); #endregion #region 3.1.5.14.9 FilePositionInformation /// <summary> /// Implement SetFilePositionInfo Interface /// </summary> /// <param name="inputBufferSize">Indicate inputBuffer size</param> /// <param name="currentByteOffset">Indicate InputBuffer.CurrentByteOffset</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFilePositionInfo( InputBufferSize inputBufferSize, InputBufferCurrentByteOffset currentByteOffset ); #endregion #region 3.1.5.14.11 FileRenameInformation /// <summary> /// Implement SetFileRenameInfo Interface /// </summary> /// <param name="inputBufferFileNameLength">InputBufferFileNameLength</param> /// <param name="inputBufferFileName">InputbBufferFileName</param> /// <param name="directoryVolumeType">Indicate if DestinationDirectory.Volume is equal to Open.File.Volume.</param> /// <param name="destinationDirectoryType">Indicate if DestinationDirectory is the same as Open.Link.ParentFile.</param> /// <param name="newLinkNameFormatType">Indicate if NewLinkName is case-sensitive</param> /// <param name="newLinkNameMatchType">Indicate if NewLinkName matched TargetLink.ShortName</param> /// <param name="replacementType">Indicate if replace target file if exists.</param> /// <param name="targetLinkDeleteType">Indicate if TargetLink is deleted or not.</param> /// <param name="oplockBreakStatusType">Indicate if there is an oplock to be broken</param> /// <param name="targetLinkFileOpenListType">Indicate if TargetLink.File.OpenList contains an Open with a Stream matching the current Stream.</param> /// <returns>An NTSTATUS code indicating the result of the operation.</returns> MessageStatus SetFileRenameInfo( InputBufferFileNameLength inputBufferFileNameLength, InputBufferFileName inputBufferFileName, DirectoryVolumeType directoryVolumeType, DestinationDirectoryType destinationDirectoryType, NewLinkNameFormatType newLinkNameFormatType, NewLinkNameMatchType newLinkNameMatchType, ReplacementType replacementType, TargetLinkDeleteType targetLinkDeleteType, OplockBreakStatusType oplockBreakStatusType, TargetLinkFileOpenListType targetLinkFileOpenListType ); #endregion #region 3.1.5.14.11.1 Algorithm for Performing Stream Rename /// <summary> /// Implement StreamRename Interface /// </summary> /// <param name="newStreamNameFormat">The format of NewStreamName</param> /// <param name="streamTypeNameFormat">The format of StreamType</param> /// <param name="replacementType">Indicate if replace target file if exists.</param> /// <returns>An NTSTATUS code indicating the result of the operation</returns> MessageStatus StreamRename( InputBufferFileName newStreamNameFormat, InputBufferFileName streamTypeNameFormat, ReplacementType replacementType ); #endregion #region 3.1.5.14.13 FileShortNameInformation /// <summary> /// Implement SetFileShortNameInfo Interface /// </summary> /// <param name="inputBufferFileName">InputBuffer.FileName. This value equals "Notvalid" /// if InputBuffer.FileName is not a valid 8.3 file name as described in [MS-FSCC] section 2.1.5.2.1.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileShortNameInfo( InputBufferFileName inputBufferFileName ); #endregion #region 3.1.5.14.14 FileValidDataLengthInformation ///<summary> /// Implement SetFileValidDataLengthInfo Interface ///</summary> ///<param name="isStreamValidLengthGreater">True: if Open.Stream.ValidDataLength is greater than InputBuffer.ValidDataLength</param> ///<returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetFileValidDataLengthInfo( bool isStreamValidLengthGreater ); #endregion #endregion #region 3.1.5.15 Server Requests Setting of File System Information /// <summary> /// Implement SetFileSystemInformation Interface /// </summary> /// <param name="fileInfoClass">The type of information being applied, as specified in [MS-FSCC] section 2.5.</param> /// <returns>An NTSTATUS code that specifies the result.</returns> MessageStatus SetFileSystemInformation( UInt32 fsInformationClass, byte[] buffer); /// <summary> /// SetFileSysInfo interface for model /// </summary> /// <param name="fileInfoClass">The type of information being applied, as specified in [MS-FSCC] section 2.5.</param> /// <param name="inputBufferSize">Indicate input buffer size.</param> /// <returns></returns> MessageStatus SetFileSysInfo( FileSystemInfoClass fileInfoClass, InputBufferSize inputBufferSize); #endregion #region 3.1.5.16 Server Requests Setting of Security Information ///<summary> /// Implement SetSecurityInfo Interface ///</summary> ///<param name="securityInformation">Indicate SecurityInformation</param> ///<param name="ownerSidEnum">Indicate InputBuffer.OwnerSid</param> ///<returns>An NTSTATUS code that specifies the result</returns> MessageStatus SetSecurityInfo( SecurityInformation securityInformation, OwnerSid ownerSidEnum); #endregion #region 3.1.5.17 Server Requests an Oplock /// <summary> /// Implement Oplock Interface /// </summary> /// <param name="opType">Oplock type</param> /// <param name="openListContainStream">True: if Open.File.OpenList contains more than one /// Open whose Stream is the same as Open.Stream.</param> /// <param name="opLockLevel">Requested oplock level</param> /// <param name="isOpenStreamOplockEmpty">True: if Open.Steam.Oplock is empty</param> /// <param name="oplockState">To specify the current state of the oplock, expressed as a combination of one or more flags</param> /// <param name="streamIsDeleted">True: if stream is deleted.</param> /// <param name="isRHBreakQueueEmpty">True: if Open.Stream.Oplock.State.RHBreakQueue is empty</param> /// <param name="isOplockKeyEqual">True: if ThisOpen.OplockKey == Open.OplockKey</param> /// <param name="isOplockKeyEqualExclusive">False: if Open.OplockKey != Open.Stream.Oplock.ExclusiveOpen.OplockKey</param> /// <param name="requestOplock">Request oplock</param> /// <param name="grantingInAck">True: if this oplock is being requested as part of an oplock break acknowledgement</param> /// <param name="keyEqualOnRHOplocks">True: if there is an Open on Open.Stream.Oplock.RHOplocks whose OplockKey is equal to Open.OplockKey</param> /// <param name="keyEqualOnRHBreakQueue">True: if there is an Open on Open.Stream.Oplock.RHBreakQueue whose OplockKey is equal to Open.OplockKey</param> /// <param name="keyEqualOnROplocks">True: if there is an Open ThisOpen on Open.Stream.Oplock.ROplocks whose OplockKey is equal to Open.OplockKey</param> /// <returns> An NTSTATUS code indicating the result of the operation</returns> MessageStatus Oplock( OpType opType, bool openListContainStream, RequestedOplockLevel opLockLevel, bool isOpenStreamOplockEmpty, OplockState oplockState, bool streamIsDeleted, bool isRHBreakQueueEmpty, bool isOplockKeyEqual, bool isOplockKeyEqualExclusive, RequestedOplock requestOplock, bool grantingInAck, bool keyEqualOnRHOplocks, bool keyEqualOnRHBreakQueue, bool keyEqualOnROplocks); #endregion #region 3.1.5.18 Server Acknowledges an Oplock Break /// <summary> /// Server Acknowledges an Oplock Break /// </summary> /// <param name="OpenStreamOplockEmpty">True: if Open.Stream.Oplock is empty</param> /// <param name="opType">Oplock type</param> /// <param name="level">Requested Oplock level</param> /// <param name="ExclusiveOpenEqual">True: if Open.Stream.Oplock.ExclusiveOpen is not equal to Open</param> /// <param name="oplockState">Oplock state</param> /// <param name="RHBreakQueueIsEmpty">True: if Open.Stream.Oplock.RHBreakQueue is empty</param> /// <param name="ThisContextOpenEqual">True: if ThisContext.Open equals Open</param> /// <param name="ThisContextBreakingToRead">False: if ThisContext.BreakingToRead is false</param> /// <param name="OplockWaitListEmpty">False: if Open.Stream.Oplock.WaitList is not empty</param> /// <param name="StreamIsDeleted">True: if Open.Stream.IsDeleted is true</param> /// <param name="GrantingInAck">True: if this oplock is being requested as part of an oplock break acknowledgement, as defined in [MS-FSA] 3.1.5.17.2</param> /// <param name="keyEqualOnRHOplocks">This value is used in [MS-FSA] 3.1.5.17.2</param> /// <param name="keyEqualOnRHBreakQueue">This value is used in [MS-FSA] 3.1.5.17.2</param> /// <param name="keyEqualOnROplocks">This value is used in [MS-FSA] 3.1.5.17.2</param> /// <param name="requestOplock">This value is used in [MS-FSA] 3.1.5.17.2</param> /// <returns> An NTSTATUS code indicating the result of the operation</returns> MessageStatus OplockBreakAcknowledge( bool OpenStreamOplockEmpty, OpType opType, RequestedOplockLevel level, bool ExclusiveOpenEqual, OplockState oplockState, bool RHBreakQueueIsEmpty, bool ThisContextOpenEqual, bool ThisContextBreakingToRead, bool OplockWaitListEmpty, bool StreamIsDeleted, bool GrantingInAck, bool keyEqualOnRHOplocks, bool keyEqualOnRHBreakQueue, bool keyEqualOnROplocks, RequestedOplock requestOplock ); #endregion #region 3.1.5.19 Server Requests Canceling an Operation /// <summary> /// Implement CancelinganOperation Interface /// Server requests to cancel an Operation /// This method is called by 3.1.5.7, and the scenario is in Scenario16_ByteRangeLock /// </summary> /// <param name="ioRequest">An implementation-specific identifier that is unique for each /// outstanding IO operation. See [MS-CIFS] section 3.3.5.51.</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus CancelinganOperation(IORequest ioRequest); #endregion #region 3.1.5.20 Server Requests Querying Quota Information /// <summary> /// Implement QueryFileQuotaInformation Interface /// </summary> /// <param name="state">Sid list state</param> /// <param name="isOutBufferSizeLess">True if OutputBufferSize is less than the size of FILE_QUOTA_INFORMATION /// multiplied by the number of elements in SidList</param> /// <param name="restartScan">True if EmptyPattern is true</param> /// <param name="isDirectoryNotRight">True if there is no match</param> /// <returns>An NTSTATUS code that specifies the result</returns> MessageStatus QueryFileQuotaInformation( SidListState state, bool isOutBufferSizeLess, bool restartScan, bool isDirectoryNotRight); #endregion #endregion #region Adapter Utilities /// <summary> /// Get SUT platformType. /// </summary> /// <param name="platformType">SUT OS platformType</param> void GetOSInfo(out PlatformType platformType); /// <summary> /// Get the system config information. /// </summary> /// <param name="securityContext">SSecurityContext</param> void GetSystemConfig(out SSecurityContext securityContext); /// <summary> /// To get whether implement object functionality /// </summary> /// <param name="isImplemented">True: if Object is functionality</param> void GetObjectFunctionality(out bool isImplemented); /// <summary> /// To get whether ObjectIDs is supported /// </summary> /// <param name="isSupported">True: if ObjectIDs is supported</param> void GetObjectIDsSupported(out bool isSupported); /// <summary> /// To get whether reparse points is supported /// </summary> /// <param name="isSupported">True: if ReparsePoints is supported</param> void GetReparsePointsSupported(out bool isSupported); /// <summary> /// To get whether open has manage.vol.privilege /// </summary> /// <param name="isSupported">True: if open has manage.vol.privilege.</param> void GetopenHasManageVolPrivilege(out bool isSupported); /// <summary> /// Get is restore has access /// </summary> /// <param name="isHas">True: if Restore has access.</param> void GetRestoreAccess(out bool isHas); /// <summary> /// To get whether is administrator /// </summary> /// <param name="isGet">True: if administrator is got</param> void GetAdministrator(out bool isGet); /// <summary> /// To get whether open generate shortname /// </summary> /// <param name="GenerateShortNames">True: if Open generate shortnames</param> void GetOpenGenerateShortNames(out bool generateShortNames); /// <summary> /// To get whether Open.File.OpenList contains more than one Open on open stream. /// defined in 3.1.5.17 /// </summary> /// <param name="openListContains">True: if Open.ListContains</param> void GetIsOpenListContains(out bool openListContains); /// <summary> /// To get whether the link, through which file is opened, is found /// </summary> /// <param name="IsLinkFound">True: if Link is Found</param> void GetIsLinkFound(out bool isLinkFound); /// <summary> /// Get file volum size. /// </summary> /// <param name="openFileVolumeSize">The volume size of the file opened</param> void GetFileVolumSize(out long openFileVolumeSize); /// <summary> /// To get whether Quotas is supported. /// </summary> /// <param name="isQuotasSupported">True: if Quotas is supported</param> void GetIFQuotasSupported(out bool isQuotasSupported); /// <summary> /// To get whether ObjectIDs is supported. /// </summary> /// <param name="isObjectIDsSupported">True: if ObjectIDs is supported</param> void GetIFObjectIDsSupported(out bool isObjectIDsSupported); /// <summary> /// Check if requirement R507 is implemented /// </summary> /// <param name="isFlagValue">A boolean value to specify the result</param> void CheckIsR507Implemented(out bool isFlagValue); /// <summary> /// Check if requirement R405 is implemented /// </summary> /// <param name="isFlagValue">A boolean value to specify the result</param> void CheckIsR405Implemented(out bool isFlagValue); /// <summary> /// To get whether Query FileFsControlInformation is implemented. /// </summary> /// <param name="isImplemented">True: if this functionality is implemented by the object store.</param> void GetIfImplementQueryFileFsControlInformation(out bool isImplemented); /// <summary> /// To get whether Query FileFsObjectIdInformation is implemented. /// </summary> /// <param name="isImplemented">True: if this functionality is implemented by the object store.</param> void GetIfImplementQueryFileFsObjectIdInformation(out bool isImplemented); /// <summary> /// To get whether Open.File.Volume is read only. /// </summary> /// <param name="isReadOnly"></param> void GetIfOpenFileVolumeIsReadOnly(out bool isReadOnly); /// <summary> /// To get whether Open.File equals to Root Directory. /// </summary> /// <param name="isEqualRootDirectory"></param> void GetIfOpenFileEqualRootDirectory(out bool isEqualRootDirectory); /// <summary> /// Get if Query FileObjectIdInformation is implemented /// </summary> /// <param name="isImplemented">true: If the object store implements this functionality.</param> void GetIfImplementQueryFileObjectIdInformation(out bool isImplemented); /// <summary> /// Get if Query FileReparsePointInformation is implemented /// </summary> /// <param name="isImplemented">true: If the object store implements this functionality.</param> void GetIfImplementQueryFileReparsePointInformation(out bool isImplemented); /// <summary> /// Get if Query FileQuotaInformation is implemented /// </summary> /// <param name="isImplemented">true: If the object store implements this functionality.</param> void GetIfImplementQueryFileQuotaInformation(out bool isImplemented); /// <summary> /// Get if ObjectId related IoCtl requests are implemented /// </summary> /// <param name="isImplemented">true: If the object store implements this functionality.</param> void GetIfImplementObjectIdIoCtlRequest(out bool isImplemented); /// <summary> /// Get if Open.File.Volume is NTFS file system. /// </summary> /// <param name="isNtfsFileSystem">true: if it is NTFS File System.</param> void GetIfNtfsFileSystem(out bool isNtfsFileSystem); /// <summary> /// Get If Open Has Manage Volume Access. /// </summary> /// <param name="isHasManageVolumeAccess">true: if open has manage volume access.</param> void GetIfOpenHasManageVolumeAccess(out bool isHasManageVolumeAccess); /// <summary> /// Get if Stream Rename is supported. /// </summary> /// <param name="isSupported">true: if stream rename is supported.</param> void GetIfStreamRenameIsSupported(out bool isSupported); #endregion } }
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [TimeSlideControl.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace open3mod { public partial class TimeSlideControl : UserControl { private double _rangeMin; private double _rangeMax; private double _pos; private double _mouseRelativePos; private bool _mouseEntered; private readonly Font _font; private readonly Pen _redPen; private readonly SolidBrush _lightGray; private readonly Pen _dimGrayPen; private readonly Pen _blackPen; public TimeSlideControl() { InitializeComponent(); _font = new Font(FontFamily.GenericMonospace,9); _redPen = new Pen(new SolidBrush(Color.Red), 1); _lightGray = new SolidBrush(Color.LightGray); _dimGrayPen = new Pen(new SolidBrush(Color.DimGray), 1); _blackPen = new Pen(new SolidBrush(Color.Black), 1); } /// <summary> /// Minimum cursor value /// </summary> public double RangeMin { get { return _rangeMin; } set { Debug.Assert(value <= _rangeMax); _rangeMin = value; if (_pos < _rangeMin) { _pos = _rangeMin; } Invalidate(); } } /// <summary> /// Maximum cursor value /// </summary> public double RangeMax { get { return _rangeMax; } set { Debug.Assert(_rangeMin <= value); _rangeMax = value; if (_pos > _rangeMax) { _pos = _rangeMax; } Invalidate(); } } /// <summary> /// Cursor position in [RangeMin, RangeMax] /// </summary> public double Position { get { return _pos; } set { _pos = value; if (_pos > RangeMax) { _pos = RangeMax; } if (_pos < RangeMin) { _pos = RangeMin; } Invalidate(); } } /// <summary> /// Valid cursor range (RangeMax-RangeMin) /// </summary> public double Range { get { return _rangeMax - _rangeMin; } } /// <summary> /// Cursor position in [0,1] /// </summary> public double RelativePosition { get { var d = Range; if (d < 1e-7) // prevent divide by zero { return 0.0; } return (_pos - _rangeMin) / d; } } public delegate void RewindDelegate(object sender, RewindDelegateArgs args); public struct RewindDelegateArgs { public double OldPosition; public double NewPosition; } /// <summary> /// Invoked when the user manually rewinds the slider thumb. /// </summary> public event RewindDelegate Rewind; public virtual void OnRewind(RewindDelegateArgs args) { RewindDelegate handler = Rewind; if (handler != null) handler(this, args); } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Invalidate(); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); var rect = ClientRectangle; var newPos = ((e.X - rect.Left) * Range / (double)rect.Width) + _rangeMin; OnRewind(new RewindDelegateArgs { OldPosition = _pos, NewPosition = newPos }); Position = newPos; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); var rect = ClientRectangle; _mouseRelativePos = (e.X - rect.Left) / (double)rect.Width; Invalidate(); } protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); _mouseEntered = true; Invalidate(); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _mouseEntered = false; Invalidate(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var graphics = e.Graphics; var rect = ClientRectangle; graphics.FillRectangle(_lightGray, rect ); if(!Enabled) { return; } var pos = RelativePosition; var xdraw = rect.Left + (int) (rect.Width*pos); graphics.DrawLine(_redPen, xdraw, 15, xdraw, rect.Bottom ); var widthPerSecond = rect.Width / Range; //calc a stepsize that is a power of 10s double log = Math.Log10(Range); int roundedLog = (int) (Math.Floor(log)); float stepsize = (float) (Math.Pow(10, roundedLog)); for (float i = 0.0f; i < (float)Range; i += stepsize) { int xpos = (int)(i * widthPerSecond); graphics.DrawLine(_dimGrayPen, xpos, 55, xpos, rect.Bottom); } if (_mouseEntered) { graphics.DrawString((_mouseRelativePos * Range).ToString("0.000") + "s", _font, _blackPen.Brush, 5, 1); xdraw = rect.Left + (int)(rect.Width * _mouseRelativePos); graphics.DrawLine(_blackPen, xdraw, 40, xdraw, rect.Bottom); } graphics.DrawString(Position.ToString("0.000") + "s", _font, _redPen.Brush, rect.Width-70, 1); } } } /* vi: set shiftwidth=4 tabstop=4: */
using MatterHackers.Agg.Image; using MatterHackers.Agg.VertexSource; namespace MatterHackers.Agg { public class ScanlineRenderer { private VectorPOD<Color> tempSpanColors = new VectorPOD<Color>(); private VectorPOD<ColorF> tempSpanColorsFloats = new VectorPOD<ColorF>(); public void RenderSolid(IImageByte destImage, IRasterizer rasterizer, IScanlineCache scanLine, Color color) { if (rasterizer.rewind_scanlines()) { scanLine.reset(rasterizer.min_x(), rasterizer.max_x()); while (rasterizer.sweep_scanline(scanLine)) { RenderSolidSingleScanLine(destImage, scanLine, color); } } } public void RenderSolid(IImageFloat destImage, IRasterizer rasterizer, IScanlineCache scanLine, ColorF color) { if (rasterizer.rewind_scanlines()) { scanLine.reset(rasterizer.min_x(), rasterizer.max_x()); while (rasterizer.sweep_scanline(scanLine)) { RenderSolidSingleScanLine(destImage, scanLine, color); } } } protected virtual void RenderSolidSingleScanLine(IImageByte destImage, IScanlineCache scanLine, Color color) { int y = scanLine.y(); int num_spans = scanLine.num_spans(); ScanlineSpan scanlineSpan = scanLine.begin(); byte[] ManagedCoversArray = scanLine.GetCovers(); for (; ; ) { int x = scanlineSpan.x; if (scanlineSpan.len > 0) { destImage.blend_solid_hspan(x, y, scanlineSpan.len, color, ManagedCoversArray, scanlineSpan.cover_index); } else { int x2 = (x - (int)scanlineSpan.len - 1); destImage.blend_hline(x, y, x2, color, ManagedCoversArray[scanlineSpan.cover_index]); } if (--num_spans == 0) break; scanlineSpan = scanLine.GetNextScanlineSpan(); } } private void RenderSolidSingleScanLine(IImageFloat destImage, IScanlineCache scanLine, ColorF color) { int y = scanLine.y(); int num_spans = scanLine.num_spans(); ScanlineSpan scanlineSpan = scanLine.begin(); byte[] ManagedCoversArray = scanLine.GetCovers(); for (; ; ) { int x = scanlineSpan.x; if (scanlineSpan.len > 0) { destImage.blend_solid_hspan(x, y, scanlineSpan.len, color, ManagedCoversArray, scanlineSpan.cover_index); } else { int x2 = (x - (int)scanlineSpan.len - 1); destImage.blend_hline(x, y, x2, color, ManagedCoversArray[scanlineSpan.cover_index]); } if (--num_spans == 0) break; scanlineSpan = scanLine.GetNextScanlineSpan(); } } private void GenerateAndRenderSingleScanline(IScanlineCache scanLineCache, IImageByte destImage, span_allocator alloc, ISpanGenerator span_gen) { int y = scanLineCache.y(); int num_spans = scanLineCache.num_spans(); ScanlineSpan scanlineSpan = scanLineCache.begin(); byte[] ManagedCoversArray = scanLineCache.GetCovers(); for (; ; ) { int x = scanlineSpan.x; int len = scanlineSpan.len; if (len < 0) len = -len; if (tempSpanColors.Capacity() < len) { tempSpanColors.Capacity(len); } span_gen.generate(tempSpanColors.Array, 0, x, y, len); bool useFirstCoverForAll = scanlineSpan.len < 0; destImage.blend_color_hspan(x, y, len, tempSpanColors.Array, 0, ManagedCoversArray, scanlineSpan.cover_index, useFirstCoverForAll); if (--num_spans == 0) break; scanlineSpan = scanLineCache.GetNextScanlineSpan(); } } private void GenerateAndRenderSingleScanline(IScanlineCache scanLineCache, IImageFloat destImageFloat, span_allocator alloc, ISpanGeneratorFloat span_gen) { int y = scanLineCache.y(); int num_spans = scanLineCache.num_spans(); ScanlineSpan scanlineSpan = scanLineCache.begin(); byte[] ManagedCoversArray = scanLineCache.GetCovers(); for (; ; ) { int x = scanlineSpan.x; int len = scanlineSpan.len; if (len < 0) len = -len; if (tempSpanColorsFloats.Capacity() < len) { tempSpanColorsFloats.Capacity(len); } span_gen.generate(tempSpanColorsFloats.Array, 0, x, y, len); bool useFirstCoverForAll = scanlineSpan.len < 0; destImageFloat.blend_color_hspan(x, y, len, tempSpanColorsFloats.Array, 0, ManagedCoversArray, scanlineSpan.cover_index, useFirstCoverForAll); if (--num_spans == 0) break; scanlineSpan = scanLineCache.GetNextScanlineSpan(); } } public void GenerateAndRender(IRasterizer rasterizer, IScanlineCache scanlineCache, IImageByte destImage, span_allocator spanAllocator, ISpanGenerator spanGenerator) { if (rasterizer.rewind_scanlines()) { scanlineCache.reset(rasterizer.min_x(), rasterizer.max_x()); spanGenerator.prepare(); while (rasterizer.sweep_scanline(scanlineCache)) { GenerateAndRenderSingleScanline(scanlineCache, destImage, spanAllocator, spanGenerator); } } } public void GenerateAndRender(IRasterizer rasterizer, IScanlineCache scanlineCache, IImageFloat destImage, span_allocator spanAllocator, ISpanGeneratorFloat spanGenerator) { if (rasterizer.rewind_scanlines()) { scanlineCache.reset(rasterizer.min_x(), rasterizer.max_x()); spanGenerator.prepare(); while (rasterizer.sweep_scanline(scanlineCache)) { GenerateAndRenderSingleScanline(scanlineCache, destImage, spanAllocator, spanGenerator); } } } public void RenderCompound(rasterizer_compound_aa ras, IScanlineCache sl_aa, IScanlineCache sl_bin, IImageByte imageFormat, span_allocator alloc, IStyleHandler sh) { #if false unsafe { if (ras.rewind_scanlines()) { int min_x = ras.min_x(); int len = ras.max_x() - min_x + 2; sl_aa.reset(min_x, ras.max_x()); sl_bin.reset(min_x, ras.max_x()); //typedef typename BaseRenderer::color_type color_type; ArrayPOD<RGBA_Bytes> color_span = alloc.allocate((int)len * 2); byte[] ManagedCoversArray = sl_aa.GetCovers(); fixed (byte* pCovers = ManagedCoversArray) { fixed (RGBA_Bytes* pColorSpan = color_span.Array) { int mix_bufferOffset = len; int num_spans; int num_styles; int style; bool solid; while ((num_styles = ras.sweep_styles()) > 0) { if (num_styles == 1) { // Optimization for a single style. Happens often //------------------------- if (ras.sweep_scanline(sl_aa, 0)) { style = ras.style(0); if (sh.is_solid(style)) { // Just solid fill //----------------------- RenderSolidSingleScanLine(imageFormat, sl_aa, sh.color(style)); } else { // Arbitrary span generator //----------------------- ScanlineSpan span_aa = sl_aa.Begin(); num_spans = sl_aa.num_spans(); for (; ; ) { len = span_aa.len; sh.generate_span(pColorSpan, span_aa.x, sl_aa.y(), (int)len, style); imageFormat.blend_color_hspan(span_aa.x, sl_aa.y(), (int)span_aa.len, pColorSpan, &pCovers[span_aa.cover_index], 0); if (--num_spans == 0) break; span_aa = sl_aa.GetNextScanlineSpan(); } } } } else // there are multiple styles { if (ras.sweep_scanline(sl_bin, -1)) { // Clear the spans of the mix_buffer //-------------------- ScanlineSpan span_bin = sl_bin.Begin(); num_spans = sl_bin.num_spans(); for (; ; ) { agg_basics.MemClear((byte*)&pColorSpan[mix_bufferOffset + span_bin.x - min_x], span_bin.len * sizeof(RGBA_Bytes)); if (--num_spans == 0) break; span_bin = sl_bin.GetNextScanlineSpan(); } for (int i = 0; i < num_styles; i++) { style = ras.style(i); solid = sh.is_solid(style); if (ras.sweep_scanline(sl_aa, (int)i)) { //IColorType* colors; //IColorType* cspan; //typename ScanlineAA::cover_type* covers; ScanlineSpan span_aa = sl_aa.Begin(); num_spans = sl_aa.num_spans(); if (solid) { // Just solid fill //----------------------- for (; ; ) { RGBA_Bytes c = sh.color(style); len = span_aa.len; RGBA_Bytes* colors = &pColorSpan[mix_bufferOffset + span_aa.x - min_x]; byte* covers = &pCovers[span_aa.cover_index]; do { if (*covers == cover_full) { *colors = c; } else { colors->add(c, *covers); } ++colors; ++covers; } while (--len != 0); if (--num_spans == 0) break; span_aa = sl_aa.GetNextScanlineSpan(); } } else { // Arbitrary span generator //----------------------- for (; ; ) { len = span_aa.len; RGBA_Bytes* colors = &pColorSpan[mix_bufferOffset + span_aa.x - min_x]; RGBA_Bytes* cspan = pColorSpan; sh.generate_span(cspan, span_aa.x, sl_aa.y(), (int)len, style); byte* covers = &pCovers[span_aa.cover_index]; do { if (*covers == cover_full) { *colors = *cspan; } else { colors->add(*cspan, *covers); } ++cspan; ++colors; ++covers; } while (--len != 0); if (--num_spans == 0) break; span_aa = sl_aa.GetNextScanlineSpan(); } } } } // Emit the blended result as a color hspan //------------------------- span_bin = sl_bin.Begin(); num_spans = sl_bin.num_spans(); for (; ; ) { imageFormat.blend_color_hspan(span_bin.x, sl_bin.y(), (int)span_bin.len, &pColorSpan[mix_bufferOffset + span_bin.x - min_x], null, cover_full); if (--num_spans == 0) break; span_bin = sl_bin.GetNextScanlineSpan(); } } // if(ras.sweep_scanline(sl_bin, -1)) } // if(num_styles == 1) ... else } // while((num_styles = ras.sweep_styles()) > 0) } } } // if(ras.rewind_scanlines()) } #endif } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Extensions; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Utils; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Layout { public class TestSceneGridContainer : FrameworkTestScene { private Container gridParent; private GridContainer grid; [SetUp] public void Setup() => Schedule(() => { Child = gridParent = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Children = new Drawable[] { grid = new GridContainer { RelativeSizeAxes = Axes.Both }, new Container { RelativeSizeAxes = Axes.Both, Masking = true, BorderColour = Color4.White, BorderThickness = 2, Child = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0, AlwaysPresent = true } } } }; }); [TestCase(false)] [TestCase(true)] public void TestAutoSizeDoesNotConsiderRelativeSizeChildren(bool row) { Box relativeBox = null; Box absoluteBox = null; setSingleDimensionContent(() => new[] { new Drawable[] { relativeBox = new FillBox { RelativeSizeAxes = Axes.Both }, absoluteBox = new FillBox { RelativeSizeAxes = Axes.None, Size = new Vector2(100) } } }, new[] { new Dimension(GridSizeMode.AutoSize) }, row); AddStep("resize absolute box", () => absoluteBox.Size = new Vector2(50)); AddAssert("relative box has length 50", () => Precision.AlmostEquals(row ? relativeBox.DrawHeight : relativeBox.DrawWidth, 50, 1)); } [Test] public void TestBlankGrid() { } [Test] public void TestSingleCellDistributedXy() { FillBox box = null; AddStep("set content", () => grid.Content = new[] { new Drawable[] { box = new FillBox() }, }); AddAssert("box is same size as grid", () => Precision.AlmostEquals(box.DrawSize, grid.DrawSize)); } [Test] public void TestSingleCellAbsoluteXy() { const float size = 100; FillBox box = null; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { box = new FillBox() }, }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Absolute, size) }; }); AddAssert("box has expected size", () => Precision.AlmostEquals(box.DrawSize, new Vector2(size))); } [Test] public void TestSingleCellRelativeXy() { const float size = 0.5f; FillBox box = null; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { box = new FillBox() }, }; grid.RowDimensions = grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, size) }; }); AddAssert("box has expected size", () => Precision.AlmostEquals(box.DrawSize, grid.DrawSize * new Vector2(size))); } [Test] public void TestSingleCellRelativeXAbsoluteY() { const float absolute_height = 100; const float relative_width = 0.5f; FillBox box = null; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { box = new FillBox() }, }; grid.RowDimensions = new[] { new Dimension(GridSizeMode.Absolute, absolute_height) }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, relative_width) }; }); AddAssert("box has expected width", () => Precision.AlmostEquals(box.DrawWidth, grid.DrawWidth * relative_width)); AddAssert("box has expected height", () => Precision.AlmostEquals(box.DrawHeight, absolute_height)); } [Test] public void TestSingleCellDistributedXRelativeY() { const float height = 0.5f; FillBox box = null; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { box = new FillBox() }, }; grid.RowDimensions = new[] { new Dimension(GridSizeMode.Relative, height) }; }); AddAssert("box has expected width", () => Precision.AlmostEquals(box.DrawWidth, grid.DrawWidth)); AddAssert("box has expected height", () => Precision.AlmostEquals(box.DrawHeight, grid.DrawHeight * height)); } [TestCase(false)] [TestCase(true)] public void Test3CellRowOrColumnDistributedXy(bool row) { FillBox[] boxes = new FillBox[3]; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() } }, row: row); for (int i = 0; i < 3; i++) { int local = i; if (row) AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth / 3f, grid.DrawHeight))); else AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, grid.DrawHeight / 3f))); } } [TestCase(false)] [TestCase(true)] public void Test3CellRowOrColumnDistributedXyAbsoluteYx(bool row) { var sizes = new[] { 50f, 100f, 75f }; var boxes = new FillBox[3]; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox() }, new Drawable[] { boxes[1] = new FillBox() }, new Drawable[] { boxes[2] = new FillBox() }, }, new[] { new Dimension(GridSizeMode.Absolute, sizes[0]), new Dimension(GridSizeMode.Absolute, sizes[1]), new Dimension(GridSizeMode.Absolute, sizes[2]) }, row); for (int i = 0; i < 3; i++) { int local = i; if (row) AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, sizes[local]))); else AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(sizes[local], grid.DrawHeight))); } } [TestCase(false)] [TestCase(true)] public void Test3CellRowOrColumnDistributedXyRelativeYx(bool row) { var sizes = new[] { 0.2f, 0.4f, 0.2f }; var boxes = new FillBox[3]; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox() }, new Drawable[] { boxes[1] = new FillBox() }, new Drawable[] { boxes[2] = new FillBox() }, }, new[] { new Dimension(GridSizeMode.Relative, sizes[0]), new Dimension(GridSizeMode.Relative, sizes[1]), new Dimension(GridSizeMode.Relative, sizes[2]) }, row); for (int i = 0; i < 3; i++) { int local = i; if (row) AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(grid.DrawWidth, sizes[local] * grid.DrawHeight))); else AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, new Vector2(sizes[local] * grid.DrawWidth, grid.DrawHeight))); } } [TestCase(false)] [TestCase(true)] public void Test3CellRowOrColumnDistributedXyMixedYx(bool row) { var sizes = new[] { 0.2f, 75f }; var boxes = new FillBox[3]; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox() }, new Drawable[] { boxes[1] = new FillBox() }, new Drawable[] { boxes[2] = new FillBox() }, }, new[] { new Dimension(GridSizeMode.Relative, sizes[0]), new Dimension(GridSizeMode.Absolute, sizes[1]), new Dimension(), }, row); if (row) { AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(grid.DrawWidth, sizes[0] * grid.DrawHeight))); AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(grid.DrawWidth, sizes[1]))); AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth, grid.DrawHeight - boxes[0].DrawHeight - boxes[1].DrawHeight))); } else { AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(sizes[0] * grid.DrawWidth, grid.DrawHeight))); AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(sizes[1], grid.DrawHeight))); AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight))); } } [Test] public void Test3X3GridDistributedXy() { var boxes = new FillBox[9]; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() }, new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() }, new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() } }; }); for (int i = 0; i < 9; i++) { int local = i; AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(grid.DrawSize / 3f, boxes[local].DrawSize)); } } [Test] public void Test3X3GridAbsoluteXy() { var boxes = new FillBox[9]; var dimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Absolute, 75) }; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() }, new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() }, new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = dimensions; }); for (int i = 0; i < 9; i++) { int local = i; AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(new Vector2(dimensions[local % 3].Size, dimensions[local / 3].Size), boxes[local].DrawSize)); } } [Test] public void Test3X3GridRelativeXy() { var boxes = new FillBox[9]; var dimensions = new[] { new Dimension(GridSizeMode.Relative, 0.2f), new Dimension(GridSizeMode.Relative, 0.4f), new Dimension(GridSizeMode.Relative, 0.2f) }; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() }, new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() }, new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = dimensions; }); for (int i = 0; i < 9; i++) { int local = i; AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(new Vector2(dimensions[local % 3].Size * grid.DrawWidth, dimensions[local / 3].Size * grid.DrawHeight), boxes[local].DrawSize)); } } [Test] public void Test3X3GridMixedXy() { var boxes = new FillBox[9]; var dimensions = new[] { new Dimension(GridSizeMode.Absolute, 50), new Dimension(GridSizeMode.Relative, 0.2f) }; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox() }, new Drawable[] { boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox() }, new Drawable[] { boxes[6] = new FillBox(), boxes[7] = new FillBox(), boxes[8] = new FillBox() } }; grid.RowDimensions = grid.ColumnDimensions = dimensions; }); // Row 1 AddAssert("box 0 has correct size", () => Precision.AlmostEquals(boxes[0].DrawSize, new Vector2(dimensions[0].Size, dimensions[0].Size))); AddAssert("box 1 has correct size", () => Precision.AlmostEquals(boxes[1].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, dimensions[0].Size))); AddAssert("box 2 has correct size", () => Precision.AlmostEquals(boxes[2].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, dimensions[0].Size))); // Row 2 AddAssert("box 3 has correct size", () => Precision.AlmostEquals(boxes[3].DrawSize, new Vector2(dimensions[0].Size, grid.DrawHeight * dimensions[1].Size))); AddAssert("box 4 has correct size", () => Precision.AlmostEquals(boxes[4].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, grid.DrawHeight * dimensions[1].Size))); AddAssert("box 5 has correct size", () => Precision.AlmostEquals(boxes[5].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight * dimensions[1].Size))); // Row 3 AddAssert("box 6 has correct size", () => Precision.AlmostEquals(boxes[6].DrawSize, new Vector2(dimensions[0].Size, grid.DrawHeight - boxes[3].DrawHeight - boxes[0].DrawHeight))); AddAssert("box 7 has correct size", () => Precision.AlmostEquals(boxes[7].DrawSize, new Vector2(grid.DrawWidth * dimensions[1].Size, grid.DrawHeight - boxes[4].DrawHeight - boxes[1].DrawHeight))); AddAssert("box 8 has correct size", () => Precision.AlmostEquals(boxes[8].DrawSize, new Vector2(grid.DrawWidth - boxes[0].DrawWidth - boxes[1].DrawWidth, grid.DrawHeight - boxes[5].DrawHeight - boxes[2].DrawHeight))); } [Test] public void TestGridWithNullRowsAndColumns() { var boxes = new FillBox[4]; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { boxes[0] = new FillBox(), null, boxes[1] = new FillBox(), null }, null, new Drawable[] { boxes[2] = new FillBox(), null, boxes[3] = new FillBox(), null }, null }; }); AddAssert("two extra rows and columns", () => { for (int i = 0; i < 4; i++) { if (!Precision.AlmostEquals(boxes[i].DrawSize, grid.DrawSize / 4)) return false; } return true; }); } [Test] public void TestNestedGrids() { var boxes = new FillBox[4]; AddStep("set content", () => { grid.Content = new[] { new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { boxes[0] = new FillBox(), new FillBox(), }, new Drawable[] { new FillBox(), boxes[1] = new FillBox(), }, } }, new FillBox(), }, new Drawable[] { new FillBox(), new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { boxes[2] = new FillBox(), new FillBox(), }, new Drawable[] { new FillBox(), boxes[3] = new FillBox(), }, } } } }; }); for (int i = 0; i < 4; i++) { int local = i; AddAssert($"box {local} has correct size", () => Precision.AlmostEquals(boxes[local].DrawSize, grid.DrawSize / 4)); } } [Test] public void TestGridWithAutoSizingCells() { FillBox fillBox = null; var autoSizingChildren = new Drawable[2]; AddStep("set content", () => { grid.Content = new[] { new[] { autoSizingChildren[0] = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(50, 10) }, fillBox = new FillBox(), }, new[] { null, autoSizingChildren[1] = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(50, 10) }, }, }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) }; grid.RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), }; }); AddAssert("fill box has correct size", () => Precision.AlmostEquals(fillBox.DrawSize, new Vector2(grid.DrawWidth - 50, grid.DrawHeight - 10))); AddStep("rotate boxes", () => autoSizingChildren.ForEach(c => c.RotateTo(90))); AddAssert("fill box has resized correctly", () => Precision.AlmostEquals(fillBox.DrawSize, new Vector2(grid.DrawWidth - 10, grid.DrawHeight - 50))); } [TestCase(false)] [TestCase(true)] public void TestDimensionsWithMaximumSize(bool row) { var boxes = new FillBox[8]; var dimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Distributed, maxSize: 100), new Dimension(), new Dimension(GridSizeMode.Distributed, maxSize: 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Distributed, maxSize: 80), new Dimension(GridSizeMode.Distributed, maxSize: 150) }; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox(), boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox(), boxes[6] = new FillBox(), boxes[7] = new FillBox() }, }.Invert(), dimensions, row); checkClampedSizes(row, boxes, dimensions); } [TestCase(false)] [TestCase(true)] public void TestDimensionsWithMinimumSize(bool row) { var boxes = new FillBox[8]; var dimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Distributed, minSize: 100), new Dimension(), new Dimension(GridSizeMode.Distributed, minSize: 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Distributed, minSize: 80), new Dimension(GridSizeMode.Distributed, minSize: 150) }; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox(), boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox(), boxes[6] = new FillBox(), boxes[7] = new FillBox() }, }.Invert(), dimensions, row); checkClampedSizes(row, boxes, dimensions); } [TestCase(false)] [TestCase(true)] public void TestDimensionsWithMinimumAndMaximumSize(bool row) { var boxes = new FillBox[8]; var dimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Distributed, minSize: 100), new Dimension(), new Dimension(GridSizeMode.Distributed, maxSize: 50), new Dimension(GridSizeMode.Absolute, 100), new Dimension(GridSizeMode.Distributed, minSize: 80), new Dimension(GridSizeMode.Distributed, maxSize: 150) }; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = new FillBox(), boxes[3] = new FillBox(), boxes[4] = new FillBox(), boxes[5] = new FillBox(), boxes[6] = new FillBox(), boxes[7] = new FillBox() }, }.Invert(), dimensions, row); checkClampedSizes(row, boxes, dimensions); } [Test] public void TestCombinedMinimumAndMaximumSize() { AddStep("set content", () => { gridParent.Masking = false; gridParent.RelativeSizeAxes = Axes.Y; gridParent.Width = 420; grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), new FillBox(), }, }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Distributed, minSize: 180), new Dimension(GridSizeMode.Distributed, minSize: 50, maxSize: 70), new Dimension(GridSizeMode.Distributed, minSize: 40, maxSize: 70), }; }); AddAssert("content spans grid size", () => Precision.AlmostEquals(grid.DrawWidth, grid.Content[0].Sum(d => d.DrawWidth))); } [Test] public void TestCombinedMinimumAndMaximumSize2() { AddStep("set content", () => { gridParent.Masking = false; gridParent.RelativeSizeAxes = Axes.Y; gridParent.Width = 230; grid.Content = new[] { new Drawable[] { new FillBox(), new FillBox(), }, }; grid.ColumnDimensions = new[] { new Dimension(GridSizeMode.Distributed, minSize: 180), new Dimension(GridSizeMode.Distributed, minSize: 40, maxSize: 70), }; }); AddAssert("content spans grid size", () => Precision.AlmostEquals(grid.DrawWidth, grid.Content[0].Sum(d => d.DrawWidth))); } [TestCase(true)] [TestCase(false)] public void TestAutoSizedCellsWithTransparentContent(bool alwaysPresent) { AddStep("set content", () => { grid.RowDimensions = new[] { new Dimension(), new Dimension(), new Dimension(GridSizeMode.AutoSize) }; grid.ColumnDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), new Dimension() }; grid.Content = new[] { new Drawable[] { new FillBox(), transparentBox(alwaysPresent), new FillBox() }, new Drawable[] { new FillBox(), transparentBox(alwaysPresent), new FillBox() }, new Drawable[] { transparentBox(alwaysPresent), transparentBox(alwaysPresent), transparentBox(alwaysPresent) } }; }); float desiredTransparentBoxSize = alwaysPresent ? 50 : 0; AddAssert("non-transparent fill boxes have correct size", () => grid.Content .SelectMany(row => row) .Where(box => box.Alpha > 0) .All(box => Precision.AlmostEquals(box.DrawWidth, (grid.DrawWidth - desiredTransparentBoxSize) / 2) && Precision.AlmostEquals(box.DrawHeight, (grid.DrawHeight - desiredTransparentBoxSize) / 2))); } [TestCase(true)] [TestCase(false)] public void TestAutoSizedRowOrColumnWithTransparentContent(bool row) { var boxes = new FillBox[5]; var dimensions = new[] { new Dimension(GridSizeMode.Absolute, 100f), new Dimension(), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.Relative, 0.2f), new Dimension() }; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox(), boxes[2] = transparentBox(false), boxes[3] = new FillBox(), boxes[4] = new FillBox() } }.Invert(), dimensions, row); AddAssert("box 0 has correct size", () => Precision.AlmostEquals(getDimension(boxes[0], row), 100f)); AddAssert("box 1 has correct size", () => Precision.AlmostEquals(getDimension(boxes[1], row), (getDimension(grid, row) * 0.8f - 100f) / 2)); AddAssert("box 3 has correct size", () => Precision.AlmostEquals(getDimension(boxes[3], row), getDimension(grid, row) * 0.2f)); AddAssert("box 4 has correct size", () => Precision.AlmostEquals(getDimension(boxes[4], row), (getDimension(grid, row) * 0.8f - 100f) / 2)); } private FillBox transparentBox(bool alwaysPresent) => new FillBox { Alpha = 0, AlwaysPresent = alwaysPresent, RelativeSizeAxes = Axes.None, Size = new Vector2(50) }; [TestCase(true)] [TestCase(false)] public void TestAutoSizedRowOrColumnWithDelayedLifetimeContent(bool row) { var boxes = new FillBox[3]; var dimensions = new[] { new Dimension(GridSizeMode.Absolute, 75f), new Dimension(GridSizeMode.AutoSize), new Dimension() }; setSingleDimensionContent(() => new[] { new Drawable[] { boxes[0] = new FillBox(), boxes[1] = new FillBox { RelativeSizeAxes = Axes.None, LifetimeStart = double.MaxValue, Size = new Vector2(50) }, boxes[2] = new FillBox() } }.Invert(), dimensions, row); AddAssert("box 0 has correct size", () => Precision.AlmostEquals(getDimension(boxes[0], row), 75f)); AddAssert("box 2 has correct size", () => Precision.AlmostEquals(getDimension(boxes[2], row), getDimension(grid, row) - 75f)); AddStep("make box 1 alive", () => boxes[1].LifetimeStart = Time.Current); AddUntilStep("wait for alive", () => boxes[1].IsAlive); AddAssert("box 0 has correct size", () => Precision.AlmostEquals(getDimension(boxes[0], row), 75f)); AddAssert("box 2 has correct size", () => Precision.AlmostEquals(getDimension(boxes[2], row), getDimension(grid, row) - 125f)); } private bool gridContentChangeEventWasFired; [Test] public void TestSetContentByIndex() { setSingleDimensionContent(() => new[] { new Drawable[] { new FillBox(), new FillBox() }, new Drawable[] { new FillBox(), new FillBox() } }); AddStep("Subscribe to event", () => grid.Content.ArrayElementChanged += () => gridContentChangeEventWasFired = true); AddStep("Replace bottom right box with a SpriteText", () => { gridContentChangeEventWasFired = false; grid.Content[1][1] = new SpriteText { Text = "test" }; }); assertContentChangeEventWasFired(); AddAssert("[1][1] cell contains a SpriteText", () => grid.Content[1][1].GetType() == typeof(SpriteText)); AddStep("Replace top line with [SpriteText][null]", () => { gridContentChangeEventWasFired = false; grid.Content[0] = new Drawable[] { new SpriteText { Text = "test" }, null }; }); assertContentChangeEventWasFired(); AddAssert("[0][0] cell contains a SpriteText", () => grid.Content[0][0].GetType() == typeof(SpriteText)); AddAssert("[0][1] cell contains null", () => grid.Content[0][1] == null); void assertContentChangeEventWasFired() => AddAssert("Content change event was fired", () => gridContentChangeEventWasFired); } /// <summary> /// Returns drawable dimension along desired axis. /// </summary> private float getDimension(Drawable drawable, bool row) => row ? drawable.DrawHeight : drawable.DrawWidth; private void checkClampedSizes(bool row, FillBox[] boxes, Dimension[] dimensions) { AddAssert("sizes not over/underflowed", () => { for (int i = 0; i < 8; i++) { if (dimensions[i].Mode != GridSizeMode.Distributed) continue; if (row && (boxes[i].DrawHeight > dimensions[i].MaxSize || boxes[i].DrawHeight < dimensions[i].MinSize)) return false; if (!row && (boxes[i].DrawWidth > dimensions[i].MaxSize || boxes[i].DrawWidth < dimensions[i].MinSize)) return false; } return true; }); AddAssert("column span total length", () => { float expectedSize = row ? grid.DrawHeight : grid.DrawWidth; float totalSize = row ? boxes.Sum(b => b.DrawHeight) : boxes.Sum(b => b.DrawWidth); // Allowed to exceed the length of the columns due to absolute sizing return totalSize >= expectedSize; }); } private void setSingleDimensionContent(Func<Drawable[][]> contentFunc, Dimension[] dimensions = null, bool row = false) => AddStep("set content", () => { var content = contentFunc(); if (!row) content = content.Invert(); grid.Content = content; if (dimensions == null) return; if (row) grid.RowDimensions = dimensions; else grid.ColumnDimensions = dimensions; }); private class FillBox : Box { public FillBox() { RelativeSizeAxes = Axes.Both; Colour = new Color4(RNG.NextSingle(1), RNG.NextSingle(1), RNG.NextSingle(1), 1); } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework 1.0 has no support for reading assembly attributes // and uses the CompactRepositorySelector instead #if !NETCF using System; using System.Collections; using System.Configuration; using System.IO; using System.Reflection; using log4net.Config; using log4net.Util; using log4net.Repository; namespace log4net.Core { /// <summary> /// The default implementation of the <see cref="IRepositorySelector"/> interface. /// </summary> /// <remarks> /// <para> /// Uses attributes defined on the calling assembly to determine how to /// configure the hierarchy for the repository. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class DefaultRepositorySelector : IRepositorySelector { #region Public Events /// <summary> /// Event to notify that a logger repository has been created. /// </summary> /// <value> /// Event to notify that a logger repository has been created. /// </value> /// <remarks> /// <para> /// Event raised when a new repository is created. /// The event source will be this selector. The event args will /// be a <see cref="LoggerRepositoryCreationEventArgs"/> which /// holds the newly created <see cref="ILoggerRepository"/>. /// </para> /// </remarks> public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent { add { m_loggerRepositoryCreatedEvent += value; } remove { m_loggerRepositoryCreatedEvent -= value; } } #endregion Public Events #region Public Instance Constructors /// <summary> /// Creates a new repository selector. /// </summary> /// <param name="defaultRepositoryType">The type of the repositories to create, must implement <see cref="ILoggerRepository"/></param> /// <remarks> /// <para> /// Create an new repository selector. /// The default type for repositories must be specified, /// an appropriate value would be <see cref="log4net.Repository.Hierarchy.Hierarchy"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="defaultRepositoryType"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="defaultRepositoryType"/> does not implement <see cref="ILoggerRepository"/>.</exception> public DefaultRepositorySelector(Type defaultRepositoryType) { if (defaultRepositoryType == null) { throw new ArgumentNullException("defaultRepositoryType"); } // Check that the type is a repository if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) ) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, "Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); } m_defaultRepositoryType = defaultRepositoryType; LogLog.Debug(declaringType, "defaultRepositoryType [" + m_defaultRepositoryType + "]"); } #endregion Public Instance Constructors #region Implementation of IRepositorySelector /// <summary> /// Gets the <see cref="ILoggerRepository"/> for the specified assembly. /// </summary> /// <param name="repositoryAssembly">The assembly use to lookup the <see cref="ILoggerRepository"/>.</param> /// <remarks> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and the repository /// to create can be overridden by specifying the <see cref="log4net.Config.RepositoryAttribute"/> /// attribute on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// The default values are to use the <see cref="log4net.Repository.Hierarchy.Hierarchy"/> /// implementation of the <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically configured using /// any <see cref="log4net.Config.ConfiguratorAttribute"/> attributes defined on /// the <paramref name="repositoryAssembly"/>. /// </para> /// </remarks> /// <returns>The <see cref="ILoggerRepository"/> for the assembly</returns> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository GetRepository(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } return CreateRepository(repositoryAssembly, m_defaultRepositoryType); } /// <summary> /// Gets the <see cref="ILoggerRepository"/> for the specified repository. /// </summary> /// <param name="repositoryName">The repository to use to lookup the <see cref="ILoggerRepository"/>.</param> /// <returns>The <see cref="ILoggerRepository"/> for the specified repository.</returns> /// <remarks> /// <para> /// Returns the named repository. If <paramref name="repositoryName"/> is <c>null</c> /// a <see cref="ArgumentNullException"/> is thrown. If the repository /// does not exist a <see cref="LogException"/> is thrown. /// </para> /// <para> /// Use <see cref="M:CreateRepository(string, Type)"/> to create a repository. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception> /// <exception cref="LogException"><paramref name="repositoryName"/> does not exist.</exception> public ILoggerRepository GetRepository(string repositoryName) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } lock(this) { // Lookup in map ILoggerRepository rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep == null) { throw new LogException("Repository [" + repositoryName + "] is NOT defined."); } return rep; } } /// <summary> /// Create a new repository for the assembly specified /// </summary> /// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the repository to create can be overridden by specifying the /// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// <paramref name="repositoryAssembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="repositoryAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) { return CreateRepository(repositoryAssembly, repositoryType, DefaultRepositoryName, true); } /// <summary> /// Creates a new repository for the assembly specified. /// </summary> /// <param name="repositoryAssembly">the assembly to use to create the repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryName">The name to assign to the created repository</param> /// <param name="readAssemblyAttributes">Set to <c>true</c> to read and apply the assembly attributes</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the repository to create can be overridden by specifying the /// <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// <paramref name="repositoryAssembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the repository. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="repositoryAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="repositoryAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.RepositoryAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryAssembly"/> is <see langword="null" />.</exception> public ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType, string repositoryName, bool readAssemblyAttributes) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { // Lookup in map ILoggerRepository rep = m_assembly2repositoryMap[repositoryAssembly] as ILoggerRepository; if (rep == null) { // Not found, therefore create LogLog.Debug(declaringType, "Creating repository for assembly [" + repositoryAssembly + "]"); // Must specify defaults string actualRepositoryName = repositoryName; Type actualRepositoryType = repositoryType; if (readAssemblyAttributes) { // Get the repository and type from the assembly attributes GetInfoForAssembly(repositoryAssembly, ref actualRepositoryName, ref actualRepositoryType); } LogLog.Debug(declaringType, "Assembly [" + repositoryAssembly + "] using repository [" + actualRepositoryName + "] and repository type [" + actualRepositoryType + "]"); // Lookup the repository in the map (as this may already be defined) rep = m_name2repositoryMap[actualRepositoryName] as ILoggerRepository; if (rep == null) { // Create the repository rep = CreateRepository(actualRepositoryName, actualRepositoryType); if (readAssemblyAttributes) { try { // Look for aliasing attributes LoadAliases(repositoryAssembly, rep); // Look for plugins defined on the assembly LoadPlugins(repositoryAssembly, rep); // Configure the repository using the assembly attributes ConfigureRepository(repositoryAssembly, rep); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); } } } else { LogLog.Debug(declaringType, "repository [" + actualRepositoryName + "] already exists, using repository type [" + rep.GetType().FullName + "]"); if (readAssemblyAttributes) { try { // Look for plugins defined on the assembly LoadPlugins(repositoryAssembly, rep); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to configure repository [" + actualRepositoryName + "] from assembly attributes.", ex); } } } m_assembly2repositoryMap[repositoryAssembly] = rep; } return rep; } } /// <summary> /// Creates a new repository for the specified repository. /// </summary> /// <param name="repositoryName">The repository to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>. /// If this param is <see langword="null" /> then the default repository type is used.</param> /// <returns>The new repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(string)"/> with the /// same repository specified will return the same repository instance. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="repositoryName"/> is <see langword="null" />.</exception> /// <exception cref="LogException"><paramref name="repositoryName"/> already exists.</exception> public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { ILoggerRepository rep = null; // First check that the repository does not exist rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep != null) { throw new LogException("Repository [" + repositoryName + "] is already defined. Repositories cannot be redefined."); } else { // Lookup an alias before trying to create the new repository ILoggerRepository aliasedRepository = m_alias2repositoryMap[repositoryName] as ILoggerRepository; if (aliasedRepository != null) { // Found an alias // Check repository type if (aliasedRepository.GetType() == repositoryType) { // Repository type is compatible LogLog.Debug(declaringType, "Aliasing repository [" + repositoryName + "] to existing repository [" + aliasedRepository.Name + "]"); rep = aliasedRepository; // Store in map m_name2repositoryMap[repositoryName] = rep; } else { // Invalid repository type for alias LogLog.Error(declaringType, "Failed to alias repository [" + repositoryName + "] to existing repository ["+aliasedRepository.Name+"]. Requested repository type ["+repositoryType.FullName+"] is not compatible with existing type [" + aliasedRepository.GetType().FullName + "]"); // We now drop through to create the repository without aliasing } } // If we could not find an alias if (rep == null) { LogLog.Debug(declaringType, "Creating repository [" + repositoryName + "] using type [" + repositoryType + "]"); // Call the no arg constructor for the repositoryType rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); // Set the name of the repository rep.Name = repositoryName; // Store in map m_name2repositoryMap[repositoryName] = rep; // Notify listeners that the repository has been created OnLoggerRepositoryCreatedEvent(rep); } } return rep; } } /// <summary> /// Test if a named repository exists /// </summary> /// <param name="repositoryName">the named repository to check</param> /// <returns><c>true</c> if the repository exists</returns> /// <remarks> /// <para> /// Test if a named repository exists. Use <see cref="M:CreateRepository(string, Type)"/> /// to create a new repository and <see cref="M:GetRepository(string)"/> to retrieve /// a repository. /// </para> /// </remarks> public bool ExistsRepository(string repositoryName) { lock(this) { return m_name2repositoryMap.ContainsKey(repositoryName); } } /// <summary> /// Gets a list of <see cref="ILoggerRepository"/> objects /// </summary> /// <returns>an array of all known <see cref="ILoggerRepository"/> objects</returns> /// <remarks> /// <para> /// Gets an array of all of the repositories created by this selector. /// </para> /// </remarks> public ILoggerRepository[] GetAllRepositories() { lock(this) { ICollection reps = m_name2repositoryMap.Values; ILoggerRepository[] all = new ILoggerRepository[reps.Count]; reps.CopyTo(all, 0); return all; } } #endregion Implementation of IRepositorySelector #region Public Instance Methods /// <summary> /// Aliases a repository to an existing repository. /// </summary> /// <param name="repositoryAlias">The repository to alias.</param> /// <param name="repositoryTarget">The repository that the repository is aliased to.</param> /// <remarks> /// <para> /// The repository specified will be aliased to the repository when created. /// The repository must not already exist. /// </para> /// <para> /// When the repository is created it must utilize the same repository type as /// the repository it is aliased to, otherwise the aliasing will fail. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <para><paramref name="repositoryAlias" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repositoryTarget" /> is <see langword="null" />.</para> /// </exception> public void AliasRepository(string repositoryAlias, ILoggerRepository repositoryTarget) { if (repositoryAlias == null) { throw new ArgumentNullException("repositoryAlias"); } if (repositoryTarget == null) { throw new ArgumentNullException("repositoryTarget"); } lock(this) { // Check if the alias is already set if (m_alias2repositoryMap.Contains(repositoryAlias)) { // Check if this is a duplicate of the current alias if (repositoryTarget != ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias])) { // Cannot redefine existing alias throw new InvalidOperationException("Repository [" + repositoryAlias + "] is already aliased to repository [" + ((ILoggerRepository)m_alias2repositoryMap[repositoryAlias]).Name + "]. Aliases cannot be redefined."); } } // Check if the alias is already mapped to a repository else if (m_name2repositoryMap.Contains(repositoryAlias)) { // Check if this is a duplicate of the current mapping if ( repositoryTarget != ((ILoggerRepository)m_name2repositoryMap[repositoryAlias]) ) { // Cannot define alias for already mapped repository throw new InvalidOperationException("Repository [" + repositoryAlias + "] already exists and cannot be aliased to repository [" + repositoryTarget.Name + "]."); } } else { // Set the alias m_alias2repositoryMap[repositoryAlias] = repositoryTarget; } } } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Notifies the registered listeners that the repository has been created. /// </summary> /// <param name="repository">The repository that has been created.</param> /// <remarks> /// <para> /// Raises the <see cref="LoggerRepositoryCreatedEvent"/> event. /// </para> /// </remarks> protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) { LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent; if (handler != null) { handler(this, new LoggerRepositoryCreationEventArgs(repository)); } } #endregion Protected Instance Methods #region Private Instance Methods /// <summary> /// Gets the repository name and repository type for the specified assembly. /// </summary> /// <param name="assembly">The assembly that has a <see cref="log4net.Config.RepositoryAttribute"/>.</param> /// <param name="repositoryName">in/out param to hold the repository name to use for the assembly, caller should set this to the default value before calling.</param> /// <param name="repositoryType">in/out param to hold the type of the repository to create for the assembly, caller should set this to the default value before calling.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly" /> is <see langword="null" />.</exception> private void GetInfoForAssembly(Assembly assembly, ref string repositoryName, ref Type repositoryType) { if (assembly == null) { throw new ArgumentNullException("assembly"); } try { LogLog.Debug(declaringType, "Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); } catch { // Ignore exception from debug call } try { // Look for the RepositoryAttribute on the assembly object[] repositoryAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.RepositoryAttribute), false); if (repositoryAttributes == null || repositoryAttributes.Length == 0) { // This is not a problem, but its nice to know what is going on. LogLog.Debug(declaringType, "Assembly [" + assembly + "] does not have a RepositoryAttribute specified."); } else { if (repositoryAttributes.Length > 1) { LogLog.Error(declaringType, "Assembly [" + assembly + "] has multiple log4net.Config.RepositoryAttribute assembly attributes. Only using first occurrence."); } log4net.Config.RepositoryAttribute domAttr = repositoryAttributes[0] as log4net.Config.RepositoryAttribute; if (domAttr == null) { LogLog.Error(declaringType, "Assembly [" + assembly + "] has a RepositoryAttribute but it does not!."); } else { // If the Name property is set then override the default if (domAttr.Name != null) { repositoryName = domAttr.Name; } // If the RepositoryType property is set then override the default if (domAttr.RepositoryType != null) { // Check that the type is a repository if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) { repositoryType = domAttr.RepositoryType; } else { LogLog.Error(declaringType, "DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); } } } } } catch (Exception ex) { LogLog.Error(declaringType, "Unhandled exception in GetInfoForAssembly", ex); } } /// <summary> /// Configures the repository using information from the assembly. /// </summary> /// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes which define the configuration for the repository.</param> /// <param name="repository">The repository to configure.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the Configurator attributes (e.g. XmlConfiguratorAttribute) on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { // Sort the ConfiguratorAttributes in priority order Array.Sort(configAttributes); // Delegate to the attribute the job of configuring the repository foreach(log4net.Config.ConfiguratorAttribute configAttr in configAttributes) { if (configAttr != null) { try { configAttr.Configure(assembly, repository); } catch (Exception ex) { LogLog.Error(declaringType, "Exception calling ["+configAttr.GetType().FullName+"] .Configure method.", ex); } } } } if (repository.Name == DefaultRepositoryName) { // Try to configure the default repository using an AppSettings specified config file // Do this even if the repository has been configured (or claims to be), this allows overriding // of the default config files etc, if that is required. string repositoryConfigFile = SystemInfo.GetAppSetting("log4net.Config"); if (repositoryConfigFile != null && repositoryConfigFile.Length > 0) { string applicationBaseDirectory = null; try { applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory; } catch(Exception ex) { LogLog.Warn(declaringType, "Exception getting ApplicationBaseDirectory. appSettings log4net.Config path ["+repositoryConfigFile+"] will be treated as an absolute URI", ex); } string repositoryConfigFilePath = repositoryConfigFile; if (applicationBaseDirectory != null) { repositoryConfigFilePath = Path.Combine(applicationBaseDirectory, repositoryConfigFile); } // Determine whether to watch the file or not based on an app setting value: bool watchRepositoryConfigFile = false; #if NET_2_0 || MONO_2_0 Boolean.TryParse(SystemInfo.GetAppSetting("log4net.Config.Watch"), out watchRepositoryConfigFile); #else { string watch = SystemInfo.GetAppSetting("log4net.Config.Watch"); if (watch != null && watch.Length > 0) { try { watchRepositoryConfigFile = Boolean.Parse(watch); } catch (FormatException) { // simply not a Boolean } } } #endif #if !MONO_IOS if (watchRepositoryConfigFile) { // As we are going to watch the config file it is required to resolve it as a // physical file system path pass that in a FileInfo object to the Configurator FileInfo repositoryConfigFileInfo = null; try { repositoryConfigFileInfo = new FileInfo(repositoryConfigFilePath); } catch (Exception ex) { LogLog.Error(declaringType, "DefaultRepositorySelector: Exception while parsing log4net.Config file physical path [" + repositoryConfigFilePath + "]", ex); } try { LogLog.Debug(declaringType, "Loading and watching configuration for default repository from AppSettings specified Config path [" + repositoryConfigFilePath + "]"); XmlConfigurator.ConfigureAndWatch(repository, repositoryConfigFileInfo); } catch (Exception ex) { LogLog.Error(declaringType, "DefaultRepositorySelector: Exception calling XmlConfigurator.ConfigureAndWatch method with ConfigFilePath [" + repositoryConfigFilePath + "]", ex); } } else #endif { // As we are not going to watch the config file it is easiest to just resolve it as a // URI and pass that to the Configurator Uri repositoryConfigUri = null; try { repositoryConfigUri = new Uri(repositoryConfigFilePath); } catch(Exception ex) { LogLog.Error(declaringType, "Exception while parsing log4net.Config file path ["+repositoryConfigFile+"]", ex); } if (repositoryConfigUri != null) { LogLog.Debug(declaringType, "Loading configuration for default repository from AppSettings specified Config URI ["+repositoryConfigUri.ToString()+"]"); try { // TODO: Support other types of configurator XmlConfigurator.Configure(repository, repositoryConfigUri); } catch (Exception ex) { LogLog.Error(declaringType, "Exception calling XmlConfigurator.Configure method with ConfigUri ["+repositoryConfigUri+"]", ex); } } } } } } /// <summary> /// Loads the attribute defined plugins on the assembly. /// </summary> /// <param name="assembly">The assembly that contains the attributes.</param> /// <param name="repository">The repository to add the plugins to.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void LoadPlugins(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the PluginAttribute on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { foreach(log4net.Plugin.IPluginFactory configAttr in configAttributes) { try { // Create the plugin and add it to the repository repository.PluginMap.Add(configAttr.CreatePlugin()); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); } } } } /// <summary> /// Loads the attribute defined aliases on the assembly. /// </summary> /// <param name="assembly">The assembly that contains the attributes.</param> /// <param name="repository">The repository to alias to.</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="assembly" /> is <see langword="null" />.</para> /// <para>-or-</para> /// <para><paramref name="repository" /> is <see langword="null" />.</para> /// </exception> private void LoadAliases(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the AliasRepositoryAttribute on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasRepositoryAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { foreach(log4net.Config.AliasRepositoryAttribute configAttr in configAttributes) { try { AliasRepository(configAttr.Name, repository); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to alias repository [" + configAttr.Name + "]", ex); } } } } #endregion Private Instance Methods #region Private Static Fields /// <summary> /// The fully qualified type of the DefaultRepositorySelector class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(DefaultRepositorySelector); private const string DefaultRepositoryName = "log4net-default-repository"; #endregion Private Static Fields #region Private Instance Fields private readonly Hashtable m_name2repositoryMap = new Hashtable(); private readonly Hashtable m_assembly2repositoryMap = new Hashtable(); private readonly Hashtable m_alias2repositoryMap = new Hashtable(); private readonly Type m_defaultRepositoryType; private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; #endregion Private Instance Fields } } #endif // !NETCF
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class ImportPoolSpectraS3Request : Ds3Request { public string Pool { get; private set; } private string _dataPolicyId; public string DataPolicyId { get { return _dataPolicyId; } set { WithDataPolicyId(value); } } private Priority? _priority; public Priority? Priority { get { return _priority; } set { WithPriority(value); } } private string _storageDomainId; public string StorageDomainId { get { return _storageDomainId; } set { WithStorageDomainId(value); } } private string _userId; public string UserId { get { return _userId; } set { WithUserId(value); } } private Priority? _verifyDataAfterImport; public Priority? VerifyDataAfterImport { get { return _verifyDataAfterImport; } set { WithVerifyDataAfterImport(value); } } private bool? _verifyDataPriorToImport; public bool? VerifyDataPriorToImport { get { return _verifyDataPriorToImport; } set { WithVerifyDataPriorToImport(value); } } public ImportPoolSpectraS3Request WithDataPolicyId(Guid? dataPolicyId) { this._dataPolicyId = dataPolicyId.ToString(); if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId.ToString()); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public ImportPoolSpectraS3Request WithDataPolicyId(string dataPolicyId) { this._dataPolicyId = dataPolicyId; if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public ImportPoolSpectraS3Request WithPriority(Priority? priority) { this._priority = priority; if (priority != null) { this.QueryParams.Add("priority", priority.ToString()); } else { this.QueryParams.Remove("priority"); } return this; } public ImportPoolSpectraS3Request WithStorageDomainId(Guid? storageDomainId) { this._storageDomainId = storageDomainId.ToString(); if (storageDomainId != null) { this.QueryParams.Add("storage_domain_id", storageDomainId.ToString()); } else { this.QueryParams.Remove("storage_domain_id"); } return this; } public ImportPoolSpectraS3Request WithStorageDomainId(string storageDomainId) { this._storageDomainId = storageDomainId; if (storageDomainId != null) { this.QueryParams.Add("storage_domain_id", storageDomainId); } else { this.QueryParams.Remove("storage_domain_id"); } return this; } public ImportPoolSpectraS3Request WithUserId(Guid? userId) { this._userId = userId.ToString(); if (userId != null) { this.QueryParams.Add("user_id", userId.ToString()); } else { this.QueryParams.Remove("user_id"); } return this; } public ImportPoolSpectraS3Request WithUserId(string userId) { this._userId = userId; if (userId != null) { this.QueryParams.Add("user_id", userId); } else { this.QueryParams.Remove("user_id"); } return this; } public ImportPoolSpectraS3Request WithVerifyDataAfterImport(Priority? verifyDataAfterImport) { this._verifyDataAfterImport = verifyDataAfterImport; if (verifyDataAfterImport != null) { this.QueryParams.Add("verify_data_after_import", verifyDataAfterImport.ToString()); } else { this.QueryParams.Remove("verify_data_after_import"); } return this; } public ImportPoolSpectraS3Request WithVerifyDataPriorToImport(bool? verifyDataPriorToImport) { this._verifyDataPriorToImport = verifyDataPriorToImport; if (verifyDataPriorToImport != null) { this.QueryParams.Add("verify_data_prior_to_import", verifyDataPriorToImport.ToString()); } else { this.QueryParams.Remove("verify_data_prior_to_import"); } return this; } public ImportPoolSpectraS3Request(string pool) { this.Pool = pool; this.QueryParams.Add("operation", "import"); } internal override HttpVerb Verb { get { return HttpVerb.PUT; } } internal override string Path { get { return "/_rest_/pool/" + Pool; } } } }
// // 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. // namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.Threading; using NLog.Common; using NLog.Internal; using Xunit; public class AsyncHelperTests : NLogTestBase { [Fact] public void OneTimeOnlyTest1() { var exceptions = new List<Exception>(); AsyncContinuation cont = exceptions.Add; cont = AsyncHelpers.PreventMultipleCalls(cont); // OneTimeOnly(OneTimeOnly(x)) == OneTimeOnly(x) var cont2 = AsyncHelpers.PreventMultipleCalls(cont); Assert.Same(cont, cont2); var sampleException = new InvalidOperationException("some message"); cont(null); cont(sampleException); cont(null); cont(sampleException); Assert.Equal(1, exceptions.Count); Assert.Null(exceptions[0]); } [Fact] public void OneTimeOnlyTest2() { var exceptions = new List<Exception>(); AsyncContinuation cont = exceptions.Add; cont = AsyncHelpers.PreventMultipleCalls(cont); var sampleException = new InvalidOperationException("some message"); cont(sampleException); cont(null); cont(sampleException); cont(null); Assert.Equal(1, exceptions.Count); Assert.Same(sampleException, exceptions[0]); } [Fact] public void OneTimeOnlyExceptionInHandlerTest() { LogManager.ThrowExceptions = false; var exceptions = new List<Exception>(); var sampleException = new InvalidOperationException("some message"); AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; }; cont = AsyncHelpers.PreventMultipleCalls(cont); cont(null); cont(null); cont(null); Assert.Equal(1, exceptions.Count); Assert.Null(exceptions[0]); } [Fact] public void OneTimeOnlyExceptionInHandlerTest_RethrowExceptionEnabled() { LogManager.ThrowExceptions = true; var exceptions = new List<Exception>(); var sampleException = new InvalidOperationException("some message"); AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; }; cont = AsyncHelpers.PreventMultipleCalls(cont); try { cont(null); } catch{} try { cont(null); } catch { } try { cont(null); } catch { } // cleanup LogManager.ThrowExceptions = false; Assert.Equal(1, exceptions.Count); Assert.Null(exceptions[0]); } [Fact] public void ContinuationTimeoutTest() { var resetEvent = new ManualResetEvent(false); var exceptions = new List<Exception>(); // set up a timer to strike in 1 second var cont = AsyncHelpers.WithTimeout(ex => { exceptions.Add(ex); resetEvent.Set(); }, TimeSpan.FromMilliseconds(1)); resetEvent.WaitOne(TimeSpan.FromSeconds(1)); // make sure we got timeout exception Assert.Equal(1, exceptions.Count); Assert.IsType(typeof(TimeoutException), exceptions[0]); Assert.Equal("Timeout.", exceptions[0].Message); // those will be ignored cont(null); cont(new InvalidOperationException("Some exception")); cont(null); cont(new InvalidOperationException("Some exception")); Assert.Equal(1, exceptions.Count); } [Fact] public void ContinuationTimeoutNotHitTest() { var exceptions = new List<Exception>(); // set up a timer to strike in 1 second var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromMilliseconds(500)); // call success quickly, hopefully before the timer comes cont(null); // sleep 2 seconds to make sure timer event comes Thread.Sleep(1000); // make sure we got success, not a timer exception Assert.Equal(1, exceptions.Count); Assert.Null(exceptions[0]); // those will be ignored cont(null); cont(new InvalidOperationException("Some exception")); cont(null); cont(new InvalidOperationException("Some exception")); Assert.Equal(1, exceptions.Count); Assert.Null(exceptions[0]); } [Fact] public void ContinuationErrorTimeoutNotHitTest() { var exceptions = new List<Exception>(); // set up a timer to strike in 3 second var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromSeconds(500)); var exception = new InvalidOperationException("Foo"); // call success quickly, hopefully before the timer comes cont(exception); // sleep 2 seconds to make sure timer event comes Thread.Sleep(1000); // make sure we got success, not a timer exception Assert.Equal(1, exceptions.Count); Assert.NotNull(exceptions[0]); Assert.Same(exception, exceptions[0]); // those will be ignored cont(null); cont(new InvalidOperationException("Some exception")); cont(null); cont(new InvalidOperationException("Some exception")); Assert.Equal(1, exceptions.Count); Assert.NotNull(exceptions[0]); } [Fact] public void RepeatTest1() { bool finalContinuationInvoked = false; Exception lastException = null; AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(null, 10, finalContinuation, cont => { callCount++; cont(null); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); Assert.Equal(10, callCount); } [Fact] public void RepeatTest2() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new InvalidOperationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(null, 10, finalContinuation, cont => { callCount++; cont(sampleException); cont(sampleException); }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, callCount); } [Fact] public void RepeatTest3() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new InvalidOperationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int callCount = 0; AsyncHelpers.Repeat(null, 10, finalContinuation, cont => { callCount++; throw sampleException; }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, callCount); } [Fact] public void ForEachItemSequentiallyTest1() { bool finalContinuationInvoked = false; Exception lastException = null; AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(null, input, finalContinuation, (i, cont) => { sum += i; cont(null); cont(null); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); Assert.Equal(55, sum); } [Fact] public void ForEachItemSequentiallyTest2() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new InvalidOperationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(null, input, finalContinuation, (i, cont) => { sum += i; cont(sampleException); cont(sampleException); }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, sum); } [Fact] public void ForEachItemSequentiallyTest3() { bool finalContinuationInvoked = false; Exception lastException = null; Exception sampleException = new InvalidOperationException("Some message"); AsyncContinuation finalContinuation = ex => { finalContinuationInvoked = true; lastException = ex; }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemSequentially(null, input, finalContinuation, (i, cont) => { sum += i; throw sampleException; }); Assert.True(finalContinuationInvoked); Assert.Same(sampleException, lastException); Assert.Equal(1, sum); } [Fact] public void ForEachItemInParallelEmptyTest() { int[] items = new int[0]; Exception lastException = null; bool finalContinuationInvoked = false; AsyncContinuation continuation = ex => { lastException = ex; finalContinuationInvoked = true; }; AsyncHelpers.ForEachItemInParallel(null, items, continuation, (i, cont) => { Assert.True(false, "Will not be reached"); }); Assert.True(finalContinuationInvoked); Assert.Null(lastException); } [Fact] public void ForEachItemInParallelTest() { var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; long sum = 0; AsyncContinuation finalContinuation = ex => { if (sum != 55) { throw new InvalidOperationException(); } lastException = ex; Interlocked.Increment(ref sum); finalContinuationInvoked.Set(); }; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(null, input, finalContinuation, (i, cont) => { lock (input) { Interlocked.Add(ref sum, i); } cont(null); cont(null); }); finalContinuationInvoked.WaitOne(); Assert.Null(lastException); if (sum == 55) { Assert.False(true, "All tasks completed, but final continuation did not complete"); } Assert.Equal(56, sum); } [Fact] public void ForEachItemInParallelSingleFailureTest() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.LogToConsole = true; var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; AsyncContinuation finalContinuation = ex => { lastException = ex; finalContinuationInvoked.Set(); }; int sum = 0; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncHelpers.ForEachItemInParallel(null, input, finalContinuation, (i, cont) => { Console.WriteLine("Callback on {0}", Thread.CurrentThread.ManagedThreadId); lock (input) { sum += i; } if (i == 7) { throw new InvalidOperationException("Some failure."); } cont(null); }); finalContinuationInvoked.WaitOne(); Assert.Equal(55, sum); Assert.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); Assert.Equal("Some failure.", lastException.Message); } } [Fact] public void ForEachItemInParallelMultipleFailuresTest() { var finalContinuationInvoked = new ManualResetEvent(false); Exception lastException = null; long[] sum = { 0 }; var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; AsyncContinuation finalContinuation = ex => { lastException = ex; Interlocked.Add(ref sum[0], 1); finalContinuationInvoked.Set(); }; AsyncHelpers.ForEachItemInParallel(null, input, finalContinuation, (i, cont) => { Interlocked.Add(ref sum[0], i); throw new InvalidOperationException("Some failure."); }); finalContinuationInvoked.WaitOne(); if (sum[0] == 55) { Assert.False(true, "All tasks completed, but final continuation did not complete"); } Assert.Equal(56, sum[0]); Assert.NotNull(lastException); Assert.IsType(typeof(NLogRuntimeException), lastException); Assert.True(lastException.Message.StartsWith("Got multiple exceptions:\r\n")); } [Fact] public void TestPreventMultipleCalls() { var finalContinuationInvoked = new ManualResetEvent(false); int sum = 0; AsyncContinuation finalContinuation = ex => { Interlocked.Add(ref sum, 1); finalContinuationInvoked.Set(); }; for (int x = 0; x < 10; x++) { AsyncContinuation cont = ex => { Interlocked.Add(ref sum, 1); }; ThreadPool.QueueUserWorkItem(o => new AsyncContinuation(new SingleCallContinuation(finalContinuation).Delegate).Invoke(null)); } //var cont = AsyncHelpers.PreventMultipleCalls(finalContinuation); //cont.Invoke(null); finalContinuationInvoked.WaitOne(); } [Fact] public void PrecededByTest1() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(null, originalContinuation, doSomethingElse); cont(null); // make sure doSomethingElse was invoked first // then original continuation Assert.Equal(7, invokedCount2Sequence); Assert.Equal(8, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(1, invokedCount2); } [Fact] public void PrecededByTest2() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(null, originalContinuation, doSomethingElse); var sampleException = new InvalidOperationException("Some message."); cont(sampleException); // make sure doSomethingElse was not invoked Assert.Equal(0, invokedCount2Sequence); Assert.Equal(7, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(0, invokedCount2); } } }