context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input.Events; using osu.Game.Graphics.Containers; using osu.Game.Scoring; using osuTK; using osuTK.Input; namespace osu.Game.Screens.Ranking { public class ScorePanelList : CompositeDrawable { /// <summary> /// Normal spacing between all panels. /// </summary> private const float panel_spacing = 5; /// <summary> /// Spacing around both sides of the expanded panel. This is added on top of <see cref="panel_spacing"/>. /// </summary> private const float expanded_panel_spacing = 15; /// <summary> /// Minimum distance from either end point of the list that the list can be considered scrolled to the end point. /// </summary> private const float scroll_endpoint_distance = 100; /// <summary> /// Whether this <see cref="ScorePanelList"/> can be scrolled and is currently scrolled to the start. /// </summary> public bool IsScrolledToStart => flow.Count > 0 && scroll.ScrollableExtent > 0 && scroll.Current <= scroll_endpoint_distance; /// <summary> /// Whether this <see cref="ScorePanelList"/> can be scrolled and is currently scrolled to the end. /// </summary> public bool IsScrolledToEnd => flow.Count > 0 && scroll.ScrollableExtent > 0 && scroll.IsScrolledToEnd(scroll_endpoint_distance); /// <summary> /// The current scroll position. /// </summary> public double Current => scroll.Current; /// <summary> /// The scrollable extent. /// </summary> public double ScrollableExtent => scroll.ScrollableExtent; /// <summary> /// An action to be invoked if a <see cref="ScorePanel"/> is clicked while in an expanded state. /// </summary> public Action PostExpandAction; public readonly Bindable<ScoreInfo> SelectedScore = new Bindable<ScoreInfo>(); private readonly Flow flow; private readonly Scroll scroll; private ScorePanel expandedPanel; /// <summary> /// Creates a new <see cref="ScorePanelList"/>. /// </summary> public ScorePanelList() { RelativeSizeAxes = Axes.Both; InternalChild = scroll = new Scroll { RelativeSizeAxes = Axes.Both, HandleScroll = () => expandedPanel?.IsHovered != true, // handle horizontal scroll only when not hovering the expanded panel. Child = flow = new Flow { Anchor = Anchor.Centre, Origin = Anchor.Centre, Direction = FillDirection.Horizontal, Spacing = new Vector2(panel_spacing, 0), AutoSizeAxes = Axes.Both, } }; } protected override void LoadComplete() { base.LoadComplete(); SelectedScore.BindValueChanged(selectedScoreChanged, true); } /// <summary> /// Adds a <see cref="ScoreInfo"/> to this list. /// </summary> /// <param name="score">The <see cref="ScoreInfo"/> to add.</param> /// <param name="isNewLocalScore">Whether this is a score that has just been achieved locally. Controls whether flair is added to the display or not.</param> public ScorePanel AddScore(ScoreInfo score, bool isNewLocalScore = false) { var panel = new ScorePanel(score, isNewLocalScore) { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, PostExpandAction = () => PostExpandAction?.Invoke() }.With(p => { p.StateChanged += s => { if (s == PanelState.Expanded) SelectedScore.Value = p.Score; }; }); flow.Add(panel.CreateTrackingContainer().With(d => { d.Anchor = Anchor.Centre; d.Origin = Anchor.Centre; })); if (IsLoaded) { if (SelectedScore.Value == score) { SelectedScore.TriggerChange(); } else { // We want the scroll position to remain relative to the expanded panel. When a new panel is added after the expanded panel, nothing needs to be done. // But when a panel is added before the expanded panel, we need to offset the scroll position by the width of the new panel. if (expandedPanel != null && flow.GetPanelIndex(score) < flow.GetPanelIndex(expandedPanel.Score)) { // A somewhat hacky property is used here because we need to: // 1) Scroll after the scroll container's visible range is updated. // 2) Scroll before the scroll container's scroll position is updated. // Without this, we would have a 1-frame positioning error which looks very jarring. scroll.InstantScrollTarget = (scroll.InstantScrollTarget ?? scroll.Target) + ScorePanel.CONTRACTED_WIDTH + panel_spacing; } } } return panel; } /// <summary> /// Brings a <see cref="ScoreInfo"/> to the centre of the screen and expands it. /// </summary> /// <param name="score">The <see cref="ScoreInfo"/> to present.</param> private void selectedScoreChanged(ValueChangedEvent<ScoreInfo> score) { // avoid contracting panels unnecessarily when TriggerChange is fired manually. if (score.OldValue != score.NewValue) { // Contract the old panel. foreach (var t in flow.Where(t => t.Panel.Score == score.OldValue)) { t.Panel.State = PanelState.Contracted; t.Margin = new MarginPadding(); } } // Find the panel corresponding to the new score. var expandedTrackingComponent = flow.SingleOrDefault(t => t.Panel.Score == score.NewValue); expandedPanel = expandedTrackingComponent?.Panel; if (expandedPanel == null) return; Debug.Assert(expandedTrackingComponent != null); // Expand the new panel. expandedTrackingComponent.Margin = new MarginPadding { Horizontal = expanded_panel_spacing }; expandedPanel.State = PanelState.Expanded; // requires schedule after children to ensure the flow (and thus ScrollContainer's ScrollableExtent) has been updated. ScheduleAfterChildren(() => { // Scroll to the new panel. This is done manually since we need: // 1) To scroll after the scroll container's visible range is updated. // 2) To account for the centre anchor/origins of panels. // In the end, it's easier to compute the scroll position manually. float scrollOffset = flow.GetPanelIndex(expandedPanel.Score) * (ScorePanel.CONTRACTED_WIDTH + panel_spacing); scroll.ScrollTo(scrollOffset); }); } protected override void Update() { base.Update(); float offset = DrawWidth / 2f; // Add padding to both sides such that the centre of an expanded panel on either side is in the middle of the screen. if (SelectedScore.Value != null) { // The expanded panel has extra padding applied to it, so it needs to be included into the offset. offset -= ScorePanel.EXPANDED_WIDTH / 2f + expanded_panel_spacing; } else offset -= ScorePanel.CONTRACTED_WIDTH / 2f; flow.Padding = new MarginPadding { Horizontal = offset }; } private bool handleInput = true; /// <summary> /// Whether this <see cref="ScorePanelList"/> or any of the <see cref="ScorePanel"/>s contained should handle scroll or click input. /// Setting to <c>false</c> will also hide the scrollbar. /// </summary> public bool HandleInput { get => handleInput; set { handleInput = value; scroll.ScrollbarVisible = value; } } public override bool PropagatePositionalInputSubTree => HandleInput && base.PropagatePositionalInputSubTree; public override bool PropagateNonPositionalInputSubTree => HandleInput && base.PropagateNonPositionalInputSubTree; /// <summary> /// Enumerates all <see cref="ScorePanel"/>s contained in this <see cref="ScorePanelList"/>. /// </summary> public IEnumerable<ScorePanel> GetScorePanels() => flow.Select(t => t.Panel); /// <summary> /// Finds the <see cref="ScorePanel"/> corresponding to a <see cref="ScoreInfo"/>. /// </summary> /// <param name="score">The <see cref="ScoreInfo"/> to find the corresponding <see cref="ScorePanel"/> for.</param> /// <returns>The <see cref="ScorePanel"/>.</returns> public ScorePanel GetPanelForScore(ScoreInfo score) => flow.Single(t => t.Panel.Score == score).Panel; /// <summary> /// Detaches a <see cref="ScorePanel"/> from its <see cref="ScorePanelTrackingContainer"/>, allowing the panel to be moved elsewhere in the hierarchy. /// </summary> /// <param name="panel">The <see cref="ScorePanel"/> to detach.</param> /// <exception cref="InvalidOperationException">If <paramref name="panel"/> is not a part of this <see cref="ScorePanelList"/>.</exception> public void Detach(ScorePanel panel) { var container = flow.SingleOrDefault(t => t.Panel == panel); if (container == null) throw new InvalidOperationException("Panel is not contained by the score panel list."); container.Detach(); } /// <summary> /// Attaches a <see cref="ScorePanel"/> to its <see cref="ScorePanelTrackingContainer"/> in this <see cref="ScorePanelList"/>. /// </summary> /// <param name="panel">The <see cref="ScorePanel"/> to attach.</param> /// <exception cref="InvalidOperationException">If <paramref name="panel"/> is not a part of this <see cref="ScorePanelList"/>.</exception> public void Attach(ScorePanel panel) { var container = flow.SingleOrDefault(t => t.Panel == panel); if (container == null) throw new InvalidOperationException("Panel is not contained by the score panel list."); container.Attach(); } protected override bool OnKeyDown(KeyDownEvent e) { var expandedPanelIndex = flow.GetPanelIndex(expandedPanel.Score); switch (e.Key) { case Key.Left: if (expandedPanelIndex > 0) SelectedScore.Value = flow.Children[expandedPanelIndex - 1].Panel.Score; return true; case Key.Right: if (expandedPanelIndex < flow.Count - 1) SelectedScore.Value = flow.Children[expandedPanelIndex + 1].Panel.Score; return true; } return base.OnKeyDown(e); } private class Flow : FillFlowContainer<ScorePanelTrackingContainer> { public override IEnumerable<Drawable> FlowingChildren => applySorting(AliveInternalChildren); public int GetPanelIndex(ScoreInfo score) => applySorting(Children).TakeWhile(s => s.Panel.Score != score).Count(); private IEnumerable<ScorePanelTrackingContainer> applySorting(IEnumerable<Drawable> drawables) => drawables.OfType<ScorePanelTrackingContainer>() .OrderByDescending(s => s.Panel.Score.TotalScore) .ThenBy(s => s.Panel.Score.OnlineScoreID); protected override int Compare(Drawable x, Drawable y) { var tX = (ScorePanelTrackingContainer)x; var tY = (ScorePanelTrackingContainer)y; int result = tY.Panel.Score.TotalScore.CompareTo(tX.Panel.Score.TotalScore); if (result != 0) return result; if (tX.Panel.Score.OnlineScoreID == null || tY.Panel.Score.OnlineScoreID == null) return base.Compare(x, y); return tX.Panel.Score.OnlineScoreID.Value.CompareTo(tY.Panel.Score.OnlineScoreID.Value); } } private class Scroll : OsuScrollContainer { public new float Target => base.Target; public Scroll() : base(Direction.Horizontal) { } /// <summary> /// The target that will be scrolled to instantaneously next frame. /// </summary> public float? InstantScrollTarget; /// <summary> /// Whether this container should handle scroll trigger events. /// </summary> public Func<bool> HandleScroll; protected override void UpdateAfterChildren() { if (InstantScrollTarget != null) { ScrollTo(InstantScrollTarget.Value, false); InstantScrollTarget = null; } base.UpdateAfterChildren(); } public override bool HandlePositionalInput => HandleScroll(); public override bool HandleNonPositionalInput => HandleScroll(); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type UserPeopleCollectionRequest. /// </summary> public partial class UserPeopleCollectionRequest : BaseRequest, IUserPeopleCollectionRequest { /// <summary> /// Constructs a new UserPeopleCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public UserPeopleCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Person to the collection via POST. /// </summary> /// <param name="person">The Person to add.</param> /// <returns>The created Person.</returns> public System.Threading.Tasks.Task<Person> AddAsync(Person person) { return this.AddAsync(person, CancellationToken.None); } /// <summary> /// Adds the specified Person to the collection via POST. /// </summary> /// <param name="person">The Person to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Person.</returns> public System.Threading.Tasks.Task<Person> AddAsync(Person person, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Person>(person, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IUserPeopleCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IUserPeopleCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<UserPeopleCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Expand(Expression<Func<Person, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Select(Expression<Func<Person, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IUserPeopleCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- function EWCreatorWindow::init( %this ) { // Just so we can recall this method for testing changes // without restarting. if ( isObject( %this.array ) ) %this.array.delete(); %this.array = new ArrayObject(); %this.array.caseSensitive = true; %this.setListView( true ); %this.beginGroup( "Environment" ); // Removed Prefab as there doesn't really seem to be a point in creating a blank one //%this.registerMissionObject( "Prefab", "Prefab" ); %this.registerMissionObject( "SkyBox", "Sky Box" ); %this.registerMissionObject( "CloudLayer", "Cloud Layer" ); %this.registerMissionObject( "BasicClouds", "Basic Clouds" ); %this.registerMissionObject( "ScatterSky", "Scatter Sky" ); %this.registerMissionObject( "Sun", "Basic Sun" ); %this.registerMissionObject( "Lightning" ); %this.registerMissionObject( "WaterBlock", "Water Block" ); %this.registerMissionObject( "SFXEmitter", "Sound Emitter" ); %this.registerMissionObject( "Precipitation" ); %this.registerMissionObject( "ParticleEmitterNode", "Particle Emitter" ); // Legacy features. Users should use Ground Cover and the Forest Editor. //%this.registerMissionObject( "fxShapeReplicator", "Shape Replicator" ); //%this.registerMissionObject( "fxFoliageReplicator", "Foliage Replicator" ); %this.registerMissionObject( "PointLight", "Point Light" ); %this.registerMissionObject( "SpotLight", "Spot Light" ); %this.registerMissionObject( "GroundCover", "Ground Cover" ); %this.registerMissionObject( "TerrainBlock", "Terrain Block" ); %this.registerMissionObject( "GroundPlane", "Ground Plane" ); %this.registerMissionObject( "WaterPlane", "Water Plane" ); %this.registerMissionObject( "PxCloth", "Cloth" ); %this.registerMissionObject( "ForestWindEmitter", "Wind Emitter" ); %this.registerMissionObject( "DustEmitter", "Dust Emitter" ); %this.registerMissionObject( "DustSimulation", "Dust Simulation" ); %this.registerMissionObject( "DustEffecter", "Dust Effecter" ); %this.endGroup(); %this.beginGroup( "Level" ); %this.registerMissionObject( "MissionArea", "Mission Area" ); %this.registerMissionObject( "Path" ); %this.registerMissionObject( "Marker", "Path Node" ); %this.registerMissionObject( "Trigger" ); %this.registerMissionObject( "PhysicalZone", "Physical Zone" ); %this.registerMissionObject( "Camera" ); %this.registerMissionObject( "LevelInfo", "Level Info" ); %this.registerMissionObject( "TimeOfDay", "Time of Day" ); %this.registerMissionObject( "Zone", "Zone" ); %this.registerMissionObject( "Portal", "Zone Portal" ); %this.registerMissionObject( "SpawnSphere", "Player Spawn Sphere", "PlayerDropPoint" ); %this.registerMissionObject( "SpawnSphere", "Observer Spawn Sphere", "ObserverDropPoint" ); %this.registerMissionObject( "SFXSpace", "Sound Space" ); %this.registerMissionObject( "OcclusionVolume", "Occlusion Volume" ); %this.endGroup(); %this.beginGroup( "System" ); %this.registerMissionObject( "SimGroup" ); %this.endGroup(); %this.beginGroup( "ExampleObjects" ); %this.registerMissionObject( "RenderObjectExample" ); %this.registerMissionObject( "RenderMeshExample" ); %this.registerMissionObject( "RenderShapeExample" ); %this.endGroup(); } function EWCreatorWindow::onWake( %this ) { CreatorTabBook.selectPage( 0 ); CreatorTabBook.onTabSelected( "Scripted" ); } function EWCreatorWindow::beginGroup( %this, %group ) { %this.currentGroup = %group; } function EWCreatorWindow::endGroup( %this, %group ) { %this.currentGroup = ""; } function EWCreatorWindow::getCreateObjectPosition() { %focusPoint = LocalClientConnection.getControlObject().getLookAtPoint(); if( %focusPoint $= "" ) return "0 0 0"; else return getWord( %focusPoint, 1 ) SPC getWord( %focusPoint, 2 ) SPC getWord( %focusPoint, 3 ); } function EWCreatorWindow::registerMissionObject( %this, %class, %name, %buildfunc, %group ) { if( !isClass(%class) ) return; if ( %name $= "" ) %name = %class; if ( %this.currentGroup !$= "" && %group $= "" ) %group = %this.currentGroup; if ( %class $= "" || %group $= "" ) { warn( "EWCreatorWindow::registerMissionObject, invalid parameters!" ); return; } %args = new ScriptObject(); %args.val[0] = %class; %args.val[1] = %name; %args.val[2] = %buildfunc; %this.array.push_back( %group, %args ); } function EWCreatorWindow::getNewObjectGroup( %this ) { return %this.objectGroup; } function EWCreatorWindow::setNewObjectGroup( %this, %group ) { if( %this.objectGroup ) { %oldItemId = EditorTree.findItemByObjectId( %this.objectGroup ); if( %oldItemId > 0 ) EditorTree.markItem( %oldItemId, false ); } %group = %group.getID(); %this.objectGroup = %group; %itemId = EditorTree.findItemByObjectId( %group ); EditorTree.markItem( %itemId ); } function EWCreatorWindow::createInterior( %this, %file ) { if ( !$missionRunning ) return; if(isFunction("getObjectLimit") && MissionGroup.getFullCount() >= getObjectLimit()) { MessageBoxOKBuy( "Object Limit Reached", "You have exceeded the object limit of " @ getObjectLimit() @ " for this demo. You can remove objects if you would like to add more.", "", "Canvas.showPurchaseScreen(\"objectlimit\");" ); return; } if( !isObject(%this.objectGroup) ) %this.setNewObjectGroup( MissionGroup ); %objId = new InteriorInstance() { position = %this.getCreateObjectPosition(); rotation = "0 0 0"; interiorFile = %file; parentGroup = %this.objectGroup; }; %this.onObjectCreated( %objId ); } function EWCreatorWindow::createStatic( %this, %file ) { if ( !$missionRunning ) return; if(isFunction("getObjectLimit") && MissionGroup.getFullCount() >= getObjectLimit()) { MessageBoxOKBuy( "Object Limit Reached", "You have exceeded the object limit of " @ getObjectLimit() @ " for this demo. You can remove objects if you would like to add more.", "", "Canvas.showPurchaseScreen(\"objectlimit\");" ); return; } if( !isObject(%this.objectGroup) ) %this.setNewObjectGroup( MissionGroup ); %objId = new TSStatic() { shapeName = %file; position = %this.getCreateObjectPosition(); parentGroup = %this.objectGroup; }; %this.onObjectCreated( %objId ); } function EWCreatorWindow::createPrefab( %this, %file ) { if ( !$missionRunning ) return; if(isFunction("getObjectLimit") && MissionGroup.getFullCount() >= getObjectLimit()) { MessageBoxOKBuy( "Object Limit Reached", "You have exceeded the object limit of " @ getObjectLimit() @ " for this demo. You can remove objects if you would like to add more.", "", "Canvas.showPurchaseScreen(\"objectlimit\");" ); return; } if( !isObject(%this.objectGroup) ) %this.setNewObjectGroup( MissionGroup ); %objId = new Prefab() { filename = %file; position = %this.getCreateObjectPosition(); parentGroup = %this.objectGroup; }; %this.onObjectCreated( %objId ); } function EWCreatorWindow::createObject( %this, %cmd ) { if ( !$missionRunning ) return; if(isFunction("getObjectLimit") && MissionGroup.getFullCount() >= getObjectLimit()) { MessageBoxOKBuy( "Object Limit Reached", "You have exceeded the object limit of " @ getObjectLimit() @ " for this demo. You can remove objects if you would like to add more.", "", "Canvas.showPurchaseScreen(\"objectlimit\");" ); return; } if( !isObject(%this.objectGroup) ) %this.setNewObjectGroup( MissionGroup ); pushInstantGroup(); %objId = eval(%cmd); popInstantGroup(); if( isObject( %objId ) ) %this.onFinishCreateObject( %objId ); return %objId; } function EWCreatorWindow::onFinishCreateObject( %this, %objId ) { %this.objectGroup.add( %objId ); if( %objId.isMemberOfClass( "SceneObject" ) ) { %objId.position = %this.getCreateObjectPosition(); //flush new position %objId.setTransform( %objId.getTransform() ); } %this.onObjectCreated( %objId ); } function EWCreatorWindow::onObjectCreated( %this, %objId ) { // Can we submit an undo action? if ( isObject( %objId ) ) MECreateUndoAction::submit( %objId ); EditorTree.clearSelection(); EWorldEditor.clearSelection(); EWorldEditor.selectObject( %objId ); // When we drop the selection don't store undo // state for it... the creation deals with it. EWorldEditor.dropSelection( true ); } function CreatorTabBook::onTabSelected( %this, %text, %idx ) { if ( %this.isAwake() ) { EWCreatorWindow.tab = %text; EWCreatorWindow.navigate( "" ); } } function EWCreatorWindow::navigate( %this, %address ) { CreatorIconArray.frozen = true; CreatorIconArray.clear(); CreatorPopupMenu.clear(); if ( %this.tab $= "Scripted" ) { %category = getWord( %address, 1 ); %dataGroup = "DataBlockGroup"; for ( %i = 0; %i < %dataGroup.getCount(); %i++ ) { %obj = %dataGroup.getObject(%i); // echo ("Obj: " @ %obj.getName() @ " - " @ %obj.category ); if ( %obj.category $= "" && %obj.category == 0 ) continue; // Add category to popup menu if not there already if ( CreatorPopupMenu.findText( %obj.category ) == -1 ) CreatorPopupMenu.add( %obj.category ); if ( %address $= "" ) { %ctrl = %this.findIconCtrl( %obj.category ); if ( %ctrl == -1 ) { %this.addFolderIcon( %obj.category ); } } else if ( %address $= %obj.category ) { %ctrl = %this.findIconCtrl( %obj.getName() ); if ( %ctrl == -1 ) %this.addShapeIcon( %obj ); } } } if ( %this.tab $= "Meshes" ) { %fullPath = findFirstFileMultiExpr( "*.dts" TAB "*.dae" TAB "*.kmz" TAB "*.dif" ); while ( %fullPath !$= "" ) { if (strstr(%fullPath, "cached.dts") != -1) { %fullPath = findNextFileMultiExpr( "*.dts" TAB "*.dae" TAB "*.kmz" TAB "*.dif" ); continue; } %fullPath = makeRelativePath( %fullPath, getMainDotCSDir() ); %splitPath = strreplace( %fullPath, "/", " " ); if( getWord(%splitPath, 0) $= "tools" ) { %fullPath = findNextFileMultiExpr( "*.dts" TAB "*.dae" TAB "*.kmz" TAB "*.dif" ); continue; } %dirCount = getWordCount( %splitPath ) - 1; %pathFolders = getWords( %splitPath, 0, %dirCount - 1 ); // Add this file's path (parent folders) to the // popup menu if it isn't there yet. %temp = strreplace( %pathFolders, " ", "/" ); %r = CreatorPopupMenu.findText( %temp ); if ( %r == -1 ) { CreatorPopupMenu.add( %temp ); } // Is this file in the current folder? if ( stricmp( %pathFolders, %address ) == 0 ) { if ( fileExt( %fullPath ) $= ".dif" ) %this.addInteriorIcon( %fullPath ); else %this.addStaticIcon( %fullPath ); } // Then is this file in a subfolder we need to add // a folder icon for? else { %wordIdx = 0; %add = false; if ( %address $= "" ) { %add = true; %wordIdx = 0; } else { for ( ; %wordIdx < %dirCount; %wordIdx++ ) { %temp = getWords( %splitPath, 0, %wordIdx ); if ( stricmp( %temp, %address ) == 0 ) { %add = true; %wordIdx++; break; } } } if ( %add == true ) { %folder = getWord( %splitPath, %wordIdx ); %ctrl = %this.findIconCtrl( %folder ); if ( %ctrl == -1 ) %this.addFolderIcon( %folder ); } } %fullPath = findNextFileMultiExpr( "*.dts" TAB "*.dae" TAB "*.kmz" TAB "*.dif" ); } } if ( %this.tab $= "Level" ) { // Add groups to popup menu %array = %this.array; %array.sortk(); %count = %array.count(); if ( %count > 0 ) { %lastGroup = ""; for ( %i = 0; %i < %count; %i++ ) { %group = %array.getKey( %i ); if ( %group !$= %lastGroup ) { CreatorPopupMenu.add( %group ); if ( %address $= "" ) %this.addFolderIcon( %group ); } if ( %address $= %group ) { %args = %array.getValue( %i ); %class = %args.val[0]; %name = %args.val[1]; %func = %args.val[2]; %this.addMissionObjectIcon( %class, %name, %func ); } %lastGroup = %group; } } } if ( %this.tab $= "Prefabs" ) { %expr = "*.prefab"; %fullPath = findFirstFile( %expr ); while ( %fullPath !$= "" ) { %fullPath = makeRelativePath( %fullPath, getMainDotCSDir() ); %splitPath = strreplace( %fullPath, "/", " " ); if( getWord(%splitPath, 0) $= "tools" ) { %fullPath = findNextFile( %expr ); continue; } %dirCount = getWordCount( %splitPath ) - 1; %pathFolders = getWords( %splitPath, 0, %dirCount - 1 ); // Add this file's path (parent folders) to the // popup menu if it isn't there yet. %temp = strreplace( %pathFolders, " ", "/" ); %r = CreatorPopupMenu.findText( %temp ); if ( %r == -1 ) { CreatorPopupMenu.add( %temp ); } // Is this file in the current folder? if ( stricmp( %pathFolders, %address ) == 0 ) { %this.addPrefabIcon( %fullPath ); } // Then is this file in a subfolder we need to add // a folder icon for? else { %wordIdx = 0; %add = false; if ( %address $= "" ) { %add = true; %wordIdx = 0; } else { for ( ; %wordIdx < %dirCount; %wordIdx++ ) { %temp = getWords( %splitPath, 0, %wordIdx ); if ( stricmp( %temp, %address ) == 0 ) { %add = true; %wordIdx++; break; } } } if ( %add == true ) { %folder = getWord( %splitPath, %wordIdx ); %ctrl = %this.findIconCtrl( %folder ); if ( %ctrl == -1 ) %this.addFolderIcon( %folder ); } } %fullPath = findNextFile( %expr ); } } CreatorIconArray.sort( "alphaIconCompare" ); for ( %i = 0; %i < CreatorIconArray.getCount(); %i++ ) { CreatorIconArray.getObject(%i).autoSize = false; } CreatorIconArray.frozen = false; CreatorIconArray.refresh(); // Recalculate the array for the parent guiScrollCtrl CreatorIconArray.getParent().computeSizes(); %this.address = %address; CreatorPopupMenu.sort(); %str = strreplace( %address, " ", "/" ); %r = CreatorPopupMenu.findText( %str ); if ( %r != -1 ) CreatorPopupMenu.setSelected( %r, false ); else CreatorPopupMenu.setText( %str ); CreatorPopupMenu.tooltip = %str; } function EWCreatorWindow::navigateDown( %this, %folder ) { if ( %this.address $= "" ) %address = %folder; else %address = %this.address SPC %folder; // Because this is called from an IconButton::onClick command // we have to wait a tick before actually calling navigate, else // we would delete the button out from under itself. %this.schedule( 1, "navigate", %address ); } function EWCreatorWindow::navigateUp( %this ) { %count = getWordCount( %this.address ); if ( %count == 0 ) return; if ( %count == 1 ) %address = ""; else %address = getWords( %this.address, 0, %count - 2 ); %this.navigate( %address ); } function EWCreatorWindow::setListView( %this, %noupdate ) { //CreatorIconArray.clear(); //CreatorIconArray.setVisible( false ); CreatorIconArray.setVisible( true ); %this.contentCtrl = CreatorIconArray; %this.isList = true; if ( %noupdate == true ) %this.navigate( %this.address ); } //function EWCreatorWindow::setIconView( %this ) //{ //echo( "setIconView" ); // //CreatorIconStack.clear(); //CreatorIconStack.setVisible( false ); // //CreatorIconArray.setVisible( true ); //%this.contentCtrl = CreatorIconArray; //%this.isList = false; // //%this.navigate( %this.address ); //} function EWCreatorWindow::findIconCtrl( %this, %name ) { for ( %i = 0; %i < %this.contentCtrl.getCount(); %i++ ) { %ctrl = %this.contentCtrl.getObject( %i ); if ( %ctrl.text $= %name ) return %ctrl; } return -1; } function EWCreatorWindow::createIcon( %this ) { %ctrl = new GuiIconButtonCtrl() { profile = "GuiCreatorIconButtonProfile"; buttonType = "radioButton"; groupNum = "-1"; }; if ( %this.isList ) { %ctrl.iconLocation = "Left"; %ctrl.textLocation = "Right"; %ctrl.extent = "348 19"; %ctrl.textMargin = 8; %ctrl.buttonMargin = "2 2"; %ctrl.autoSize = true; } else { %ctrl.iconLocation = "Center"; %ctrl.textLocation = "Bottom"; %ctrl.extent = "40 40"; } return %ctrl; } function EWCreatorWindow::addFolderIcon( %this, %text ) { %ctrl = %this.createIcon(); %ctrl.altCommand = "EWCreatorWindow.navigateDown(\"" @ %text @ "\");"; %ctrl.iconBitmap = "core/art/gui/images/folder.png"; %ctrl.text = %text; %ctrl.tooltip = %text; %ctrl.class = "CreatorFolderIconBtn"; %ctrl.buttonType = "radioButton"; %ctrl.groupNum = "-1"; %this.contentCtrl.addGuiControl( %ctrl ); } function EWCreatorWindow::addMissionObjectIcon( %this, %class, %name, %buildfunc ) { %ctrl = %this.createIcon(); // If we don't find a specific function for building an // object then fall back to the stock one %method = "build" @ %buildfunc; if( !ObjectBuilderGui.isMethod( %method ) ) %method = "build" @ %class; if( !ObjectBuilderGui.isMethod( %method ) ) %cmd = "return new " @ %class @ "();"; else %cmd = "ObjectBuilderGui." @ %method @ "();"; %ctrl.altCommand = "ObjectBuilderGui.newObjectCallback = \"EWCreatorWindow.onFinishCreateObject\"; EWCreatorWindow.createObject( \"" @ %cmd @ "\" );"; %ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class ); %ctrl.text = %name; %ctrl.class = "CreatorMissionObjectIconBtn"; %ctrl.tooltip = %class; %ctrl.buttonType = "radioButton"; %ctrl.groupNum = "-1"; %this.contentCtrl.addGuiControl( %ctrl ); } function EWCreatorWindow::addShapeIcon( %this, %datablock ) { %ctrl = %this.createIcon(); %name = %datablock.getName(); %class = %datablock.getClassName(); %cmd = %class @ "::create(" @ %name @ ");"; %shapePath = ( %datablock.shapeFile !$= "" ) ? %datablock.shapeFile : %datablock.shapeName; %createCmd = "EWCreatorWindow.createObject( \\\"" @ %cmd @ "\\\" );"; %ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %shapePath @ "\", \"" @ %createCmd @ "\" );"; %ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( %class ); %ctrl.text = %name; %ctrl.class = "CreatorShapeIconBtn"; %ctrl.tooltip = %name; %ctrl.buttonType = "radioButton"; %ctrl.groupNum = "-1"; %this.contentCtrl.addGuiControl( %ctrl ); } function EWCreatorWindow::addStaticIcon( %this, %fullPath ) { %ctrl = %this.createIcon(); %ext = fileExt( %fullPath ); %file = fileBase( %fullPath ); %fileLong = %file @ %ext; %tip = %fileLong NL "Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL "Date Created: " @ fileCreatedTime( %fullPath ) NL "Last Modified: " @ fileModifiedTime( %fullPath ); %createCmd = "EWCreatorWindow.createStatic( \\\"" @ %fullPath @ "\\\" );"; %ctrl.altCommand = "ColladaImportDlg.showDialog( \"" @ %fullPath @ "\", \"" @ %createCmd @ "\" );"; %ctrl.iconBitmap = ( ( %ext $= ".dts" ) ? EditorIconRegistry::findIconByClassName( "TSStatic" ) : "tools/gui/images/iconCollada" ); %ctrl.text = %file; %ctrl.class = "CreatorStaticIconBtn"; %ctrl.tooltip = %tip; %ctrl.buttonType = "radioButton"; %ctrl.groupNum = "-1"; %this.contentCtrl.addGuiControl( %ctrl ); } function EWCreatorWindow::addInteriorIcon( %this, %fullPath ) { %ctrl = EWCreatorWindow.createIcon(); %file = fileBase( %fullPath ); %fileLong = %file @ fileExt( %fullPath ); %tip = %fileLong NL "Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL "Date Created: " @ fileCreatedTime( %fullPath ) NL "Last Modified: " @ fileModifiedTime( %fullPath ); %ctrl.altCommand = "EWCreatorWindow.createInterior( \"" @ %fullPath @ "\" );"; %ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "InteriorInstance" ); %ctrl.text = %file; %ctrl.class = "CreatorInteriorIconBtn"; %ctrl.tooltip = %tip; %ctrl.buttonType = "radioButton"; %ctrl.groupNum = "-1"; %this.contentCtrl.addGuiControl( %ctrl ); } function EWCreatorWindow::addPrefabIcon( %this, %fullPath ) { %ctrl = %this.createIcon(); %ext = fileExt( %fullPath ); %file = fileBase( %fullPath ); %fileLong = %file @ %ext; %tip = %fileLong NL "Size: " @ fileSize( %fullPath ) / 1000.0 SPC "KB" NL "Date Created: " @ fileCreatedTime( %fullPath ) NL "Last Modified: " @ fileModifiedTime( %fullPath ); %ctrl.altCommand = "EWCreatorWindow.createPrefab( \"" @ %fullPath @ "\" );"; %ctrl.iconBitmap = EditorIconRegistry::findIconByClassName( "Prefab" ); %ctrl.text = %file; %ctrl.class = "CreatorPrefabIconBtn"; %ctrl.tooltip = %tip; %ctrl.buttonType = "radioButton"; %ctrl.groupNum = "-1"; %this.contentCtrl.addGuiControl( %ctrl ); } function CreatorPopupMenu::onSelect( %this, %id, %text ) { %split = strreplace( %text, "/", " " ); EWCreatorWindow.navigate( %split ); } function alphaIconCompare( %a, %b ) { if ( %a.class $= "CreatorFolderIconBtn" ) if ( %b.class !$= "CreatorFolderIconBtn" ) return -1; if ( %b.class $= "CreatorFolderIconBtn" ) if ( %a.class !$= "CreatorFolderIconBtn" ) return 1; %result = stricmp( %a.text, %b.text ); return %result; } // Generic create object helper for use from the console. function genericCreateObject( %class ) { if ( !isClass( %class ) ) { warn( "createObject( " @ %class @ " ) - Was not a valid class." ); return; } %cmd = "return new " @ %class @ "();"; %obj = EWCreatorWindow.createObject( %cmd ); // In case the caller wants it. return %obj; }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.IO { /// <summary> /// Wrapper to help with path normalization. /// </summary> unsafe internal class PathHelper { // Can't be over 8.3 and be a short name private const int MaxShortName = 12; private const char LastAnsi = (char)255; private const char Delete = (char)127; // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. // string.WhitespaceChars will trim more aggressively than what the underlying FS does (for ex, NTFS, FAT). private static readonly char[] s_trimEndChars = { (char)0x9, // Horizontal tab (char)0xA, // Line feed (char)0xB, // Vertical tab (char)0xC, // Form feed (char)0xD, // Carriage return (char)0x20, // Space (char)0x85, // Next line (char)0xA0 // Non breaking space }; [ThreadStatic] private static StringBuffer t_fullPathBuffer; /// <summary> /// Normalize the given path. /// </summary> /// <remarks> /// Normalizes via Win32 GetFullPathName(). It will also trim all "typical" whitespace at the end of the path (see s_trimEndChars). Will also trim initial /// spaces if the path is determined to be rooted. /// /// Note that invalid characters will be checked after the path is normalized, which could remove bad characters. (C:\|\..\a.txt -- C:\a.txt) /// </remarks> /// <param name="path">Path to normalize</param> /// <param name="checkInvalidCharacters">True to check for invalid characters</param> /// <param name="expandShortPaths">Attempt to expand short paths if true</param> /// <exception cref="ArgumentException">Thrown if the path is an illegal UNC (does not contain a full server/share) or contains illegal characters.</exception> /// <exception cref="PathTooLongException">Thrown if the path or a path segment exceeds the filesystem limits.</exception> /// <exception cref="FileNotFoundException">Thrown if Windows returns ERROR_FILE_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="DirectoryNotFoundException">Thrown if Windows returns ERROR_PATH_NOT_FOUND. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="UnauthorizedAccessException">Thrown if Windows returns ERROR_ACCESS_DENIED. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <exception cref="IOException">Thrown if Windows returns an error that doesn't map to the above. (See Win32Marshal.GetExceptionForWin32Error)</exception> /// <returns>Normalized path</returns> internal static string Normalize(string path, bool checkInvalidCharacters, bool expandShortPaths) { // Get the full path StringBuffer fullPath = t_fullPathBuffer ?? (t_fullPathBuffer = new StringBuffer(PathInternal.MaxShortPath)); try { GetFullPathName(path, fullPath); // Trim whitespace off the end of the string. Win32 normalization trims only U+0020. fullPath.TrimEnd(s_trimEndChars); if (fullPath.Length >= PathInternal.MaxLongPath) { // Fullpath is genuinely too long throw new PathTooLongException(SR.IO_PathTooLong); } // Checking path validity used to happen before getting the full path name. To avoid additional input allocation // (to trim trailing whitespace) we now do it after the Win32 call. This will allow legitimate paths through that // used to get kicked back (notably segments with invalid characters might get removed via ".."). // // There is no way that GetLongPath can invalidate the path so we'll do this (cheaper) check before we attempt to // expand short file names. // Scan the path for: // // - Illegal path characters. // - Invalid UNC paths like \\, \\server, \\server\. // - Segments that are too long (over MaxComponentLength) // As the path could be > 30K, we'll combine the validity scan. None of these checks are performed by the Win32 // GetFullPathName() API. bool possibleShortPath = false; bool foundTilde = false; // We can get UNCs as device paths through this code (e.g. \\.\UNC\), we won't validate them as there isn't // an easy way to normalize without extensive cost (we'd have to hunt down the canonical name for any device // path that contains UNC or to see if the path was doing something like \\.\GLOBALROOT\Device\Mup\, // \\.\GLOBAL\UNC\, \\.\GLOBALROOT\GLOBAL??\UNC\, etc. bool specialPath = fullPath.Length > 1 && fullPath[0] == '\\' && fullPath[1] == '\\'; bool isDevice = PathInternal.IsDevice(fullPath); bool possibleBadUnc = specialPath && !isDevice; uint index = specialPath ? 2u : 0; uint lastSeparator = specialPath ? 1u : 0; uint segmentLength; char* start = fullPath.CharPointer; char current; while (index < fullPath.Length) { current = start[index]; // Try to skip deeper analysis. '?' and higher are valid/ignorable except for '\', '|', and '~' if (current < '?' || current == '\\' || current == '|' || current == '~') { switch (current) { case '|': case '>': case '<': case '\"': if (checkInvalidCharacters) throw new ArgumentException(SR.Argument_InvalidPathChars); foundTilde = false; break; case '~': foundTilde = true; break; case '\\': segmentLength = index - lastSeparator - 1; if (segmentLength > (uint)PathInternal.MaxComponentLength) throw new PathTooLongException(SR.IO_PathTooLong + fullPath.ToString()); lastSeparator = index; if (foundTilde) { if (segmentLength <= MaxShortName) { // Possibly a short path. possibleShortPath = true; } foundTilde = false; } if (possibleBadUnc) { // If we're at the end of the path and this is the first separator, we're missing the share. // Otherwise we're good, so ignore UNC tracking from here. if (index == fullPath.Length - 1) throw new ArgumentException(SR.Arg_PathIllegalUNC); else possibleBadUnc = false; } break; default: if (checkInvalidCharacters && current < ' ') throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); break; } } index++; } if (possibleBadUnc) throw new ArgumentException(SR.Arg_PathIllegalUNC); segmentLength = fullPath.Length - lastSeparator - 1; if (segmentLength > (uint)PathInternal.MaxComponentLength) throw new PathTooLongException(SR.IO_PathTooLong); if (foundTilde && segmentLength <= MaxShortName) possibleShortPath = true; // Check for a short filename path and try and expand it. Technically you don't need to have a tilde for a short name, but // this is how we've always done this. This expansion is costly so we'll continue to let other short paths slide. if (expandShortPaths && possibleShortPath) { return TryExpandShortFileName(fullPath, originalPath: path); } else { if (fullPath.Length == (uint)path.Length && fullPath.StartsWith(path)) { // If we have the exact same string we were passed in, don't bother to allocate another string from the StringBuilder. return path; } else { return fullPath.ToString(); } } } finally { // Clear the buffer fullPath.Free(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsDosUnc(StringBuffer buffer) { return !PathInternal.IsDevice(buffer) && buffer.Length > 1 && buffer[0] == '\\' && buffer[1] == '\\'; } private static void GetFullPathName(string path, StringBuffer fullPath) { // If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as // it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here. Debug.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path)); // Historically we would skip leading spaces *only* if the path started with a drive " C:" or a UNC " \\" int startIndex = PathInternal.PathStartSkip(path); fixed (char* pathStart = path) { uint result = 0; while ((result = Interop.mincore.GetFullPathNameW(pathStart + startIndex, fullPath.CharCapacity, fullPath.GetHandle(), IntPtr.Zero)) > fullPath.CharCapacity) { // Reported size (which does not include the null) is greater than the buffer size. Increase the capacity. fullPath.EnsureCharCapacity(result); } if (result == 0) { // Failure, get the error and throw int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.mincore.Errors.ERROR_BAD_PATHNAME; throw Win32Marshal.GetExceptionForWin32Error(errorCode, path); } fullPath.Length = result; } } private static uint GetInputBuffer(StringBuffer content, bool isDosUnc, out StringBuffer buffer) { uint length = content.Length; length += isDosUnc ? (uint)PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength : PathInternal.DevicePrefixLength; buffer = new StringBuffer(length); if (isDosUnc) { // Put the extended UNC prefix (\\?\UNC\) in front of the path buffer.CopyFrom(bufferIndex: 0, source: PathInternal.UncExtendedPathPrefix); // Copy the source buffer over after the existing UNC prefix content.CopyTo( bufferIndex: PathInternal.UncPrefixLength, destination: buffer, destinationIndex: PathInternal.UncExtendedPrefixLength, count: content.Length - PathInternal.UncPrefixLength); // Return the prefix difference return (uint)PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength; } else { uint prefixSize = (uint)PathInternal.ExtendedPathPrefix.Length; buffer.CopyFrom(bufferIndex: 0, source: PathInternal.ExtendedPathPrefix); content.CopyTo(bufferIndex: 0, destination: buffer, destinationIndex: prefixSize, count: content.Length); return prefixSize; } } private static string TryExpandShortFileName(StringBuffer outputBuffer, string originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. Debug.Assert(!PathInternal.IsPartiallyQualified(outputBuffer), "should have resolved by now"); // We'll have one of a few cases by now (the normalized path will have already: // // 1. Dos path (C:\) // 2. Dos UNC (\\Server\Share) // 3. Dos device path (\\.\C:\, \\?\C:\) // // We want to put the extended syntax on the front if it doesn't already have it, which may mean switching from \\.\. // // Note that we will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is). uint rootLength = PathInternal.GetRootLength(outputBuffer); bool isDevice = PathInternal.IsDevice(outputBuffer); StringBuffer inputBuffer = null; bool isDosUnc = false; uint rootDifference = 0; bool wasDotDevice = false; // Add the extended prefix before expanding to allow growth over MAX_PATH if (isDevice) { // We have one of the following (\\?\ or \\.\) inputBuffer = new StringBuffer(); inputBuffer.Append(outputBuffer); if (outputBuffer[2] == '.') { wasDotDevice = true; inputBuffer[2] = '?'; } } else { isDosUnc = IsDosUnc(outputBuffer); rootDifference = GetInputBuffer(outputBuffer, isDosUnc, out inputBuffer); } rootLength += rootDifference; uint inputLength = inputBuffer.Length; bool success = false; uint foundIndex = inputBuffer.Length - 1; while (!success) { uint result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity); // Replace any temporary null we added if (inputBuffer[foundIndex] == '\0') inputBuffer[foundIndex] = '\\'; if (result == 0) { // Look to see if we couldn't find the file int error = Marshal.GetLastWin32Error(); if (error != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND && error != Interop.mincore.Errors.ERROR_PATH_NOT_FOUND) { // Some other failure, give up break; } // We couldn't find the path at the given index, start looking further back in the string. foundIndex--; for (; foundIndex > rootLength && inputBuffer[foundIndex] != '\\'; foundIndex--) ; if (foundIndex == rootLength) { // Can't trim the path back any further break; } else { // Temporarily set a null in the string to get Windows to look further up the path inputBuffer[foundIndex] = '\0'; } } else if (result > outputBuffer.CharCapacity) { // Not enough space. The result count for this API does not include the null terminator. outputBuffer.EnsureCharCapacity(result); result = Interop.mincore.GetLongPathNameW(inputBuffer.GetHandle(), outputBuffer.GetHandle(), outputBuffer.CharCapacity); } else { // Found the path success = true; outputBuffer.Length = result; if (foundIndex < inputLength - 1) { // It was a partial find, put the non-existent part of the path back outputBuffer.Append(inputBuffer, foundIndex, inputBuffer.Length - foundIndex); } } } // Strip out the prefix and return the string StringBuffer bufferToUse = success ? outputBuffer : inputBuffer; // Switch back from \\?\ to \\.\ if necessary if (wasDotDevice) bufferToUse[2] = '.'; string returnValue = null; int newLength = (int)(bufferToUse.Length - rootDifference); if (isDosUnc) { // Need to go from \\?\UNC\ to \\?\UN\\ bufferToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\'; } // We now need to strip out any added characters at the front of the string if (bufferToUse.SubstringEquals(originalPath, rootDifference, newLength)) { // Use the original path to avoid allocating returnValue = originalPath; } else { returnValue = bufferToUse.Substring(rootDifference, newLength); } inputBuffer.Dispose(); return returnValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography.Pal; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate2Collection : X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(X509Certificate2 certificate) { Add(certificate); } public X509Certificate2Collection(X509Certificate2[] certificates) { AddRange(certificates); } public X509Certificate2Collection(X509Certificate2Collection certificates) { AddRange(certificates); } public new X509Certificate2 this[int index] { get { return (X509Certificate2)(base[index]); } set { base[index] = value; } } public int Add(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); return base.Add(certificate); } public void AddRange(X509Certificate2[] certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Length; i++) { Add(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Remove(certificates[j]); } throw; } } public void AddRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Count; i++) { Add(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Remove(certificates[j]); } throw; } } public bool Contains(X509Certificate2 certificate) { // This method used to throw ArgumentNullException, but it has been deliberately changed // to no longer throw to match the behavior of X509CertificateCollection.Contains and the // IList.Contains implementation, which do not throw. return base.Contains(certificate); } public byte[] Export(X509ContentType contentType) { return Export(contentType, password: null); } public byte[] Export(X509ContentType contentType, string password) { using (var safePasswordHandle = new SafePasswordHandle(password)) using (IExportPal storePal = StorePal.LinkFromCertificateCollection(this)) { return storePal.Export(contentType, safePasswordHandle); } } public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly) { if (findValue == null) throw new ArgumentNullException(nameof(findValue)); return FindPal.FindFromCollection(this, findType, findValue, validOnly); } public new X509Certificate2Enumerator GetEnumerator() { return new X509Certificate2Enumerator(this); } public void Import(byte[] rawData) { Import(rawData, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet); } public void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null) throw new ArgumentNullException(nameof(rawData)); X509Certificate.ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) using (ILoaderPal storePal = StorePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags)) { storePal.MoveTo(this); } } public void Import(string fileName) { Import(fileName, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet); } public void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); X509Certificate.ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) using (ILoaderPal storePal = StorePal.FromFile(fileName, safePasswordHandle, keyStorageFlags)) { storePal.MoveTo(this); } } public void Insert(int index, X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); base.Insert(index, certificate); } public void Remove(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); base.Remove(certificate); } public void RemoveRange(X509Certificate2[] certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Length; i++) { Remove(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Add(certificates[j]); } throw; } } public void RemoveRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Count; i++) { Remove(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Add(certificates[j]); } throw; } } } }
//----------------------------------------------------------------------- // <copyright file="EventLog.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Computer { using System.Diagnostics; using System.Globalization; using System.IO; using System.Management; using Microsoft.Build.Framework; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Backup</i> (<b>Required: </b> LogName, BackupPath <b>Optional: </b>MachineName)</para> /// <para><i>CheckExists</i> (<b>Required: </b>LogName <b>Optional: </b>MachineName <b>Output: </b>Exists)</para> /// <para><i>Clear</i> (<b>Required: </b> LogName <b>Optional: </b>MachineName)</para> /// <para><i>Create</i> (<b>Required: </b>LogName <b>Optional: </b>MaxSize, Retention, MachineName, CategoryCount, MessageResourceFile, CategoryResourceFile, ParameterResourceFile)</para> /// <para><i>Delete</i> (<b>Required: </b>LogName <b>Optional: </b>MachineName)</para> /// <para><i>Modify</i> (<b>Required: </b>LogName <b>Optional: </b>MaxSize, Retention, MachineName)</para> /// <para><b>Remote Execution Support:</b> Yes</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <Target Name="Default"> /// <!-- Backup an eventlog --> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="Backup" LogName="Security" BackupPath="C:\Securitybackup.evt"/> /// <!-- Delete an eventlog --> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="Delete" LogName="DemoEventLog"/> /// <!-- Check whether an eventlog exists --> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="CheckExists" LogName="DemoEventLog"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.EventLog> /// <Message Text="DemoEventLog Exists: $(DoesExist)"/> /// <!-- Create whether an eventlog --> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="Create" LogName="DemoEventLog" MaxSize="20" Retention="14"/> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="CheckExists" LogName="DemoEventLog"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.EventLog> /// <Message Text="DemoEventLog Exists: $(DoesExist)"/> /// <!-- Various other quick tasks --> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="Clear" LogName="DemoEventLog"/> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="Modify" LogName="DemoEventLog" MaxSize="55" Retention="25"/> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="Delete" LogName="DemoEventLog"/> /// <MSBuild.ExtensionPack.Computer.EventLog TaskAction="CheckExists" LogName="DemoEventLog"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.EventLog> /// <Message Text="Exists: $(DoesExist)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class EventLog : BaseTask { private const string BackupTaskAction = "Backup"; private const string CheckExistsTaskAction = "CheckExists"; private const string ClearTaskAction = "Clear"; private const string CreateTaskAction = "Create"; private const string DeleteTaskAction = "Delete"; private const string ModifyTaskAction = "Modify"; /// <summary> /// Sets the size of the max. /// </summary> public int MaxSize { get; set; } /// <summary> /// Sets the retention. Any value > 0 is interpreted as days to retain. Use -1 for 'Overwrite as needed'. Use -2 for 'Never Overwrite' /// </summary> public int Retention { get; set; } /// <summary> /// Sets the name of the Event Log /// </summary> [Required] public string LogName { get; set; } /// <summary> /// Gets a value indicating whether the event log exists. /// </summary> [Output] public bool Exists { get; set; } /// <summary> /// Sets the number of categories in the category resource file /// </summary> public int CategoryCount { get; set; } /// <summary> /// Sets the path of the message resource file to configure an event log source to write localized event messages /// </summary> public string MessageResourceFile { get; set; } /// <summary> /// Sets the path of the category resource file to write events with localized category strings /// </summary> public string CategoryResourceFile { get; set; } /// <summary> /// Sets the path of the parameter resource file to configure an event log source to write localized event messages with inserted parameter strings /// </summary> public string ParameterResourceFile { get; set; } /// <summary> /// Sets the Backup Path /// </summary> public string BackupPath { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { switch (this.TaskAction) { case BackupTaskAction: this.Backup(); break; case CreateTaskAction: this.Create(); break; case CheckExistsTaskAction: this.CheckExists(); break; case DeleteTaskAction: this.Delete(); break; case ClearTaskAction: this.Clear(); break; case ModifyTaskAction: this.Modify(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private void Modify() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Modifying EventLog: {0} on {1}", this.LogName, this.MachineName)); if (System.Diagnostics.EventLog.Exists(this.LogName, this.MachineName)) { using (System.Diagnostics.EventLog el = new System.Diagnostics.EventLog(this.LogName, this.MachineName)) { this.ConfigureEventLog(el); } } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "EventLog does not exist: {0}", this.LogName)); } } private void Delete() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting EventLog: {0} on: {1}", this.LogName, this.MachineName)); if (System.Diagnostics.EventLog.Exists(this.LogName, this.MachineName)) { System.Diagnostics.EventLog.Delete(this.LogName, this.MachineName); } } private void CheckExists() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking EventLog exists: {0} on: {1}", this.LogName, this.MachineName)); this.Exists = System.Diagnostics.EventLog.Exists(this.LogName, this.MachineName); } private void Create() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating EventLog: {0} on: {1}", this.LogName, this.MachineName)); if (!System.Diagnostics.EventLog.Exists(this.LogName, this.MachineName)) { EventSourceCreationData ecd = new EventSourceCreationData(this.LogName, this.LogName) { MachineName = this.MachineName, CategoryCount = this.CategoryCount, MessageResourceFile = this.MessageResourceFile ?? string.Empty, CategoryResourceFile = this.CategoryResourceFile ?? string.Empty, ParameterResourceFile = this.ParameterResourceFile ?? string.Empty }; System.Diagnostics.EventLog.CreateEventSource(ecd); using (System.Diagnostics.EventLog el = new System.Diagnostics.EventLog(this.LogName, this.MachineName)) { this.ConfigureEventLog(el); } } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "EventLog already exists: {0} on: {1}", this.LogName, this.MachineName)); } } private void ConfigureEventLog(System.Diagnostics.EventLog el) { if (this.MaxSize > 0) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting EventLog Size: {0}Mb", this.MaxSize)); el.MaximumKilobytes = this.MaxSize * 1024; } if (this.Retention > 0) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Retention: {0} days", this.Retention)); el.ModifyOverflowPolicy(OverflowAction.OverwriteOlder, this.Retention); } else if (this.Retention == -1) { this.LogTaskMessage("Setting Retention to 'Overwrite As Needed'"); el.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 0); } else if (this.Retention == -2) { this.LogTaskMessage("Setting Retention to 'Do Not Overwrite'"); el.ModifyOverflowPolicy(OverflowAction.DoNotOverwrite, 0); } } private void Clear() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Clearing EventLog: {0}", this.LogName)); if (System.Diagnostics.EventLog.Exists(this.LogName, this.MachineName)) { using (System.Diagnostics.EventLog targetLog = new System.Diagnostics.EventLog(this.LogName, this.MachineName)) { targetLog.Clear(); } } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid LogName Supplied: {0}", this.LogName)); } } private void Backup() { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Backup EventLog: {0}", this.LogName)); // check the backup path. if (string.IsNullOrEmpty(this.BackupPath)) { this.Log.LogError("Invalid BackupPath Supplied"); return; } // check if the eventlog exists if (System.Diagnostics.EventLog.SourceExists(this.LogName)) { // check if the file to backup to exists if (System.IO.File.Exists(this.BackupPath)) { // First make sure the file is writable. FileAttributes fileAttributes = System.IO.File.GetAttributes(this.BackupPath); // If readonly attribute is set, reset it. if ((fileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // make it readable. System.IO.File.SetAttributes(this.BackupPath, fileAttributes ^ FileAttributes.ReadOnly); // delete it System.IO.File.Delete(this.BackupPath); } } ConnectionOptions options = new ConnectionOptions { Username = this.UserName, Password = this.UserPassword, Authority = this.Authority, EnablePrivileges = true }; // set the scope this.GetManagementScope(@"\root\cimv2", options); // set the query SelectQuery query = new SelectQuery("Select * from Win32_NTEventLogFile where LogFileName='" + this.LogName + "'"); // configure the searcher and execute a get using (ManagementObjectSearcher search = new ManagementObjectSearcher(this.Scope, query)) { foreach (ManagementObject obj in search.Get()) { object[] path = { this.BackupPath }; obj.InvokeMethod("BackupEventLog", path); } } } else { this.Log.LogError(string.Format(CultureInfo.CurrentUICulture, "Invalid LogName Supplied: {0}", this.LogName)); } } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011 Zynga Inc. Copyright (c) 2011-2012 openxlive.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.Diagnostics; using Microsoft.Xna.Framework.Graphics; namespace Cocos2D { /// <summary> /// A class that implements a Texture Atlas. /// </summary> ///<remarks> /// Supported features: /// The atlas file can be a PVRTC, PNG or any other fomrat supported by Texture2D /// Quads can be udpated in runtime /// Quads can be added in runtime /// Quads can be removed in runtime /// Quads can be re-ordered in runtime /// The TextureAtlas capacity can be increased or decreased in runtime /// OpenGL component: V3F, C4B, T2F. /// The quads are rendered using an OpenGL ES VBO. /// To render the quads using an interleaved vertex array list, you should modify the ccConfig.h file ///</remarks> public class CCTextureAtlas { internal bool Dirty = true; //indicates whether or not the array buffer of the VBO needs to be updated private CCQuadVertexBuffer m_pVertexBuffer; public CCRawList<CCV3F_C4B_T2F_Quad> m_pQuads; protected CCTexture2D m_pTexture; #region properties /// <summary> /// quantity of quads that are going to be drawn /// </summary> public int TotalQuads { get { return m_pQuads.count; } } /// <summary> /// quantity of quads that can be stored with the current texture atlas size /// </summary> public int Capacity { get { return m_pQuads.Capacity; } set { m_pQuads.Capacity = value; } } /// <summary> /// Texture of the texture atlas /// </summary> public CCTexture2D Texture { get { return m_pTexture; } set { m_pTexture = value; } } public bool IsAntialiased { get { return Texture.IsAntialiased; } set { Texture.IsAntialiased = value; } } #endregion public override string ToString() { return string.Format("TotalQuads:{0}", TotalQuads); } /// <summary> /// draws all the Atlas's Quads /// </summary> public void DrawQuads() { DrawNumberOfQuads(TotalQuads, 0); } /// <summary> /// draws n quads /// can't be greater than the capacity of the Atlas /// n /// </summary> public void DrawNumberOfQuads(int n) { DrawNumberOfQuads(n, 0); } /// <summary> /// draws n quads from an index (offset). /// n + start can't be greater than the capacity of the atlas /// @since v1.0 /// </summary> public void DrawNumberOfQuads(int n, int start) { if (n == 0) { return; } CCDrawManager.BindTexture(Texture); if (Dirty) { m_pVertexBuffer.UpdateBuffer(); Dirty = false; } CCDrawManager.DrawQuadsBuffer(m_pVertexBuffer, start, n); } /// <summary> /// resize the capacity of the CCTextureAtlas. /// The new capacity can be lower or higher than the current one /// It returns YES if the resize was successful. /// If it fails to resize the capacity it will return NO with a new capacity of 0. /// </summary> public bool ResizeCapacity(int newCapacity) { if (newCapacity <= m_pQuads.Capacity) { return true; } m_pVertexBuffer.Capacity = newCapacity; m_pQuads = m_pVertexBuffer.Data; Dirty = true; return true; } public void IncreaseTotalQuadsWith(int amount) { m_pVertexBuffer.Count += amount; } public void MoveQuadsFromIndex(int oldIndex, int amount, int newIndex) { Debug.Assert(newIndex + amount <= m_pQuads.count, "insertQuadFromIndex:atIndex: Invalid index"); Debug.Assert(oldIndex < m_pQuads.count, "insertQuadFromIndex:atIndex: Invalid index"); if (oldIndex == newIndex) { return; } var tmp = new CCV3F_C4B_T2F_Quad[amount]; Array.Copy(m_pQuads.Elements, oldIndex, tmp, 0, amount); if (newIndex < oldIndex) { // move quads from newIndex to newIndex + amount to make room for buffer Array.Copy(m_pQuads.Elements, newIndex + amount, m_pQuads.Elements, newIndex, oldIndex - newIndex); } else { // move quads above back Array.Copy(m_pQuads.Elements, oldIndex + amount, m_pQuads.Elements, oldIndex, newIndex - oldIndex); } Array.Copy(tmp, 0, m_pQuads.Elements, newIndex, amount); Dirty = true; } public void MoveQuadsFromIndex(int index, int newIndex) { Debug.Assert(newIndex + (m_pQuads.count - index) <= m_pQuads.Capacity, "moveQuadsFromIndex move is out of bounds"); Array.Copy(m_pQuads.Elements, index, m_pQuads.Elements, newIndex, m_pQuads.count - index); Dirty = true; } public void FillWithEmptyQuadsFromIndex(int index, int amount) { int to = index + amount; CCV3F_C4B_T2F_Quad[] elements = m_pQuads.Elements; var empty = new CCV3F_C4B_T2F_Quad(); for (int i = index; i < to; i++) { elements[i] = empty; } Dirty = true; } #region create and init /// <summary> /// creates a TextureAtlas with an filename and with an initial capacity for Quads. /// The TextureAtlas capacity can be increased in runtime. /// </summary> public static CCTextureAtlas Create(string file, int capacity) { var pTextureAtlas = new CCTextureAtlas(); if (pTextureAtlas.InitWithFile(file, capacity)) { return pTextureAtlas; } return null; } /// <summary> /// initializes a TextureAtlas with a filename and with a certain capacity for Quads. /// The TextureAtlas capacity can be increased in runtime. /// WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) /// </summary> public bool InitWithFile(string file, int capacity) { // retained in property CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(file); if (texture != null) { return InitWithTexture(texture, capacity); } return false; } /// <summary> /// creates a TextureAtlas with a previously initialized Texture2D object, and /// with an initial capacity for n Quads. /// The TextureAtlas capacity can be increased in runtime. /// </summary> public static CCTextureAtlas Create(CCTexture2D texture, int capacity) { var pTextureAtlas = new CCTextureAtlas(); if (pTextureAtlas.InitWithTexture(texture, capacity)) { return pTextureAtlas; } return null; } /// <summary> /// initializes a TextureAtlas with a previously initialized Texture2D object, and /// with an initial capacity for Quads. /// The TextureAtlas capacity can be increased in runtime. /// WARNING: Do not reinitialize the TextureAtlas because it will leak memory (issue #706) /// </summary> public bool InitWithTexture(CCTexture2D texture, int capacity) { //Debug.Assert(texture != null); // retained in property m_pTexture = texture; // Re-initialization is not allowed Debug.Assert(m_pQuads == null); if (capacity < 4) { capacity = 4; } m_pVertexBuffer = new CCQuadVertexBuffer(capacity, BufferUsage.WriteOnly); m_pQuads = m_pVertexBuffer.Data; Dirty = true; return true; } #endregion #region Quads /// <summary> /// updates a Quad (texture, vertex and color) at a certain index /// index must be between 0 and the atlas capacity - 1 /// @since v0.8 /// </summary> public void UpdateQuad(ref CCV3F_C4B_T2F_Quad quad, int index) { Debug.Assert(index >= 0 && index < m_pQuads.Capacity, "updateQuadWithTexture: Invalid index"); m_pQuads.count = Math.Max(index + 1, m_pQuads.count); m_pQuads.Elements[index] = quad; Dirty = true; } /// <summary> /// Inserts a Quad (texture, vertex and color) at a certain index /// index must be between 0 and the atlas capacity - 1 /// @since v0.8 /// </summary> public void InsertQuad(ref CCV3F_C4B_T2F_Quad quad, int index) { Debug.Assert(index < m_pQuads.Capacity, "insertQuadWithTexture: Invalid index"); m_pQuads.Insert(index, quad); Dirty = true; } /// Removes the quad that is located at a certain index and inserts it at a new index /// This operation is faster than removing and inserting in a quad in 2 different steps /// @since v0.7.2 public void InsertQuadFromIndex(int oldIndex, int newIndex) { Debug.Assert(newIndex >= 0 && newIndex < m_pQuads.count, "insertQuadFromIndex:atIndex: Invalid index"); Debug.Assert(oldIndex >= 0 && oldIndex < m_pQuads.count, "insertQuadFromIndex:atIndex: Invalid index"); if (oldIndex == newIndex) return; // because it is ambigious in iphone, so we implement abs ourself // unsigned int howMany = abs( oldIndex - newIndex); int howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); int dst = oldIndex; int src = oldIndex + 1; if (oldIndex > newIndex) { dst = newIndex + 1; src = newIndex; } CCV3F_C4B_T2F_Quad[] elements = m_pQuads.Elements; CCV3F_C4B_T2F_Quad quadsBackup = elements[oldIndex]; Array.Copy(elements, src, elements, dst, howMany); elements[newIndex] = quadsBackup; Dirty = true; } /// <summary> /// removes a quad at a given index number. /// The capacity remains the same, but the total number of quads to be drawn is reduced in 1 /// @since v0.7.2 /// </summary> public void RemoveQuadAtIndex(int index) { Debug.Assert(index < m_pQuads.count, "removeQuadAtIndex: Invalid index"); m_pQuads.RemoveAt(index); Dirty = true; } public void RemoveQuadsAtIndex(int index, int amount) { Debug.Assert(index + amount <= m_pQuads.count, "removeQuadAtIndex: Invalid index"); m_pQuads.RemoveAt(index, amount); Dirty = true; } public void RemoveAllQuads() { m_pQuads.Clear(); Dirty = true; } #endregion } }
namespace GigyaSDK.iOS { using System; using UIKit; using Foundation; using ObjCRuntime; // @interface GSSession : NSObject <NSCoding> [BaseType (typeof(NSObject))] interface GSSession : INSCoding { // -(BOOL)isValid; [Export ("isValid")] //[Verify (MethodToProperty)] bool IsValid { get; } // @property (copy, nonatomic) NSString * token; [Export ("token")] string Token { get; set; } // @property (copy, nonatomic) NSString * secret; [Export ("secret")] string Secret { get; set; } // @property (copy, nonatomic) NSDate * expiration; [Export ("expiration", ArgumentSemantic.Copy)] NSDate Expiration { get; set; } // @property (copy, nonatomic) NSString * lastLoginProvider; [Export ("lastLoginProvider")] string LastLoginProvider { get; set; } // -(GSSession *)initWithSessionToken:(NSString *)token secret:(NSString *)secret; [Export ("initWithSessionToken:secret:")] IntPtr Constructor (string token, string secret); // -(GSSession *)initWithSessionToken:(NSString *)token secret:(NSString *)secret expiration:(NSDate *)expiration; [Export ("initWithSessionToken:secret:expiration:")] IntPtr Constructor (string token, string secret, NSDate expiration); } // @interface GSObject : NSObject [BaseType (typeof(NSObject))] interface GSObject { // @property (copy, nonatomic) NSString * source; [Export ("source")] string Source { get; set; } // -(id)objectForKeyedSubscript:(NSString *)key; [Export ("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript (string key); // -(void)setObject:(id)obj forKeyedSubscript:(NSString *)key; [Export ("setObject:forKeyedSubscript:")] void SetObjectForKeyedSubscript (NSObject obj, string key); // -(id)objectForKey:(NSString *)key; [Export ("objectForKey:")] NSObject ObjectForKey (string key); // -(void)setObject:(id)obj forKey:(NSString *)key; [Export ("setObject:forKey:")] void SetObject (NSObject obj, string key); // -(void)removeObjectForKey:(NSString *)key; [Export ("removeObjectForKey:")] void RemoveObjectForKey (string key); // -(NSArray *)allKeys; [Export ("allKeys")] //[Verify (MethodToProperty), Verify (StronglyTypedNSArray)] NSObject[] AllKeys { get; } // -(NSString *)JSONString; [Export ("JSONString")] //[Verify (MethodToProperty)] string JSONString { get; } } // @interface GSResponse : GSObject [BaseType (typeof(GSObject))] interface GSResponse { // +(GSResponse *)responseForMethod:(NSString *)method data:(NSData *)data; [Static] [Export ("responseForMethod:data:")] GSResponse ResponseForMethod (string method, NSData data); // +(GSResponse *)responseWithError:(NSError *)error; [Static] [Export ("responseWithError:")] GSResponse ResponseWithError (NSError error); // @property (readonly, weak) NSString * method; [Export ("method", ArgumentSemantic.Weak)] string Method { get; } // @property (readonly) int errorCode; [Export ("errorCode")] int ErrorCode { get; } // @property (readonly, weak) NSString * callId; [Export ("callId", ArgumentSemantic.Weak)] string CallId { get; } // -(NSArray *)allKeys; [Export ("allKeys")] //[Verify (MethodToProperty), Verify (StronglyTypedNSArray)] NSObject[] AllKeys { get; } // -(id)objectForKey:(NSString *)key; [Export ("objectForKey:")] NSObject ObjectForKey (string key); // -(id)objectForKeyedSubscript:(NSString *)key; [Export ("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript (string key); // -(NSString *)JSONString; [Export ("JSONString")] //[Verify (MethodToProperty)] string JSONString { get; } } // typedef void (^GSResponseHandler)(GSResponse *NSError *); delegate void GSResponseHandler (GSResponse arg0, NSError arg1); // @interface GSRequest : NSObject [BaseType (typeof(NSObject))] interface GSRequest { // +(GSRequest *)requestForMethod:(NSString *)method; [Static] [Export ("requestForMethod:")] GSRequest RequestForMethod (string method); // +(GSRequest *)requestForMethod:(NSString *)method parameters:(NSDictionary *)parameters; [Static] [Export ("requestForMethod:parameters:")] GSRequest RequestForMethod (string method, NSDictionary parameters); // @property (copy, nonatomic) NSString * method; [Export ("method")] string Method { get; set; } // @property (nonatomic, strong) NSMutableDictionary * parameters; [Export ("parameters", ArgumentSemantic.Strong)] NSMutableDictionary Parameters { get; set; } // @property (nonatomic) BOOL useHTTPS; [Export ("useHTTPS")] bool UseHTTPS { get; set; } // @property (nonatomic) NSTimeInterval requestTimeout; [Export ("requestTimeout")] double RequestTimeout { get; set; } // -(void)sendWithResponseHandler:(GSResponseHandler)handler; [Export ("sendWithResponseHandler:")] void SendWithResponseHandler (GSResponseHandler handler); // -(GSResponse *)sendSynchronouslyWithError:(NSError **)error; [Export ("sendSynchronouslyWithError:")] GSResponse SendSynchronouslyWithError (out NSError error); // -(void)cancel; [Export ("cancel")] void Cancel (); // @property (nonatomic, strong) GSSession * session; [Export ("session", ArgumentSemantic.Strong)] GSSession Session { get; set; } // @property (readonly, nonatomic, strong) NSString * requestID; [Export ("requestID", ArgumentSemantic.Strong)] string RequestID { get; } // @property (nonatomic) BOOL includeAuthInfo; [Export ("includeAuthInfo")] bool IncludeAuthInfo { get; set; } // @property (copy, nonatomic) NSString * source; [Export ("source")] string Source { get; set; } } // @interface GSUser : GSResponse [BaseType (typeof(GSResponse))] interface GSUser { // @property (readonly, nonatomic, weak) NSString * UID; [Export ("UID", ArgumentSemantic.Weak)] string UID { get; } // @property (readonly, nonatomic, weak) NSString * loginProvider; [Export ("loginProvider", ArgumentSemantic.Weak)] string LoginProvider { get; } // @property (readonly, nonatomic, weak) NSString * nickname; [Export ("nickname", ArgumentSemantic.Weak)] string Nickname { get; } // @property (readonly, nonatomic, weak) NSString * firstName; [Export ("firstName", ArgumentSemantic.Weak)] string FirstName { get; } // @property (readonly, nonatomic, weak) NSString * lastName; [Export ("lastName", ArgumentSemantic.Weak)] string LastName { get; } // @property (readonly, nonatomic, weak) NSString * email; [Export ("email", ArgumentSemantic.Weak)] string Email { get; } // @property (readonly, nonatomic, weak) NSArray * identities; [Export ("identities", ArgumentSemantic.Weak)] //[Verify (StronglyTypedNSArray)] NSObject[] Identities { get; } // @property (readonly, nonatomic, weak) NSURL * photoURL; [Export ("photoURL", ArgumentSemantic.Weak)] NSUrl PhotoURL { get; } // @property (readonly, nonatomic, weak) NSURL * thumbnailURL; [Export ("thumbnailURL", ArgumentSemantic.Weak)] NSUrl ThumbnailURL { get; } // -(NSArray *)allKeys; [Export ("allKeys")] //[Verify (MethodToProperty), Verify (StronglyTypedNSArray)] NSObject[] AllKeys { get; } // -(id)objectForKey:(NSString *)key; [Export ("objectForKey:")] NSObject ObjectForKey (string key); // -(id)objectForKeyedSubscript:(NSString *)key; [Export ("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript (string key); // -(NSString *)JSONString; [Export ("JSONString")] //[Verify (MethodToProperty)] string JSONString { get; } } // @interface GSAccount : GSResponse [BaseType (typeof(GSResponse))] interface GSAccount { // @property (readonly, nonatomic, weak) NSString * UID; [Export ("UID", ArgumentSemantic.Weak)] string UID { get; } // @property (readonly, nonatomic, weak) NSDictionary * profile; [Export ("profile", ArgumentSemantic.Weak)] NSDictionary Profile { get; } // @property (readonly, nonatomic, weak) NSDictionary * data; [Export ("data", ArgumentSemantic.Weak)] NSDictionary Data { get; } // @property (readonly, nonatomic, weak) NSString * nickname; [Export ("nickname", ArgumentSemantic.Weak)] string Nickname { get; } // @property (readonly, nonatomic, weak) NSString * firstName; [Export ("firstName", ArgumentSemantic.Weak)] string FirstName { get; } // @property (readonly, nonatomic, weak) NSString * lastName; [Export ("lastName", ArgumentSemantic.Weak)] string LastName { get; } // @property (readonly, nonatomic, weak) NSString * email; [Export ("email", ArgumentSemantic.Weak)] string Email { get; } // @property (readonly, nonatomic, weak) NSURL * photoURL; [Export ("photoURL", ArgumentSemantic.Weak)] NSUrl PhotoURL { get; } // @property (readonly, nonatomic, weak) NSURL * thumbnailURL; [Export ("thumbnailURL", ArgumentSemantic.Weak)] NSUrl ThumbnailURL { get; } // -(NSArray *)allKeys; [Export ("allKeys")] //[Verify (MethodToProperty), Verify (StronglyTypedNSArray)] NSObject[] AllKeys { get; } // -(id)objectForKey:(NSString *)key; [Export ("objectForKey:")] NSObject ObjectForKey (string key); // -(id)objectForKeyedSubscript:(NSString *)key; [Export ("objectForKeyedSubscript:")] NSObject ObjectForKeyedSubscript (string key); // -(NSString *)JSONString; [Export ("JSONString")] //[Verify (MethodToProperty)] string JSONString { get; } } // __attribute((deprecated("Use [Gigya setSocializeDelegate:] with a GSSocializeDelegate instead"))) // @protocol GSSessionDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface GSSessionDelegate { // @optional -(void)userDidLogin:(GSUser *)user; [Export ("userDidLogin:")] void UserDidLogin (GSUser user); // @optional -(void)userDidLogout; [Export ("userDidLogout")] void UserDidLogout (); // @optional -(void)userInfoDidChange:(GSUser *)user; [Export ("userInfoDidChange:")] void UserInfoDidChange (GSUser user); } // @protocol GSSocializeDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface GSSocializeDelegate { // @optional -(void)userDidLogin:(GSUser *)user; [Export ("userDidLogin:")] void UserDidLogin (GSUser user); // @optional -(void)userDidLogout; [Export ("userDidLogout")] void UserDidLogout (); // @optional -(void)userInfoDidChange:(GSUser *)user; [Export ("userInfoDidChange:")] void UserInfoDidChange (GSUser user); } // @protocol GSAccountsDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface GSAccountsDelegate { // @optional -(void)accountDidLogin:(GSAccount *)account; [Export ("accountDidLogin:")] void AccountDidLogin (GSAccount account); // @optional -(void)accountDidLogout; [Export ("accountDidLogout")] void AccountDidLogout (); } // @protocol GSWebBridgeDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface GSWebBridgeDelegate { // @optional -(void)webView:(id)webView startedLoginForMethod:(NSString *)method parameters:(NSDictionary *)parameters; [Export ("webView:startedLoginForMethod:parameters:")] void StartedLoginForMethod (NSObject webView, string method, NSDictionary parameters); // @optional -(void)webView:(id)webView finishedLoginWithResponse:(GSResponse *)response; [Export ("webView:finishedLoginWithResponse:")] void FinishedLoginWithResponse (NSObject webView, GSResponse response); // @optional -(void)webView:(id)webView receivedPluginEvent:(NSDictionary *)event fromPluginInContainer:(NSString *)containerID; [Export ("webView:receivedPluginEvent:fromPluginInContainer:")] void ReceivedPluginEvent (NSObject webView, NSDictionary dict, string containerID); // @optional -(void)webView:(id)webView receivedJsLog:(NSString *)logType logInfo:(NSDictionary *)logInfo; [Export ("webView:receivedJsLog:logInfo:")] void ReceivedJsLog (NSObject webView, string logType, NSDictionary logInfo); } // @interface GSWebBridge : NSObject [BaseType (typeof(NSObject))] interface GSWebBridge { // +(void)registerWebView:(id)webView delegate:(id<GSWebBridgeDelegate>)delegate; [Static] [Export ("registerWebView:delegate:")] void RegisterWebView (NSObject webView, GSWebBridgeDelegate bridge_delegate); // +(void)registerWebView:(id)webView delegate:(id<GSWebBridgeDelegate>)delegate settings:(NSDictionary *)settings; [Static] [Export ("registerWebView:delegate:settings:")] void RegisterWebView (NSObject webView, GSWebBridgeDelegate bridge_delegate, NSDictionary settings); // +(void)unregisterWebView:(id)webView; [Static] [Export ("unregisterWebView:")] void UnregisterWebView (NSObject webView); // +(void)webViewDidStartLoad:(id)webView; [Static] [Export ("webViewDidStartLoad:")] void WebViewDidStartLoad (NSObject webView); // +(BOOL)handleRequest:(NSURLRequest *)request webView:(id)webView; [Static] [Export ("handleRequest:webView:")] bool HandleRequest (NSUrlRequest request, NSObject webView); } // @protocol GSPluginViewDelegate <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface GSPluginViewDelegate { // @optional -(void)pluginView:(GSPluginView *)pluginView finishedLoadingPluginWithEvent:(NSDictionary *)event; [Export ("pluginView:finishedLoadingPluginWithEvent:")] void FinishedLoadingPluginWithEvent (GSPluginView pluginView, NSDictionary dict); // @optional -(void)pluginView:(GSPluginView *)pluginView firedEvent:(NSDictionary *)event; [Export ("pluginView:firedEvent:")] void FiredEvent (GSPluginView pluginView, NSDictionary dict); // @optional -(void)pluginView:(GSPluginView *)pluginView didFailWithError:(NSError *)error; [Export ("pluginView:didFailWithError:")] void DidFailWithError (GSPluginView pluginView, NSError error); } // @interface GSPluginView : UIView [BaseType (typeof(UIView))] interface GSPluginView { [Wrap ("WeakDelegate")] GSPluginViewDelegate Delegate { get; set; } // @property (nonatomic, weak) id<GSPluginViewDelegate> delegate; [NullAllowed, Export ("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // -(void)loadPlugin:(NSString *)plugin; [Export ("loadPlugin:")] void LoadPlugin (string plugin); // -(void)loadPlugin:(NSString *)plugin parameters:(NSDictionary *)parameters; [Export ("loadPlugin:parameters:")] void LoadPlugin (string plugin, NSDictionary parameters); // @property (readonly, nonatomic) NSString * plugin; [Export ("plugin")] string Plugin { get; } // @property (nonatomic) BOOL showLoginProgress; [Export ("showLoginProgress")] bool ShowLoginProgress { get; set; } // @property (copy, nonatomic) NSString * loginProgressText; [Export ("loginProgressText")] string LoginProgressText { get; set; } // @property (nonatomic) BOOL showLoadingProgress; [Export ("showLoadingProgress")] bool ShowLoadingProgress { get; set; } // @property (copy, nonatomic) NSString * loadingProgressText; [Export ("loadingProgressText")] string LoadingProgressText { get; set; } // @property (nonatomic) NSInteger javascriptLoadingTimeout; [Export ("javascriptLoadingTimeout", ArgumentSemantic.Assign)] nint JavascriptLoadingTimeout { get; set; } } // typedef void (^GSUserInfoHandler)(GSUser *NSError *); delegate void GSUserInfoHandler (GSUser arg0, NSError arg1); // typedef void (^GSPermissionRequestResultHandler)(BOOLNSError *NSArray *); delegate void GSPermissionRequestResultHandler (bool arg0, NSError arg1, NSObject[] arg2); // typedef void (^GSPluginCompletionHandler)(BOOLNSError *); delegate void GSPluginCompletionHandler (bool arg0, NSError arg1); // @interface Gigya : NSObject [BaseType (typeof(NSObject))] interface Gigya { // +(void)initWithAPIKey:(NSString *)apiKey application:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions; [Static] [Export ("initWithAPIKey:application:launchOptions:")] void InitWithAPIKey (string apiKey, UIApplication application, [NullAllowed] NSDictionary launchOptions); // +(void)initWithAPIKey:(NSString *)apiKey application:(UIApplication *)application launchOptions:(NSDictionary *)launchOptions APIDomain:(NSString *)apiDomain; [Static] [Export ("initWithAPIKey:application:launchOptions:APIDomain:")] void InitWithAPIKey (string apiKey, UIApplication application, [NullAllowed] NSDictionary launchOptions, string apiDomain); // +(NSString *)APIKey; [Static] [Export ("APIKey")] //[Verify (MethodToProperty)] string APIKey { get; } // +(NSString *)APIDomain; [Static] [Export ("APIDomain")] //[Verify (MethodToProperty)] string APIDomain { get; } // +(GSSession *)session; // +(void)setSession:(GSSession *)session; [Static] [Export ("session")] //[Verify (MethodToProperty)] GSSession Session { get; set; } // +(id<GSSessionDelegate>)sessionDelegate; [Static] [Export ("sessionDelegate")] GSSessionDelegate SessionDelegate (); // +(void)setSessionDelegate:(id<GSSessionDelegate>)delegate __attribute__((deprecated("Use [Gigya setSocializeDelegate:] with a GSSocializeDelegate instead"))); [Static] [Export ("setSessionDelegate:")] void SetSessionDelegate (GSSessionDelegate session_delegate); // +(id<GSSocializeDelegate>)socializeDelegate; [Static] [Export ("socializeDelegate")] GSSocializeDelegate SocializeDelegate (); // +(void)setSocializeDelegate:(id<GSSocializeDelegate>)socializeDelegate; [Static] [Export ("setSocializeDelegate:")] void SetSocializeDelegate (GSSocializeDelegate socializeDelegate); // +(id<GSAccountsDelegate>)accountsDelegate; [Static] [Export ("accountsDelegate")] GSAccountsDelegate AccountsDelegate (); // +(void)setAccountsDelegate:(id<GSAccountsDelegate>)accountsDelegate; [Static] [Export ("setAccountsDelegate:")] void SetAccountsDelegate (GSAccountsDelegate accountsDelegate); // +(void)loginToProvider:(NSString *)provider; [Static] [Export ("loginToProvider:")] void LoginToProvider (string provider); // +(void)showLoginDialogOver:(UIViewController *)viewController provider:(NSString *)provider __attribute__((deprecated("Use loginToProvider: instead"))); [Static] [Export ("showLoginDialogOver:provider:")] void ShowLoginDialogOver (UIViewController viewController, string provider); // +(void)loginToProvider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("loginToProvider:parameters:completionHandler:")] void LoginToProvider (string provider, [NullAllowed] NSDictionary parameters, GSUserInfoHandler handler); // +(void)showLoginDialogOver:(UIViewController *)viewController provider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler __attribute__((deprecated("Use loginToProvider:parameters:completionHandler: instead"))); [Static] [Export ("showLoginDialogOver:provider:parameters:completionHandler:")] void ShowLoginDialogOver (UIViewController viewController, string provider, NSDictionary parameters, GSUserInfoHandler handler); // +(void)loginToProvider:(NSString *)provider parameters:(NSDictionary *)parameters over:(UIViewController *)viewController completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("loginToProvider:parameters:over:completionHandler:")] void LoginToProvider (string provider, [NullAllowed] NSDictionary parameters, UIViewController viewController, GSUserInfoHandler handler); // +(void)showLoginProvidersDialogOver:(UIViewController *)viewController; [Static] [Export ("showLoginProvidersDialogOver:")] void ShowLoginProvidersDialogOver (UIViewController viewController); // +(void)showLoginProvidersPopoverFrom:(UIView *)view; [Static] [Export ("showLoginProvidersPopoverFrom:")] void ShowLoginProvidersPopoverFrom (UIView view); // +(void)showLoginProvidersDialogOver:(UIViewController *)viewController providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("showLoginProvidersDialogOver:providers:parameters:completionHandler:")] //[Verify (StronglyTypedNSArray)] void ShowLoginProvidersDialogOver (UIViewController viewController, NSObject[] providers, NSDictionary parameters, GSUserInfoHandler handler); // +(void)showLoginProvidersPopoverFrom:(UIView *)view providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("showLoginProvidersPopoverFrom:providers:parameters:completionHandler:")] //[Verify (StronglyTypedNSArray)] void ShowLoginProvidersPopoverFrom (UIView view, NSObject[] providers, NSDictionary parameters, GSUserInfoHandler handler); // +(void)logout; [Static] [Export ("logout")] void Logout (); // +(void)logoutWithCompletionHandler:(GSResponseHandler)handler; [Static] [Export ("logoutWithCompletionHandler:")] void LogoutWithCompletionHandler (GSResponseHandler handler); // +(void)addConnectionToProvider:(NSString *)provider; [Static] [Export ("addConnectionToProvider:")] void AddConnectionToProvider (string provider); // +(void)showAddConnectionDialogOver:(UIViewController *)viewController provider:(NSString *)provider __attribute__((deprecated("Use addConnectionToProvider: instead"))); [Static] [Export ("showAddConnectionDialogOver:provider:")] void ShowAddConnectionDialogOver (UIViewController viewController, string provider); // +(void)addConnectionToProvider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("addConnectionToProvider:parameters:completionHandler:")] void AddConnectionToProvider (string provider, NSDictionary parameters, GSUserInfoHandler handler); // +(void)showAddConnectionDialogOver:(UIViewController *)viewController provider:(NSString *)provider parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler __attribute__((deprecated("Use addConnectionToProvider:parameters:completionHandler: instead"))); [Static] [Export ("showAddConnectionDialogOver:provider:parameters:completionHandler:")] void ShowAddConnectionDialogOver (UIViewController viewController, string provider, NSDictionary parameters, GSUserInfoHandler handler); // +(void)addConnectionToProvider:(NSString *)provider parameters:(NSDictionary *)parameters over:(UIViewController *)viewController completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("addConnectionToProvider:parameters:over:completionHandler:")] void AddConnectionToProvider (string provider, NSDictionary parameters, UIViewController viewController, GSUserInfoHandler handler); // +(void)showAddConnectionProvidersDialogOver:(UIViewController *)viewController; [Static] [Export ("showAddConnectionProvidersDialogOver:")] void ShowAddConnectionProvidersDialogOver (UIViewController viewController); // +(void)showAddConnectionProvidersPopoverFrom:(UIView *)view; [Static] [Export ("showAddConnectionProvidersPopoverFrom:")] void ShowAddConnectionProvidersPopoverFrom (UIView view); // +(void)showAddConnectionProvidersDialogOver:(UIViewController *)viewController providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("showAddConnectionProvidersDialogOver:providers:parameters:completionHandler:")] //[Verify (StronglyTypedNSArray)] void ShowAddConnectionProvidersDialogOver (UIViewController viewController, NSObject[] providers, NSDictionary parameters, GSUserInfoHandler handler); // +(void)showAddConnectionProvidersPopoverFrom:(UIView *)view providers:(NSArray *)providers parameters:(NSDictionary *)parameters completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("showAddConnectionProvidersPopoverFrom:providers:parameters:completionHandler:")] //[Verify (StronglyTypedNSArray)] void ShowAddConnectionProvidersPopoverFrom (UIView view, NSObject[] providers, NSDictionary parameters, GSUserInfoHandler handler); // +(void)removeConnectionToProvider:(NSString *)provider; [Static] [Export ("removeConnectionToProvider:")] void RemoveConnectionToProvider (string provider); // +(void)removeConnectionToProvider:(NSString *)provider completionHandler:(GSUserInfoHandler)handler; [Static] [Export ("removeConnectionToProvider:completionHandler:")] void RemoveConnectionToProvider (string provider, GSUserInfoHandler handler); // +(void)showPluginDialogOver:(UIViewController *)viewController plugin:(NSString *)plugin parameters:(NSDictionary *)parameters; [Static] [Export ("showPluginDialogOver:plugin:parameters:")] void ShowPluginDialogOver (UIViewController viewController, string plugin, NSDictionary parameters); // +(void)showPluginDialogOver:(UIViewController *)viewController plugin:(NSString *)plugin parameters:(NSDictionary *)parameters completionHandler:(GSPluginCompletionHandler)handler; [Static] [Export ("showPluginDialogOver:plugin:parameters:completionHandler:")] void ShowPluginDialogOver (UIViewController viewController, string plugin, NSDictionary parameters, GSPluginCompletionHandler handler); // +(void)showPluginDialogOver:(UIViewController *)viewController plugin:(NSString *)plugin parameters:(NSDictionary *)parameters completionHandler:(GSPluginCompletionHandler)handler delegate:(id<GSPluginViewDelegate>)delegate; [Static] [Export ("showPluginDialogOver:plugin:parameters:completionHandler:delegate:")] void ShowPluginDialogOver (UIViewController viewController, string plugin, NSDictionary parameters, GSPluginCompletionHandler handler, GSPluginViewDelegate plugin_delegate); // +(void)requestNewFacebookPublishPermissions:(NSString *)permissions responseHandler:(GSPermissionRequestResultHandler)handler; [Static] [Export ("requestNewFacebookPublishPermissions:responseHandler:")] void RequestNewFacebookPublishPermissions (string permissions, GSPermissionRequestResultHandler handler); // +(void)requestNewFacebookReadPermissions:(NSString *)permissions responseHandler:(GSPermissionRequestResultHandler)handler; [Static] [Export ("requestNewFacebookReadPermissions:responseHandler:")] void RequestNewFacebookReadPermissions (string permissions, GSPermissionRequestResultHandler handler); // +(BOOL)handleOpenURL:(NSURL *)url application:(UIApplication *)application sourceApplication:(NSString *)sourceApplication annotation:(id)annotation; [Static] [Export ("handleOpenURL:application:sourceApplication:annotation:")] bool HandleOpenURL (NSUrl url, UIApplication application, string sourceApplication, [NullAllowed] NSObject annotation); // +(void)handleDidBecomeActive; [Static] [Export ("handleDidBecomeActive")] void HandleDidBecomeActive (); // +(BOOL)useHTTPS; [Static] [Export ("useHTTPS")] bool UseHTTPS (); // +(void)setUseHTTPS:(BOOL)useHTTPS; [Static] [Export ("setUseHTTPS:")] void SetUseHTTPS (bool useHTTPS); // +(BOOL)networkActivityIndicatorEnabled; [Static] [Export ("networkActivityIndicatorEnabled")] bool NetworkActivityIndicatorEnabled (); // +(void)setNetworkActivityIndicatorEnabled:(BOOL)networkActivityIndicatorEnabled; [Static] [Export ("setNetworkActivityIndicatorEnabled:")] void SetNetworkActivityIndicatorEnabled (bool networkActivityIndicatorEnabled); // +(NSTimeInterval)requestTimeout; [Static] [Export ("requestTimeout")] double RequestTimeout (); // +(void)setRequestTimeout:(NSTimeInterval)requestTimeout; [Static] [Export ("setRequestTimeout:")] void SetRequestTimeout (double requestTimeout); } }
using System; using System.Linq; using System.Reflection; using Lucene.Net.Documents; namespace Lucene.Net.Index { using NUnit.Framework; using BaseDirectoryWrapper = Lucene.Net.Store.BaseDirectoryWrapper; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; [TestFixture] public class TestFilterAtomicReader : LuceneTestCase { private class TestReader : FilterAtomicReader { /// <summary> /// Filter that only permits terms containing 'e'. </summary> private class TestFields : FilterFields { internal TestFields(Fields @in) : base(@in) { } public override Terms GetTerms(string field) { return new TestTerms(base.GetTerms(field)); } } private class TestTerms : FilterTerms { internal TestTerms(Terms @in) : base(@in) { } public override TermsEnum GetIterator(TermsEnum reuse) { return new TestTermsEnum(base.GetIterator(reuse)); } } private class TestTermsEnum : FilterTermsEnum { public TestTermsEnum(TermsEnum @in) : base(@in) { } /// <summary> /// Scan for terms containing the letter 'e'. </summary> public override BytesRef Next() { BytesRef text; while ((text = m_input.Next()) != null) { if (text.Utf8ToString().IndexOf('e') != -1) { return text; } } return null; } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { return new TestPositions(base.DocsAndPositions(liveDocs, reuse == null ? null : ((FilterDocsAndPositionsEnum)reuse).m_input, flags)); } } /// <summary> /// Filter that only returns odd numbered documents. </summary> private class TestPositions : FilterDocsAndPositionsEnum { public TestPositions(DocsAndPositionsEnum input) : base(input) { } /// <summary> /// Scan for odd numbered documents. </summary> public override int NextDoc() { int doc; while ((doc = m_input.NextDoc()) != NO_MORE_DOCS) { if ((doc % 2) == 1) { return doc; } } return NO_MORE_DOCS; } } public TestReader(IndexReader reader) : base(SlowCompositeReaderWrapper.Wrap(reader)) { } public override Fields Fields { get { return new TestFields(base.Fields); } } } /// <summary> /// Tests the IndexReader.getFieldNames implementation </summary> /// <exception cref="Exception"> on error </exception> [Test] public virtual void TestFilterIndexReader() { Directory directory = NewDirectory(); IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document d1 = new Document(); d1.Add(NewTextField("default", "one two", Field.Store.YES)); writer.AddDocument(d1); Document d2 = new Document(); d2.Add(NewTextField("default", "one three", Field.Store.YES)); writer.AddDocument(d2); Document d3 = new Document(); d3.Add(NewTextField("default", "two four", Field.Store.YES)); writer.AddDocument(d3); writer.Dispose(); Directory target = NewDirectory(); // We mess with the postings so this can fail: ((BaseDirectoryWrapper)target).CrossCheckTermVectorsOnClose = false; writer = new IndexWriter(target, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); IndexReader reader = new TestReader(DirectoryReader.Open(directory)); writer.AddIndexes(reader); writer.Dispose(); reader.Dispose(); reader = DirectoryReader.Open(target); TermsEnum terms = MultiFields.GetTerms(reader, "default").GetIterator(null); while (terms.Next() != null) { Assert.IsTrue(terms.Term.Utf8ToString().IndexOf('e') != -1); } Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(new BytesRef("one"))); DocsAndPositionsEnum positions = terms.DocsAndPositions(MultiFields.GetLiveDocs(reader), null); while (positions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { Assert.IsTrue((positions.DocID % 2) == 1); } reader.Dispose(); directory.Dispose(); target.Dispose(); } private static void CheckOverrideMethods(Type clazz) { Type superClazz = clazz.GetTypeInfo().BaseType; foreach (MethodInfo m in superClazz.GetMethods()) { // LUCENENET specific - since we changed to using a property for Attributes rather than a method, // we need to reflect that as get_Attributes here. if (m.IsStatic || m.IsAbstract || m.IsFinal || /*m.Synthetic ||*/ m.Name.Equals("get_Attributes")) { continue; } // The point of these checks is to ensure that methods that have a default // impl through other methods are not overridden. this makes the number of // methods to override to have a working impl minimal and prevents from some // traps: for example, think about having getCoreCacheKey delegate to the // filtered impl by default MethodInfo subM = clazz.GetMethod(m.Name, m.GetParameters().Select(p => p.ParameterType).ToArray()); if (subM.DeclaringType == clazz && m.DeclaringType != typeof(object) && m.DeclaringType != subM.DeclaringType) { Assert.Fail(clazz + " overrides " + m + " although it has a default impl"); } } } [Test] public virtual void TestOverrideMethods() { CheckOverrideMethods(typeof(FilterAtomicReader)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterFields)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterTerms)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterTermsEnum)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterDocsEnum)); CheckOverrideMethods(typeof(FilterAtomicReader.FilterDocsAndPositionsEnum)); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Glass.Mapper.Pipelines.ConfigurationResolver; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.MultiInterfaceResolver; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.StandardResolver; using Glass.Mapper.Pipelines.DataMapperResolver; using Glass.Mapper.Pipelines.DataMapperResolver.Tasks; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateConcrete; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateInterface; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateMultiInterface; using Glass.Mapper.Pipelines.ObjectSaving; using Glass.Mapper.Pipelines.ObjectSaving.Tasks; using Glass.Mapper.Sc.CastleWindsor.Pipelines.ObjectConstruction; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using Glass.Mapper.Sc.DataMappers.SitecoreQueryParameters; using Glass.Mapper.Sc.Pipelines.ConfigurationResolver; using Glass.Mapper.Sc.Pipelines.ObjectConstruction; namespace Glass.Mapper.Sc.CastleWindsor { /// <summary> /// Class SitecoreInstaller /// </summary> public class SitecoreInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Gets or sets the data mapper installer. /// </summary> /// <value> /// The data mapper installer. /// </value> public IWindsorInstaller DataMapperInstaller { get; set; } /// <summary> /// Gets or sets the query parameter installer. /// </summary> /// <value> /// The query parameter installer. /// </value> public IWindsorInstaller QueryParameterInstaller { get; set; } /// <summary> /// Gets or sets the data mapper task installer. /// </summary> /// <value> /// The data mapper task installer. /// </value> public IWindsorInstaller DataMapperTaskInstaller { get; set; } /// <summary> /// Gets or sets the configuration resolver task installer. /// </summary> /// <value> /// The configuration resolver task installer. /// </value> public IWindsorInstaller ConfigurationResolverTaskInstaller { get; set; } /// <summary> /// Gets or sets the objection construction task installer. /// </summary> /// <value> /// The objection construction task installer. /// </value> public IWindsorInstaller ObjectionConstructionTaskInstaller { get; set; } /// <summary> /// Gets or sets the object saving task installer. /// </summary> /// <value> /// The object saving task installer. /// </value> public IWindsorInstaller ObjectSavingTaskInstaller { get; set; } /// <summary> /// Initializes a new instance of the <see cref="SitecoreInstaller"/> class. /// </summary> public SitecoreInstaller():this(new Config()) { } /// <summary> /// Initializes a new instance of the <see cref="SitecoreInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public SitecoreInstaller(Config config) { Config = config; DataMapperInstaller = new DataMapperInstaller(config); QueryParameterInstaller = new QueryParameterInstaller(config); DataMapperTaskInstaller = new DataMapperTaskInstaller(config); ConfigurationResolverTaskInstaller = new ConfigurationResolverTaskInstaller(config); ObjectionConstructionTaskInstaller = new ObjectionConstructionTaskInstaller(config); ObjectSavingTaskInstaller = new ObjectSavingTaskInstaller(config); } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { // For more on component registration read: http://docs.castleproject.org/Windsor.Registering-components-one-by-one.ashx container.Install( DataMapperInstaller, QueryParameterInstaller, DataMapperTaskInstaller, ConfigurationResolverTaskInstaller, ObjectionConstructionTaskInstaller, ObjectSavingTaskInstaller ); container.Register( Component.For<Glass.Mapper.Sc.Config>().Instance(Config) ); } } /// <summary> /// Installs the components descended from AbstractDataMapper. These are used to map data /// to and from the CMS. /// </summary> public class DataMapperInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="DataMapperInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public DataMapperInstaller(Config config) { Config = config; } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<AbstractDataMapper>().ImplementedBy<SitecoreIgnoreMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreChildrenCastMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreChildrenMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldBooleanMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldDateTimeMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldDecimalMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldDoubleMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldEnumMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldFileMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldFloatMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldGuidMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldHtmlEncodingMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldIEnumerableMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldImageMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldIntegerMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldLinkMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldLongMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNameValueCollectionMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldDictionaryMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableDateTimeMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableDoubleMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableDecimalMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableFloatMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableGuidMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldNullableIntMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldRulesMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldStreamMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldStringMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreFieldTypeMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreIdMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreItemMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreInfoMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreNodeMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreLinkedMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreParentMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreDelegateMapper>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreQueryMapper>() .DynamicParameters((k, d) => { d["parameters"] = k.ResolveAll<ISitecoreQueryParameter>(); }) .LifestyleCustom<NoTrackLifestyleManager>() ); } } /// <summary> /// Used by the SitecoreQueryMapper to replace placeholders in a query /// </summary> public class QueryParameterInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="QueryParameterInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public QueryParameterInstaller(Config config) { Config = config; } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<ISitecoreQueryParameter>().ImplementedBy<ItemDateNowParameter>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>().ImplementedBy<ItemEscapedPathParameter>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>().ImplementedBy<ItemIdNoBracketsParameter>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>().ImplementedBy<ItemIdParameter>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>().ImplementedBy<ItemPathParameter>().LifestyleCustom<NoTrackLifestyleManager>() ); } } /// <summary> /// Data Mapper Resolver Tasks - /// These tasks are run when Glass.Mapper tries to resolve which DataMapper should handle a given property, e.g. /// </summary> public class DataMapperTaskInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="DataMapperTaskInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public DataMapperTaskInstaller(Config config) { Config = config; } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { // Tasks are called in the order they are specified. container.Register( Component.For<IDataMapperResolverTask>() .ImplementedBy<DataMapperStandardResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>() ); } } /// <summary> /// Configuration Resolver Tasks - These tasks are run when Glass.Mapper tries to find the configuration the user has requested based on the type passsed. /// </summary> public class ConfigurationResolverTaskInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ConfigurationResolverTaskInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public ConfigurationResolverTaskInstaller(Config config) { Config = config; } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { // These tasks are run when Glass.Mapper tries to find the configuration the user has requested based on the type passed, e.g. // if your code contained // service.GetItem<MyClass>(id) // the standard resolver will return the MyClass configuration. // Tasks are called in the order they are specified below. container.Register( Component.For<IConfigurationResolverTask>() .ImplementedBy<SitecoreItemResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>() ); container.Register( Component.For<IConfigurationResolverTask>() .ImplementedBy<MultiInterfaceResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>() ); container.Register( Component.For<IConfigurationResolverTask>() .ImplementedBy<TemplateInferredTypeTask>() .LifestyleCustom<NoTrackLifestyleManager>() ); container.Register( Component.For<IConfigurationResolverTask>() .ImplementedBy<ConfigurationStandardResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>() ); container.Register( Component.For<IConfigurationResolverTask>() .ImplementedBy<ConfigurationOnDemandResolverTask<SitecoreTypeConfiguration>>() .LifestyleCustom<NoTrackLifestyleManager>() ); } } /// <summary> /// Object Construction Tasks - These tasks are run when an a class needs to be instantiated by Glass.Mapper. /// </summary> public class ObjectionConstructionTaskInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ObjectionConstructionTaskInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public ObjectionConstructionTaskInstaller(Config config) { Config = config; } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { //dynamic must be first container.Register( Component.For<IObjectConstructionTask>().ImplementedBy<CreateDynamicTask>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IObjectConstructionTask>().ImplementedBy<SitecoreItemTask>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IObjectConstructionTask>().ImplementedBy<EnforcedTemplateCheck>().LifestyleCustom<NoTrackLifestyleManager>() ); if (Config.UseWindsorContructor) { container.Register( Component.For<IObjectConstructionTask>().ImplementedBy<WindsorConstruction>().LifestyleCustom<NoTrackLifestyleManager>() ); } container.Register( // Tasks are called in the order they are specified below. Component.For<IObjectConstructionTask>().ImplementedBy<CreateMultiInferaceTask>().LifestyleTransient(), Component.For<IObjectConstructionTask>().ImplementedBy<CreateConcreteTask>().LifestyleTransient(), Component.For<IObjectConstructionTask>().ImplementedBy<CreateInterfaceTask>().LifestyleTransient() ); } } /// <summary> /// Object Saving Tasks - These tasks are run when an a class needs to be saved by Glass.Mapper. /// </summary> public class ObjectSavingTaskInstaller : IWindsorInstaller { /// <summary> /// Gets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ObjectSavingTaskInstaller"/> class. /// </summary> /// <param name="config">The config.</param> public ObjectSavingTaskInstaller(Config config) { Config = config; } /// <summary> /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer" />. /// </summary> /// <param name="container">The container.</param> /// <param name="store">The configuration store.</param> public virtual void Install(IWindsorContainer container, IConfigurationStore store) { // Tasks are called in the order they are specified below. container.Register( Component.For<IObjectSavingTask>().ImplementedBy<StandardSavingTask>().LifestyleCustom<NoTrackLifestyleManager>() ); } } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { [System.Runtime.InteropServices.GuidAttribute("268CA962-2FEF-3152-BA46-E18658B7FA4F")] [System.Runtime.InteropServices.ComVisible(true)] public enum JSError { //0 - 1000 legacy scripting errors, not JScript specific. NoError = 0, InvalidCall = 5, //"Invalid procedure call or argument" OutOfMemory = 7, // "Out of memory" TypeMismatch = 13, // "Type mismatch" OutOfStack = 28, // "Out of stack space" InternalError = 51, // "Internal error" FileNotFound = 53, // "File not found" NeedObject = 424, // "Object required" CantCreateObject = 429, // "Can't create object" OLENoPropOrMethod = 438, // "Object doesn't support this property or method" ActionNotSupported = 445, // "Object doesn't support this action" NotCollection = 451, // "Object not a collection" //1000 - 2000 JScript errors that occur during compilation only. (regard Eval and Function as compilation). Typically used only in HandleError. SyntaxError = 1002, // "Syntax error" NoColon = 1003, // "Expected ':'" NoSemicolon = 1004, // "Expected ';'" NoLeftParen = 1005, // "Expected '('" NoRightParen = 1006, // "Expected ')'" NoRightBracket = 1007, // "Expected ']'" NoLeftCurly = 1008, // "Expected '{'" NoRightCurly = 1009, // "Expected '}'" NoIdentifier = 1010, // "Expected identifier" NoEqual = 1011, // "Expected '='" IllegalChar = 1014, // "Invalid character" UnterminatedString = 1015, // "Unterminated string constant" NoCommentEnd = 1016, // "Unterminated comment" BadReturn = 1018, // "'return' statement outside of function" BadBreak = 1019, // "Can't have 'break' outside of loop" BadContinue = 1020, // "Can't have 'continue' outside of loop" BadHexDigit = 1023, // "Expected hexadecimal digit" NoWhile = 1024, // "Expected 'while'" BadLabel = 1025, // "Label redefined" NoLabel = 1026, // "Label not found" DupDefault = 1027, // "'default' can only appear once in a 'switch' statement" NoMemberIdentifier = 1028, // "Expected identifier or string" NoCcEnd = 1029, // "Expected '@end'" CcOff = 1030, // "Conditional compilation is turned off" NotConst = 1031, // "Expected constant" NoAt = 1032, // "Expected '@'" NoCatch = 1033, // "Expected 'catch'" InvalidElse = 1034, // "Unmatched 'else'; no 'if' defined" NoComma = 1100, // "Expected ','" DupVisibility = 1101, // "Visibility modifier already definied" IllegalVisibility = 1102, // "Illegal visibility modifier" BadSwitch = 1103, // "Missing 'case' or 'default' statement" CcInvalidEnd = 1104, // "Unmatched '@end'; no '@if' defined" CcInvalidElse = 1105, // "Unmatched '@else'; no '@if' defined" CcInvalidElif = 1106, // "Unmatched '@elif'; no '@if' defined" ErrEOF = 1107, // "Expecting more source characters" IncompatibleVisibility = 1108, // "Incompatible visibility modifier" ClassNotAllowed = 1109, //"Class definition not allowed in this context" NeedCompileTimeConstant = 1110, //"Expression must be a compile time constant" DuplicateName = 1111, // "Identifier already in use" NeedType = 1112, // "Type name expected" NotInsideClass = 1113, // "Only valid inside a class definition" InvalidPositionDirective = 1114, // "Unknown position directive" MustBeEOL = 1115, // "Directive may not be followed by other code on the same line" WrongDirective = 1118, CannotNestPositionDirective = 1119, // "Position directive must be ended before a new one can be started" CircularDefinition = 1120, // "Circular definition" Deprecated = 1121, // "Deprecated" IllegalUseOfThis = 1122, //"Illegal to use 'this' in current context" NotAccessible = 1123, // "Not accessible from this scope" CannotUseNameOfClass = 1124, //"Only a constructor function can have the same name as the class it appears in" MustImplementMethod = 1128, //"Class must provide implementation" NeedInterface = 1129, //"Interface name expected" UnreachableCatch = 1133, //"Catch clause will never be reached" TypeCannotBeExtended = 1134, //"Type cannot be extended" UndeclaredVariable = 1135, // "Variable has not been declared" VariableLeftUninitialized = 1136, // "Uninitialized variables are dangerous and slow to use. Did you intend to leave it uninitialized?" KeywordUsedAsIdentifier = 1137, // "'xxxx' is a new reserved word and should not be used as an identifier" NotAllowedInSuperConstructorCall = 1140, //"Not allowed in a call to the super class constructor" NotMeantToBeCalledDirectly = 1141, //"This method is not meant to be called directly. It is probably part of a property definition." GetAndSetAreInconsistent = 1142, //"The get and set methods of this property do not match each other" InvalidCustomAttribute = 1143, //"A custom attribute class must derive from System.Attribute" InvalidCustomAttributeArgument = 1144, //"Only primitive types are allowed in a custom attribute constructor arguments list" InvalidCustomAttributeClassOrCtor = 1146, //"Unknown custom attribute class or constructor" TooManyParameters = 1148, //"There are too many actual parameters. The excess parameters will be ignored." AmbiguousBindingBecauseOfWith = 1149, //"The with statement has made the use of this name ambiguous" AmbiguousBindingBecauseOfEval = 1150, //"The presence of eval has made the use of this name ambiguous" NoSuchMember = 1151, //"Object of this type do not have such a member" ItemNotAllowedOnExpandoClass = 1152, //"Cannot define the property Item on an Expando class. Item is reserved for the expando fields." MethodNotAllowedOnExpandoClass = 1153, //"Cannot define get_Item or set_Item on an Expando class. Methods reserved for the expando fields." MethodClashOnExpandoSuperClass = 1155, //"Base class defines get_Item or set_Item, cannot create expando class. Methods reserved for the expando fields." BaseClassIsExpandoAlready = 1156, //"A base class is already marked expando; current specification will be ignored." AbstractCannotBePrivate = 1157, //"An abstract method cannot be private" NotIndexable = 1158, //"Objects of this type are not indexable" StaticMissingInStaticInit = 1159, //"Static intializer must specify the 'static' keyword MissingConstructForAttributes = 1160, //"The list of attributes does not apply to the current context." OnlyClassesAllowed = 1161, //"Only classes are allowed inside a package." ExpandoClassShouldNotImpleEnumerable = 1162, //"Expando class should not implement IEnumerable or GetEnumerator. The interface is implicitely defined on expando classes" NonCLSCompliantMember = 1163, //"The specified member is not CLS compliant" NotDeletable = 1164, //"'xxxx' can not be deleted" PackageExpected = 1165, //"Package name expected" UselessExpression = 1169, //"Expression has no effect. Parentheses are required for function calls" HidesParentMember = 1170, // "Base class contains already a member by this name" CannotChangeVisibility = 1171, // "Cannot change visibility specification of a base method" HidesAbstractInBase = 1172, // "Method hides abstract in a base class" NewNotSpecifiedInMethodDeclaration = 1173, // "Method matches a method in a base class. Must specify 'override' or 'hide'" MethodInBaseIsNotVirtual = 1174, // "Method in base class is final or not virtual, 'override' ignored. Should specify 'hide'" NoMethodInBaseToNew = 1175, // "There is no member in a base class to 'hide'" DifferentReturnTypeFromBase = 1176, // "Method in base has a different return type" ClashWithProperty = 1177, // "Clashes with property" OverrideAndHideUsedTogether = 1178, // "Cannot use 'override' and 'hide' together in a member declaraton" InvalidLanguageOption = 1179, // "Must specify either 'fast' or 'versionSafe'" NoMethodInBaseToOverride = 1180, // "There is no member in a base class to 'override'" NotValidForConstructor = 1181, //"Not valid for a constructor" CannotReturnValueFromVoidFunction = 1182, //"Cannot return a value from a void function or constructor" AmbiguousMatch = 1183, //"More than one method or property matches this parameter list" AmbiguousConstructorCall = 1184, //"More than one constructor matches this parameter list" SuperClassConstructorNotAccessible = 1185, //"Superclass constructor is not accessible from this scope" OctalLiteralsAreDeprecated = 1186, //"Octal literals are deprecated" VariableMightBeUnitialized = 1187, //"Variable might not be initialized" NotOKToCallSuper = 1188, //"It is not valid to call a super constructor from this location" IllegalUseOfSuper = 1189, //"It is not valid to use the super keyword in this way BadWayToLeaveFinally = 1190, //"It is slow and potentially confusing to leave a finally block this way. Is this intentional?" NoCommaOrTypeDefinitionError = 1191, // "Expected ',' or illegal type declaration, write '<Identifier> : <Type>' not '<Type> <Identifier>'" AbstractWithBody = 1192, // "Abstract function cannot have body" NoRightParenOrComma = 1193, // "Expected ',' or ')'" NoRightBracketOrComma = 1194, // "Expected ',' or ']'" ExpressionExpected = 1195, // "Expected expression" UnexpectedSemicolon = 1196, // "Unexpected ';'" TooManyTokensSkipped = 1197, // "Too many tokens have been skipped in the process of recovering from errors. The file may not be a JScript file" BadVariableDeclaration = 1198, // "Possible illegal variable declaration, 'var' missing, or unrecognized syntax error" BadFunctionDeclaration = 1199, // "Possible illegal function declaration, 'function' missing, or unrecognized syntax error" BadPropertyDeclaration = 1200, // "Illegal properties declaration. The getter must not have arguments and the setter must have one argument" DoesNotHaveAnAddress = 1203, //"Expression does not have an address" TooFewParameters = 1204, //"Not all required parameters have been supplied" UselessAssignment = 1205, //"Assignment creates an expando property that is immediately thrown away" SuspectAssignment = 1206, //"Did you intend to write an assignment here?" SuspectSemicolon = 1207, //"Did you intend to have an empty statement for this branch of the if statement?" ImpossibleConversion = 1208, //"The specified conversion or coercion is not possible" FinalPrecludesAbstract = 1209, //"final and abstract cannot be used together" NeedInstance = 1210, //"Must be an instance" CannotBeAbstract = 1212, //"Cannot be abstract unless class is marked as abstract" InvalidBaseTypeForEnum = 1213, //"Enum base type must be a primitive integral type" CannotInstantiateAbstractClass = 1214, //"It is not possible to construct an instance of an abstract class" ArrayMayBeCopied = 1215, //"Assigning a JScript Array to a System.Array may cause the array to be copied." AbstractCannotBeStatic = 1216, //"Static methods cannot be abstract" StaticIsAlreadyFinal = 1217, //"Static methods cannot be final" StaticMethodsCannotOverride = 1218, //"Static methods cannot override base class methods" StaticMethodsCannotHide = 1219, //"Static methods cannot hide base class methods" ExpandoPrecludesOverride = 1220, //"Expando methods cannot override base class methods" IllegalParamArrayAttribute = 1221, //"A variable argument list must be of an array type" ExpandoPrecludesAbstract = 1222, //"Expando methods cannot be abstract" ShouldBeAbstract = 1223, // "A function without a body should be abstract" BadModifierInInterface = 1224, // "This modifier cannot be used on an interface member" VarIllegalInInterface = 1226, //"Variables cannot be declared in an interface" InterfaceIllegalInInterface = 1227, //"Interfaces cannot be declared in an interface" NoVarInEnum = 1228, //"Enum member declarations should not use the 'var' keyword" InvalidImport = 1229, //"The import statement is not valid in this context" EnumNotAllowed = 1230, //"Enum definition not allowed in this context" InvalidCustomAttributeTarget = 1231, //"Attribute not valid for this type of declaration" PackageInWrongContext = 1232, //"Package definition is not allowed in this context" ConstructorMayNotHaveReturnType = 1233, //"A constructor function may not have a return type" OnlyClassesAndPackagesAllowed = 1234, //"Only classes and packages are allowed inside a library" InvalidDebugDirective = 1235, // "Invalid debug directive" CustomAttributeUsedMoreThanOnce = 1236, //"This type of attribute must be unique" NestedInstanceTypeCannotBeExtendedByStatic = 1237, //"A non-static nested type can only be extended by non-static type nested in the same class" PropertyLevelAttributesMustBeOnGetter = 1238, //"An attribute that targets the property must be specified on the property getter, if present" BadThrow = 1239, //"A throw must have an argument when not inside the catch block of a try statement ParamListNotLast = 1240, //"A variable argument list must be the last argument NoSuchType = 1241, //"Type could not be found, is an assembly reference missing? BadOctalLiteral = 1242, //"Malformed octal literal treated as decimal literal" InstanceNotAccessibleFromStatic = 1243, //"A non-static member is not accessible from a static scope" StaticRequiresTypeName = 1244, //"A static member must be accessed with the class name" NonStaticWithTypeName = 1245, //"A non-static member cannot be accessed with the class name" NoSuchStaticMember = 1246, //"Type does not have such a static member" SuspectLoopCondition = 1247, //"The loop condition is a function reference. Did you intend to call the function?" ExpectedAssembly = 1248, //"Expected assembly" AssemblyAttributesMustBeGlobal = 1249, //Assembly custom attributes may not be part of another construct ExpandoPrecludesStatic = 1250, //"Expando methods cannot be static" DuplicateMethod = 1251, //"This method has the same name, parameter types and return type as another method in this class" NotAnExpandoFunction = 1252, //"Class members used as constructors should be marked as expando functions" NotValidVersionString = 1253, //"Not a valid version string" ExecutablesCannotBeLocalized = 1254, //Executables cannot be localized, Culture should always be empty StringConcatIsSlow = 1255, CcInvalidInDebugger = 1256, //"Conditional compilation directives and variables cannot be used in the debugger" ExpandoMustBePublic = 1257, //Expando methods must be public DelegatesShouldNotBeExplicitlyConstructed = 1258, //Delegates should not be explicitly constructed, simply use the method name ImplicitlyReferencedAssemblyNotFound = 1259, //"A referenced assembly depends on another assembly that is not referenced or could not be found" PossibleBadConversion = 1260, //"This conversion may fail at runtime" PossibleBadConversionFromString = 1261, //"Converting a string to a number or boolean is slow and may fail at runtime" InvalidResource = 1262, //"Not a valid .resources file" WrongUseOfAddressOf = 1263, //"The address of operator can only be used in a list of arguments" NonCLSCompliantType = 1264, //"The specified type is not CLS compliant" MemberTypeCLSCompliantMismatch = 1265, //"Class member cannot be marked CLS compliant because the class is not marked as CLS compliant" TypeAssemblyCLSCompliantMismatch = 1266, //"Type cannot be marked CLS compliant because the assembly is not marked as CLS compliant" IncompatibleAssemblyReference = 1267, //"Referenced assembly targets a different processor" InvalidAssemblyKeyFile = 1268, //"Assembly key file not found or contains invalid data" TypeNameTooLong = 1269, //"Fully qualified type name must be less than 1024 characters" MemberInitializerCannotContainFuncExpr = 1270, //"A class member initializer cannot contain a function expression" //5000 - 6000 JScript errors that can occur during execution. Typically (also) used in "throw new JScriptException". CantAssignThis = 5000, // "Cannot assign to 'this'" NumberExpected = 5001, // "Number expected" FunctionExpected = 5002, // "Function expected" CannotAssignToFunctionResult = 5003, // "Cannot assign to a function result" StringExpected = 5005, // "String expected" DateExpected = 5006, // "Date object expected" ObjectExpected = 5007, // "Object expected" IllegalAssignment = 5008, // "Illegal assignment" UndefinedIdentifier = 5009, // "Undefined identifier" BooleanExpected = 5010, // "Boolean expected" VBArrayExpected = 5013, // "VBArray expected" EnumeratorExpected = 5015, // "Enumerator object expected" RegExpExpected = 5016, // "Regular Expression object expected" RegExpSyntax = 5017, // "Syntax error in regular expression" UncaughtException = 5022, // "Exception thrown and not caught" InvalidPrototype = 5023, // "Function does not have a valid prototype object" URIEncodeError = 5024, //"The URI to be encoded contains an invalid character" URIDecodeError = 5025, //"The URI to be decoded is not a valid encoding" FractionOutOfRange = 5026, //"The number of fractional digits is out of range" PrecisionOutOfRange = 5027, //"The precision is out of range" ArrayLengthConstructIncorrect = 5029, //"Array length must be a finite positive integer" ArrayLengthAssignIncorrect = 5030, //"Array length must be assigned a finite positive number" NeedArrayObject = 5031, //"| is not an Array object", "Array object expected" NoConstructor = 5032, // "No such constructor" IllegalEval = 5033, // "Eval may not be called via an alias" NotYetImplemented = 5034, // "Not yet implemented" MustProvideNameForNamedParameter = 5035, // "Cannot provide null or empty named parameter name" DuplicateNamedParameter = 5036, // "Duplicate named parameter name" MissingNameParameter = 5037, // "The specified named parameter name it is not one of the formal parameters" MoreNamedParametersThanArguments = 5038, // "Too few arguments specified. The number of named parameters names cannot exceed the number of arguments passed in." NonSupportedInDebugger = 5039, //"The expression cannot be evaluated in the debugger" AssignmentToReadOnly = 5040, //"Assignment to read-only field or property" WriteOnlyProperty = 5041, //"The property can only be assigned to" IncorrectNumberOfIndices = 5042, //"The number of indices does not match the dimension of the array" RefParamsNonSupportedInDebugger = 5043, //"Methods with ref parameters cannot be called in the debugger" CannotCallSecurityMethodLateBound = 5044, //"The Deny, PermitOnly and Assert security methods cannot be called using late binding" CannotUseStaticSecurityAttribute = 5045, //"JScript does not support static security attributes" NonClsException = 5046, //"A target threw a non-CLS exception" // 6000 - 7000 Errors which are only given by the JScript debugger FuncEvalAborted = 6000, //"Function evaluation was aborted" FuncEvalTimedout = 6001, //"Function evaluation timed out" FuncEvalThreadSuspended = 6002, //"Function evaluation failed : the thread is suspended" FuncEvalThreadSleepWaitJoin = 6003, //"Function evaluation failed : the thread is sleeping, waiting on an object, or waiting for another thread to finish" FuncEvalBadThreadState = 6004, //"Function evaluation failed : the thread is in a bad state" FuncEvalBadThreadNotStarted = 6005, //"Function evaluation failed : the thread has not started" NoFuncEvalAllowed = 6006, //"Function evaluation aborted. To turn property evaluation on goto Tools - Options - Debugging" FuncEvalBadLocation = 6007, //"Function evaluation cannot be be done when stopped at this point in the program" FuncEvalWebMethod = 6008, //"Cannot call a web method in the debugger" StaticVarNotAvailable = 6009, //"Static variable is not available" TypeObjectNotAvailable = 6010, //"The type object for this type is not available" ExceptionFromHResult = 6011, //"Exception from HRESULT : SideEffectsDisallowed = 6012, //"This expression causes side effects and will not be evaluated" } }
// 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 { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EventInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class EventInfo : MemberInfo, _EventInfo { #region Constructor protected EventInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(EventInfo left, EventInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeEventInfo || right is RuntimeEventInfo) { return false; } return left.Equals(right); } public static bool operator !=(EventInfo left, EventInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } #endregion #region Public Abstract\Virtual Members public virtual MethodInfo[] GetOtherMethods(bool nonPublic) { throw new NotImplementedException(); } public abstract MethodInfo GetAddMethod(bool nonPublic); public abstract MethodInfo GetRemoveMethod(bool nonPublic); public abstract MethodInfo GetRaiseMethod(bool nonPublic); public abstract EventAttributes Attributes { get; } #endregion #region Public Members public virtual MethodInfo AddMethod { get { return GetAddMethod(true); } } public virtual MethodInfo RemoveMethod { get { return GetRemoveMethod(true); } } public virtual MethodInfo RaiseMethod { get { return GetRaiseMethod(true); } } public MethodInfo[] GetOtherMethods() { return GetOtherMethods(false); } public MethodInfo GetAddMethod() { return GetAddMethod(false); } public MethodInfo GetRemoveMethod() { return GetRemoveMethod(false); } public MethodInfo GetRaiseMethod() { return GetRaiseMethod(false); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void AddEventHandler(Object target, Delegate handler) { MethodInfo addMethod = GetAddMethod(); if (addMethod == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); #if FEATURE_COMINTEROP if (addMethod.ReturnType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event Contract.Assert(addMethod.ReturnType == typeof(void)); #endif // FEATURE_COMINTEROP addMethod.Invoke(target, new object[] { handler }); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void RemoveEventHandler(Object target, Delegate handler) { MethodInfo removeMethod = GetRemoveMethod(); if (removeMethod == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicRemoveMethod")); #if FEATURE_COMINTEROP ParameterInfo[] parameters = removeMethod.GetParametersNoCopy(); Contract.Assert(parameters != null && parameters.Length == 1); if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); #endif // FEATURE_COMINTEROP removeMethod.Invoke(target, new object[] { handler }); } public virtual Type EventHandlerType { get { MethodInfo m = GetAddMethod(true); ParameterInfo[] p = m.GetParametersNoCopy(); Type del = typeof(Delegate); for (int i = 0; i < p.Length; i++) { Type c = p[i].ParameterType; if (c.IsSubclassOf(del)) return c; } return null; } } public bool IsSpecialName { get { return(Attributes & EventAttributes.SpecialName) != 0; } } public virtual bool IsMulticast { get { Type cl = EventHandlerType; Type mc = typeof(MulticastDelegate); return mc.IsAssignableFrom(cl); } } #endregion #if !FEATURE_CORECLR Type _EventInfo.GetType() { return base.GetType(); } void _EventInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and // include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable { #region Private Data Members private int m_token; private EventAttributes m_flags; private string m_name; [System.Security.SecurityCritical] private void* m_utf8name; private RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_addMethod; private RuntimeMethodInfo m_removeMethod; private RuntimeMethodInfo m_raiseMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; #endregion #region Constructor internal RuntimeEventInfo() { // Used for dummy head node during population } [System.Security.SecurityCritical] // auto-generated internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); Contract.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; m_token = tkEvent; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType(); scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); RuntimeMethodInfo dummy; Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, out m_addMethod, out m_removeMethod, out m_raiseMethod, out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeEventInfo m = o as RuntimeEventInfo; if ((object)m == null) return false; return m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } #endregion #region Object Overrides public override String ToString() { if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = new Utf8String(m_utf8name).ToString(); return m_name; } } public override Type DeclaringType { get { return m_declaringType; } } public override Type ReflectedType { get { return ReflectedTypeInternal; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } public override int MetadataToken { get { return m_token; } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region ISerializable [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, null, MemberTypes.Event); } #endregion #region EventInfo Overrides public override MethodInfo[] GetOtherMethods(bool nonPublic) { List<MethodInfo> ret = new List<MethodInfo>(); if ((object)m_otherMethod == null) return new MethodInfo[0]; for(int i = 0; i < m_otherMethod.Length; i ++) { if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic)) ret.Add(m_otherMethod[i]); } return ret.ToArray(); } public override MethodInfo GetAddMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) return null; return m_addMethod; } public override MethodInfo GetRemoveMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) return null; return m_removeMethod; } public override MethodInfo GetRaiseMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) return null; return m_raiseMethod; } public override EventAttributes Attributes { get { return m_flags; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxFactsService : ISyntaxFactsService { public bool IsAwaitKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.AwaitKeyword); } public bool IsIdentifier(SyntaxToken token) { return token.IsKind(SyntaxKind.IdentifierToken); } public bool IsGlobalNamespaceKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.GlobalKeyword); } public bool IsVerbatimIdentifier(SyntaxToken token) { return token.IsVerbatimIdentifier(); } public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords } public bool IsContextualKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsContextualKeyword(kind); } public bool IsPreprocessorKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsPreprocessorKeyword(kind); } public bool IsHashToken(SyntaxToken token) { return (SyntaxKind)token.RawKind == SyntaxKind.HashToken; } public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInNonUserCode(position, cancellationToken); } public bool IsEntirelyWithinStringOrCharOrNumericLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective(SyntaxNode node) { return node is DirectiveTriviaSyntax; } public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info) { var lineDirective = node as LineDirectiveTriviaSyntax; if (lineDirective != null) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default(ExternalSourceInfo); return false; } public bool IsRightSideOfQualifiedName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsMemberAccessExpressionName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsMemberAccessExpressionName(); } public bool IsObjectCreationExpressionType(SyntaxNode node) { return node.IsParentKind(SyntaxKind.ObjectCreationExpression) && ((ObjectCreationExpressionSyntax)node.Parent).Type == node; } public bool IsAttributeName(SyntaxNode node) { return SyntaxFacts.IsAttributeName(node); } public bool IsInvocationExpression(SyntaxNode node) { return node is InvocationExpressionSyntax; } public bool IsAnonymousFunction(SyntaxNode node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsGenericName(SyntaxNode node) { return node is GenericNameSyntax; } public bool IsNamedParameter(SyntaxNode node) { return node.CheckParent<NameColonSyntax>(p => p.Name == node); } public bool IsSkippedTokensTrivia(SyntaxNode node) { return node is SkippedTokensTriviaSyntax; } public bool HasIncompleteParentMember(SyntaxNode node) { return node.IsParentKind(SyntaxKind.IncompleteMember); } public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName) { var csharpGenericName = genericName as GenericNameSyntax; return csharpGenericName != null ? csharpGenericName.Identifier : default(SyntaxToken); } public bool IsCaseSensitive { get { return true; } } public bool IsUsingDirectiveName(SyntaxNode node) { return node.IsParentKind(SyntaxKind.UsingDirective) && ((UsingDirectiveSyntax)node.Parent).Name == node; } public bool IsForEachStatement(SyntaxNode node) { return node is ForEachStatementSyntax; } public bool IsLockStatement(SyntaxNode node) { return node is LockStatementSyntax; } public bool IsUsingStatement(SyntaxNode node) { return node is UsingStatementSyntax; } public bool IsThisConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsBaseConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsQueryExpression(SyntaxNode node) { return node is QueryExpressionSyntax; } public bool IsPredefinedType(SyntaxToken token) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None; } public bool IsPredefinedType(SyntaxToken token, PredefinedType type) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType == type; } public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private PredefinedType GetPredefinedType(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.BoolKeyword: return PredefinedType.Boolean; case SyntaxKind.ByteKeyword: return PredefinedType.Byte; case SyntaxKind.SByteKeyword: return PredefinedType.SByte; case SyntaxKind.IntKeyword: return PredefinedType.Int32; case SyntaxKind.UIntKeyword: return PredefinedType.UInt32; case SyntaxKind.ShortKeyword: return PredefinedType.Int16; case SyntaxKind.UShortKeyword: return PredefinedType.UInt16; case SyntaxKind.LongKeyword: return PredefinedType.Int64; case SyntaxKind.ULongKeyword: return PredefinedType.UInt64; case SyntaxKind.FloatKeyword: return PredefinedType.Single; case SyntaxKind.DoubleKeyword: return PredefinedType.Double; case SyntaxKind.DecimalKeyword: return PredefinedType.Decimal; case SyntaxKind.StringKeyword: return PredefinedType.String; case SyntaxKind.CharKeyword: return PredefinedType.Char; case SyntaxKind.ObjectKeyword: return PredefinedType.Object; case SyntaxKind.VoidKeyword: return PredefinedType.Void; default: return PredefinedType.None; } } public bool IsPredefinedOperator(SyntaxToken token) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None; } public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op; } public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) { return SyntaxFacts.GetText((SyntaxKind)kind); } public bool IsIdentifierStartCharacter(char c) { return SyntaxFacts.IsIdentifierStartCharacter(c); } public bool IsIdentifierPartCharacter(char c) { return SyntaxFacts.IsIdentifierPartCharacter(c); } public bool IsIdentifierEscapeCharacter(char c) { return c == '@'; } public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) { return false; } public bool IsStartOfUnicodeEscapeSequence(char c) { return c == '\\'; } public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; } return false; } public bool IsStringLiteral(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); } public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration)) { declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration)) { declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent) { var typedParent = parent as ExpressionSyntax; if (typedParent != null) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } return false; } public bool IsMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression; } public bool IsConditionalMemberAccessExpression(SyntaxNode node) { return node is ConditionalAccessExpressionSyntax; } public bool IsPointerMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression; } public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { name = null; arity = 0; var simpleName = node as SimpleNameSyntax; if (simpleName != null) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node) { return node.IsKind(SyntaxKind.MemberBindingExpression) ? GetExpressionOfConditionalMemberAccessExpression(node.GetParentConditionalAccessExpression()) : (node as MemberAccessExpressionSyntax)?.Expression; } public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node) { return (node as ConditionalAccessExpressionSyntax)?.Expression; } public bool IsInStaticContext(SyntaxNode node) { return node.IsInStaticContext(); } public bool IsInNamespaceOrTypeContext(SyntaxNode node) { return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); } public SyntaxNode GetExpressionOfArgument(SyntaxNode node) { return ((ArgumentSyntax)node).Expression; } public RefKind GetRefKindOfArgument(SyntaxNode node) { return (node as ArgumentSyntax).GetRefKind(); } public bool IsInConstantContext(SyntaxNode node) { return (node as ExpressionSyntax).IsInConstantContext(); } public bool IsInConstructor(SyntaxNode node) { return node.GetAncestor<ConstructorDeclarationSyntax>() != null; } public bool IsUnsafeContext(SyntaxNode node) { return node.IsUnsafeContext(); } public SyntaxNode GetNameOfAttribute(SyntaxNode node) { return ((AttributeSyntax)node).Name; } public bool IsAttribute(SyntaxNode node) { return node is AttributeSyntax; } public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsParentKind(SyntaxKind.NameEquals) && identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument); } public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node) { throw ExceptionUtilities.Unreachable; } public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsObjectCreationExpression(SyntaxNode node) { return node is ObjectCreationExpressionSyntax; } public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsLeftSideOfAssignExpression() && identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression); } public bool IsElementAccessExpression(SyntaxNode node) { return node.Kind() == SyntaxKind.ElementAccessExpression; } public SyntaxNode ConvertToSingleLine(SyntaxNode node) { return node.ConvertToSingleLine(); } public SyntaxToken ToIdentifierToken(string name) { return name.ToIdentifierToken(); } public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia) { return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia); } public bool IsIndexerMemberCRef(SyntaxNode node) { return node.Kind() == SyntaxKind.IndexerMemberCref; } public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember(SyntaxNode node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers(SyntaxNode node) { return node is NamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span); return true; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ctorDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Constructor, ctorDecl.Identifier.Span, parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span); return true; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span); return true; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span); return true; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span); return true; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span); return true; case SyntaxKind.InterfaceDeclaration: var interfaceDecl = (InterfaceDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span); return true; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Method, method.Identifier.Span, parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0), typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Property, property.Identifier.Span); return true; case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span); return true; case SyntaxKind.VariableDeclarator: // could either be part of a field declaration or an event field declaration var variableDeclarator = (VariableDeclaratorSyntax)node; var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax; var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax; if (fieldDeclaration != null) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText, GetContainerDisplayName(fieldDeclaration.Parent), GetFullyQualifiedContainerName(fieldDeclaration.Parent), kind, variableDeclarator.Identifier.Span); return true; } break; } declaredSymbolInfo = default(DeclaredSymbolInfo); return false; } private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier) { if (explicitInterfaceSpecifier == null) { return identifier; } else { var builder = new StringBuilder(); ExpandTypeName(explicitInterfaceSpecifier.Name, builder); builder.Append('.'); builder.Append(identifier); return builder.ToString(); } } private static void ExpandTypeName(TypeSyntax type, StringBuilder builder) { switch (type.Kind()) { case SyntaxKind.AliasQualifiedName: var alias = (AliasQualifiedNameSyntax)type; builder.Append(alias.Alias.Identifier.ValueText); break; case SyntaxKind.ArrayType: var array = (ArrayTypeSyntax)type; ExpandTypeName(array.ElementType, builder); for (int i = 0; i < array.RankSpecifiers.Count; i++) { var rankSpecifier = array.RankSpecifiers[i]; builder.Append(rankSpecifier.OpenBracketToken.Text); for (int j = 1; j < rankSpecifier.Sizes.Count; j++) { builder.Append(','); } builder.Append(rankSpecifier.CloseBracketToken.Text); } break; case SyntaxKind.GenericName: var generic = (GenericNameSyntax)type; builder.Append(generic.Identifier.ValueText); if (generic.TypeArgumentList != null) { var arguments = generic.TypeArgumentList.Arguments; builder.Append(generic.TypeArgumentList.LessThanToken.Text); for (int i = 0; i < arguments.Count; i++) { if (i != 0) { builder.Append(','); } ExpandTypeName(arguments[i], builder); } builder.Append(generic.TypeArgumentList.GreaterThanToken.Text); } break; case SyntaxKind.IdentifierName: var identifierName = (IdentifierNameSyntax)type; builder.Append(identifierName.Identifier.ValueText); break; case SyntaxKind.NullableType: var nullable = (NullableTypeSyntax)type; ExpandTypeName(nullable.ElementType, builder); builder.Append(nullable.QuestionToken.Text); break; case SyntaxKind.OmittedTypeArgument: // do nothing since it was omitted, but don't reach the default block break; case SyntaxKind.PointerType: var pointer = (PointerTypeSyntax)type; ExpandTypeName(pointer.ElementType, builder); builder.Append(pointer.AsteriskToken.Text); break; case SyntaxKind.PredefinedType: var predefined = (PredefinedTypeSyntax)type; builder.Append(predefined.Keyword.Text); break; case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)type; ExpandTypeName(qualified.Left, builder); builder.Append(qualified.DotToken.Text); ExpandTypeName(qualified.Right, builder); break; default: Debug.Assert(false, "Unexpected type syntax " + type.Kind()); break; } } private string GetContainerDisplayName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); } private string GetFullyQualifiedContainerName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); } private const string dotToken = "."; public string GetDisplayName(SyntaxNode node, DisplayNameOptions options, string rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: return GetName(((NamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string name = null; var memberDeclaration = node as MemberDeclarationSyntax; if (memberDeclaration != null) { var nameToken = memberDeclaration.GetNameToken(); if (nameToken == default(SyntaxToken)) { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration); name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } } else { var fieldDeclarator = node as VariableDeclaratorSyntax; if (fieldDeclarator != null) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default(SyntaxToken)) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (int i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root) { var list = new List<SyntaxNode>(); AppendMethodLevelMembers(root, list); return list; } private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { AppendMethodLevelMembers(member, list); continue; } if (IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default(TextSpan); } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default(TextSpan); } // TODO: currently we only support method for now var method = member as BaseMethodDeclarationSyntax; if (method != null) { if (method.Body == null) { return default(TextSpan); } return GetBlockBodySpan(method.Body); } return default(TextSpan); } public bool ContainsInMemberBody(SyntaxNode node, TextSpan span) { var constructor = node as ConstructorDeclarationSyntax; if (constructor != null) { return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); } var method = node as BaseMethodDeclarationSyntax; if (method != null) { return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); } var property = node as BasePropertyDeclarationSyntax; if (property != null) { return property.AccessorList != null && property.AccessorList.Span.Contains(span); } var @enum = node as EnumMemberDeclarationSyntax; if (@enum != null) { return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); } var field = node as BaseFieldDeclarationSyntax; if (field != null) { return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private TextSpan GetBlockBodySpan(BlockSyntax body) { return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); } public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node) { Contract.Requires(root.SyntaxTree == node.SyntaxTree); int currentId = 0; SyntaxNode currentNode; Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode)); Contract.ThrowIfFalse(currentId >= 0); CheckMemberId(root, node, currentId); return currentId; } public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId) { int currentId = 0; SyntaxNode currentNode; if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode)) { return null; } Contract.ThrowIfNull(currentNode); CheckMemberId(root, currentNode, memberId); return currentNode; } private bool TryGetMethodLevelMember( SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode)) { return true; } continue; } if (IsMethodLevelMember(member)) { if (predicate(member, currentId)) { currentNode = member; return true; } currentId++; } } currentNode = null; return false; } [Conditional("DEBUG")] private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId) { var list = GetMethodLevelMembers(root); var index = list.IndexOf(node); Contract.ThrowIfFalse(index == memberId); } public SyntaxNode GetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. var qualifiedName = parent as QualifiedNameSyntax; if (qualifiedName != null) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. var aliasQualifiedName = parent as AliasQualifiedNameSyntax; if (aliasQualifiedName != null) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. var objectCreation = parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. var name = parent as NameSyntax; if (name == null) { break; } node = parent; } return node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken) { var compilationUnit = root as CompilationUnitSyntax; if (compilationUnit == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); var constructor = member as ConstructorDeclarationSyntax; if (constructor != null) { constructors.Add(constructor); continue; } var @namespace = member as NamespaceDeclarationSyntax; if (@namespace != null) { AppendConstructors(@namespace.Members, constructors, cancellationToken); } var @class = member as ClassDeclarationSyntax; if (@class != null) { AppendConstructors(@class.Members, constructors, cancellationToken); } var @struct = member as StructDeclarationSyntax; if (@struct != null) { AppendConstructors(@struct.Members, constructors, cancellationToken); } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.Item1; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default(SyntaxToken); return false; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Common.Policies; using Gallio.Common.Concurrency; using Gallio.Model; using Gallio.Common.Diagnostics; using Gallio.Common.Markup; namespace Gallio.Framework { /// <summary> /// A sandbox is an isolated environments for executing test actions. /// </summary> /// <remarks> /// <para> /// It provides the ability to abort actions in progress so that the test runner can proceed /// to run other actions. /// </para> /// <para> /// Sandboxes are hierarchically structured. When an outer sandbox is aborted, all /// of its inner sandboxes are likewise aborted. A sandbox also provides the ability /// to create new child sandboxes at will so that test actions can be isolated with /// fine granularity. /// </para> /// <para> /// This class is safe for use from multiple concurrent threads. /// </para> /// </remarks> [SystemInternal] public sealed class Sandbox : IDisposable { private Sandbox parent; private readonly object syncRoot = new object(); private List<Pair<ThreadAbortScope, Thread>> scopesAndThreads; private TestOutcome? abortOutcome; private string abortMessage; private event EventHandler aborted; private bool alreadyLoggedAbortOnce; private bool isDisposed; /// <summary> /// Creates a root sandbox. /// </summary> public Sandbox() { } /// <summary> /// An event that is dispatched when <see cref="Abort(TestOutcome, string)" /> is called. /// </summary> /// <remarks> /// <para> /// If the sandbox has already been aborted then the event handler is immediately invoked. /// </para> /// </remarks> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> public event EventHandler Aborted { add { lock (syncRoot) { ThrowIfDisposed(); if (!abortOutcome.HasValue) { aborted += value; return; } } EventHandlerPolicy.SafeInvoke(value, this, EventArgs.Empty); } remove { lock (syncRoot) { ThrowIfDisposed(); aborted -= value; } } } /// <summary> /// Returns <c>true</c> if <see cref="Abort(TestOutcome, string)" /> was called. /// </summary> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> public bool WasAborted { get { lock (syncRoot) { ThrowIfDisposed(); return abortOutcome.HasValue; } } } /// <summary> /// Returns the <see cref="TestOutcome" /> passed to <see cref="Abort(TestOutcome, string)" />, /// or null if <see cref="Abort(TestOutcome, string)" /> has not been called. /// </summary> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> public TestOutcome? AbortOutcome { get { lock (syncRoot) { ThrowIfDisposed(); return abortOutcome; } } } /// <summary> /// Gets a message that will be logged when the sandbox is aborted, or null if none. /// </summary> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> public string AbortMessage { get { lock (syncRoot) { ThrowIfDisposed(); return abortMessage; } } } /// <summary> /// Disposes the sandbox. /// </summary> /// <remarks> /// <para> /// All currently executing actions are aborted with <see cref="TestOutcome.Error" /> /// if <see cref="Abort(TestOutcome, string)" /> has not already been called. /// </para> /// </remarks> public void Dispose() { Abort(TestOutcome.Error, "The sandbox was disposed.", false); Sandbox cachedParent; lock (syncRoot) { if (isDisposed) return; cachedParent = parent; parent = null; isDisposed = true; } if (cachedParent != null) cachedParent.Aborted -= HandleParentAborted; } /// <summary> /// Creates a child sandbox. /// </summary> /// <remarks> /// <para> /// When the parent sandbox is aborted, the child will likewise be aborted. This policy /// offers a mechanism to scope actions recursively. /// </para> /// </remarks> /// <returns>The child sandbox.</returns> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> public Sandbox CreateChild() { ThrowIfDisposed(); Sandbox child = new Sandbox(); child.parent = this; Aborted += child.HandleParentAborted; return child; } /// <summary> /// Aborts all actions in progress within this context. /// </summary> /// <remarks> /// <para> /// The abort is persistent and cannot be reverted. Therefore once aborted, no further /// test actions will be permitted to run. Subsequent calls to <see cref="Abort(TestOutcome, string)" /> /// will have no effect. /// </para> /// </remarks> /// <param name="outcome">The outcome to be returned from aborted actions.</param> /// <param name="message">A message to be logged when the action is aborted, or null if none.</param> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> public void Abort(TestOutcome outcome, string message) { Abort(outcome, message, true); } private void Abort(TestOutcome outcome, string message, bool throwIfDisposed) { EventHandler cachedHandler; ThreadAbortScope[] cachedScopes; lock (syncRoot) { if (throwIfDisposed) ThrowIfDisposed(); if (abortOutcome.HasValue) return; abortOutcome = outcome; abortMessage = message; cachedScopes = scopesAndThreads != null ? GenericCollectionUtils.ConvertAllToArray(scopesAndThreads, pair => pair.First) : null; scopesAndThreads = null; cachedHandler = aborted; aborted = null; } if (cachedScopes != null) { foreach (ThreadAbortScope scope in cachedScopes) scope.Abort(); } EventHandlerPolicy.SafeInvoke(cachedHandler, this, EventArgs.Empty); } /// <summary> /// Uses a specified timeout for all actions run within a block of code. /// When the timeout expires, the sandbox will be aborted. /// </summary> /// <example> /// <![CDATA[ /// using (sandbox.UseTimeout(TimeSpan.FromSeconds(5)) /// { /// // do abortable code /// } /// ]]> /// </example> /// <param name="timeout">The execution timeout or null if none.</param> /// <returns>An object that when disposed ends the timeout block, possibly null if there was no timeout.</returns> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="timeout"/> is negative.</exception> public IDisposable StartTimer(TimeSpan? timeout) { if (timeout.HasValue && timeout.Value.Ticks < 0) throw new ArgumentOutOfRangeException("timeout", "Timeout must not be negative."); ThrowIfDisposed(); if (!timeout.HasValue) return null; return new Timer(delegate { Abort(TestOutcome.Timeout, String.Format("The test timed out after {0} seconds.", timeout.Value.TotalSeconds), false); }, null, (int)timeout.Value.TotalMilliseconds, Timeout.Infinite); } /// <summary> /// Runs a test action. /// </summary> /// <remarks> /// <para> /// If the action throws an exception or if the test action is aborted, then logs a /// message to the <paramref name="markupDocumentWriter"/>. Exceptions of type <see cref="TestException" /> /// are handled specially since they may modify the effective outcome of the run. /// If <see cref="TestException.ExcludeStackTrace" /> is <c>true</c> and <see cref="TestException.HasNonDefaultMessage" /> /// is <c>false</c> then the exception is effectively silent. Therefore the action can modify /// its outcome and cause messages to be logged by throwing a suitable exception such as /// <see cref="TestException"/> or <see cref="SilentTestException" />. /// </para> /// <para> /// If the <see cref="Abort(TestOutcome, string)" /> method is called or has already been called, the action /// is aborted and the appropriate outcome is returned. The abort is manifested as an /// asynchronous <see cref="ThreadAbortException" /> which should cause the action to /// terminate. It may not terminate immediately, however. /// </para> /// <para> /// Produces an outcome in the following manner: /// <list type="bullet"> /// <item>If the action completed without throwing an exception returns <see cref="TestOutcome.Passed"/>.</item> /// <item>If the action threw a <see cref="TestException" />, returns the value of the /// <see cref="TestException.Outcome" /> property.</item> /// <item>If the action threw an different kind of exception, logs /// the exception and returns <see cref="TestOutcome.Failed"/>.</item> /// <item>If the action was aborted, returns <see cref="AbortOutcome" />.</item> /// <item>If the action timed out, returns <see cref="TestOutcome.Timeout" />.</item> /// </list> /// </para> /// </remarks> /// <param name="markupDocumentWriter">The log writer for reporting failures.</param> /// <param name="action">The action to run.</param> /// <param name="description">A description of the action being performed, /// to be used as a log section name when reporting failures, or null if none.</param> /// <returns>The outcome of the action.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="markupDocumentWriter"/> or <paramref name="action"/> is null.</exception> /// <exception cref="ObjectDisposedException">Thrown if the sandbox was disposed.</exception> [DebuggerHidden, DebuggerStepThrough] public TestOutcome Run(MarkupDocumentWriter markupDocumentWriter, Action action, string description) { // NOTE: This method has been optimized to minimize the total stack depth of the action // by inlining blocks on the critical path that had previously been factored out. if (markupDocumentWriter == null) throw new ArgumentNullException("markupDocumentWriter"); if (action == null) throw new ArgumentNullException("action"); ThreadAbortScope scope = null; try { lock (syncRoot) { ThrowIfDisposed(); if (!abortOutcome.HasValue) { if (scopesAndThreads == null) scopesAndThreads = new List<Pair<ThreadAbortScope, Thread>>(); scope = new ThreadAbortScope(); scopesAndThreads.Add(new Pair<ThreadAbortScope, Thread>(scope, Thread.CurrentThread)); } } if (scope == null) return HandleAbort(markupDocumentWriter, description, null); // Run the action within the scope we have acquired. try { ThreadAbortException ex = scope.Run(action); if (ex != null) return HandleAbort(markupDocumentWriter, description, ex); return TestOutcome.Passed; } catch (Exception ex) { // If the test itself threw a thread abort, not because we aborted it // ourselves but most likely due to a bug in the test subject, then we // prevent the abort from bubbling up any further. if (ex is ThreadAbortException && !AppDomain.CurrentDomain.IsFinalizingForUnload()) Thread.ResetAbort(); TestOutcome outcome; TestException testException = ex as TestException; if (testException != null) { outcome = testException.Outcome; if (testException.ExcludeStackTrace) LogMessage(markupDocumentWriter, description, outcome, testException.HasNonDefaultMessage ? testException.Message : null, null); else LogMessage(markupDocumentWriter, description, outcome, null, testException); } else { outcome = TestOutcome.Failed; LogMessage(markupDocumentWriter, description, outcome, null, ex); } return outcome; } } finally { if (scope != null) { lock (syncRoot) { if (scopesAndThreads != null) { for (int i = 0; i < scopesAndThreads.Count; i++) if (scopesAndThreads[i].First == scope) scopesAndThreads.RemoveAt(i); } } } } } /// <summary> /// Runs an action inside of a protected context wherein it cannot receive /// a thread abort from this <see cref="Sandbox"/>. /// </summary> /// <remarks> /// <para> /// This method enables critical system code to be protected from aborts that /// may affect the sandbox. This call cannot be nested. /// </para> /// </remarks> /// <returns>An object that when disposed ends the protected block, possibly null if there was no protection necessary.</returns> [DebuggerHidden, DebuggerStepThrough] public IDisposable Protect() { ThreadAbortScope scope = FindActiveScopeForThread(Thread.CurrentThread); return scope != null ? scope.Protect() : null; } [DebuggerHidden, DebuggerStepThrough] private ThreadAbortScope FindActiveScopeForThread(Thread currentThread) { lock (syncRoot) { // Choose the most recently added scope for the thread because if // the sandbox is called re-entrantly then we can reasonably assume // that Protect occurred in the outer scope. Otherwise we'd be running // code somewhat unsafely... for (int i = scopesAndThreads.Count - 1; i >= 0; i--) { if (scopesAndThreads[i].Second == currentThread) return scopesAndThreads[i].First; } } return null; } private void HandleParentAborted(object sender, EventArgs e) { var parent = (Sandbox)sender; Abort(parent.AbortOutcome.Value, parent.AbortMessage); } private TestOutcome HandleAbort(MarkupDocumentWriter markupDocumentWriter, string actionDescription, ThreadAbortException ex) { TestOutcome outcome = abortOutcome.Value; if (ex == null && alreadyLoggedAbortOnce) return outcome; alreadyLoggedAbortOnce = true; LogMessage(markupDocumentWriter, actionDescription, outcome, abortMessage, null); return outcome; } private static void LogMessage(MarkupDocumentWriter markupDocumentWriter, string actionDescription, TestOutcome outcome, string message, Exception ex) { if (string.IsNullOrEmpty(message) && ex == null) return; MarkupStreamWriter stream = GetLogStreamWriterForOutcome(markupDocumentWriter, outcome); using (actionDescription != null ? stream.BeginSection(actionDescription) : null) { if (! string.IsNullOrEmpty(message)) stream.WriteLine(message); if (ex != null) stream.WriteException(StackTraceFilter.FilterException(ex)); } } private static MarkupStreamWriter GetLogStreamWriterForOutcome(MarkupDocumentWriter markupDocumentWriter, TestOutcome outcome) { switch (outcome.Status) { case TestStatus.Passed: return markupDocumentWriter.Default; case TestStatus.Failed: return markupDocumentWriter.Failures; default: return markupDocumentWriter.Warnings; } } private void ThrowIfDisposed() { if (isDisposed) throw new ObjectDisposedException("Sandbox was disposed."); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedGlobalOperationsClientSnippets { /// <summary>Snippet for AggregatedList</summary> public void AggregatedListRequestObject() { // Snippet: AggregatedList(AggregatedListGlobalOperationsRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) AggregatedListGlobalOperationsRequest request = new AggregatedListGlobalOperationsRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<OperationAggregatedList, KeyValuePair<string, OperationsScopedList>> response = globalOperationsClient.AggregatedList(request); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, OperationsScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (OperationAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, OperationsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, OperationsScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, OperationsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListRequestObjectAsync() { // Snippet: AggregatedListAsync(AggregatedListGlobalOperationsRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) AggregatedListGlobalOperationsRequest request = new AggregatedListGlobalOperationsRequest { OrderBy = "", Project = "", Filter = "", IncludeAllScopes = false, ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<OperationAggregatedList, KeyValuePair<string, OperationsScopedList>> response = globalOperationsClient.AggregatedListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, OperationsScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((OperationAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, OperationsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, OperationsScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, OperationsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedList</summary> public void AggregatedList() { // Snippet: AggregatedList(string, string, int?, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<OperationAggregatedList, KeyValuePair<string, OperationsScopedList>> response = globalOperationsClient.AggregatedList(project); // Iterate over all response items, lazily performing RPCs as required foreach (KeyValuePair<string, OperationsScopedList> item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (OperationAggregatedList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, OperationsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, OperationsScopedList>> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, OperationsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for AggregatedListAsync</summary> public async Task AggregatedListAsync() { // Snippet: AggregatedListAsync(string, string, int?, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<OperationAggregatedList, KeyValuePair<string, OperationsScopedList>> response = globalOperationsClient.AggregatedListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((KeyValuePair<string, OperationsScopedList> item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((OperationAggregatedList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (KeyValuePair<string, OperationsScopedList> item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<KeyValuePair<string, OperationsScopedList>> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (KeyValuePair<string, OperationsScopedList> item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteGlobalOperationRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) DeleteGlobalOperationRequest request = new DeleteGlobalOperationRequest { Operation = "", Project = "", }; // Make the request DeleteGlobalOperationResponse response = globalOperationsClient.Delete(request); // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteGlobalOperationRequest, CallSettings) // Additional: DeleteAsync(DeleteGlobalOperationRequest, CancellationToken) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) DeleteGlobalOperationRequest request = new DeleteGlobalOperationRequest { Operation = "", Project = "", }; // Make the request DeleteGlobalOperationResponse response = await globalOperationsClient.DeleteAsync(request); // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) string project = ""; string operation = ""; // Make the request DeleteGlobalOperationResponse response = globalOperationsClient.Delete(project, operation); // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string operation = ""; // Make the request DeleteGlobalOperationResponse response = await globalOperationsClient.DeleteAsync(project, operation); // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetGlobalOperationRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) GetGlobalOperationRequest request = new GetGlobalOperationRequest { Operation = "", Project = "", }; // Make the request Operation response = globalOperationsClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetGlobalOperationRequest, CallSettings) // Additional: GetAsync(GetGlobalOperationRequest, CancellationToken) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) GetGlobalOperationRequest request = new GetGlobalOperationRequest { Operation = "", Project = "", }; // Make the request Operation response = await globalOperationsClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) string project = ""; string operation = ""; // Make the request Operation response = globalOperationsClient.Get(project, operation); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string operation = ""; // Make the request Operation response = await globalOperationsClient.GetAsync(project, operation); // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListGlobalOperationsRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) ListGlobalOperationsRequest request = new ListGlobalOperationsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<OperationList, Operation> response = globalOperationsClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (Operation item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (OperationList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListGlobalOperationsRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) ListGlobalOperationsRequest request = new ListGlobalOperationsRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<OperationList, Operation> response = globalOperationsClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Operation item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((OperationList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<OperationList, Operation> response = globalOperationsClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (Operation item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (OperationList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<OperationList, Operation> response = globalOperationsClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Operation item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((OperationList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Operation item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Operation> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Operation item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for Wait</summary> public void WaitRequestObject() { // Snippet: Wait(WaitGlobalOperationRequest, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) WaitGlobalOperationRequest request = new WaitGlobalOperationRequest { Operation = "", Project = "", }; // Make the request Operation response = globalOperationsClient.Wait(request); // End snippet } /// <summary>Snippet for WaitAsync</summary> public async Task WaitRequestObjectAsync() { // Snippet: WaitAsync(WaitGlobalOperationRequest, CallSettings) // Additional: WaitAsync(WaitGlobalOperationRequest, CancellationToken) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) WaitGlobalOperationRequest request = new WaitGlobalOperationRequest { Operation = "", Project = "", }; // Make the request Operation response = await globalOperationsClient.WaitAsync(request); // End snippet } /// <summary>Snippet for Wait</summary> public void Wait() { // Snippet: Wait(string, string, CallSettings) // Create client GlobalOperationsClient globalOperationsClient = GlobalOperationsClient.Create(); // Initialize request argument(s) string project = ""; string operation = ""; // Make the request Operation response = globalOperationsClient.Wait(project, operation); // End snippet } /// <summary>Snippet for WaitAsync</summary> public async Task WaitAsync() { // Snippet: WaitAsync(string, string, CallSettings) // Additional: WaitAsync(string, string, CancellationToken) // Create client GlobalOperationsClient globalOperationsClient = await GlobalOperationsClient.CreateAsync(); // Initialize request argument(s) string project = ""; string operation = ""; // Make the request Operation response = await globalOperationsClient.WaitAsync(project, operation); // End snippet } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #if !SILVERLIGHT // ComObject using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using ComTypes = System.Runtime.InteropServices.ComTypes; //using Microsoft.Scripting.Utils; namespace System.Management.Automation.ComInterop { /// <summary> /// This class implements an event sink for a particular RCW. /// Unlike the implementation of events in TlbImp'd assemblies, /// we will create only one event sink per RCW (theoretically RCW might have /// several ComEventSink evenk sinks - but all these implement different source intefaces). /// Each ComEventSink contains a list of ComEventSinkMethod objects - which represent /// a single method on the source interface an a multicast delegate to redirect /// the calls. Notice that we are chaining multicast delegates so that same /// ComEventSinkMedhod can invoke multiple event handlers). /// /// ComEventSink implements an IDisposable pattern to Unadvise from the connection point. /// Typically, when RCW is finalized the corresponding Dispose will be triggered by /// ComEventSinksContainer finalizer. Notice that lifetime of ComEventSinksContainer /// is bound to the lifetime of the RCW. /// </summary> internal sealed class ComEventSink : MarshalByRefObject, IReflect, IDisposable { #region private fields private Guid _sourceIid; private ComTypes.IConnectionPoint _connectionPoint; private int _adviseCookie; private List<ComEventSinkMethod> _comEventSinkMethods; private object _lockObject = new object(); // We cannot lock on ComEventSink since it causes a DoNotLockOnObjectsWithWeakIdentity warning #endregion #region private classes /// <summary> /// Contains a methods DISPID (in a string formatted of "[DISPID=N]" /// and a chained list of delegates to invoke /// </summary> private class ComEventSinkMethod { public string _name; public Func<object[], object> _handlers; } #endregion #region ctor private ComEventSink(object rcw, Guid sourceIid) { Initialize(rcw, sourceIid); } #endregion private void Initialize(object rcw, Guid sourceIid) { _sourceIid = sourceIid; _adviseCookie = -1; Debug.Assert(_connectionPoint == null, "re-initializing event sink w/o unadvising from connection point"); ComTypes.IConnectionPointContainer cpc = rcw as ComTypes.IConnectionPointContainer; if (cpc == null) throw Error.COMObjectDoesNotSupportEvents(); cpc.FindConnectionPoint(ref _sourceIid, out _connectionPoint); if (_connectionPoint == null) throw Error.COMObjectDoesNotSupportSourceInterface(); // Read the comments for ComEventSinkProxy about why we need it ComEventSinkProxy proxy = new ComEventSinkProxy(this, _sourceIid); _connectionPoint.Advise(proxy.GetTransparentProxy(), out _adviseCookie); } #region static methods public static ComEventSink FromRuntimeCallableWrapper(object rcw, Guid sourceIid, bool createIfNotFound) { List<ComEventSink> comEventSinks = ComEventSinksContainer.FromRuntimeCallableWrapper(rcw, createIfNotFound); if (comEventSinks == null) { return null; } ComEventSink comEventSink = null; lock (comEventSinks) { foreach (ComEventSink sink in comEventSinks) { if (sink._sourceIid == sourceIid) { comEventSink = sink; break; } else if (sink._sourceIid == Guid.Empty) { // we found a ComEventSink object that // was previously disposed. Now we will reuse it. sink.Initialize(rcw, sourceIid); comEventSink = sink; } } if (comEventSink == null && createIfNotFound == true) { comEventSink = new ComEventSink(rcw, sourceIid); comEventSinks.Add(comEventSink); } } return comEventSink; } #endregion public void AddHandler(int dispid, object func) { string name = String.Format(CultureInfo.InvariantCulture, "[DISPID={0}]", dispid); lock (_lockObject) { ComEventSinkMethod sinkMethod; sinkMethod = FindSinkMethod(name); if (sinkMethod == null) { if (_comEventSinkMethods == null) { _comEventSinkMethods = new List<ComEventSinkMethod>(); } sinkMethod = new ComEventSinkMethod(); sinkMethod._name = name; _comEventSinkMethods.Add(sinkMethod); } sinkMethod._handlers += new SplatCallSite(func).Invoke; } } public void RemoveHandler(int dispid, object func) { string name = String.Format(CultureInfo.InvariantCulture, "[DISPID={0}]", dispid); lock (_lockObject) { ComEventSinkMethod sinkEntry = FindSinkMethod(name); if (sinkEntry == null) { return; } // Remove the delegate from multicast delegate chain. // We will need to find the delegate that corresponds // to the func handler we want to remove. This will be // easy since we Target property of the delegate object // is a ComEventCallContext object. Delegate[] delegates = sinkEntry._handlers.GetInvocationList(); foreach (Delegate d in delegates) { SplatCallSite callContext = d.Target as SplatCallSite; if (callContext != null && callContext._callable.Equals(func)) { sinkEntry._handlers -= d as Func<object[], object>; break; } } // If the delegates chain is empty - we can remove // corresponding ComEvenSinkEntry if (sinkEntry._handlers == null) _comEventSinkMethods.Remove(sinkEntry); // We can Unadvise from the ConnectionPoint if no more sink entries // are registered for this interface //(calling Dispose will call IConnectionPoint.Unadvise). if (_comEventSinkMethods.Count == 0) { // notice that we do not remove // ComEventSinkEntry from the list, we will re-use this data structure // if a new handler needs to be attached. Dispose(); } } } public object ExecuteHandler(string name, object[] args) { ComEventSinkMethod site; site = FindSinkMethod(name); if (site != null && site._handlers != null) { return site._handlers(args); } return null; } #region IReflect #region Unimplemented members public FieldInfo GetField(string name, BindingFlags bindingAttr) { return null; } public FieldInfo[] GetFields(BindingFlags bindingAttr) { return Utils.EmptyArray<FieldInfo>(); } public MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Utils.EmptyArray<MemberInfo>(); } public MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Utils.EmptyArray<MemberInfo>(); } public MethodInfo GetMethod(string name, BindingFlags bindingAttr) { return null; } public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) { return null; } public MethodInfo[] GetMethods(BindingFlags bindingAttr) { return Utils.EmptyArray<MethodInfo>(); } public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { return null; } public PropertyInfo GetProperty(string name, BindingFlags bindingAttr) { return null; } public PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return Utils.EmptyArray<PropertyInfo>(); } #endregion public Type UnderlyingSystemType { get { return typeof(object); } } public object InvokeMember( string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { return ExecuteHandler(name, args); } #endregion #region IDisposable public void Dispose() { DisposeAll(); GC.SuppressFinalize(this); } #endregion ~ComEventSink() { DisposeAll(); } private void DisposeAll() { if (_connectionPoint == null) { return; } if (_adviseCookie == -1) { return; } try { _connectionPoint.Unadvise(_adviseCookie); // _connectionPoint has entered the CLR in the constructor // for this object and hence its ref counter has been increased // by us. We have not exposed it to other components and // hence it is safe to call RCO on it w/o worrying about // killing the RCW for other objects that link to it. Marshal.ReleaseComObject(_connectionPoint); } catch (Exception ex) { // if something has gone wrong, and the object is no longer attached to the CLR, // the Unadvise is going to throw. In this case, since we're going away anyway, // we'll ignore the failure and quietly go on our merry way. COMException exCOM = ex as COMException; if (exCOM != null && exCOM.ErrorCode == ComHresults.CONNECT_E_NOCONNECTION) { Debug.Assert(false, "IConnectionPoint::Unadvise returned CONNECT_E_NOCONNECTION."); throw; } } finally { _connectionPoint = null; _adviseCookie = -1; _sourceIid = Guid.Empty; } } private ComEventSinkMethod FindSinkMethod(string name) { if (_comEventSinkMethods == null) return null; ComEventSinkMethod site; site = _comEventSinkMethods.Find(element => element._name == name); return site; } } } #endif
/* * 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 OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; namespace OpenSim.Region.CoreModules.Framework.InterfaceCommander { /// <summary> /// A single function call encapsulated in a class which enforces arguments when passing around as Object[]'s. /// Used for console commands and script API generation /// </summary> public class Command : ICommand { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<CommandArgument> m_args = new List<CommandArgument>(); private Action<object[]> m_command; private string m_help; private string m_name; private CommandIntentions m_intentions; //A permission type system could implement this and know what a command intends on doing. public Command(string name, CommandIntentions intention, Action<Object[]> command, string help) { m_name = name; m_command = command; m_help = help; m_intentions = intention; } #region ICommand Members public void AddArgument(string name, string helptext, string type) { m_args.Add(new CommandArgument(name, helptext, type)); } public string Name { get { return m_name; } } public CommandIntentions Intentions { get { return m_intentions; } } public string Help { get { return m_help; } } public Dictionary<string, string> Arguments { get { Dictionary<string, string> tmp = new Dictionary<string, string>(); foreach (CommandArgument arg in m_args) { tmp.Add(arg.Name, arg.ArgumentType); } return tmp; } } public string ShortHelp() { string help = m_name; foreach (CommandArgument arg in m_args) { help += " <" + arg.Name + ">"; } return help; } public void ShowConsoleHelp() { Console.WriteLine("== " + Name + " =="); Console.WriteLine(m_help); Console.WriteLine("= Parameters ="); foreach (CommandArgument arg in m_args) { Console.WriteLine("* " + arg.Name + " (" + arg.ArgumentType + ")"); Console.WriteLine("\t" + arg.HelpText); } } public void Run(Object[] args) { Object[] cleanArgs = new Object[m_args.Count]; if (args.Length < cleanArgs.Length) { Console.WriteLine("ERROR: Missing " + (cleanArgs.Length - args.Length) + " argument(s)"); ShowConsoleHelp(); return; } if (args.Length > cleanArgs.Length) { Console.WriteLine("ERROR: Too many arguments for this command. Type '<module> <command> help' for help."); return; } int i = 0; foreach (Object arg in args) { if (string.IsNullOrEmpty(arg.ToString())) { Console.WriteLine("ERROR: Empty arguments are not allowed"); return; } try { switch (m_args[i].ArgumentType) { case "String": m_args[i].ArgumentValue = arg.ToString(); break; case "Integer": m_args[i].ArgumentValue = Int32.Parse(arg.ToString()); break; case "Double": m_args[i].ArgumentValue = Double.Parse(arg.ToString(), OpenSim.Framework.Culture.NumberFormatInfo); break; case "Boolean": m_args[i].ArgumentValue = Boolean.Parse(arg.ToString()); break; case "UUID": m_args[i].ArgumentValue = UUID.Parse(arg.ToString()); break; default: Console.WriteLine("ERROR: Unknown desired type for argument " + m_args[i].Name + " on command " + m_name); break; } } catch (FormatException) { Console.WriteLine("ERROR: Argument number " + (i + 1) + " (" + m_args[i].Name + ") must be a valid " + m_args[i].ArgumentType.ToLower() + "."); return; } cleanArgs[i] = m_args[i].ArgumentValue; i++; } m_command.Invoke(cleanArgs); } #endregion } /// <summary> /// A single command argument, contains name, type and at runtime, value. /// </summary> public class CommandArgument { private string m_help; private string m_name; private string m_type; private Object m_val; public CommandArgument(string name, string help, string type) { m_name = name; m_help = help; m_type = type; } public string Name { get { return m_name; } } public string HelpText { get { return m_help; } } public string ArgumentType { get { return m_type; } } public Object ArgumentValue { get { return m_val; } set { m_val = value; } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; namespace RefactoringEssentials { // struct with two values #if NR6 public #endif struct ValueTuple<T1, T2> : IEquatable<ValueTuple<T1, T2>> { private static readonly EqualityComparer<T1> s_comparer1 = EqualityComparer<T1>.Default; private static readonly EqualityComparer<T2> s_comparer2 = EqualityComparer<T2>.Default; public readonly T1 Item1; public readonly T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public bool Equals(ValueTuple<T1, T2> other) { return s_comparer1.Equals(this.Item1, other.Item1) && s_comparer2.Equals(this.Item2, other.Item2); } public override bool Equals(object obj) { if (obj is ValueTuple<T1, T2>) { var other = (ValueTuple<T1, T2>)obj; return this.Equals(other); } return false; } public override int GetHashCode() { return Hash.Combine(s_comparer1.GetHashCode(Item1), s_comparer2.GetHashCode(Item2)); } public static bool operator ==(ValueTuple<T1, T2> left, ValueTuple<T1, T2> right) { return left.Equals(right); } public static bool operator !=(ValueTuple<T1, T2> left, ValueTuple<T1, T2> right) { return !left.Equals(right); } } static class Hash { /// <summary> /// This is how VB Anonymous Types combine hash values for fields. /// </summary> internal static int Combine(int newKey, int currentKey) { return unchecked((currentKey * (int)0xA5555529) + newKey); } internal static int Combine(bool newKeyPart, int currentKey) { return Combine(currentKey, newKeyPart ? 1 : 0); } /// <summary> /// This is how VB Anonymous Types combine hash values for fields. /// PERF: Do not use with enum types because that involves multiple /// unnecessary boxing operations. Unfortunately, we can't constrain /// T to "non-enum", so we'll use a more restrictive constraint. /// </summary> internal static int Combine<T>(T newKeyPart, int currentKey) where T : class { int hash = unchecked(currentKey * (int)0xA5555529); if (newKeyPart != null) { return unchecked(hash + newKeyPart.GetHashCode()); } return hash; } internal static int CombineValues<T>(IEnumerable<T> values, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues<T>(T[] values, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var maxSize = Math.Min(maxItemsToHash, values.Length); var hashCode = 0; for (int i = 0; i < maxSize; i++) { T value = values[i]; // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues<T>(ImmutableArray<T> values, int maxItemsToHash = int.MaxValue) { if (values.IsDefaultOrEmpty) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } // Should end up with a constrained virtual call to object.GetHashCode (i.e. avoid boxing where possible). if (value != null) { hashCode = Hash.Combine(value.GetHashCode(), hashCode); } } return hashCode; } internal static int CombineValues(IEnumerable<string> values, StringComparer stringComparer, int maxItemsToHash = int.MaxValue) { if (values == null) { return 0; } var hashCode = 0; var count = 0; foreach (var value in values) { if (count++ >= maxItemsToHash) { break; } if (value != null) { hashCode = Hash.Combine(stringComparer.GetHashCode(value), hashCode); } } return hashCode; } /// <summary> /// The offset bias value used in the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> //internal const int FnvOffsetBias = unchecked((int)2166136261); /// <summary> /// The generative factor used in the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> internal const int FnvPrime = 16777619; /// <summary> /// Compute the FNV-1a hash of a sequence of bytes /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> //internal static int GetFNVHashCode(byte[] data) //{ // int hashCode = Hash.FnvOffsetBias; // for (int i = 0; i < data.Length; i++) // { // hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); // } // return hashCode; //} /// <summary> /// Compute the FNV-1a hash of a sequence of bytes and determines if the byte /// sequence is valid ASCII and hence the hash code matches a char sequence /// encoding the same text. /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes that are likely to be ASCII text.</param> /// <param name="length">The length of the sequence.</param> /// <param name="isAscii">True if the sequence contains only characters in the ASCII range.</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> //internal static unsafe int GetFNVHashCode(byte* data, int length, out bool isAscii) //{ // int hashCode = Hash.FnvOffsetBias; // byte asciiMask = 0; // for (int i = 0; i < length; i++) // { // byte b = data[i]; // asciiMask |= b; // hashCode = unchecked((hashCode ^ b) * Hash.FnvPrime); // } // isAscii = (asciiMask & 0x80) == 0; // return hashCode; //} /// <summary> /// Compute the FNV-1a hash of a sequence of bytes /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="data">The sequence of bytes</param> /// <returns>The FNV-1a hash of <paramref name="data"/></returns> //internal static int GetFNVHashCode(ImmutableArray<byte> data) //{ // int hashCode = Hash.FnvOffsetBias; // for (int i = 0; i < data.Length; i++) // { // hashCode = unchecked((hashCode ^ data[i]) * Hash.FnvPrime); // } // return hashCode; //} /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: FNV-1a was developed and tuned for 8-bit sequences. We're using it here /// for 16-bit Unicode chars on the understanding that the majority of chars will /// fit into 8-bits and, therefore, the algorithm will retain its desirable traits /// for generating hash codes. /// </summary> /// <param name="text">The input string</param> /// <param name="start">The start index of the first character to hash</param> /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns> //internal static int GetFNVHashCode(string text, int start, int length) //{ // int hashCode = Hash.FnvOffsetBias; // int end = start + length; // for (int i = start; i < end; i++) // { // hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); // } // return hashCode; //} /// <summary> /// Compute the hashcode of a sub-string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <param name="start">The start index of the first character to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending at the end of the string.</returns> //internal static int GetFNVHashCode(string text, int start) //{ // return GetFNVHashCode(text, start, length: text.Length - start); //} /// <summary> /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <returns>The FNV-1a hash code of <paramref name="text"/></returns> //internal static int GetFNVHashCode(string text) //{ // return CombineFNVHash(Hash.FnvOffsetBias, text); //} /// <summary> /// Compute the hashcode of a string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string</param> /// <returns>The FNV-1a hash code of <paramref name="text"/></returns> //internal static int GetFNVHashCode(System.Text.StringBuilder text) //{ // int hashCode = Hash.FnvOffsetBias; // int end = text.Length; // for (int i = 0; i < end; i++) // { // hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); // } // return hashCode; //} /// <summary> /// Compute the hashcode of a sub string using FNV-1a /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="text">The input string as a char array</param> /// <param name="start">The start index of the first character to hash</param> /// <param name="length">The number of characters, beginning with <paramref name="start"/> to hash</param> /// <returns>The FNV-1a hash code of the substring beginning at <paramref name="start"/> and ending after <paramref name="length"/> characters.</returns> //internal static int GetFNVHashCode(char[] text, int start, int length) //{ // int hashCode = Hash.FnvOffsetBias; // int end = start + length; // for (int i = start; i < end; i++) // { // hashCode = unchecked((hashCode ^ text[i]) * Hash.FnvPrime); // } // return hashCode; //} /// <summary> /// Compute the hashcode of a single character using the FNV-1a algorithm /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// Note: In general, this isn't any more useful than "char.GetHashCode". However, /// it may be needed if you need to generate the same hash code as a string or /// substring with just a single character. /// </summary> /// <param name="ch">The character to hash</param> /// <returns>The FNV-1a hash code of the character.</returns> //internal static int GetFNVHashCode(char ch) //{ // return Hash.CombineFNVHash(Hash.FnvOffsetBias, ch); //} /// <summary> /// Combine a string with an existing FNV-1a hash code /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="hashCode">The accumulated hash code</param> /// <param name="text">The string to combine</param> /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="text"/> using the FNV-1a algorithm</returns> //internal static int CombineFNVHash(int hashCode, string text) //{ // foreach (char ch in text) // { // hashCode = unchecked((hashCode ^ ch) * Hash.FnvPrime); // } // return hashCode; //} /// <summary> /// Combine a char with an existing FNV-1a hash code /// See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function /// </summary> /// <param name="hashCode">The accumulated hash code</param> /// <param name="ch">The new character to combine</param> /// <returns>The result of combining <paramref name="hashCode"/> with <paramref name="ch"/> using the FNV-1a algorithm</returns> internal static int CombineFNVHash(int hashCode, char ch) { return unchecked((hashCode ^ ch) * Hash.FnvPrime); } } }
#region Copyright 2014 North Carolina State University //--------------------------------------------------------------------------------------- // Copyright 2015 North Carolina State University // // Computer Science Department // Center for Educational Informatics // http://www.cei.ncsu.edu/ // // 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. // // 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. // //--------------------------------------------------------------------------------------- #endregion using System; using System.Linq; using System.Reflection; using UnityEngine; using System.Collections.Generic; using IntelliMedia.Utilities; namespace IntelliMedia.Repositories { public class PlayerPrefsRepository<T> : Repository<T> where T : class, new() { protected ISerializer Serializer { get; set; } private string KeysIndexName; private List<object> keysIndex; private List<object> KeysIndex { get { if (keysIndex == null) { keysIndex = LoadIndex(); } return keysIndex; } } public PlayerPrefsRepository(ISerializer serializer = null) { KeysIndexName = GetKeyPath("KeysIndex"); // Default to XML serializer Serializer = (serializer != null ? serializer : SerializerXml.Instance); } #region IRepository implementation public override IAsyncTask Insert(T instance) { return new AsyncTask((onCompleted, onError) => { if (IsIdNull(instance)) { AssignUniqueId(instance); } string keyPath = GetKeyFromInstance(instance); if (PlayerPrefs.HasKey(keyPath)) { throw new Exception("Attempting to insert an object that already exists. Key=" + keyPath); } string serializedObject = Serializer.Serialize<T>(instance, true); PlayerPrefs.SetString(keyPath, serializedObject); KeysIndex.Add(GetKey(instance)); OnPlayerPrefsChanged(); onCompleted(instance); }); } public override IAsyncTask Update(T instance) { return new AsyncTask((onCompleted, onError) => { string serializedObject = Serializer.Serialize<T>(instance, true); string keyPath = GetKeyFromInstance(instance); if (!PlayerPrefs.HasKey(keyPath)) { throw new Exception("Attempting to update an object that has not been inserted. Key=" + keyPath); } PlayerPrefs.SetString(keyPath, serializedObject); OnPlayerPrefsChanged(); onCompleted(instance); }); } public override IAsyncTask Delete(T instance) { return new AsyncTask((onCompleted, onError) => { string keyPath = GetKeyFromInstance(instance); PlayerPrefs.DeleteKey(keyPath); KeysIndex.Remove(GetKey(instance)); OnPlayerPrefsChanged(); onCompleted(instance); }); } public override IAsyncTask Get(System.Func<T, bool> predicate) { return new AsyncTask((onCompleted, onError) => { onCompleted(GetAll().Where(predicate).ToList()); }); } public override IAsyncTask GetByKeys(object[] keys) { return new AsyncTask((onCompleted, onError) => { List<T> instances = new List<T>(); foreach (object key in keys) { string keyString = GetKeyPath(key); if (PlayerPrefs.HasKey(keyString)) { string serializeObject = PlayerPrefs.GetString(keyString); instances.Add(Serializer.Deserialize<T>(serializeObject)); } else { throw new Exception(String.Format("Unable to find {0} with id = {1}", typeof(T).Name, key.ToString())); } } onCompleted(instances); }); } public override IAsyncTask GetByKey(object key) { return new AsyncTask((onCompleted, onError) => { T instance = null; string keyString = GetKeyPath(key); if (PlayerPrefs.HasKey(keyString)) { string serializeObject = PlayerPrefs.GetString(keyString); instance = Serializer.Deserialize<T>(serializeObject); } onCompleted(instance); }); } #endregion protected virtual void OnPlayerPrefsChanged() { SaveIndex(); PlayerPrefs.Save(); } private static string GetKeyPath(object key) { if (key == null) { throw new Exception(string.Format("Key property for {0} is null", typeof(T).Name)); } return string.Format("{0}/{1}", typeof(T).Name, key.ToString()); } private string GetKeyFromInstance(T instance) { return GetKeyPath(GetKey(instance)); } private List<T> GetAll() { List<T> items = new List<T>(); foreach (String key in KeysIndex) { string keyPath = GetKeyPath(key); if (PlayerPrefs.HasKey(keyPath)) { string serializeObject = PlayerPrefs.GetString(keyPath); items.Add(Serializer.Deserialize<T>(serializeObject)); } } return items; } private List<object> LoadIndex() { if (PlayerPrefs.HasKey(KeysIndexName)) { string serializeObject = PlayerPrefs.GetString(KeysIndexName); return Serializer.Deserialize<List<object>>(serializeObject); } else { return new List<object>(); } } private void SaveIndex() { string serializedObject = Serializer.Serialize<List<object>>(KeysIndex, true); PlayerPrefs.SetString(KeysIndexName, serializedObject); } } }
// 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.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// DataLakeStoreAccountsOperations operations. /// </summary> internal partial class DataLakeStoreAccountsOperations : IServiceOperations<DataLakeAnalyticsAccountManagementClient>, IDataLakeStoreAccountsOperations { /// <summary> /// Initializes a new instance of the DataLakeStoreAccountsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountsOperations(DataLakeAnalyticsAccountManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeAnalyticsAccountManagementClient /// </summary> public DataLakeAnalyticsAccountManagementClient Client { get; private set; } /// <summary> /// Updates the specified Data Lake Analytics account to include the additional /// Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to which to add the Data Lake /// Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to add. /// </param> /// <param name='parameters'> /// The details of the Data Lake Store account. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> AddWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, AddDataLakeStoreParameters parameters = default(AddDataLakeStoreParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (dataLakeStoreAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Add", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{dataLakeStoreAccountName}", System.Uri.EscapeDataString(dataLakeStoreAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the Data Lake Analytics account specified to remove the specified /// Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to remove the Data /// Lake Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to remove /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (dataLakeStoreAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{dataLakeStoreAccountName}", System.Uri.EscapeDataString(dataLakeStoreAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified Data Lake Store account details in the specified Data /// Lake Analytics account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to retrieve the Data /// Lake Store account details. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to retrieve /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataLakeStoreAccountInfo>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (dataLakeStoreAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{dataLakeStoreAccountName}", System.Uri.EscapeDataString(dataLakeStoreAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataLakeStoreAccountInfo>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<DataLakeStoreAccountInfo>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next page, /// if any. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account for which to list Data Lake /// Store accounts. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<DataLakeStoreAccountInfo>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, ODataQuery<DataLakeStoreAccountInfo> odataQuery = default(ODataQuery<DataLakeStoreAccountInfo>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("select", select); tracingParameters.Add("count", count); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<DataLakeStoreAccountInfo>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DataLakeStoreAccountInfo>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next page, /// if any. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<DataLakeStoreAccountInfo>>> ListByAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<DataLakeStoreAccountInfo>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DataLakeStoreAccountInfo>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects { public unsafe class NetConnection : SimGroup { public NetConnection() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.NetConnectionCreateInstance()); } public NetConnection(uint pId) : base(pId) { } public NetConnection(string pName) : base(pName) { } public NetConnection(IntPtr pObjPtr) : base(pObjPtr) { } public NetConnection(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public NetConnection(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NetConnectionCreateInstance(); private static _NetConnectionCreateInstance _NetConnectionCreateInstanceFunc; internal static IntPtr NetConnectionCreateInstance() { if (_NetConnectionCreateInstanceFunc == null) { _NetConnectionCreateInstanceFunc = (_NetConnectionCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionCreateInstance"), typeof(_NetConnectionCreateInstance)); } return _NetConnectionCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NetConnectionGetAddress(IntPtr connection); private static _NetConnectionGetAddress _NetConnectionGetAddressFunc; internal static IntPtr NetConnectionGetAddress(IntPtr connection) { if (_NetConnectionGetAddressFunc == null) { _NetConnectionGetAddressFunc = (_NetConnectionGetAddress)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionGetAddress"), typeof(_NetConnectionGetAddress)); } return _NetConnectionGetAddressFunc(connection); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _NetConnectionSetSimulatedNetParams(IntPtr connection, float packetLoss, int delay); private static _NetConnectionSetSimulatedNetParams _NetConnectionSetSimulatedNetParamsFunc; internal static void NetConnectionSetSimulatedNetParams(IntPtr connection, float packetLoss, int delay) { if (_NetConnectionSetSimulatedNetParamsFunc == null) { _NetConnectionSetSimulatedNetParamsFunc = (_NetConnectionSetSimulatedNetParams)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionSetSimulatedNetParams"), typeof(_NetConnectionSetSimulatedNetParams)); } _NetConnectionSetSimulatedNetParamsFunc(connection, packetLoss, delay); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float _NetConnectionGetPing(IntPtr connection); private static _NetConnectionGetPing _NetConnectionGetPingFunc; internal static float NetConnectionGetPing(IntPtr connection) { if (_NetConnectionGetPingFunc == null) { _NetConnectionGetPingFunc = (_NetConnectionGetPing)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionGetPing"), typeof(_NetConnectionGetPing)); } return _NetConnectionGetPingFunc(connection); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float _NetConnectionGetPacketLoss(IntPtr connection); private static _NetConnectionGetPacketLoss _NetConnectionGetPacketLossFunc; internal static float NetConnectionGetPacketLoss(IntPtr connection) { if (_NetConnectionGetPacketLossFunc == null) { _NetConnectionGetPacketLossFunc = (_NetConnectionGetPacketLoss)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionGetPacketLoss"), typeof(_NetConnectionGetPacketLoss)); } return _NetConnectionGetPacketLossFunc(connection); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _NetConnectionCheckMaxRate(IntPtr connection); private static _NetConnectionCheckMaxRate _NetConnectionCheckMaxRateFunc; internal static void NetConnectionCheckMaxRate(IntPtr connection) { if (_NetConnectionCheckMaxRateFunc == null) { _NetConnectionCheckMaxRateFunc = (_NetConnectionCheckMaxRate)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionCheckMaxRate"), typeof(_NetConnectionCheckMaxRate)); } _NetConnectionCheckMaxRateFunc(connection); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _NetConnectionSetLogging(IntPtr connection, bool value); private static _NetConnectionSetLogging _NetConnectionSetLoggingFunc; internal static void NetConnectionSetLogging(IntPtr connection, bool value) { if (_NetConnectionSetLoggingFunc == null) { _NetConnectionSetLoggingFunc = (_NetConnectionSetLogging)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionSetLogging"), typeof(_NetConnectionSetLogging)); } _NetConnectionSetLoggingFunc(connection, value); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NetConnectionResolveGhostID(IntPtr connection, int ghostId); private static _NetConnectionResolveGhostID _NetConnectionResolveGhostIDFunc; internal static IntPtr NetConnectionResolveGhostID(IntPtr connection, int ghostId) { if (_NetConnectionResolveGhostIDFunc == null) { _NetConnectionResolveGhostIDFunc = (_NetConnectionResolveGhostID)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionResolveGhostID"), typeof(_NetConnectionResolveGhostID)); } return _NetConnectionResolveGhostIDFunc(connection, ghostId); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NetConnectionResolveObjectFromGhostIndex(IntPtr connection, int ghostId); private static _NetConnectionResolveObjectFromGhostIndex _NetConnectionResolveObjectFromGhostIndexFunc; internal static IntPtr NetConnectionResolveObjectFromGhostIndex(IntPtr connection, int ghostId) { if (_NetConnectionResolveObjectFromGhostIndexFunc == null) { _NetConnectionResolveObjectFromGhostIndexFunc = (_NetConnectionResolveObjectFromGhostIndex)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionResolveObjectFromGhostIndex"), typeof(_NetConnectionResolveObjectFromGhostIndex)); } return _NetConnectionResolveObjectFromGhostIndexFunc(connection, ghostId); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NetConnectionGetGhostID(IntPtr connection, IntPtr netObj); private static _NetConnectionGetGhostID _NetConnectionGetGhostIDFunc; internal static int NetConnectionGetGhostID(IntPtr connection, IntPtr netObj) { if (_NetConnectionGetGhostIDFunc == null) { _NetConnectionGetGhostIDFunc = (_NetConnectionGetGhostID)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionGetGhostID"), typeof(_NetConnectionGetGhostID)); } return _NetConnectionGetGhostIDFunc(connection, netObj); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _NetConnectionConnect(IntPtr connection, string remoteAddress); private static _NetConnectionConnect _NetConnectionConnectFunc; internal static void NetConnectionConnect(IntPtr connection, string remoteAddress) { if (_NetConnectionConnectFunc == null) { _NetConnectionConnectFunc = (_NetConnectionConnect)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionConnect"), typeof(_NetConnectionConnect)); } _NetConnectionConnectFunc(connection, remoteAddress); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NetConnectionConnectLocal(IntPtr connection); private static _NetConnectionConnectLocal _NetConnectionConnectLocalFunc; internal static IntPtr NetConnectionConnectLocal(IntPtr connection) { if (_NetConnectionConnectLocalFunc == null) { _NetConnectionConnectLocalFunc = (_NetConnectionConnectLocal)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionConnectLocal"), typeof(_NetConnectionConnectLocal)); } return _NetConnectionConnectLocalFunc(connection); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NetConnectionGetGhostsActive(IntPtr connection); private static _NetConnectionGetGhostsActive _NetConnectionGetGhostsActiveFunc; internal static int NetConnectionGetGhostsActive(IntPtr connection) { if (_NetConnectionGetGhostsActiveFunc == null) { _NetConnectionGetGhostsActiveFunc = (_NetConnectionGetGhostsActive)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NetConnectionGetGhostsActive"), typeof(_NetConnectionGetGhostsActive)); } return _NetConnectionGetGhostsActiveFunc(connection); } } #endregion #region Properties #endregion #region Methods public string GetAddress() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.NetConnectionGetAddress(ObjectPtr->ObjPtr)); } public void SetSimulatedNetParams(float packetLoss, int delay) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.NetConnectionSetSimulatedNetParams(ObjectPtr->ObjPtr, packetLoss, delay); } public float GetPing() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NetConnectionGetPing(ObjectPtr->ObjPtr); } public float GetPacketLoss() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NetConnectionGetPacketLoss(ObjectPtr->ObjPtr); } public void CheckMaxRate() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.NetConnectionCheckMaxRate(ObjectPtr->ObjPtr); } public void SetLogging(bool value) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.NetConnectionSetLogging(ObjectPtr->ObjPtr, value); } public NetObject ResolveGhostID(int ghostId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new NetObject(InternalUnsafeMethods.NetConnectionResolveGhostID(ObjectPtr->ObjPtr, ghostId)); } public NetObject ResolveObjectFromGhostIndex(int ghostId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new NetObject(InternalUnsafeMethods.NetConnectionResolveObjectFromGhostIndex(ObjectPtr->ObjPtr, ghostId)); } public int GetGhostID(NetObject netObj) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NetConnectionGetGhostID(ObjectPtr->ObjPtr, netObj.ObjectPtr->ObjPtr); } public void Connect(string remoteAddress) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.NetConnectionConnect(ObjectPtr->ObjPtr, remoteAddress); } public string ConnectLocal() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.NetConnectionConnectLocal(ObjectPtr->ObjPtr)); } public int GetGhostsActive() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NetConnectionGetGhostsActive(ObjectPtr->ObjPtr); } #endregion } }
// Copyright 2021 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 Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks; using Esri.ArcGISRuntime.Tasks.Offline; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using UIKit; namespace ArcGISRuntime.Samples.GenerateOfflineMap { [Register("GenerateOfflineMap")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Generate offline map", category: "Map", description: "Take a web map offline.", instructions: "When the app starts, you will be prompted to sign in using a free ArcGIS Online account. Once the map loads, zoom to the extent you want to take offline. The red border shows the extent that will be downloaded. Tap the \"Take Map Offline\" button to start the offline map job. The progress bar will show the job's progress. When complete, the offline map will replace the online map in the map view.", tags: new[] { "download", "offline", "save", "web map" })] public class GenerateOfflineMap : UIViewController { // Hold references to UI controls. private MapView _myMapView; private UIActivityIndicatorView _loadingIndicator; private UIBarButtonItem _takeMapOfflineButton; private UILabel _statusLabel; // The job to generate an offline map. private GenerateOfflineMapJob _generateOfflineMapJob; // The extent of the data to take offline. private readonly Envelope _areaOfInterest = new Envelope(-88.1541, 41.7690, -88.1471, 41.7720, SpatialReferences.Wgs84); // The ID for a web map item hosted on the server (water network map of Naperville IL). private const string WebMapId = "acc027394bc84c2fb04d1ed317aac674"; public GenerateOfflineMap() { Title = "Generate offline map"; } private async void Initialize() { try { // Start the loading indicator. _loadingIndicator.StartAnimating(); // Create the ArcGIS Online portal. ArcGISPortal portal = await ArcGISPortal.CreateAsync(); // Get the Naperville water web map item using its ID. PortalItem webmapItem = await PortalItem.CreateAsync(portal, WebMapId); // Create a map from the web map item. Map onlineMap = new Map(webmapItem); // Display the map in the MapView. _myMapView.Map = onlineMap; // Disable user interactions on the map (no panning or zooming from the initial extent). _myMapView.InteractionOptions = new MapViewInteractionOptions { IsEnabled = false }; // Create a graphics overlay for the extent graphic and apply a renderer. SimpleLineSymbol aoiOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Red, 3); GraphicsOverlay extentOverlay = new GraphicsOverlay { Renderer = new SimpleRenderer(aoiOutlineSymbol) }; _myMapView.GraphicsOverlays.Add(extentOverlay); // Add a graphic to show the area of interest (extent) that will be taken offline. Graphic aoiGraphic = new Graphic(_areaOfInterest); extentOverlay.Graphics.Add(aoiGraphic); // Hide the map loading progress indicator. _loadingIndicator.StopAnimating(); } catch (Exception ex) { // Show the exception message to the user. UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert); messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(messageAlert, true, null); } } private async void TakeMapOfflineButton_Click(object sender, EventArgs e) { // Show the loading indicator. _loadingIndicator.StartAnimating(); // Create a path for the output mobile map. string tempPath = $"{Path.GetTempPath()}"; string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*"); // Loop through the folder names and delete them. foreach (string dir in outputFolders) { try { // Delete the folder. Directory.Delete(dir, true); } catch (Exception) { // Ignore exceptions (files might be locked, for example). } } // Create a new folder for the output mobile map. string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork"); int num = 1; while (Directory.Exists(packagePath)) { packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num); num++; } // Create the output directory. Directory.CreateDirectory(packagePath); try { // Show the loading overlay while the job is running. _statusLabel.Text = "Taking map offline..."; // Create an offline map task with the current (online) map. OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map); // Create the default parameters for the task, pass in the area of interest. GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest); // Create the job with the parameters and output location. _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath); // Handle the progress changed event for the job. _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged; // Await the job to generate geodatabases, export tile packages, and create the mobile map package. GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync(); // Check for job failure (writing the output was denied, e.g.). if (_generateOfflineMapJob.Status != JobStatus.Succeeded) { // Report failure to the user. UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert); messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(messageAlert, true, null); } // Check for errors with individual layers. if (results.LayerErrors.Any()) { // Build a string to show all layer errors. System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder(); foreach (KeyValuePair<Layer, Exception> layerError in results.LayerErrors) { errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message)); } // Show layer errors. UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert); messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(messageAlert, true, null); } // Display the offline map. _myMapView.Map = results.OfflineMap; // Apply the original viewpoint for the offline map. _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest)); // Enable map interaction so the user can explore the offline data. _myMapView.InteractionOptions.IsEnabled = true; // Change the title and disable the "Take map offline" button. _statusLabel.Text = "Map is offline"; _takeMapOfflineButton.Enabled = false; } catch (TaskCanceledException) { // Generate offline map task was canceled. UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert); messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(messageAlert, true, null); } catch (Exception ex) { // Exception while taking the map offline. UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert); messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(messageAlert, true, null); } finally { // Hide the loading overlay when the job is done. _loadingIndicator.StopAnimating(); } } // Show changes in job progress. private void OfflineMapJob_ProgressChanged(object sender, EventArgs e) { // Get the job. GenerateOfflineMapJob job = sender as GenerateOfflineMapJob; // Dispatch to the UI thread. InvokeOnMainThread(() => { // Show the percent complete and update the progress bar. _statusLabel.Text = $"Taking map offline ({job.Progress}%) ..."; }); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor }; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _takeMapOfflineButton = new UIBarButtonItem(); _takeMapOfflineButton.Title = "Generate offline map"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _takeMapOfflineButton, new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace) }; _statusLabel = new UILabel { Text = "Use the button to take the map offline.", AdjustsFontSizeToFitWidth = true, TextAlignment = UITextAlignment.Center, BackgroundColor = UIColor.FromWhiteAlpha(0, .6f), TextColor = UIColor.White, Lines = 1, TranslatesAutoresizingMaskIntoConstraints = false }; _loadingIndicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge); _loadingIndicator.TranslatesAutoresizingMaskIntoConstraints = false; _loadingIndicator.BackgroundColor = UIColor.FromWhiteAlpha(0, .6f); // Add the views. View.AddSubviews(_myMapView, toolbar, _loadingIndicator, _statusLabel); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor), _statusLabel.TopAnchor.ConstraintEqualTo(_myMapView.TopAnchor), _statusLabel.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _statusLabel.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _statusLabel.HeightAnchor.ConstraintEqualTo(40), _loadingIndicator.TopAnchor.ConstraintEqualTo(_statusLabel.BottomAnchor), _loadingIndicator.BottomAnchor.ConstraintEqualTo(View.BottomAnchor), _loadingIndicator.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _loadingIndicator.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. if (_generateOfflineMapJob != null) _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged; _takeMapOfflineButton.Clicked += TakeMapOfflineButton_Click; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _generateOfflineMapJob.ProgressChanged -= OfflineMapJob_ProgressChanged; _takeMapOfflineButton.Clicked -= TakeMapOfflineButton_Click; } } }
//------------------------------------------------------------------------------ // <copyright file="PageCodeDomTreeGenerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Compilation { using System; using System.CodeDom; using System.Reflection; using System.Web.Configuration; using System.Web.SessionState; using System.Web.UI; using System.Web.Util; using Debug = System.Web.Util.Debug; internal class PageCodeDomTreeGenerator : TemplateControlCodeDomTreeGenerator { private PageParser _pageParser; PageParser Parser { get { return _pageParser; } } private const string fileDependenciesName = "__fileDependencies"; private const string dependenciesLocalName = "dependencies"; private const string outputCacheSettingsLocalName = "outputCacheSettings"; private const string _previousPagePropertyName = "PreviousPage"; private const string _masterPropertyName = "Master"; private const string _styleSheetThemePropertyName = "StyleSheetTheme"; private const string outputCacheSettingsFieldName = "__outputCacheSettings"; internal const int DebugScriptTimeout = 30000000; internal PageCodeDomTreeGenerator(PageParser pageParser) : base(pageParser) { _pageParser = pageParser; } /* * Generate the list of implemented interfaces */ protected override void GenerateInterfaces() { base.GenerateInterfaces(); if (Parser.FRequiresSessionState) { _intermediateClass.BaseTypes.Add(new CodeTypeReference(typeof(IRequiresSessionState))); } if (Parser.FReadOnlySessionState) { _intermediateClass.BaseTypes.Add(new CodeTypeReference(typeof(IReadOnlySessionState))); } // Skip if we're only generating the intermediate class if (!_designerMode && _sourceDataClass != null && (Parser.AspCompatMode || Parser.AsyncMode)) { _sourceDataClass.BaseTypes.Add(new CodeTypeReference(typeof(IHttpAsyncHandler))); } } /* * Build first-time intialization statements */ protected override void BuildInitStatements(CodeStatementCollection trueStatements, CodeStatementCollection topLevelStatements) { base.BuildInitStatements(trueStatements, topLevelStatements); // CodeMemberField fileDependencies = new CodeMemberField(typeof(object), fileDependenciesName); fileDependencies.Attributes |= MemberAttributes.Static; _sourceDataClass.Members.Add(fileDependencies); // Note: it may look like this local variable declaration is redundant. However it is necessary // to make this init code re-entrant safe. This way, even if two threads enter the contructor // at the same time, they will not add multiple dependencies. // e.g. string[] dependencies; CodeVariableDeclarationStatement dependencies = new CodeVariableDeclarationStatement(); dependencies.Type = new CodeTypeReference(typeof(string[])); dependencies.Name = dependenciesLocalName; // Note: it is important to add all local variables at the top level for CodeDom Subset compliance. topLevelStatements.Insert(0, dependencies); Debug.Assert(Parser.SourceDependencies != null); StringSet virtualDependencies = new StringSet(); virtualDependencies.AddCollection(Parser.SourceDependencies); // e.g. dependencies = new string[{{virtualDependencies.Count}}];; CodeAssignStatement assignDependencies = new CodeAssignStatement(); assignDependencies.Left = new CodeVariableReferenceExpression(dependenciesLocalName); assignDependencies.Right = new CodeArrayCreateExpression(typeof(String), virtualDependencies.Count); trueStatements.Add(assignDependencies); int i = 0; foreach (string virtualDependency in virtualDependencies) { // e.g. dependencies[i] = "~/sub/foo.aspx"; CodeAssignStatement addFileDep = new CodeAssignStatement(); addFileDep.Left = new CodeArrayIndexerExpression( new CodeVariableReferenceExpression(dependenciesLocalName), new CodeExpression[] {new CodePrimitiveExpression(i++)}); string src = UrlPath.MakeVirtualPathAppRelative(virtualDependency); addFileDep.Right = new CodePrimitiveExpression(src); trueStatements.Add(addFileDep); } // e.g. __fileDependencies = this.GetWrappedFileDependencies(dependencies); CodeAssignStatement initFile = new CodeAssignStatement(); initFile.Left = new CodeFieldReferenceExpression(_classTypeExpr, fileDependenciesName); CodeMethodInvokeExpression createWrap = new CodeMethodInvokeExpression(); createWrap.Method.TargetObject = new CodeThisReferenceExpression(); createWrap.Method.MethodName = "GetWrappedFileDependencies"; createWrap.Parameters.Add(new CodeVariableReferenceExpression(dependenciesLocalName)); initFile.Right = createWrap; #if DBG AppendDebugComment(trueStatements); #endif trueStatements.Add(initFile); } /* * Build the default constructor */ protected override void BuildDefaultConstructor() { base.BuildDefaultConstructor(); if (CompilParams.IncludeDebugInformation) { // If in debug mode, set the timeout to some huge value (ASURT 49427) // Server.ScriptTimeout = 30000000; CodeAssignStatement setScriptTimeout = new CodeAssignStatement(); setScriptTimeout.Left = new CodePropertyReferenceExpression( new CodePropertyReferenceExpression( new CodeThisReferenceExpression(), "Server"), "ScriptTimeout"); setScriptTimeout.Right = new CodePrimitiveExpression(DebugScriptTimeout); _ctor.Statements.Add(setScriptTimeout); } if (Parser.TransactionMode != 0 /*TransactionOption.Disabled*/) { _ctor.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "TransactionMode"), new CodePrimitiveExpression(Parser.TransactionMode))); } if (Parser.AspCompatMode) { _ctor.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "AspCompatMode"), new CodePrimitiveExpression(Parser.AspCompatMode))); } if (Parser.AsyncMode) { _ctor.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "AsyncMode"), new CodePrimitiveExpression(Parser.AsyncMode))); } if (Parser.OutputCacheParameters != null) { OutputCacheParameters cacheSettings = Parser.OutputCacheParameters; if ((cacheSettings.CacheProfile != null && cacheSettings.CacheProfile.Length != 0) || cacheSettings.Duration != 0 || cacheSettings.Location == OutputCacheLocation.None) { // Add the following code snippet as a static on the class: // // private static OutputCacheParameters __outputCacheSettings = null; // CodeMemberField outputCacheSettingsField = new CodeMemberField(typeof(OutputCacheParameters), outputCacheSettingsFieldName); outputCacheSettingsField.Attributes |= MemberAttributes.Static; outputCacheSettingsField.InitExpression = new CodePrimitiveExpression(null); _sourceDataClass.Members.Add(outputCacheSettingsField); // Then, add the following code to the default constructor: // // if (__outputCacheSettings == null) // __outputCacheSettings = new OutputCacheParameters(.....) // // This is the "if (__outputCacheSettings == null)" part CodeConditionStatement outputCacheSettingsCondition = new CodeConditionStatement(); outputCacheSettingsCondition.Condition = new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression( _classTypeExpr, outputCacheSettingsFieldName), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); // This is the "__outputCacheSettings = new OutputCacheParameters()" part // e.g. declare local variable: OutputCacheParameters outputCacheSettings; CodeVariableDeclarationStatement outputCacheSettingsDeclaration = new CodeVariableDeclarationStatement(); outputCacheSettingsDeclaration.Type = new CodeTypeReference(typeof(OutputCacheParameters)); outputCacheSettingsDeclaration.Name = outputCacheSettingsLocalName; outputCacheSettingsCondition.TrueStatements.Insert(0, outputCacheSettingsDeclaration); // e.g. outputCacheSettings = new outputCacheParameters; CodeObjectCreateExpression cacheSettingsObject = new CodeObjectCreateExpression(); cacheSettingsObject.CreateType = new CodeTypeReference(typeof(OutputCacheParameters)); CodeVariableReferenceExpression outputCacheSettings = new CodeVariableReferenceExpression(outputCacheSettingsLocalName); CodeAssignStatement setOutputCacheObject = new CodeAssignStatement(outputCacheSettings, cacheSettingsObject); // Add the statement to the "true" clause outputCacheSettingsCondition.TrueStatements.Add(setOutputCacheObject); if (cacheSettings.IsParameterSet(OutputCacheParameter.CacheProfile)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "CacheProfile"), new CodePrimitiveExpression(cacheSettings.CacheProfile)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.Duration)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "Duration"), new CodePrimitiveExpression(cacheSettings.Duration)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.Enabled)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "Enabled"), new CodePrimitiveExpression(cacheSettings.Enabled)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.Location)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "Location"), new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(OutputCacheLocation)), cacheSettings.Location.ToString())); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.NoStore)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "NoStore"), new CodePrimitiveExpression(cacheSettings.NoStore)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.SqlDependency)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "SqlDependency"), new CodePrimitiveExpression(cacheSettings.SqlDependency)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByControl)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "VaryByControl"), new CodePrimitiveExpression(cacheSettings.VaryByControl)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByCustom)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "VaryByCustom"), new CodePrimitiveExpression(cacheSettings.VaryByCustom)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByContentEncoding)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "VaryByContentEncoding"), new CodePrimitiveExpression(cacheSettings.VaryByContentEncoding)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByHeader)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "VaryByHeader"), new CodePrimitiveExpression(cacheSettings.VaryByHeader)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } if (cacheSettings.IsParameterSet(OutputCacheParameter.VaryByParam)) { CodeAssignStatement setPropertyStatement = new CodeAssignStatement( new CodePropertyReferenceExpression(outputCacheSettings, "VaryByParam"), new CodePrimitiveExpression(cacheSettings.VaryByParam)); outputCacheSettingsCondition.TrueStatements.Add(setPropertyStatement); } // e.g. __outputCacheSettings = outputCacheSettings; CodeFieldReferenceExpression staticOutputCacheSettings = new CodeFieldReferenceExpression(_classTypeExpr, outputCacheSettingsFieldName); CodeAssignStatement assignOutputCacheSettings = new CodeAssignStatement(staticOutputCacheSettings, outputCacheSettings); // Add the statement to the "true" clause outputCacheSettingsCondition.TrueStatements.Add(assignOutputCacheSettings); _ctor.Statements.Add(outputCacheSettingsCondition); } } } /* * Build various properties, fields, methods */ protected override void BuildMiscClassMembers() { base.BuildMiscClassMembers(); // The following method should not be built in designer mode, and should only be built // when we're generating the full class (as opposed to the partial stub) if (!_designerMode && _sourceDataClass != null) { BuildGetTypeHashCodeMethod(); if (Parser.AspCompatMode) BuildAspCompatMethods(); if (Parser.AsyncMode) BuildAsyncPageMethods(); BuildProcessRequestOverride(); } if (Parser.PreviousPageType != null) BuildStronglyTypedProperty(_previousPagePropertyName, Parser.PreviousPageType); if (Parser.MasterPageType != null) BuildStronglyTypedProperty(_masterPropertyName, Parser.MasterPageType); } /* * Build the data tree for the GetTypeHashCode method */ private void BuildGetTypeHashCodeMethod() { CodeMemberMethod method = new CodeMemberMethod(); AddDebuggerNonUserCodeAttribute(method); method.Name = "GetTypeHashCode"; method.ReturnType = new CodeTypeReference(typeof(int)); method.Attributes &= ~MemberAttributes.AccessMask; method.Attributes &= ~MemberAttributes.ScopeMask; method.Attributes |= MemberAttributes.Override | MemberAttributes.Public; _sourceDataClass.Members.Add(method); #if DBG AppendDebugComment(method.Statements); #endif method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(Parser.TypeHashCode))); } internal override CodeExpression BuildPagePropertyReferenceExpression() { return new CodeThisReferenceExpression(); } /* * Build the contents of the FrameworkInitialize method */ protected override void BuildFrameworkInitializeMethodContents(CodeMemberMethod method) { // Generate code to apply stylesheet before calling base.FrameworkInitialize(); if (Parser.StyleSheetTheme != null) { CodeExpression rightExpr = new CodePrimitiveExpression(Parser.StyleSheetTheme); CodeExpression leftExpr = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), _styleSheetThemePropertyName); CodeAssignStatement setStatment = new CodeAssignStatement(leftExpr, rightExpr); method.Statements.Add(setStatment); } base.BuildFrameworkInitializeMethodContents(method); CodeMethodInvokeExpression addDeps = new CodeMethodInvokeExpression(); addDeps.Method.TargetObject = new CodeThisReferenceExpression(); addDeps.Method.MethodName = "AddWrappedFileDependencies"; addDeps.Parameters.Add(new CodeFieldReferenceExpression(_classTypeExpr, fileDependenciesName)); method.Statements.Add(addDeps); if (Parser.OutputCacheParameters != null) { OutputCacheParameters cacheSettings = Parser.OutputCacheParameters; if ((cacheSettings.CacheProfile != null && cacheSettings.CacheProfile.Length != 0) || cacheSettings.Duration != 0 || cacheSettings.Location == OutputCacheLocation.None) { CodeMethodInvokeExpression call = new CodeMethodInvokeExpression(); call.Method.TargetObject = new CodeThisReferenceExpression(); call.Method.MethodName = "InitOutputCache"; call.Parameters.Add(new CodeFieldReferenceExpression( _classTypeExpr, outputCacheSettingsFieldName)); method.Statements.Add(call); } } if (Parser.TraceEnabled != TraceEnable.Default) { method.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "TraceEnabled"), new CodePrimitiveExpression(Parser.TraceEnabled == TraceEnable.Enable))); } if (Parser.TraceMode != TraceMode.Default) { method.Statements.Add(new CodeAssignStatement( new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "TraceModeValue"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(TraceMode)), Parser.TraceMode.ToString()))); } if (Parser.ValidateRequest) { // e.g. Request.ValidateInput(); CodeMethodInvokeExpression invokeExpr = new CodeMethodInvokeExpression(); invokeExpr.Method.TargetObject = new CodePropertyReferenceExpression( new CodeThisReferenceExpression(), "Request"); invokeExpr.Method.MethodName = "ValidateInput"; method.Statements.Add(new CodeExpressionStatement(invokeExpr)); } else if (MultiTargetingUtil.TargetFrameworkVersion >= VersionUtil.Framework45) { // Only emit the ValidateRequestMode setter if the target framework is 4.5 or higher. // On frameworks 4.0 and earlier that property did not exist. CodePropertyReferenceExpression left = new CodePropertyReferenceExpression( new CodeThisReferenceExpression(), "ValidateRequestMode"); CodeFieldReferenceExpression right = new CodeFieldReferenceExpression( new CodeTypeReferenceExpression(typeof(ValidateRequestMode)), "Disabled"); CodeAssignStatement statement = new CodeAssignStatement(left, right); method.Statements.Add(statement); } } /* * Build the data tree for the AspCompat implementation for IHttpAsyncHandler: */ private void BuildAspCompatMethods() { CodeMemberMethod method; CodeMethodInvokeExpression call; // public IAsyncResult BeginProcessRequest(HttpContext context, Async'back cb, Object extraData) { // IAsyncResult ar; // ar = this.AspCompatBeginProcessRequest(context, cb, extraData); // return ar; // } method = new CodeMemberMethod(); AddDebuggerNonUserCodeAttribute(method); method.Name = "BeginProcessRequest"; method.Attributes &= ~MemberAttributes.AccessMask; method.Attributes &= ~MemberAttributes.ScopeMask; method.Attributes |= MemberAttributes.Public; method.ImplementationTypes.Add(new CodeTypeReference(typeof(IHttpAsyncHandler))); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(HttpContext), "context")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), "cb")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Object), "data")); method.ReturnType = new CodeTypeReference(typeof(IAsyncResult)); CodeMethodInvokeExpression invokeExpr = new CodeMethodInvokeExpression(); invokeExpr.Method.TargetObject = new CodeThisReferenceExpression(); invokeExpr.Method.MethodName = "AspCompatBeginProcessRequest"; invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("context")); invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("cb")); invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("data")); method.Statements.Add(new CodeMethodReturnStatement(invokeExpr)); _sourceDataClass.Members.Add(method); // public void EndProcessRequest(IAsyncResult ar) { // this.AspCompatEndProcessRequest(ar); // } method = new CodeMemberMethod(); AddDebuggerNonUserCodeAttribute(method); method.Name = "EndProcessRequest"; method.Attributes &= ~MemberAttributes.AccessMask; method.Attributes &= ~MemberAttributes.ScopeMask; method.Attributes |= MemberAttributes.Public; method.ImplementationTypes.Add(typeof(IHttpAsyncHandler)); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), "ar")); call = new CodeMethodInvokeExpression(); call.Method.TargetObject = new CodeThisReferenceExpression(); call.Method.MethodName = "AspCompatEndProcessRequest"; call.Parameters.Add(new CodeArgumentReferenceExpression("ar")); method.Statements.Add(call); _sourceDataClass.Members.Add(method); } /* * Build the data tree for the Async page implementation for IHttpAsyncHandler: */ private void BuildAsyncPageMethods() { CodeMemberMethod method; CodeMethodInvokeExpression call; // public IAsyncResult BeginProcessRequest(HttpContext context, Async'back cb, Object extraData) { // IAsyncResult ar; // ar = this.AsyncPageBeginProcessRequest(context, cb, extraData); // return ar; // } method = new CodeMemberMethod(); AddDebuggerNonUserCodeAttribute(method); method.Name = "BeginProcessRequest"; method.Attributes &= ~MemberAttributes.AccessMask; method.Attributes &= ~MemberAttributes.ScopeMask; method.Attributes |= MemberAttributes.Public; method.ImplementationTypes.Add(new CodeTypeReference(typeof(IHttpAsyncHandler))); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(HttpContext), "context")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), "cb")); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Object), "data")); method.ReturnType = new CodeTypeReference(typeof(IAsyncResult)); CodeMethodInvokeExpression invokeExpr = new CodeMethodInvokeExpression(); invokeExpr.Method.TargetObject = new CodeThisReferenceExpression(); invokeExpr.Method.MethodName = "AsyncPageBeginProcessRequest"; invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("context")); invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("cb")); invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("data")); method.Statements.Add(new CodeMethodReturnStatement(invokeExpr)); _sourceDataClass.Members.Add(method); // public void EndProcessRequest(IAsyncResult ar) { // this.AsyncPageEndProcessRequest(ar); // } method = new CodeMemberMethod(); AddDebuggerNonUserCodeAttribute(method); method.Name = "EndProcessRequest"; method.Attributes &= ~MemberAttributes.AccessMask; method.Attributes &= ~MemberAttributes.ScopeMask; method.Attributes |= MemberAttributes.Public; method.ImplementationTypes.Add(typeof(IHttpAsyncHandler)); method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), "ar")); call = new CodeMethodInvokeExpression(); call.Method.TargetObject = new CodeThisReferenceExpression(); call.Method.MethodName = "AsyncPageEndProcessRequest"; call.Parameters.Add(new CodeArgumentReferenceExpression("ar")); method.Statements.Add(call); _sourceDataClass.Members.Add(method); } /* * Build a ProcessRequest override which just calls the base. This is used to make sure * there is user code on the stack when requests are executed (VSWhidbey 499386) */ private void BuildProcessRequestOverride() { // public override void ProcessRequest(HttpContext context) { // base.ProcessRequest(context); // } CodeMemberMethod method = new CodeMemberMethod(); AddDebuggerNonUserCodeAttribute(method); method.Name = "ProcessRequest"; method.Attributes &= ~MemberAttributes.AccessMask; method.Attributes &= ~MemberAttributes.ScopeMask; // If the base type is non-default (i.e. not Page) we have to be careful overriding // ProcessRequest, because if the base has its own IHttpHandler.ProcessRequest implementation // and it's not overridable, we would fail to compile. So when we detect this situation, // we instead generate it as a new IHttpHandler.ProcessRequest implementation instead of an // override. In theory, we could *always* do this, but it's safer to limit it to this // constrained scenario (VSWhidbey 517240) MethodInfo methodInfo = null; if (Parser.BaseType != typeof(Page)) { methodInfo = Parser.BaseType.GetMethod("ProcessRequest", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(HttpContext) }, null); Debug.Assert(methodInfo != null); } _sourceDataClass.BaseTypes.Add(new CodeTypeReference(typeof(IHttpHandler))); if (methodInfo != null && methodInfo.DeclaringType != typeof(Page)) { method.Attributes |= MemberAttributes.New | MemberAttributes.Public; } else { method.Attributes |= MemberAttributes.Override | MemberAttributes.Public; } method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(HttpContext), "context")); CodeMethodInvokeExpression invokeExpr = new CodeMethodInvokeExpression(); invokeExpr.Method.TargetObject = new CodeBaseReferenceExpression(); invokeExpr.Method.MethodName = "ProcessRequest"; invokeExpr.Parameters.Add(new CodeArgumentReferenceExpression("context")); method.Statements.Add(invokeExpr); _sourceDataClass.Members.Add(method); } } }
using System; using System.Text; using Cosmos.IL2CPU.API.Attribs; namespace Cosmos.Plugs.TapRoot.System { [Plug(Target = typeof(global::System.Console))] public static class Console { //private static ConsoleColor mForeground = ConsoleColor.White; //private static ConsoleColor mBackground = ConsoleColor.Black; //private static Cosmos.System.Console GetConsole() //{ // return mFallbackConsole; //} //public static ConsoleColor get_BackgroundColor() //{ // return mBackground; //} //public static void set_BackgroundColor(ConsoleColor value) //{ // mBackground = value; // //Cosmos.HAL.Global.TextScreen.SetColors(mForeground, mBackground); // if (GetConsole() != null) GetConsole().Background = value; //} //public static int get_BufferHeight() //{ // WriteLine("Not implemented: get_BufferHeight"); // return -1; //} //public static void set_BufferHeight(int aHeight) //{ // WriteLine("Not implemented: set_BufferHeight"); //} //public static int get_BufferWidth() //{ // WriteLine("Not implemented: get_BufferWidth"); // return -1; //} //public static void set_BufferWidth(int aWidth) //{ // WriteLine("Not implemented: set_BufferWidth"); //} //public static bool get_CapsLock() //{ // return Global.CapsLock; //} //public static int get_CursorLeft() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return 0; // } // return GetConsole().X; //} //public static void set_CursorLeft(int x) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // if (x < get_WindowWidth()) // { // xConsole.X = x; // } // else // { // WriteLine("x must be lower than the console width!"); // } //} //public static int get_CursorSize() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return 0; // } // return xConsole.CursorSize; //} //public static void set_CursorSize(int aSize) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // xConsole.CursorSize = aSize; //} //public static int get_CursorTop() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return 0; // } // return GetConsole().Y; //} //public static void set_CursorTop(int y) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // if (y < get_WindowHeight()) // { // xConsole.Y = y; // } // else // { // WriteLine("y must be lower than the console height!"); // } //} //public static bool get_CursorVisible() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // return false; // } // return GetConsole().CursorVisible; //} //public static void set_CursorVisible(bool value) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // xConsole.CursorVisible = value; //} ////public static TextWriter get_Error() { //// WriteLine("Not implemented: get_Error"); //// return null; ////} //public static ConsoleColor get_ForegroundColor() //{ // return mForeground; //} //public static void set_ForegroundColor(ConsoleColor value) //{ // mForeground = value; // //Cosmos.HAL.Global.TextScreen.SetColors(mForeground, mBackground); // if (GetConsole() != null) GetConsole().Foreground = value; //} ////public static TextReader get_In() ////{ //// WriteLine("Not implemented: get_In"); //// return null; ////} //public static Encoding get_InputEncoding() //{ // WriteLine("Not implemented: get_InputEncoding"); // return null; //} //public static void set_InputEncoding(Encoding value) //{ // WriteLine("Not implemented: set_InputEncoding"); //} //public static bool get_KeyAvailable() //{ // WriteLine("Not implemented: get_KeyAvailable"); // return false; //} //public static int get_LargestWindowHeight() //{ // WriteLine("Not implemented: get_LargestWindowHeight"); // return -1; //} //public static int get_LargestWindowWidth() //{ // WriteLine("Not implemented: get_LargestWindowWidth"); // return -1; //} //public static bool get_NumberLock() //{ // return Global.NumLock; //} ////public static TextWriter get_Out() { //// WriteLine("Not implemented: get_Out"); //// return null; ////} //public static Encoding get_OutputEncoding() //{ // WriteLine("Not implemented: get_OutputEncoding"); // return null; //} //public static void set_OutputEncoding(Encoding value) //{ // WriteLine("Not implemented: set_OutputEncoding"); //} //public static string get_Title() //{ // WriteLine("Not implemented: get_Title"); // return string.Empty; //} //public static void set_Title(string value) //{ // WriteLine("Not implemented: set_Title"); //} //public static bool get_TreatControlCAsInput() //{ // WriteLine("Not implemented: get_TreatControlCAsInput"); // return false; //} //public static void set_TreatControlCAsInput(bool value) //{ // WriteLine("Not implemented: set_TreatControlCAsInput"); //} //public static int get_WindowHeight() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return 25; // } // return GetConsole().Rows; //} //public static void set_WindowHeight(int value) //{ // WriteLine("Not implemented: set_WindowHeight"); //} //public static int get_WindowLeft() //{ // WriteLine("Not implemented: get_WindowLeft"); // return -1; //} //public static void set_WindowLeft(int value) //{ // WriteLine("Not implemented: set_WindowLeft"); //} //public static int get_WindowTop() //{ // WriteLine("Not implemented: get_WindowTop"); // return -1; //} //public static void set_WindowTop(int value) //{ // WriteLine("Not implemented: set_WindowTop"); //} //public static int get_WindowWidth() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return 85; // } // return GetConsole().Cols; //} //public static void set_WindowWidth(int value) //{ // WriteLine("Not implemented: set_WindowWidth"); //} //// Beep() is pure CIL //public static void Beep(int aFrequency, int aDuration) //{ // if (aFrequency < 37 || aFrequency > 32767) // { // throw new ArgumentOutOfRangeException("Frequency must be between 37 and 32767Hz"); // } // if (aDuration <= 0) // { // throw new ArgumentOutOfRangeException("Duration must be more than 0"); // } // WriteLine("Not implemented: Beep"); // //var xPIT = Hardware.Global.PIT; // //xPIT.EnableSound(); // //xPIT.T2Frequency = (uint)aFrequency; // //xPIT.Wait((uint)aDuration); // //xPIT.DisableSound(); //} ////TODO: Console uses TextWriter - intercept and plug it instead //public static void Clear() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // GetConsole().Clear(); //} //// MoveBufferArea(int, int, int, int, int, int) is pure CIL //public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, // int targetLeft, int targetTop, Char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) //{ // WriteLine("Not implemented: MoveBufferArea"); //} ////public static Stream OpenStandardError() { //// WriteLine("Not implemented: OpenStandardError"); ////} ////public static Stream OpenStandardError(int bufferSize) { //// WriteLine("Not implemented: OpenStandardError"); ////} ////public static Stream OpenStandardInput(int bufferSize) { //// WriteLine("Not implemented: OpenStandardInput"); ////} ////public static Stream OpenStandardInput() { //// WriteLine("Not implemented: OpenStandardInput"); ////} ////public static Stream OpenStandardOutput(int bufferSize) { //// WriteLine("Not implemented: OpenStandardOutput"); ////} ////public static Stream OpenStandardOutput() { //// WriteLine("Not implemented: OpenStandardOutput"); ////} //public static int Read() //{ // // TODO special cases, if needed, that returns -1 // KeyEvent xResult; // if (KeyboardManager.TryReadKey(out xResult)) // { // return xResult.KeyChar; // } // else // { // return -1; // } //} //public static String ReadLine() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return null; // } // List<char> chars = new List<char>(32); // KeyEvent current; // int currentCount = 0; // while ((current = KeyboardManager.ReadKey()).Key != ConsoleKeyEx.Enter) // { // if (current.Key == ConsoleKeyEx.NumEnter) break; // //Check for "special" keys // if (current.Key == ConsoleKeyEx.Backspace) // Backspace // { // if (currentCount > 0) // { // int curCharTemp = GetConsole().X; // chars.RemoveAt(currentCount - 1); // GetConsole().X = GetConsole().X - 1; // //Move characters to the left // for (int x = currentCount - 1; x < chars.Count; x++) // { // Write(chars[x]); // } // Write(' '); // GetConsole().X = curCharTemp - 1; // currentCount--; // } // continue; // } // else if (current.Key == ConsoleKeyEx.LeftArrow) // { // if (currentCount > 0) // { // GetConsole().X = GetConsole().X - 1; // currentCount--; // } // continue; // } // else if (current.Key == ConsoleKeyEx.RightArrow) // { // if (currentCount < chars.Count) // { // GetConsole().X = GetConsole().X + 1; // currentCount++; // } // continue; // } // if (current.KeyChar == '\0') continue; // //Write the character to the screen // if (currentCount == chars.Count) // { // chars.Add(current.KeyChar); // Write(current.KeyChar); // currentCount++; // } // else // { // //Insert the new character in the correct location // //For some reason, List.Insert() doesn't work properly // //so the character has to be inserted manually // List<char> temp = new List<char>(); // for (int x = 0; x < chars.Count; x++) // { // if (x == currentCount) // { // temp.Add(current.KeyChar); // } // temp.Add(chars[x]); // } // chars = temp; // //Shift the characters to the right // for (int x = currentCount; x < chars.Count; x++) // { // Write(chars[x]); // } // GetConsole().X -= (chars.Count - currentCount) - 1; // currentCount++; // } // } // WriteLine(); // char[] final = chars.ToArray(); // return new string(final); //} //public static void ResetColor() //{ // set_BackgroundColor(ConsoleColor.Black); // set_ForegroundColor(ConsoleColor.White); //} //public static void SetBufferSize(int width, int height) //{ // WriteLine("Not implemented: SetBufferSize"); //} //public static void SetCursorPosition(int left, int top) //{ // set_CursorLeft(left); // set_CursorTop(top); //} ////public static void SetError(TextWriter newError) { //// WriteLine("Not implemented: SetError"); ////} ////public static void SetIn(TextReader newIn) { //// WriteLine("Not implemented: SetIn"); ////} ////public static void SetOut(TextWriter newOut) { //// WriteLine("Not implemented: SetOut"); ////} //public static void SetWindowPosition(int left, int top) //{ // WriteLine("Not implemented: SetWindowPosition"); //} //public static void SetWindowSize(int width, int height) //{ // WriteLine("Not implemented: SetWindowSize"); //} //#region Write //public static void Write(bool aBool) //{ // Write(aBool.ToString()); //} //public static void Write(char aChar) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // GetConsole().WriteChar(aChar); //} //public static void Write(char[] aBuffer) //{ // Write(aBuffer, 0, aBuffer.Length); //} ////public static void Write(decimal aBuffer) { //// Write("No Decimal.ToString()"); ////} //public static void Write(double aDouble) //{ // Write(aDouble.ToString()); //} //public static void Write(float aFloat) //{ // Write(aFloat.ToString()); //} //public static void Write(int aInt) //{ // Write(aInt.ToString()); //} //public static void Write(long aLong) //{ // Write(aLong.ToString()); //} //public static void Write(object value) //{ // if (value != null) // { // Write(value.ToString()); // } //} //public static void Write(string aText) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // GetConsole().Write(aText); //} //public static void Write(uint aInt) //{ // Write(aInt.ToString()); //} //public static void Write(ulong aLong) //{ // Write(aLong.ToString()); //} //public static void Write(string format, object arg0) //{ // WriteLine("Not implemented: Write"); //} //public static void Write(string format, params object[] arg) //{ // WriteLine("Not implemented: Write"); //} //public static void Write(char[] aBuffer, int aIndex, int aCount) //{ // if (aBuffer == null) // { // throw new ArgumentNullException("aBuffer"); // } // if (aIndex < 0) // { // throw new ArgumentOutOfRangeException("aIndex"); // } // if (aCount < 0) // { // throw new ArgumentOutOfRangeException("aCount"); // } // if ((aBuffer.Length - aIndex) < aCount) // { // throw new ArgumentException(); // } // for (int i = 0; i < aCount; i++) // { // Write(aBuffer[aIndex + i]); // } //} //public static void Write(string format, object arg0, object arg1) //{ // WriteLine("Not implemented: Write"); //} //public static void Write(string format, object arg0, object arg1, object arg2) //{ // WriteLine("Not implemented: Write"); //} //public static void Write(string format, object arg0, object arg1, object arg2, object arg3) //{ // WriteLine("Not implemented: Write"); //} ////You'd expect this to be on System.Console wouldn't you? Well, it ain't so we just rely on Write(object value) ////public static void Write(byte aByte) { //// Write(aByte.ToString()); ////} //#endregion //public static void WriteLine() //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // GetConsole().NewLine(); //} //public static void WriteLine(bool aBool) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // Write(aBool.ToString()); // GetConsole().NewLine(); //} //public static void WriteLine(char aChar) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // Write(aChar); // GetConsole().NewLine(); //} //public static void WriteLine(char[] aBuffer) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // Write(aBuffer, 0, aBuffer.Length); // GetConsole().NewLine(); //} ////public static void WriteLine(decimal aDecimal) { //// Write(aDecimal); //// Global.Console.NewLine(); ////} //public static void WriteLine(double aDouble) //{ // Write(aDouble.ToString()); // GetConsole().NewLine(); //} //public static void WriteLine(float aFloat) //{ // Write(aFloat.ToString()); // GetConsole().NewLine(); //} //public static void WriteLine(int aInt) //{ // Write(aInt.ToString()); // GetConsole().NewLine(); //} //public static void WriteLine(long aLong) //{ // Write(aLong.ToString()); // GetConsole().NewLine(); //} //public static void WriteLine(object value) //{ // if (value != null) // { // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // Write(value.ToString()); // xConsole.NewLine(); // } //} public static void WriteLine(string aText) { } //public static void WriteLine(uint aInt) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // Write(aInt.ToString()); // xConsole.NewLine(); //} //public static void WriteLine(ulong aLong) //{ // var xConsole = GetConsole(); // if (xConsole == null) // { // // for now: // return; // } // Write(aLong.ToString()); // xConsole.NewLine(); //} //public static void WriteLine(string format, object arg0) //{ // WriteLine("Not implemented: WriteLine"); //} //public static void WriteLine(string format, params object[] arg) //{ // WriteLine("Not implemented: WriteLine"); //} //public static void WriteLine(char[] aBuffer, int aIndex, int aCount) //{ // Write(aBuffer, aIndex, aCount); // GetConsole().NewLine(); //} //public static void WriteLine(string format, object arg0, object arg1) //{ // WriteLine("Not implemented: WriteLine"); //} //public static void WriteLine(string format, object arg0, object arg1, object arg2) //{ // WriteLine("Not implemented: WriteLine"); //} //public static void WriteLine(string format, object arg0, object arg1, object arg2, object arg3) //{ // WriteLine("Not implemented: WriteLine"); //} } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Collections.Generic; using log4net; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// Circuit data for an agent. Connection information shared between /// regions that accept UDP connections from a client /// </summary> public class AgentCircuitData { // DEBUG ON private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // DEBUG OFF /// <summary> /// Avatar Unique Agent Identifier /// </summary> public UUID AgentID; /// <summary> /// Avatar's Appearance /// </summary> public AvatarAppearance Appearance; /// <summary> /// Agent's root inventory folder /// </summary> public UUID BaseFolder; /// <summary> /// Base Caps path for user /// </summary> public string CapsPath = String.Empty; /// <summary> /// Seed caps for neighbor regions that the user can see into /// </summary> public Dictionary<ulong, string> ChildrenCapSeeds; /// <summary> /// Root agent, or Child agent /// </summary> public bool child; /// <summary> /// Number given to the client when they log-in that they provide /// as credentials to the UDP server /// </summary> public uint circuitcode; /// <summary> /// How this agent got here /// </summary> public uint teleportFlags; /// <summary> /// Agent's account first name /// </summary> public string firstname; public UUID InventoryFolder; /// <summary> /// Agent's account last name /// </summary> public string lastname; /// <summary> /// Agent's full name. /// </summary> public string Name { get { return string.Format("{0} {1}", firstname, lastname); } } /// <summary> /// Random Unique GUID for this session. Client gets this at login and it's /// only supposed to be disclosed over secure channels /// </summary> public UUID SecureSessionID; /// <summary> /// Non secure Session ID /// </summary> public UUID SessionID; /// <summary> /// Hypergrid service token; generated by the user domain, consumed by the receiving grid. /// There is one such unique token for each grid visited. /// </summary> public string ServiceSessionID = string.Empty; /// <summary> /// The client's IP address, as captured by the login service /// </summary> public string IPAddress; /// <summary> /// Viewer's version string as reported by the viewer at login /// </summary> public string Viewer; /// <summary> /// The channel strinf sent by the viewer at login /// </summary> public string Channel; /// <summary> /// The Mac address as reported by the viewer at login /// </summary> public string Mac; /// <summary> /// The id0 as reported by the viewer at login /// </summary> public string Id0; /// <summary> /// Position the Agent's Avatar starts in the region /// </summary> public Vector3 startpos; public Dictionary<string, object> ServiceURLs; public AgentCircuitData() { } /// <summary> /// Pack AgentCircuitData into an OSDMap for transmission over LLSD XML or LLSD json /// </summary> /// <returns>map of the agent circuit data</returns> public OSDMap PackAgentCircuitData() { OSDMap args = new OSDMap(); args["agent_id"] = OSD.FromUUID(AgentID); args["base_folder"] = OSD.FromUUID(BaseFolder); args["caps_path"] = OSD.FromString(CapsPath); if (ChildrenCapSeeds != null) { OSDArray childrenSeeds = new OSDArray(ChildrenCapSeeds.Count); foreach (KeyValuePair<ulong, string> kvp in ChildrenCapSeeds) { OSDMap pair = new OSDMap(); pair["handle"] = OSD.FromString(kvp.Key.ToString()); pair["seed"] = OSD.FromString(kvp.Value); childrenSeeds.Add(pair); } if (ChildrenCapSeeds.Count > 0) args["children_seeds"] = childrenSeeds; } args["child"] = OSD.FromBoolean(child); args["circuit_code"] = OSD.FromString(circuitcode.ToString()); args["first_name"] = OSD.FromString(firstname); args["last_name"] = OSD.FromString(lastname); args["inventory_folder"] = OSD.FromUUID(InventoryFolder); args["secure_session_id"] = OSD.FromUUID(SecureSessionID); args["session_id"] = OSD.FromUUID(SessionID); args["service_session_id"] = OSD.FromString(ServiceSessionID); args["start_pos"] = OSD.FromString(startpos.ToString()); args["client_ip"] = OSD.FromString(IPAddress); args["viewer"] = OSD.FromString(Viewer); args["channel"] = OSD.FromString(Channel); args["mac"] = OSD.FromString(Mac); args["id0"] = OSD.FromString(Id0); if (Appearance != null) { args["appearance_serial"] = OSD.FromInteger(Appearance.Serial); args["xml3d"] = OSD.FromString(Appearance.XML3D); OSDMap appmap = Appearance.Pack(); args["packed_appearance"] = appmap; } // Old, bad way. Keeping it fow now for backwards compatibility // OBSOLETE -- soon to be deleted if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls.Add(OSD.FromString(kvp.Key)); urls.Add(OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString())); } args["service_urls"] = urls; } // again, this time the right way if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDMap urls = new OSDMap(); foreach (KeyValuePair<string, object> kvp in ServiceURLs) { //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); urls[kvp.Key] = OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString()); } args["serviceurls"] = urls; } return args; } /// <summary> /// Unpack agent circuit data map into an AgentCiruitData object /// </summary> /// <param name="args"></param> public void UnpackAgentCircuitData(OSDMap args) { if (args["agent_id"] != null) AgentID = args["agent_id"].AsUUID(); if (args["base_folder"] != null) BaseFolder = args["base_folder"].AsUUID(); if (args["caps_path"] != null) CapsPath = args["caps_path"].AsString(); if ((args["children_seeds"] != null) && (args["children_seeds"].Type == OSDType.Array)) { OSDArray childrenSeeds = (OSDArray)(args["children_seeds"]); ChildrenCapSeeds = new Dictionary<ulong, string>(); foreach (OSD o in childrenSeeds) { if (o.Type == OSDType.Map) { ulong handle = 0; string seed = ""; OSDMap pair = (OSDMap)o; if (pair["handle"] != null) if (!UInt64.TryParse(pair["handle"].AsString(), out handle)) continue; if (pair["seed"] != null) seed = pair["seed"].AsString(); if (!ChildrenCapSeeds.ContainsKey(handle)) ChildrenCapSeeds.Add(handle, seed); } } } else ChildrenCapSeeds = new Dictionary<ulong, string>(); if (args["child"] != null) child = args["child"].AsBoolean(); if (args["circuit_code"] != null) UInt32.TryParse(args["circuit_code"].AsString(), out circuitcode); if (args["first_name"] != null) firstname = args["first_name"].AsString(); if (args["last_name"] != null) lastname = args["last_name"].AsString(); if (args["inventory_folder"] != null) InventoryFolder = args["inventory_folder"].AsUUID(); if (args["secure_session_id"] != null) SecureSessionID = args["secure_session_id"].AsUUID(); if (args["session_id"] != null) SessionID = args["session_id"].AsUUID(); if (args["service_session_id"] != null) ServiceSessionID = args["service_session_id"].AsString(); if (args["client_ip"] != null) IPAddress = args["client_ip"].AsString(); if (args["viewer"] != null) Viewer = args["viewer"].AsString(); if (args["channel"] != null) Channel = args["channel"].AsString(); if (args["mac"] != null) Mac = args["mac"].AsString(); if (args["id0"] != null) Id0 = args["id0"].AsString(); if (args["start_pos"] != null) Vector3.TryParse(args["start_pos"].AsString(), out startpos); //m_log.InfoFormat("[AGENTCIRCUITDATA]: agentid={0}, child={1}, startpos={2}", AgentID, child, startpos); try { // Unpack various appearance elements Appearance = new AvatarAppearance(); // Eventually this code should be deprecated, use full appearance // packing in packed_appearance if (args["appearance_serial"] != null) Appearance.Serial = args["appearance_serial"].AsInteger(); if (args["xml3d"] != null) Appearance.XML3D = args["xml3d"].AsString(); if (args.ContainsKey("packed_appearance") && (args["packed_appearance"].Type == OSDType.Map)) { Appearance.Unpack((OSDMap)args["packed_appearance"]); // m_log.InfoFormat("[AGENTCIRCUITDATA] unpacked appearance"); } else { m_log.Warn("[AGENTCIRCUITDATA]: failed to find a valid packed_appearance"); } } catch (Exception e) { m_log.ErrorFormat("[AGENTCIRCUITDATA] failed to unpack appearance; {0}",e.Message); } ServiceURLs = new Dictionary<string, object>(); // Try parse the new way, OSDMap if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map) { OSDMap urls = (OSDMap)(args["serviceurls"]); foreach (KeyValuePair<String, OSD> kvp in urls) { ServiceURLs[kvp.Key] = kvp.Value.AsString(); //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]); } } // else try the old way, OSDArray // OBSOLETE -- soon to be deleted else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) { OSDArray urls = (OSDArray)(args["service_urls"]); for (int i = 0; i < urls.Count / 2; i++) { ServiceURLs[urls[i * 2].AsString()] = urls[(i * 2) + 1].AsString(); //System.Console.WriteLine("XXX " + urls[i * 2].AsString() + "=" + urls[(i * 2) + 1].AsString()); } } } } }
// Lookup generator // Created by Charles Greivelding using UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.Collections.Generic; using System.IO; #endif class AntonovSuitLookupGenerator : ScriptableWizard { public string nameTex = "MyLookUp_LUT"; public enum size_Enum { _64px = 64, _128px = 128, _256px = 256, _512px = 512 }; public size_Enum size = size_Enum._256px; private int samples = 256; public enum D_Enum { D_GGX, D_Blinn }; public D_Enum D_Model = D_Enum.D_GGX; public enum G_Enum { G_Schlick, G_Smith }; public G_Enum G_Model = G_Enum.G_Schlick; [MenuItem ("Antonov Suit/Lookup Generator")] static void CreateWizard () { ScriptableWizard.DisplayWizard<AntonovSuitLookupGenerator>("BRDF Lookup Generator", "Compute"); } float RadicalInverse(int n, int b) { float bits = 0.0f; float invBase = 1.0f / b, invBi = invBase; while (n > 0) { int d_i = (n % b); bits += d_i * invBi; n /= b; invBi *= invBase; } return (bits); } Vector2 Hammersley(int i, int N) { return new Vector2( (float)i * ( 1.0f / (float)N ), RadicalInverse(i,3) ); } Vector2 Hammersley2D(int i, int N) { return new Vector2((float)i/(float)N, RadicalInverse(i,3)); } Vector3 ImportanceSampleGGX(Vector2 Xi, float Roughness) { float a = Roughness; float phi = 2 * Mathf.PI * Xi.x; float cosTheta = Mathf.Sqrt( (1 - Xi.y) / ( 1 + (a*a - 1) * Xi.y) ); float sinTheta = Mathf.Sqrt(1 - cosTheta * cosTheta); Vector3 H = new Vector3(sinTheta * Mathf.Cos(phi), sinTheta * Mathf.Sin(phi), cosTheta); return H; } Vector3 ImportanceSampleBlinn( Vector2 Xi, float Roughness ) { float m = Roughness * Roughness; float n = 2 / (m*m) - 2; float phi = 2 * Mathf.PI * Xi.x; float CosTheta = Mathf.Pow( Mathf.Max(Xi.y, 0.0001f), 1 / (n + 1) ); float SinTheta = Mathf.Sqrt( 1 - CosTheta * CosTheta ); Vector3 H = new Vector3(SinTheta * Mathf.Cos( phi ), SinTheta * Mathf.Sin( phi ), CosTheta); return H; } float G_Schlick(float Roughness, float NdotV, float NdotL) { float m = Roughness; return (NdotV * NdotL) / ( (NdotV * (1 - m) + m) * (NdotL * (1 - m) + m) ); } float G_Smith( float Roughness, float NoV, float NoL ) { float m = Roughness; float G_SmithV = NoV + Mathf.Sqrt( NoV * (NoV - NoV * m) + m ); float G_SmithL = NoL + Mathf.Sqrt( NoL * (NoL - NoL * m) + m ); return 1 / G_SmithV * G_SmithL; } Vector2 IntegrateBRDF(float NoV, float roughness) { Vector3 V = new Vector3(Mathf.Sqrt( 1.0f - NoV * NoV ), 0, NoV); float m = roughness*roughness; float A = 0; float B = 0; int numSamples = samples; for( int i = 0; i < numSamples; i++ ) { Vector2 Xi = Hammersley( i, numSamples ); Vector3 H = new Vector3(0,0,0); if( D_Model == D_Enum.D_GGX ) { H = ImportanceSampleGGX( Xi, m); } if( D_Model == D_Enum.D_Blinn ) { H = ImportanceSampleBlinn( Xi, m); } Vector3 L = 2 * Vector3.Dot( V, H ) * H - V; float NoL = L.z; float NoH = H.z; float VoH = Vector3.Dot( V, H ); if( NoL > 0 ) { if( G_Model == G_Enum.G_Schlick ) { float G = G_Schlick( m, NoV, NoL ); float G_Vis = G * VoH / (NoH * NoV); float Fc = Mathf.Pow( 1.0f - VoH, 5.0f ); A += (1.0f - Fc) * G_Vis; B += Fc * G_Vis; } if( G_Model == G_Enum.G_Smith ) { float G = G_Smith( m, NoV, NoL ); float Fc = Mathf.Pow( 1.0f - VoH, 5.0f ); A += (1.0f - Fc) * G; B += Fc * G; } } } return new Vector2(A, B) / numSamples; } void OnWizardCreate () { string extension = ".png"; string path = Application.dataPath + "/Antonov Suit/Textures/Shaders/" + nameTex + extension; int width = (int)size; int height = (int)size; Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false); try { for (int j = 0; j < height; ++j) { for (int i = 0; i < width; ++i) { Vector2 FG = IntegrateBRDF( (i+1)/(float) width, (j+1)/(float)height); texture.SetPixel(i, j, new Color( FG.x,FG.y,0)); } float progress = (float)j / (float)height; bool canceled = EditorUtility.DisplayCancelableProgressBar("Processing Computation", "", progress); if (canceled) return; } texture.wrapMode = TextureWrapMode.Clamp; texture.Apply(); byte[] bytes = texture.EncodeToPNG(); File.WriteAllBytes(path, bytes); } finally { DestroyImmediate(texture); EditorUtility.ClearProgressBar(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; namespace GoldenAnvil.Utility { /// <summary> /// Simplifies implementation of INotifyPropertyChanged. /// </summary> public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged, INotifyPropertyChanging { /// <summary> /// Raised before a property changes. /// </summary> public event PropertyChangingEventHandler PropertyChanging; /// <summary> /// Raised when a property changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the property changing event and returns an object that, when disposed, /// will raise the property changed event. /// </summary> /// <param name="propertyName">Name of the property that will change.</param> /// <returns>An object that, when disposed, will raise the property changed event.</returns> protected IDisposable ScopedPropertyChange(string propertyName) { RaisePropertyChanging(propertyName); return Scope.Create(() => RaisePropertyChanged(propertyName)); } /// <summary> /// Raises property changing events and returns an object that, when disposed, /// will raise property changed events. /// </summary> /// <param name="propertyNames">Names of the properties that will change.</param> /// <returns>An object that, when disposed, will raise property changed events.</returns> /// <remarks>Null or empty strings are ignored.</remarks> protected IDisposable ScopedPropertyChange(params string[] propertyNames) { RaisePropertyChanging(propertyNames); string[] reversedNames = propertyNames.Reverse().ToArray(); return Scope.Create(() => RaisePropertyChanged(reversedNames)); } /// <summary> /// Sets the property field and raises property changed when value changes. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="newValue">The new value of the field.</param> /// <param name="field">The field.</param> /// <returns><c>true</c>, if the field was updated; otherwise <c>false</c>.</returns> protected bool SetPropertyField<T>(string propertyName, T newValue, ref T field) { return SetPropertyField(propertyName, newValue, ref field, EqualityComparer<T>.Default); } /// <summary> /// Sets the property field and raises property changed when value changes. This methods is intended /// for use only in the setter of the property being changed. /// </summary> /// <param name="newValue">The new value of the field.</param> /// <param name="field">The field.</param> /// <param name="propertyName">Name of the property. Do not explicitly specify this value.</param> /// <returns><c>true</c>, if the field was updated; otherwise <c>false</c>.</returns> protected bool SetPropertyField<T>(T newValue, ref T field, [CallerMemberName] string propertyName = "") { return SetPropertyField(propertyName, newValue, ref field, EqualityComparer<T>.Default); } /// <summary> /// Sets the property field and raises property changed when value changes. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="newValue">The new value of the field.</param> /// <param name="field">The field.</param> /// <param name="comparer">The equality comparer.</param> /// <returns><c>true</c>, if the field was updated; otherwise <c>false</c>.</returns> protected bool SetPropertyField<T>(string propertyName, T newValue, ref T field, IEqualityComparer<T> comparer) { if (comparer.Equals(field, newValue)) return false; using (ScopedPropertyChange(propertyName)) field = newValue; return true; } /// <summary> /// Sets the property field and raises property changed when value changes. This methods is intended /// for use only in the setter of the property being changed. /// </summary> /// <param name="newValue">The new value of the field.</param> /// <param name="field">The field.</param> /// <param name="comparer">The equality comparer.</param> /// <param name="propertyName">Name of the property. Do not explicitly specify this value.</param> /// <returns><c>true</c>, if the field was updated; otherwise <c>false</c>.</returns> protected bool SetPropertyField<T>(T newValue, ref T field, IEqualityComparer<T> comparer, [CallerMemberName] string propertyName = "") { return SetPropertyField(propertyName, newValue, ref field, comparer); } /// <summary> /// Sets the property field and raises property changed when value changes. /// </summary> /// <param name="propertyNames">Names of the properties for which to raise the PropertyChanged event.</param> /// <param name="newValue">The new value of the field.</param> /// <param name="field">The field.</param> /// <returns><c>true</c>, if the field was updated; otherwise <c>false</c>.</returns> protected bool SetPropertyField<T>(string[] propertyNames, T newValue, ref T field) { return SetPropertyField(propertyNames, newValue, ref field, EqualityComparer<T>.Default); } /// <summary> /// Sets the property field and raises property changed when value changes. /// </summary> /// <param name="propertyNames">Names of the properties for which to raise the PropertyChanged event.</param> /// <param name="newValue">The new value of the field.</param> /// <param name="field">The field.</param> /// <param name="comparer">The equality comparer.</param> /// <returns><c>true</c>, if the field was updated; otherwise <c>false</c>.</returns> protected bool SetPropertyField<T>(string[] propertyNames, T newValue, ref T field, IEqualityComparer<T> comparer) { if (comparer.Equals(field, newValue)) return false; using (ScopedPropertyChange(propertyNames)) field = newValue; return true; } /// <summary> /// Disposes the property field, sets it to null, and raises property change notifications. /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="propertyName">Name of the property.</param> /// <param name="field">The field.</param> /// <returns><c>true</c>, if the field was disposed and set to null; otherwise <c>false</c>.</returns> /// <remarks>This method does nothing if the field is already set to null.</remarks> protected bool DisposePropertyField<T>(string propertyName, ref T field) where T : class, IDisposable { if (field == null) return false; using (ScopedPropertyChange(propertyName)) { field.Dispose(); field = null; } return true; } /// <summary> /// Disposes the property field, sets it to null, and raises property change notifications. /// </summary> /// <typeparam name="T">The type of the property.</typeparam> /// <param name="propertyNames">Name of the property.</param> /// <param name="field">The field.</param> /// <returns><c>true</c>, if the field was disposed and set to null; otherwise <c>false</c>.</returns> /// <remarks>This method does nothing if the field is already set to null.</remarks> protected bool DisposePropertyField<T>(string[] propertyNames, ref T field) where T : class, IDisposable { if (field == null) return false; using (ScopedPropertyChange(propertyNames)) { field.Dispose(); field = null; } return true; } /// <summary> /// Called after a property has changed. /// </summary> /// <param name="propertyName">The name of the property.</param> protected virtual void OnPropertyChanged(string propertyName) { } /// <summary> /// Called before a property has changed. /// </summary> /// <param name="propertyName"></param> protected virtual void OnPropertyChanging(string propertyName) { } /// <summary> /// Call this method to verify in DEBUG builds that this class can be accessed in the current context. /// </summary> [Conditional("DEBUG")] protected virtual void VerifyAccess() { } /// <summary> /// Call this method to verify in DEBUG builds that this class can be accessed in the current context. /// </summary> /// <param name="value">The value to return.</param> /// <returns>The value passed as an argument.</returns> protected T VerifyAccess<T>(T value) { VerifyAccess(); return value; } private void RaisePropertyChanging(string propertyName) { VerifyAccess(); OnPropertyChanging(propertyName); PropertyChanging.Raise(this, propertyName); } private void RaisePropertyChanging(params string[] propertyNames) { VerifyAccess(); foreach (string propertyName in propertyNames) { if (!string.IsNullOrEmpty(propertyName)) { OnPropertyChanging(propertyName); PropertyChanging.Raise(this, propertyName); } } } private void RaisePropertyChanged(string propertyName) { VerifyAccess(); OnPropertyChanged(propertyName); PropertyChanged.Raise(this, propertyName); } private void RaisePropertyChanged(params string[] propertyNames) { VerifyAccess(); foreach (string propertyName in propertyNames) { if (!string.IsNullOrEmpty(propertyName)) { OnPropertyChanged(propertyName); PropertyChanged.Raise(this, propertyName); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Timers; using log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; /// <summary> /// Prompt to use for simulator command line. /// </summary> private string m_consolePrompt; /// <summary> /// Regex for parsing out special characters in the prompt. /// </summary> private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled); private string m_timedScript = "disabled"; private int m_timeInterval = 1200; private Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = Config.Configs["Startup"]; IConfig networkConfig = Config.Configs["Network"]; int stpMinThreads = 2; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_timedScript != "disabled") { m_timeInterval = startupConfig.GetInt("timer_Interval", 1200); } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMinThreads = startupConfig.GetInt("MinPoolThreads", 15); stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15); m_consolePrompt = startupConfig.GetString("ConsolePrompt", @"Region (\R) "); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMinThreads, stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI { m_console = new CommandConsole("Region"); } else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(Config); break; default: m_console = new LocalConsole("Region"); break; } } MainConsole.Instance = m_console; LogEnvironmentInformation(); RegisterCommonAppenders(Config.Configs["Startup"]); RegisterConsoleCommands(); base.StartupSpecific(); MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler()); MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this)); if (userStatsURI != String.Empty) MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this)); if (managedStatsURI != String.Empty) { string urlBase = String.Format("/{0}/", managedStatsURI); MainServer.Instance.AddHTTPHandler(urlBase, StatsManager.HandleStatsRequest); m_log.InfoFormat("[OPENSIM] Enabling remote managed stats fetch. URL = {0}", urlBase); } if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); // For now, start at the 'root' level by default if (SceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", SceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = m_timeInterval*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { MainServer.RegisterHttpConsoleCommands(m_console); m_console.Commands.AddCommand("Objects", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("General", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("Archiving", false, "save xml", "save xml", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("Archiving", false, "save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("Archiving", false, "load xml", "load xml [-newIDs [<x> <y> <z>]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("Archiving", false, "load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("Archiving", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("Archiving", false, "load oar", "load oar [--merge] [--skip-assets] [<OAR path>]", "Load a region's data from an OAR archive.", "--merge will merge the OAR with the existing scene." + Environment.NewLine + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine + "The path can be either a filesystem location or a URI." + " If this is not given then the command looks for an OAR named region.oar in the current directory.", LoadOar); m_console.Commands.AddCommand("Archiving", false, "save oar", //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]", "save oar [-h|--home=<url>] [--noassets] [--publish] [--perm=<permissions>] [--all] [<OAR path>]", "Save a region's data to an OAR archive.", // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine "-h|--home=<url> adds the url of the profile service to the saved user information.\n" + "--noassets stops assets being saved to the OAR.\n" + "--publish saves an OAR stripped of owner and last owner information.\n" + " on reload, the estate owner will be the owner of all objects\n" + " this is useful if you're making oars generally available that might be reloaded to the same grid from which you published\n" + "--perm=<permissions> stops objects with insufficient permissions from being saved to the OAR.\n" + " <permissions> can contain one or more of these characters: \"C\" = Copy, \"T\" = Transfer\n" + "--all saves all the regions in the simulator, instead of just the current region.\n" + "The OAR path must be a filesystem path." + " If this is not given then the oar is saved to region.oar in the current directory.", SaveOar); m_console.Commands.AddCommand("Objects", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("Users", false, "kick user", "kick user <first> <last> [--force] [message]", "Kick a user off the simulator", "The --force option will kick the user without any checks to see whether it's already in the process of closing\n" + "Only use this option if you are sure the avatar is inactive and a normal kick user operation does not removed them", KickUserCommand); m_console.Commands.AddCommand("Users", false, "show users", "show users [full]", "Show user data for users currently on the region", "Without the 'full' option, only users actually on the region are shown." + " With the 'full' option child agents of users in neighbouring regions are also shown.", HandleShow); m_console.Commands.AddCommand("Comms", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show circuits", "show circuits", "Show agent circuit data", HandleShow); m_console.Commands.AddCommand("Comms", false, "show pending-objects", "show pending-objects", "Show # of objects on the pending queues of all scene viewers", HandleShow); m_console.Commands.AddCommand("General", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("Regions", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("Objects", false, "backup", "backup", "Persist currently unsaved object changes immediately instead of waiting for the normal persistence call.", RunCommand); m_console.Commands.AddCommand("Regions", false, "create region", "create region [\"region name\"] <region_file.ini>", "Create a new region.", "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given." + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine + "If <region_file.ini> does not exist, it will be created.", HandleCreateRegion); m_console.Commands.AddCommand("Regions", false, "restart", "restart", "Restart all sims in this instance", RunCommand); m_console.Commands.AddCommand("General", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("Regions", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("Regions", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); } protected override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(Watchdog.ThreadWatchdogInfo twi) { int now = Environment.TickCount & Int32.MaxValue; m_log.ErrorFormat( "[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago. {3}", twi.Thread.Name, twi.Thread.ThreadState, now - twi.LastTick, twi.AlarmMethod != null ? string.Format("Data: {0}", twi.AlarmMethod()) : ""); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { bool force = false; OptionSet options = new OptionSet().Add("f|force", delegate (string v) { force = v != null; }); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) return; string alert = null; if (mainParams.Count > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = SceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; if (presence.Firstname.ToLower().Equals(mainParams[2].ToLower()) && presence.Lastname.ToLower().Equals(mainParams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n"); presence.Scene.CloseAgent(presence.UUID, force); break; } } MainConsole.Instance.Output(""); } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { StreamReader readFile = File.OpenText(fileName); string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); SceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { SceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region ini or XML file</param> private void HandleCreateRegion(string module, string[] cmd) { string regionName = string.Empty; string regionFile = string.Empty; if (cmd.Length == 3) { regionFile = cmd[2]; } else if (cmd.Length > 3) { regionName = cmd[2]; regionFile = cmd[3]; } string extension = Path.GetExtension(regionFile).ToLower(); bool isXml = extension.Equals(".xml"); bool isIni = extension.Equals(".ini"); if (!isXml && !isIni) { MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>"); return; } if (!Path.IsPathRooted(regionFile)) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); regionFile = Path.Combine(regionsDir, regionFile); } RegionInfo regInfo; if (isXml) { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source); } else { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName); } Scene existingScene; if (SceneManager.TryGetScene(regInfo.RegionID, out existingScene)) { MainConsole.Instance.OutputFormat( "ERROR: Cannot create region {0} with ID {1}, this ID is already assigned to region {2}", regInfo.RegionName, regInfo.RegionID, existingScene.RegionInfo.RegionName); return; } bool changed = PopulateRegionEstateInfo(regInfo); IScene scene; CreateRegion(regInfo, true, out scene); if (changed) regInfo.EstateSettings.Save(); } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "backup": MainConsole.Instance.Output("Triggering save of pending object updates to persistent store"); SceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (SceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("No region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (SceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": SceneManager.RestartCurrentScene(); break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!SceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); else RefreshPrompt(); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } } /// <summary> /// Refreshs prompt with the current selection details. /// </summary> private void RefreshPrompt() { string regionName = (SceneManager.CurrentScene == null ? "root" : SceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); // m_log.DebugFormat("Original prompt is {0}", m_consolePrompt); string prompt = m_consolePrompt; // Replace "\R" with the region name // Replace "\\" with "\" prompt = m_consolePromptRegex.Replace(prompt, m => { // m_log.DebugFormat("Matched {0}", m.Groups[2].Value); if (m.Groups[2].Value == "R") return m.Groups[1].Value + regionName; else return m.Groups[0].Value; }); m_console.DefaultPrompt = prompt; m_console.ConsoleScene = SceneManager.CurrentScene; } protected override void HandleRestartRegion(RegionInfo whichRegion) { base.HandleRestartRegion(whichRegion); // Where we are restarting multiple scenes at once, a previous call to RefreshPrompt may have set the // m_console.ConsoleScene to null (indicating all scenes). if (m_console.ConsoleScene != null && whichRegion.RegionName == ((Scene)m_console.ConsoleScene).Name) SceneManager.TrySetCurrentScene(whichRegion.RegionName); RefreshPrompt(); } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = SceneManager.GetCurrentScenePresences(); } else { agents = SceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position") ); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString()) ); } MainConsole.Instance.Output(String.Empty); break; case "connections": HandleShowConnections(); break; case "circuits": HandleShowCircuits(); break; case "modules": SceneManager.ForEachSelectedScene( scene => { MainConsole.Instance.OutputFormat("Loaded region modules in {0} are:", scene.Name); List<IRegionModuleBase> sharedModules = new List<IRegionModuleBase>(); List<IRegionModuleBase> nonSharedModules = new List<IRegionModuleBase>(); foreach (IRegionModuleBase module in scene.RegionModules.Values) { if (module.GetType().GetInterface("ISharedRegionModule") != null) nonSharedModules.Add(module); else sharedModules.Add(module); } foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Shared): {0}", module.Name); foreach (IRegionModuleBase module in sharedModules.OrderBy(m => m.Name)) MainConsole.Instance.OutputFormat("New Region Module (Non-Shared): {0}", module.Name); } ); MainConsole.Instance.Output(""); break; case "regions": SceneManager.ForEachScene( delegate(Scene scene) { MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}, Estate Name: {4}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.InternalEndPoint.Port, scene.RegionInfo.EstateSettings.EstateName)); }); break; case "ratings": SceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } private void HandleShowCircuits() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Type", 5); cdt.AddColumn("Code", 10); cdt.AddColumn("IP", 16); cdt.AddColumn("Viewer Name", 24); SceneManager.ForEachScene( s => { foreach (AgentCircuitData aCircuit in s.AuthenticateHandler.GetAgentCircuits().Values) cdt.AddRow( s.Name, aCircuit.Name, aCircuit.child ? "child" : "root", aCircuit.circuitcode.ToString(), aCircuit.IPAddress != null ? aCircuit.IPAddress.ToString() : "not set", aCircuit.Viewer); }); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowConnections() { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("Region", 20); cdt.AddColumn("Avatar name", 24); cdt.AddColumn("Circuit code", 12); cdt.AddColumn("Endpoint", 23); cdt.AddColumn("Active?", 7); SceneManager.ForEachScene( s => s.ForEachClient( c => cdt.AddRow( s.Name, c.Name, c.CircuitCode.ToString(), c.RemoteEndPoint.ToString(), c.IsActive.ToString()))); MainConsole.Instance.Output(cdt.ToString()); } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 5) { SceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { SceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 0) { SceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } SceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset); } else { try { SceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { SceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { SceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { SceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { SceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { SceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { SceneManager.SaveCurrentSceneToArchive(cmdparams); } private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } #endregion } }
namespace XenAdmin.TabPages { partial class NICPage { /// <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) { // Deregister listeners. Host = null; if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NICPage)); this.label6 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.CreateBondButton = new System.Windows.Forms.Button(); this.DeleteBondButton = new System.Windows.Forms.Button(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.buttonRescan = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.TitleLabel = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.ColumnNIC = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnMAC = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnLinkStatus = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSpeed = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDuplex = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnVendorName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDeviceName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnBusPath = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.pageContainerPanel.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // pageContainerPanel // this.pageContainerPanel.Controls.Add(this.panel1); this.pageContainerPanel.Controls.Add(this.label1); resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // CreateBondButton // resources.ApplyResources(this.CreateBondButton, "CreateBondButton"); this.CreateBondButton.Name = "CreateBondButton"; this.CreateBondButton.UseVisualStyleBackColor = true; this.CreateBondButton.Click += new System.EventHandler(this.CreateBondButton_Click); // // DeleteBondButton // resources.ApplyResources(this.DeleteBondButton, "DeleteBondButton"); this.DeleteBondButton.Name = "DeleteBondButton"; this.DeleteBondButton.UseVisualStyleBackColor = true; this.DeleteBondButton.Click += new System.EventHandler(this.DeleteBondButton_Click); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.CreateBondButton); this.flowLayoutPanel1.Controls.Add(this.DeleteBondButton); this.flowLayoutPanel1.Controls.Add(this.buttonRescan); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // buttonRescan // resources.ApplyResources(this.buttonRescan, "buttonRescan"); this.buttonRescan.Name = "buttonRescan"; this.buttonRescan.UseVisualStyleBackColor = true; this.buttonRescan.Click += new System.EventHandler(this.buttonRescan_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // TitleLabel // resources.ApplyResources(this.TitleLabel, "TitleLabel"); this.TitleLabel.ForeColor = System.Drawing.Color.White; this.TitleLabel.Name = "TitleLabel"; // // panel1 // resources.ApplyResources(this.panel1, "panel1"); this.panel1.Controls.Add(this.dataGridView1); this.panel1.Controls.Add(this.flowLayoutPanel1); this.panel1.MaximumSize = new System.Drawing.Size(900, 400); this.panel1.Name = "panel1"; // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToResizeRows = false; this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnNIC, this.ColumnMAC, this.ColumnLinkStatus, this.ColumnSpeed, this.ColumnDuplex, this.ColumnVendorName, this.ColumnDeviceName, this.ColumnBusPath}); resources.ApplyResources(this.dataGridView1, "dataGridView1"); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.dataGridView1_MouseClick); this.dataGridView1.SelectionChanged += new System.EventHandler(this.datagridview_SelectedIndexChanged); // // ColumnNIC // resources.ApplyResources(this.ColumnNIC, "ColumnNIC"); this.ColumnNIC.Name = "ColumnNIC"; this.ColumnNIC.ReadOnly = true; // // ColumnMAC // resources.ApplyResources(this.ColumnMAC, "ColumnMAC"); this.ColumnMAC.Name = "ColumnMAC"; this.ColumnMAC.ReadOnly = true; // // ColumnLinkStatus // resources.ApplyResources(this.ColumnLinkStatus, "ColumnLinkStatus"); this.ColumnLinkStatus.Name = "ColumnLinkStatus"; this.ColumnLinkStatus.ReadOnly = true; // // ColumnSpeed // resources.ApplyResources(this.ColumnSpeed, "ColumnSpeed"); this.ColumnSpeed.Name = "ColumnSpeed"; this.ColumnSpeed.ReadOnly = true; // // ColumnDuplex // resources.ApplyResources(this.ColumnDuplex, "ColumnDuplex"); this.ColumnDuplex.Name = "ColumnDuplex"; this.ColumnDuplex.ReadOnly = true; // // ColumnVendorName // resources.ApplyResources(this.ColumnVendorName, "ColumnVendorName"); this.ColumnVendorName.Name = "ColumnVendorName"; this.ColumnVendorName.ReadOnly = true; // // ColumnDeviceName // resources.ApplyResources(this.ColumnDeviceName, "ColumnDeviceName"); this.ColumnDeviceName.Name = "ColumnDeviceName"; this.ColumnDeviceName.ReadOnly = true; // // ColumnBusPath // this.ColumnBusPath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnBusPath, "ColumnBusPath"); this.ColumnBusPath.Name = "ColumnBusPath"; this.ColumnBusPath.ReadOnly = true; // // contextMenuStrip1 // this.contextMenuStrip1.Name = "contextMenuStrip1"; resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1"); // // NICPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.DoubleBuffered = true; this.Name = "NICPage"; this.Controls.SetChildIndex(this.pageContainerPanel, 0); this.pageContainerPanel.ResumeLayout(false); this.pageContainerPanel.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label TitleLabel; private System.Windows.Forms.Button CreateBondButton; private System.Windows.Forms.Button DeleteBondButton; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button buttonRescan; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnNIC; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnMAC; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnLinkStatus; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSpeed; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDuplex; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnVendorName; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDeviceName; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnBusPath; } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * 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. * * 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. ******************************************************************************/ /** * Created at 4:35:29 AM Jul 15, 2010 */ using System; using SharpBox2D.Common; using SharpBox2D.Particle; namespace SharpBox2D.Callbacks { /** * Implement this abstract class to allow JBox2d to automatically draw your physics for debugging * purposes. Not intended to replace your own custom rendering routines! * * @author Daniel Murphy */ [Flags] public enum DebugDrawFlags { None = 0, Shapes = 1 << 1, Joints = 1 << 2, AABB = 1 << 3, Pairs = 1 << 4, CenterOfMass = 1 << 5, DynamicTree = 1 << 6, Wireframe = 1 << 7 } public abstract class DebugDraw { protected DebugDrawFlags m_drawFlags; protected IViewportTransform viewportTransform; protected DebugDraw() : this(null) { } protected DebugDraw(IViewportTransform viewport) { m_drawFlags = DebugDrawFlags.None; viewportTransform = viewport; } public void setViewportTransform(IViewportTransform viewportTransform) { this.viewportTransform = viewportTransform; } public void setFlags(DebugDrawFlags flags) { m_drawFlags = flags; } public DebugDrawFlags getFlags() { return m_drawFlags; } public void appendFlags(DebugDrawFlags flags) { m_drawFlags |= flags; } public void clearFlags(DebugDrawFlags flags) { m_drawFlags &= ~flags; } /** * Draw a closed polygon provided in CCW order. This implementation uses * {@link #drawSegment(Vec2, Vec2, Color4f)} to draw each side of the polygon. * * @param vertices * @param vertexCount * @param color */ public void drawPolygon(Vec2[] vertices, int vertexCount, Color4f color) { if (vertexCount == 1) { drawSegment(vertices[0], vertices[0], color); return; } for (int i = 0; i < vertexCount - 1; i += 1) { drawSegment(vertices[i], vertices[i + 1], color); } if (vertexCount > 2) { drawSegment(vertices[vertexCount - 1], vertices[0], color); } } public abstract void drawPoint(Vec2 argPoint, float argRadiusOnScreen, Color4f argColor); /** * Draw a solid closed polygon provided in CCW order. * * @param vertices * @param vertexCount * @param color */ public abstract void drawSolidPolygon(Vec2[] vertices, int vertexCount, Color4f color); /** * Draw a circle. * * @param center * @param radius * @param color */ public abstract void drawCircle(Vec2 center, float radius, Color4f color); /** Draws a circle with an axis */ public void drawCircle(Vec2 center, float radius, Vec2 axis, Color4f color) { drawCircle(center, radius, color); } /** * Draw a solid circle. * * @param center * @param radius * @param axis * @param color */ public abstract void drawSolidCircle(Vec2 center, float radius, Vec2 axis, Color4f color); /** * Draw a line segment. * * @param p1 * @param p2 * @param color */ public abstract void drawSegment(Vec2 p1, Vec2 p2, Color4f color); /** * Draw a transform. Choose your own length scale * * @param xf */ public abstract void drawTransform(Transform xf); /** * Draw a string. * * @param x * @param y * @param s * @param color */ public abstract void drawString(float x, float y, string s, Color4f color); /** * Draw a particle array * * @param colors can be null */ public abstract void drawParticles(Vec2[] centers, float radius, ParticleColor[] colors, int count); /** * Draw a particle array * * @param colors can be null */ public abstract void drawParticlesWireframe(Vec2[] centers, float radius, ParticleColor[] colors, int count); /** Called at the end of drawing a world */ public void flush() { } public void drawString(Vec2 pos, string s, Color4f color) { drawString(pos.x, pos.y, s, color); } public IViewportTransform getViewportTranform() { return viewportTransform; } /** * @param x * @param y * @param scale * @deprecated use the viewport transform in {@link #getViewportTranform()} */ public void setCamera(float x, float y, float scale) { viewportTransform.setCamera(x, y, scale); } /** * @param argScreen * @param argWorld */ public void getScreenToWorldToOut(Vec2 argScreen, Vec2 argWorld) { viewportTransform.getScreenToWorld(argScreen, argWorld); } /** * @param argWorld * @param argScreen */ public void getWorldToScreenToOut(Vec2 argWorld, Vec2 argScreen) { viewportTransform.getWorldToScreen(argWorld, argScreen); } /** * Takes the world coordinates and puts the corresponding screen coordinates in argScreen. * * @param worldX * @param worldY * @param argScreen */ public void getWorldToScreenToOut(float worldX, float worldY, Vec2 argScreen) { argScreen.set(worldX, worldY); viewportTransform.getWorldToScreen(argScreen, argScreen); } /** * takes the world coordinate (argWorld) and returns the screen coordinates. * * @param argWorld */ public Vec2 getWorldToScreen(Vec2 argWorld) { Vec2 screen = new Vec2(); viewportTransform.getWorldToScreen(argWorld, screen); return screen; } /** * Takes the world coordinates and returns the screen coordinates. * * @param worldX * @param worldY */ public Vec2 getWorldToScreen(float worldX, float worldY) { Vec2 argScreen = new Vec2(worldX, worldY); viewportTransform.getWorldToScreen(argScreen, argScreen); return argScreen; } /** * takes the screen coordinates and puts the corresponding world coordinates in argWorld. * * @param screenX * @param screenY * @param argWorld */ public void getScreenToWorldToOut(float screenX, float screenY, Vec2 argWorld) { argWorld.set(screenX, screenY); viewportTransform.getScreenToWorld(argWorld, argWorld); } /** * takes the screen coordinates (argScreen) and returns the world coordinates * * @param argScreen */ public Vec2 getScreenToWorld(Vec2 argScreen) { Vec2 world = new Vec2(); viewportTransform.getScreenToWorld(argScreen, world); return world; } /** * takes the screen coordinates and returns the world coordinates. * * @param screenX * @param screenY */ public Vec2 getScreenToWorld(float screenX, float screenY) { Vec2 screen = new Vec2(screenX, screenY); viewportTransform.getScreenToWorld(screen, screen); return screen; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Xunit; namespace System.Globalization.Tests { public class CultureInfoAll { [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoke to Win32 function public void TestAllCultures() { Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed"); Assert.All(cultures, Validate); } private void Validate(CultureInfo ci) { Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME)); // si-LK has some special case when running on Win7 so we just ignore this one if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase)) { Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName); } // zh-Hans and zh-Hant has different behavior on different platform Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase); Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME)); ValidateDTFI(ci); ValidateNFI(ci); ValidateRegionInfo(ci); } private void ValidateDTFI(CultureInfo ci) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; Calendar cal = dtfi.Calendar; int calId = GetCalendarId(cal); Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames); Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames); Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames); Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(calId, GetDefaultcalendar(ci)); Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK))); Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR)); Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true)); Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern); Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern); Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern); string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0]; string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE)); string longTimePattern1 = GetTimeFormats(ci, 0)[0]; string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT)); string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1; string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2; Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 }); Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 }); Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 }); Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) }); Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) }); Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) }); int eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); } private void ValidateNFI(CultureInfo ci) { NumberFormatInfo nfi = ci.NumberFormat; Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol); } private void ValidateRegionInfo(CultureInfo ci) { if (ci.Name.Length == 0) // no region for invariant return; RegionInfo ri = new RegionInfo(ci.Name); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric); Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol); Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase); } private int[] ConvertWin32GroupString(String win32Str) { // None of these cases make any sense if (win32Str == null || win32Str.Length == 0) { return (new int[] { 3 }); } if (win32Str[0] == '0') { return (new int[] { 0 }); } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str[win32Str.Length - 1] == '0') { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[(win32Str.Length / 2)]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[values.Length - 1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (win32Str[i] < '1' || win32Str[i] > '9') return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return (values); } private List<string> _timePatterns; private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam) { _timePatterns.Add(ReescapeWin32String(lpTimeFormatString)); return true; } private string[] GetTimeFormats(CultureInfo ci, uint flags) { _timePatterns = new List<string>(); Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), String.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags)); return _timePatterns.ToArray(); } internal String ReescapeWin32String(String str) { // If we don't have data, then don't try anything if (str == null) return null; StringBuilder result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) result.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[13]; for (uint i = 0; i < 13; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i, false); } return names; } private int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } private string[] GetDayNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[7]; for (uint i = 1; i < 7; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true); } names[0] = GetCalendarInfo(ci, calendar, calType + 6, true); return names; } private int GetCalendarId(Calendar cal) { int calId = 0; if (cal is System.Globalization.GregorianCalendar) { calId = (int)(cal as GregorianCalendar).CalendarType; } else if (cal is System.Globalization.JapaneseCalendar) { calId = CAL_JAPAN; } else if (cal is System.Globalization.TaiwanCalendar) { calId = CAL_TAIWAN; } else if (cal is System.Globalization.KoreanCalendar) { calId = CAL_KOREA; } else if (cal is System.Globalization.HijriCalendar) { calId = CAL_HIJRI; } else if (cal is System.Globalization.ThaiBuddhistCalendar) { calId = CAL_THAI; } else if (cal is System.Globalization.HebrewCalendar) { calId = CAL_HEBREW; } else if (cal is System.Globalization.UmAlQuraCalendar) { calId = CAL_UMALQURA; } else if (cal is System.Globalization.PersianCalendar) { calId = CAL_PERSIAN; } else { throw new KeyNotFoundException(String.Format("Got a calendar {0} which we cannot map its Id", cal)); } return calId; } internal bool EnumLocales(string name, uint dwFlags, IntPtr param) { CultureInfo ci = new CultureInfo(name); if (!ci.IsNeutralCulture) cultures.Add(ci); return true; } private string GetLocaleInfo(CultureInfo ci, uint lctype) { Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, String.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci)); return sb.ToString(); } private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail) { if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0) { Assert.False(throwInFail, String.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar)); return ""; } return ReescapeWin32String(sb.ToString()); } private List<int> _optionalCals = new List<int>(); private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _optionalCals.Add(calendar); return true; } private int[] GetOptionalCalendars(CultureInfo ci) { _optionalCals = new List<int>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed."); return _optionalCals.ToArray(); } private List<string> _calPatterns; private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _calPatterns.Add(ReescapeWin32String(lpCalendarInfoString)); return true; } private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType) { _calPatterns = new List<string>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo."); return _calPatterns.ToArray(); } private int GetDefaultcalendar(CultureInfo ci) { int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE); if (calId != 0) return calId; int[] cals = GetOptionalCalendars(ci); Assert.True(cals.Length > 0); return cals[0]; } private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType) { int data = 0; Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, String.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType)); return data; } internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param); internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam); internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam); internal static StringBuilder sb = new StringBuilder(400); internal static List<CultureInfo> cultures = new List<CultureInfo>(); internal const uint LOCALE_WINDOWS = 0x00000001; internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072; internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073; internal const uint LOCALE_SPARENT = 0x0000006d; internal const uint LOCALE_SISO639LANGNAME = 0x00000059; internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM" internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM" internal const uint LOCALE_ICALENDARTYPE = 0x00001009; internal const uint LOCALE_RETURN_NUMBER = 0x20000000; internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D; internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; internal const uint LOCALE_SLONGDATE = 0x00000020; internal const uint LOCALE_STIMEFORMAT = 0x00001003; internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000; internal const uint LOCALE_SSHORTDATE = 0x0000001F; internal const uint LOCALE_SSHORTTIME = 0x00000079; internal const uint LOCALE_SYEARMONTH = 0x00001006; internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign internal const uint LOCALE_SDECIMAL = 0x0000000E; internal const uint LOCALE_STHOUSAND = 0x0000000F; internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017; internal const uint LOCALE_SMONDECIMALSEP = 0x00000016; internal const uint LOCALE_SCURRENCY = 0x00000014; internal const uint LOCALE_IDIGITS = 0x00000011; internal const uint LOCALE_ICURRDIGITS = 0x00000019; internal const uint LOCALE_ICURRENCY = 0x0000001B; internal const uint LOCALE_INEGCURR = 0x0000001C; internal const uint LOCALE_INEGNUMBER = 0x00001010; internal const uint LOCALE_SMONGROUPING = 0x00000018; internal const uint LOCALE_SNAN = 0x00000069; internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity internal const uint LOCALE_SGROUPING = 0x00000010; internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074; internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075; internal const uint LOCALE_SPERCENT = 0x00000076; internal const uint LOCALE_SPERMILLE = 0x00000077; internal const uint LOCALE_SPOSINFINITY = 0x0000006a; internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002; internal const uint LOCALE_IMEASURE = 0x0000000D; internal const uint LOCALE_SINTLSYMBOL = 0x00000015; internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008; internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e; internal const uint CAL_SMONTHNAME1 = 0x00000015; internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022; internal const uint CAL_ICALINTVALUE = 0x00000001; internal const uint CAL_SDAYNAME1 = 0x00000007; internal const uint CAL_SLONGDATE = 0x00000006; internal const uint CAL_SMONTHDAY = 0x00000038; internal const uint CAL_SSHORTDATE = 0x00000005; internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031; internal const uint CAL_SYEARMONTH = 0x0000002f; internal const uint CAL_SERASTRING = 0x00000004; internal const uint CAL_SABBREVERASTRING = 0x00000039; internal const uint ENUM_ALL_CALENDARS = 0xffffffff; internal const uint TIME_NOSECONDS = 0x00000002; internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4; // Taiwan Era calendar internal const int CAL_KOREA = 5; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7; // Thai calendar internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam); public static IEnumerable<object[]> CultureInfo_TestData() { yield return new object[] { "en" , 0x0009, "en-US", "eng", "ENU", "en" , "en-US" }; yield return new object[] { "ar" , 0x0001, "ar-SA", "ara", "ARA", "ar" , "en-US" }; yield return new object[] { "en-US" , 0x0409, "en-US", "eng", "ENU", "en-US" , "en-US" }; yield return new object[] { "ar-SA" , 0x0401, "ar-SA", "ara", "ARA", "ar-SA" , "en-US" }; yield return new object[] { "ja-JP" , 0x0411, "ja-JP", "jpn", "JPN", "ja-JP" , "ja-JP" }; yield return new object[] { "zh-CN" , 0x0804, "zh-CN", "zho", "CHS", "zh-Hans-CN" , "zh-CN" }; yield return new object[] { "en-GB" , 0x0809, "en-GB", "eng", "ENG", "en-GB" , "en-GB" }; yield return new object[] { "tr-TR" , 0x041f, "tr-TR", "tur", "TRK", "tr-TR" , "tr-TR" }; } [Theory] [MemberData(nameof(CultureInfo_TestData))] public void LcidTest(string cultureName, int lcid, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName) { CultureInfo ci = new CultureInfo(lcid); Assert.Equal(cultureName, ci.Name); Assert.Equal(lcid, ci.LCID); Assert.True(ci.UseUserOverride, "UseUserOverride for lcid created culture expected to be true"); Assert.False(ci.IsReadOnly, "IsReadOnly for lcid created culture expected to be false"); Assert.Equal(threeLetterISOLanguageName, ci.ThreeLetterISOLanguageName); Assert.Equal(threeLetterWindowsLanguageName, ci.ThreeLetterWindowsLanguageName); ci = new CultureInfo(cultureName); Assert.Equal(cultureName, ci.Name); Assert.Equal(lcid, ci.LCID); Assert.True(ci.UseUserOverride, "UseUserOverride for named created culture expected to be true"); Assert.False(ci.IsReadOnly, "IsReadOnly for named created culture expected to be false"); ci = new CultureInfo(lcid, false); Assert.Equal(cultureName, ci.Name); Assert.Equal(lcid, ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with false user override culture expected to be false"); Assert.False(ci.IsReadOnly, "IsReadOnly with false user override culture expected to be false"); ci = CultureInfo.GetCultureInfo(lcid); Assert.Equal(cultureName, ci.Name); Assert.Equal(lcid, ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and lcid expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and lcid expected to be true"); ci = CultureInfo.GetCultureInfo(cultureName); Assert.Equal(cultureName, ci.Name); Assert.Equal(lcid, ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and name expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and name expected to be true"); ci = CultureInfo.GetCultureInfo(cultureName, ""); Assert.Equal(cultureName, ci.Name); Assert.Equal(lcid, ci.LCID); Assert.False(ci.UseUserOverride, "UseUserOverride with Culture created by GetCultureInfo and sort name expected to be false"); Assert.True(ci.IsReadOnly, "IsReadOnly with Culture created by GetCultureInfo and sort name expected to be true"); Assert.Equal(CultureInfo.InvariantCulture.TextInfo, ci.TextInfo); Assert.Equal(CultureInfo.InvariantCulture.CompareInfo, ci.CompareInfo); ci = CultureInfo.CreateSpecificCulture(cultureName); Assert.Equal(specificCultureName, ci.Name); ci = CultureInfo.GetCultureInfoByIetfLanguageTag(cultureName); Assert.Equal(cultureName, ci.Name); Assert.Equal(ci.Name, ci.IetfLanguageTag); Assert.Equal(lcid, ci.KeyboardLayoutId); Assert.Equal(consoleUICultureName, ci.GetConsoleFallbackUICulture().Name); } [Fact] public void InstalledUICultureTest() { var c1 = CultureInfo.InstalledUICulture; var c2 = CultureInfo.InstalledUICulture; // we cannot expect the value we get for InstalledUICulture without reading the OS. // instead we test ensuring the value doesn't change if we requested it multiple times. Assert.Equal(c1.Name, c2.Name); } [Theory] [MemberData(nameof(CultureInfo_TestData))] public void GetCulturesTest(string cultureName, int lcid, string specificCultureName, string threeLetterISOLanguageName, string threeLetterWindowsLanguageName, string alternativeCultureName, string consoleUICultureName) { bool found = false; Assert.All(CultureInfo.GetCultures(CultureTypes.NeutralCultures), c => Assert.True( (c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.NeutralCultures) != 0)) || c.Equals(CultureInfo.InvariantCulture))); found = CultureInfo.GetCultures(CultureTypes.NeutralCultures).Any(c => c.Name.Equals(cultureName, StringComparison.OrdinalIgnoreCase) || c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase)); Assert.All(CultureInfo.GetCultures(CultureTypes.SpecificCultures), c => Assert.True(!c.IsNeutralCulture && ((c.CultureTypes & CultureTypes.SpecificCultures) != 0))); if (!found) { found = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Any(c => c.Name.Equals(cultureName, StringComparison.OrdinalIgnoreCase) || c.Name.Equals(alternativeCultureName, StringComparison.OrdinalIgnoreCase)); } Assert.True(found, $"Expected to find the culture {cultureName} in the enumerated list"); } [Fact] public void ClearCachedDataTest() { CultureInfo ci = CultureInfo.GetCultureInfo("ja-JP"); Assert.True((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "Expected getting same object reference"); ci.ClearCachedData(); Assert.False((object) ci == (object) CultureInfo.GetCultureInfo("ja-JP"), "expected to get a new object reference"); } [Fact] public void CultureNotFoundExceptionTest() { AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("!@#$%^&*()")); AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture")); AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("longCulture" + new string('a', 100))); AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000)); CultureNotFoundException e = AssertExtensions.Throws<CultureNotFoundException>("name", () => new CultureInfo("This is invalid culture")); Assert.Equal("This is invalid culture", e.InvalidCultureName); e = AssertExtensions.Throws<CultureNotFoundException>("culture", () => new CultureInfo(0x1000)); Assert.Equal(0x1000, e.InvalidCultureId); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using ColladaXna.Base; using System.IO; using ColladaXna.Base.Geometry; using ColladaXna.Base.Materials; namespace ColladaXnaImporter { using CVertexChannel = ColladaXna.Base.Geometry.VertexChannel; /// <summary> /// This class imports a COLLADA ".dae" file into the XNA default content model for models. /// As a result models imported with this class can be processed and loaded with all the /// default content processors just like FBX models. /// </summary> [ContentImporter(".dae", CacheImportedData = true, DisplayName="COLLADA Standard Importer", DefaultProcessor="ModelProcessor")] public class ColladaStdModelImporter : ContentImporter<NodeContent> { /// <summary> /// This options determines how vertex channels for skinned mesh animation are imported. /// If true, a single vertex channel called "Weights" containing "BoneWeightCollection" /// elements is created. Otherwise two separate channels "BlendIndices0" and /// "BlendWeights0" are created, containing Vector4 and Vector3 elements. /// </summary> public const Boolean UseBoneWeightCollection = true; ColladaModel collada; protected static ContentImporterContext importerContext; NodeContent rootNode; MeshBuilder meshBuilder; Dictionary<String, MaterialContent> materials; static int boneIndex = 0; // Set true to exclude vertex channels for blend weights and indices bool excludeBlendWeights = false; /// <summary> /// Imports the COLLADA Model from the given .DAE file into the XNA Content Model. /// </summary> /// <param name="filename">Path to .DAE file</param> /// <param name="context">Context (is not used)</param> /// <returns></returns> public override NodeContent Import(string filename, ContentImporterContext context) { boneIndex = 0; importerContext = context; // Load the complete collada model which is to be converted / imported collada = new ColladaModel(filename); //Debugger.Launch(); //Debugger.Break(); rootNode = new NodeContent(); rootNode.Name = Path.GetFileNameWithoutExtension(filename); rootNode.Identity = new ContentIdentity(filename); // The default XNA processor only supports up to 255 joints / bones if (collada.Joints.Count < 255) { CreateBones(CreateAnimations()); } else { String helpLink = ""; ContentIdentity cid = rootNode.Identity; String msg = String.Format("Model contains {0} bones. Maximum is 255. " + "Skinning Data (Bones and Vertex Channels) will not be imported!", collada.Joints.Count); importerContext.Logger.LogWarning(helpLink, cid, msg); excludeBlendWeights = true; } CreateMaterials(); CreateMeshes(); return rootNode; } /// <summary> /// Creates BasicMaterialContent instances for each COLLADA material and stores /// them in the "materials" dictionary of this class. /// </summary> void CreateMaterials() { materials = new Dictionary<string, MaterialContent>(); for (int i = 0; i < collada.Materials.Count; i++) { String baseDir = Path.GetDirectoryName(collada.SourceFilename) + "/"; BasicMaterialContent material = new BasicMaterialContent(); material.Name = collada.Materials[i].Name; var diffuse = collada.Materials[i].Properties.OfType<DiffuseColor>().FirstOrDefault(); if (diffuse != null) material.DiffuseColor = diffuse.Color.ToVector3(); var texture = collada.Materials[i].Properties.OfType<DiffuseMap>().FirstOrDefault(); if (texture != null) { String path = texture.Texture.Filename; if (!Path.IsPathRooted(path)) path = baseDir + "/" + path; material.Texture = new ExternalReference<TextureContent>(path); } var specular = collada.Materials[i].Properties.OfType<SpecularColor>().FirstOrDefault(); if (specular != null) material.SpecularColor = specular.Color.ToVector3(); var specpow = collada.Materials[i].Properties.OfType<SpecularPower>().FirstOrDefault(); if (specpow != null) material.SpecularPower = specpow.Value; var alpha = collada.Materials[i].Properties.OfType<Opacity>().FirstOrDefault(); if (alpha != null) material.Alpha = alpha.Value; var emissive = collada.Materials[i].Properties.OfType<EmissiveColor>().FirstOrDefault(); if (emissive != null) material.EmissiveColor = emissive.Color.ToVector3(); // Add other texture maps than Diffuse Map (non-standard) such as Normal Maps // and Specular Maps var textureMaps = from property in collada.Materials[i].Properties where property is TextureProperty && !(property is DiffuseMap) select property as TextureProperty; foreach (var textureMap in textureMaps) { String path = textureMap.Texture.Filename; if (!Path.IsPathRooted(path)) path = baseDir + "/" + path; material.OpaqueData.Add(textureMap.Name, path); material.Textures.Add(textureMap.Name, new ExternalReference<TextureContent>(path)); } materials.Add(material.Name, material); } } /// <summary> /// Creates MeshContent instances for each mesh in the COLLADA model and attaches /// them to the NodeContent root. /// </summary> void CreateMeshes() { foreach (Mesh mesh in collada.Meshes) { foreach (MeshPart part in mesh.MeshParts) { var material = materials[part.MaterialName]; meshBuilder = MeshBuilder.StartMesh(mesh.Name); meshBuilder.SwapWindingOrder = false; meshBuilder.MergeDuplicatePositions = false; meshBuilder.SetMaterial(material); meshBuilder.Name = mesh.Name; // Positions CVertexChannel posChannel = part.Vertices.VertexChannels.Where(c => c.Description.VertexElementUsage == VertexElementUsage.Position). FirstOrDefault(); VertexContainer container = part.Vertices; float[] data = container.Vertices; int posOffset = posChannel.Source.Offset; for (int i = 0; i < container.Vertices.Length; i += container.VertexSize) { Vector3 pos = new Vector3(data[i + posOffset + 0], data[i + posOffset + 1], data[i + posOffset + 2]); meshBuilder.CreatePosition(pos); } // Vertex channels other than position List<XnaVertexChannel> channels = new List<XnaVertexChannel>(); foreach (CVertexChannel cvChannel in part.Vertices.VertexChannels) { switch (cvChannel.Description.VertexElementUsage) { case VertexElementUsage.Position: // Position is already created above break; case VertexElementUsage.BlendWeight: case VertexElementUsage.BlendIndices: // When bone weight collections are used these two // channels get added separately later if (UseBoneWeightCollection || excludeBlendWeights) break; else goto default; default: // standard channel like texcoord, normal etc. channels.Add(new XnaVertexChannel(meshBuilder, cvChannel)); break; } } // BoneWeightCollection vertex channel if (UseBoneWeightCollection && !excludeBlendWeights) { try { channels.Add(new XnaBoneWeightChannel(meshBuilder, part.Vertices, collada.Joints)); } catch (Exception) { importerContext.Logger.LogMessage("No skinning information found"); } } // Triangles for (int i = 0; i < part.Indices.Length; i += 3) { for (int j = i; j < i + 3; j++) { // Set channel components (other than position) foreach (var channel in channels) channel.SetData(j); meshBuilder.AddTriangleVertex(part.Indices[j]); } } MeshContent meshContent = meshBuilder.FinishMesh(); if (material.OpaqueData.Count > 0) { // Copy opaque data from material to mesh for convenience and // to make it compatible to Normal Mapping sample from App Hub foreach (var pair in material.OpaqueData) { meshContent.OpaqueData.Add(pair.Key, pair.Value); } } else { importerContext.Logger.LogWarning(null, null, "No opaque data in mesh"); } rootNode.Children.Add(meshContent); } } } List<AnimationContent> CreateAnimations() { var animations = new List<AnimationContent>(); for (int i = 0; i < collada.JointAnimations.Count; i++) { var sourceAnim = collada.JointAnimations[i]; AnimationContent animation = new AnimationContent(); animation.Name = sourceAnim.Name ?? String.Format("Take {0:000}", (i+1)); animation.Duration = TimeSpan.FromSeconds(sourceAnim.EndTime - sourceAnim.StartTime); foreach (var sourceChannel in sourceAnim.Channels) { AnimationChannel channel = new AnimationChannel(); // Adds the different keyframes to the animation channel // NOTE: Might be better to sample the keyframes foreach (var sourceKeyframe in sourceChannel.Sampler.Keyframes) { TimeSpan time = TimeSpan.FromSeconds(sourceKeyframe.Time); Matrix transform = sourceKeyframe.Transform; AnimationKeyframe keyframe = new AnimationKeyframe(time, transform); channel.Add(keyframe); } String key = GetJointKey(sourceChannel.Target); animation.Channels.Add(key, channel); } animation.OpaqueData.Add("FPS", sourceAnim.FramesPerSecond); animations.Add(animation); } return animations; } /// <summary> /// Usually Joints (or Bones) are referenced by their name. However, in COLLADA /// names are optional. Instead each joint might only have an ID or SID, or nothing. /// This method generates a reliable string key for each joint. /// </summary> /// <param name="joint">An joint</param> /// <returns>String key that assumes one of the following possible values in ascending /// precedence (depending on the availability of each property): /// Name > GlobalID > ScopedID > Joint[NR]</returns> protected static String GetJointKey(Joint joint) { if (joint.Name != null && joint.Name.Length > 0) return joint.Name; if (joint.GlobalID != null && joint.GlobalID.Length > 0) return joint.GlobalID; if (joint.ScopedID != null && joint.ScopedID.Length > 0) return joint.ScopedID; return String.Format("Bone{0}", ++boneIndex); } void CreateBones(List<AnimationContent> animations) { if (collada.Joints.Count == 0) return; boneIndex = 0; Joint rootJoint = collada.Joints[collada.Joints.Count - 1]; // Create skeleton recursively from joints BoneContent root = CreateSkeleton(rootJoint); // Attach animations to root bone foreach (var animation in animations) root.Animations.Add(animation.Name, animation); rootNode.Children.Add(root); } BoneContent CreateSkeleton(Joint joint) { var bone = new BoneContent(); bone.Name = GetJointKey(joint); bone.Transform = joint.Transform; if (joint.Children != null && joint.Children.Count > 0) { foreach (var childJoint in joint.Children) { bone.Children.Add(CreateSkeleton(childJoint)); } } return bone; } /// <summary> /// Helper class for creating vertex channels with MeshBuilder /// from Collada VertexChannels. /// </summary> class XnaVertexChannel { protected MeshBuilder _meshBuilder; protected CVertexChannel _colladaVertexChannel; protected int _channelIndex; protected int _vertexSize; protected int _offset; /// <summary> /// Creates a new vertex channel using the given MeshBuilder based on a /// Collada VertexChannel. No data is initially added to the vertex channel! /// For this, use the SetData method. /// </summary> /// <param name="meshBuilder">MeshBuilder instance to store vertex channel in</param> /// <param name="colladaVertexChannel">Original COLLADA Vertex Channel</param> public XnaVertexChannel(MeshBuilder meshBuilder, CVertexChannel colladaVertexChannel) { _colladaVertexChannel = colladaVertexChannel; _meshBuilder = meshBuilder; _vertexSize = colladaVertexChannel.Source.Stride; _offset = colladaVertexChannel.Source.Offset; Create(); } protected XnaVertexChannel(MeshBuilder mb) { _meshBuilder = mb; } /// <summary> /// Creates the vertex channel using the MeshBuilder (no data is added yet). /// </summary> protected virtual void Create() { var usage = _colladaVertexChannel.Description.VertexElementUsage; int usageIndex = _colladaVertexChannel.Description.UsageIndex; // Construct correct usage string String usageString = VertexChannelNames.EncodeName(usage, usageIndex); // Generic standard channel (TexCoord, Normal, Binormal, etc.) switch (_colladaVertexChannel.Description.VertexElementFormat) { case VertexElementFormat.Vector4: _channelIndex = _meshBuilder.CreateVertexChannel<Vector4>(usageString); break; case VertexElementFormat.Vector3: _channelIndex = _meshBuilder.CreateVertexChannel<Vector3>(usageString); break; case VertexElementFormat.Vector2: _channelIndex = _meshBuilder.CreateVertexChannel<Vector2>(usageString); break; case VertexElementFormat.Single: _channelIndex = _meshBuilder.CreateVertexChannel<Single>(usageString); break; default: throw new Exception("Unexpected vertex element format"); } } /// <summary> /// Sets vertex channel data for the current vertex (controlled externally through the /// MeshBuilder instance) to the value found at given index in the original COLLADA /// Vertex Channel. /// </summary> /// <param name="index">Index of element in the original COLLADA Vertex Channel</param> public virtual void SetData(int index) { int i = _colladaVertexChannel.Indices[index] * _vertexSize + _offset; float[] data = _colladaVertexChannel.Source.Data; object value; switch (_colladaVertexChannel.Description.VertexElementFormat) { case VertexElementFormat.Vector4: value = new Vector4(data[i], data[i + 1], data[i + 2], data[i + 3]); break; case VertexElementFormat.Vector3: value = new Vector3(data[i], data[i + 1], data[i + 2]); break; case VertexElementFormat.Vector2: value = new Vector2(data[i], data[i + 1]); break; case VertexElementFormat.Single: value = data[i]; break; default: throw new Exception("Unexpected vertex element format"); } _meshBuilder.SetVertexChannelData(_channelIndex, value); } } class XnaBoneWeightChannel : XnaVertexChannel { JointList _joints; CVertexChannel _indicesChannel; CVertexChannel _weightChannel; int _indicesOffset; int _weightOffset; public XnaBoneWeightChannel(MeshBuilder mb, VertexContainer vc, JointList joints) : base(mb) { try { _indicesChannel = (from c in vc.VertexChannels where c.Contains(VertexElementUsage.BlendIndices) select c).First(); _weightChannel = (from c in vc.VertexChannels where c.Contains(VertexElementUsage.BlendWeight) select c).First(); } catch (Exception) { throw new Exception("Missing blend indices or weights"); } _joints = joints; _vertexSize = vc.VertexSize; _indicesOffset = _indicesChannel.Source.Offset; _weightOffset = _weightChannel.Source.Offset; this.Create(); } protected override void Create() { String usageString = VertexChannelNames.Weights(); _channelIndex = _meshBuilder.CreateVertexChannel<BoneWeightCollection>(usageString); } public override void SetData(int index) { int i = _indicesChannel.Indices[index] * _vertexSize + _indicesOffset; int j = _weightChannel.Indices[index] * _vertexSize + _weightOffset; // Both channels use the same source data float[] data = _indicesChannel.Source.Data; float[] blendIndices = new float[] { data[i + 0], data[i + 1], data[i + 2], data[i + 3] }; float[] blendWeights = new float[] { data[j + 0], data[j + 1], data[j + 2], 0 }; // Fourth blend weight is stored implicitly blendWeights[3] = 1 - blendWeights[0] - blendWeights[1] - blendWeights[2]; if (blendWeights[3] == 1) blendWeights[3] = 0; BoneWeightCollection weights = new BoneWeightCollection(); for (int k = 0; k < blendIndices.Length; k++) { int jointIndex = (int)blendIndices[k]; float jointWeight = blendWeights[k]; if (jointWeight <= 0) continue; String jointName = GetJointKey(_joints[jointIndex]); weights.Add(new BoneWeight(jointName, jointWeight)); } if (weights.Count > 0) _meshBuilder.SetVertexChannelData(_channelIndex, weights); } } } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Cecil.Metadata; using Mono.Collections.Generic; namespace Mono.Cecil { public enum MetadataType : byte { Void = ElementType.Void, Boolean = ElementType.Boolean, Char = ElementType.Char, SByte = ElementType.I1, Byte = ElementType.U1, Int16 = ElementType.I2, UInt16 = ElementType.U2, Int32 = ElementType.I4, UInt32 = ElementType.U4, Int64 = ElementType.I8, UInt64 = ElementType.U8, Single = ElementType.R4, Double = ElementType.R8, String = ElementType.String, Pointer = ElementType.Ptr, ByReference = ElementType.ByRef, ValueType = ElementType.ValueType, Class = ElementType.Class, Var = ElementType.Var, Array = ElementType.Array, GenericInstance = ElementType.GenericInst, TypedByReference = ElementType.TypedByRef, IntPtr = ElementType.I, UIntPtr = ElementType.U, FunctionPointer = ElementType.FnPtr, Object = ElementType.Object, MVar = ElementType.MVar, RequiredModifier = ElementType.CModReqD, OptionalModifier = ElementType.CModOpt, Sentinel = ElementType.Sentinel, Pinned = ElementType.Pinned, } // HACK - Reflexil - Partial for legacy classes public partial class TypeReference : MemberReference, IGenericParameterProvider, IGenericContext { string @namespace; bool value_type; internal IMetadataScope scope; internal ModuleDefinition module; internal ElementType etype = ElementType.None; string fullname; protected Collection<GenericParameter> generic_parameters; public override string Name { get { return base.Name; } set { if (IsWindowsRuntimeProjection && value != base.Name) throw new InvalidOperationException ("Projected type reference name can't be changed."); base.Name = value; ClearFullName (); } } public virtual string Namespace { get { return @namespace; } set { if (IsWindowsRuntimeProjection && value != @namespace) throw new InvalidOperationException ("Projected type reference namespace can't be changed."); @namespace = value; ClearFullName (); } } public virtual bool IsValueType { get { return value_type; } set { value_type = value; } } public override ModuleDefinition Module { get { if (module != null) return module; var declaring_type = this.DeclaringType; if (declaring_type != null) return declaring_type.Module; return null; } } internal new TypeReferenceProjection WindowsRuntimeProjection { get { return (TypeReferenceProjection) projection; } set { projection = value; } } IGenericParameterProvider IGenericContext.Type { get { return this; } } IGenericParameterProvider IGenericContext.Method { get { return null; } } GenericParameterType IGenericParameterProvider.GenericParameterType { get { return GenericParameterType.Type; } } public virtual bool HasGenericParameters { get { return !generic_parameters.IsNullOrEmpty (); } } public virtual Collection<GenericParameter> GenericParameters { get { if (generic_parameters != null) return generic_parameters; return generic_parameters = new GenericParameterCollection (this); } } public virtual IMetadataScope Scope { get { var declaring_type = this.DeclaringType; if (declaring_type != null) return declaring_type.Scope; return scope; } set { var declaring_type = this.DeclaringType; if (declaring_type != null) { if (IsWindowsRuntimeProjection && value != declaring_type.Scope) throw new InvalidOperationException ("Projected type scope can't be changed."); declaring_type.Scope = value; return; } if (IsWindowsRuntimeProjection && value != scope) throw new InvalidOperationException ("Projected type scope can't be changed."); scope = value; } } public bool IsNested { get { return this.DeclaringType != null; } } public override TypeReference DeclaringType { get { return base.DeclaringType; } set { if (IsWindowsRuntimeProjection && value != base.DeclaringType) throw new InvalidOperationException ("Projected type declaring type can't be changed."); base.DeclaringType = value; ClearFullName (); } } public override string FullName { get { if (fullname != null) return fullname; fullname = this.TypeFullName (); if (IsNested) fullname = DeclaringType.FullName + "/" + fullname; return fullname; } } public virtual bool IsByReference { get { return false; } } public virtual bool IsPointer { get { return false; } } public virtual bool IsSentinel { get { return false; } } public virtual bool IsArray { get { return false; } } public virtual bool IsGenericParameter { get { return false; } } public virtual bool IsGenericInstance { get { return false; } } public virtual bool IsRequiredModifier { get { return false; } } public virtual bool IsOptionalModifier { get { return false; } } public virtual bool IsPinned { get { return false; } } public virtual bool IsFunctionPointer { get { return false; } } public virtual bool IsPrimitive { get { return etype.IsPrimitive (); } } public virtual MetadataType MetadataType { get { switch (etype) { case ElementType.None: return IsValueType ? MetadataType.ValueType : MetadataType.Class; default: return (MetadataType) etype; } } } protected TypeReference (string @namespace, string name) : base (name) { this.@namespace = @namespace ?? string.Empty; this.token = new MetadataToken (TokenType.TypeRef, 0); } public TypeReference (string @namespace, string name, ModuleDefinition module, IMetadataScope scope) : this (@namespace, name) { this.module = module; this.scope = scope; } public TypeReference (string @namespace, string name, ModuleDefinition module, IMetadataScope scope, bool valueType) : this (@namespace, name, module, scope) { value_type = valueType; } protected virtual void ClearFullName () { this.fullname = null; } public virtual TypeReference GetElementType () { return this; } protected override IMemberDefinition ResolveDefinition () { return this.Resolve (); } public new virtual TypeDefinition Resolve () { var module = this.Module; if (module == null) throw new NotSupportedException (); return module.Resolve (this); } } static partial class Mixin { public static bool IsPrimitive (this ElementType self) { switch (self) { case ElementType.Boolean: case ElementType.Char: case ElementType.I: case ElementType.U: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: return true; default: return false; } } public static string TypeFullName (this TypeReference self) { return string.IsNullOrEmpty (self.Namespace) ? self.Name : self.Namespace + '.' + self.Name; } public static bool IsTypeOf (this TypeReference self, string @namespace, string name) { return self.Name == name && self.Namespace == @namespace; } public static bool IsTypeSpecification (this TypeReference type) { switch (type.etype) { case ElementType.Array: case ElementType.ByRef: case ElementType.CModOpt: case ElementType.CModReqD: case ElementType.FnPtr: case ElementType.GenericInst: case ElementType.MVar: case ElementType.Pinned: case ElementType.Ptr: case ElementType.SzArray: case ElementType.Sentinel: case ElementType.Var: return true; } return false; } public static TypeDefinition CheckedResolve (this TypeReference self) { var type = self.Resolve (); if (type == null) throw new ResolutionException (self); return type; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE40 || PORTABLE) using System.Numerics; #endif using System.Text; using System.IO; using System.Xml; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. /// </summary> public class JsonTextWriter : JsonWriter { private readonly TextWriter _writer; private Base64Encoder _base64Encoder; private char _indentChar; private int _indentation; private char _quoteChar; private bool _quoteName; private bool[] _charEscapeFlags; private char[] _writeBuffer; private Base64Encoder Base64Encoder { get { if (_base64Encoder == null) _base64Encoder = new Base64Encoder(_writer); return _base64Encoder; } } /// <summary> /// Gets or sets how many IndentChars to write for each level in the hierarchy when <see cref="Formatting"/> is set to <c>Formatting.Indented</c>. /// </summary> public int Indentation { get { return _indentation; } set { if (value < 0) throw new ArgumentException("Indentation value must be greater than 0."); _indentation = value; } } /// <summary> /// Gets or sets which character to use to quote attribute values. /// </summary> public char QuoteChar { get { return _quoteChar; } set { if (value != '"' && value != '\'') throw new ArgumentException(@"Invalid JavaScript string quote character. Valid quote characters are ' and ""."); _quoteChar = value; UpdateCharEscapeFlags(); } } /// <summary> /// Gets or sets which character to use for indenting when <see cref="Formatting"/> is set to <c>Formatting.Indented</c>. /// </summary> public char IndentChar { get { return _indentChar; } set { _indentChar = value; } } /// <summary> /// Gets or sets a value indicating whether object names will be surrounded with quotes. /// </summary> public bool QuoteName { get { return _quoteName; } set { _quoteName = value; } } /// <summary> /// Creates an instance of the <c>JsonWriter</c> class using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <c>TextWriter</c> to write to.</param> public JsonTextWriter(TextWriter textWriter) { if (textWriter == null) throw new ArgumentNullException("textWriter"); _writer = textWriter; _quoteChar = '"'; _quoteName = true; _indentChar = ' '; _indentation = 2; UpdateCharEscapeFlags(); } /// <summary> /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public override void Flush() { _writer.Flush(); } /// <summary> /// Closes this stream and the underlying stream. /// </summary> public override void Close() { base.Close(); if (CloseOutput && _writer != null) #if !(NETFX_CORE || PORTABLE40 || PORTABLE) _writer.Close(); #else _writer.Dispose(); #endif } /// <summary> /// Writes the beginning of a Json object. /// </summary> public override void WriteStartObject() { InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object); _writer.Write("{"); } /// <summary> /// Writes the beginning of a Json array. /// </summary> public override void WriteStartArray() { InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array); _writer.Write("["); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public override void WriteStartConstructor(string name) { InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor); _writer.Write("new "); _writer.Write(name); _writer.Write("("); } /// <summary> /// Writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> protected override void WriteEnd(JsonToken token) { switch (token) { case JsonToken.EndObject: _writer.Write("}"); break; case JsonToken.EndArray: _writer.Write("]"); break; case JsonToken.EndConstructor: _writer.Write(")"); break; default: throw JsonWriterException.Create(this, "Invalid JsonToken: " + token, null); } } /// <summary> /// Writes the property name of a name/value pair on a Json object. /// </summary> /// <param name="name">The name of the property.</param> public override void WritePropertyName(string name) { InternalWritePropertyName(name); WriteEscapedString(name); _writer.Write(':'); } /// <summary> /// Writes the property name of a name/value pair on a JSON object. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param> public override void WritePropertyName(string name, bool escape) { InternalWritePropertyName(name); if (escape) { WriteEscapedString(name); } else { if (_quoteName) _writer.Write(_quoteChar); _writer.Write(name); if (_quoteName) _writer.Write(_quoteChar); } _writer.Write(':'); } internal override void OnStringEscapeHandlingChanged() { UpdateCharEscapeFlags(); } private void UpdateCharEscapeFlags() { if (StringEscapeHandling == StringEscapeHandling.EscapeHtml) _charEscapeFlags = JavaScriptUtils.HtmlCharEscapeFlags; else if (_quoteChar == '"') _charEscapeFlags = JavaScriptUtils.DoubleQuoteCharEscapeFlags; else _charEscapeFlags = JavaScriptUtils.SingleQuoteCharEscapeFlags; } /// <summary> /// Writes indent characters. /// </summary> protected override void WriteIndent() { _writer.Write(Environment.NewLine); // levels of indentation multiplied by the indent count int currentIndentCount = Top*_indentation; while (currentIndentCount > 0) { // write up to a max of 10 characters at once to avoid creating too many new strings int writeCount = Math.Min(currentIndentCount, 10); _writer.Write(new string(_indentChar, writeCount)); currentIndentCount -= writeCount; } } /// <summary> /// Writes the JSON value delimiter. /// </summary> protected override void WriteValueDelimiter() { _writer.Write(','); } /// <summary> /// Writes an indent space. /// </summary> protected override void WriteIndentSpace() { _writer.Write(' '); } private void WriteValueInternal(string value, JsonToken token) { _writer.Write(value); } #region WriteValue methods /// <summary> /// Writes a <see cref="Object"/> value. /// An error will raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public override void WriteValue(object value) { #if !(NET20 || NET35 || SILVERLIGHT || PORTABLE || PORTABLE40) if (value is BigInteger) { InternalWriteValue(JsonToken.Integer); WriteValueInternal(((BigInteger)value).ToString(CultureInfo.InvariantCulture), JsonToken.String); } else #endif { base.WriteValue(value); } } /// <summary> /// Writes a null value. /// </summary> public override void WriteNull() { InternalWriteValue(JsonToken.Null); WriteValueInternal(JsonConvert.Null, JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public override void WriteUndefined() { InternalWriteValue(JsonToken.Undefined); WriteValueInternal(JsonConvert.Undefined, JsonToken.Undefined); } /// <summary> /// Writes raw JSON. /// </summary> /// <param name="json">The raw JSON to write.</param> public override void WriteRaw(string json) { InternalWriteRaw(); _writer.Write(json); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public override void WriteValue(string value) { InternalWriteValue(JsonToken.String); if (value == null) WriteValueInternal(JsonConvert.Null, JsonToken.Null); else WriteEscapedString(value); } private void WriteEscapedString(string value) { EnsureWriteBuffer(); JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, true, _charEscapeFlags, StringEscapeHandling, ref _writeBuffer); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public override void WriteValue(int value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(uint value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public override void WriteValue(long value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(ulong value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public override void WriteValue(float value) { InternalWriteValue(JsonToken.Float); WriteValueInternal(JsonConvert.ToString(value, FloatFormatHandling, QuoteChar, false), JsonToken.Float); } /// <summary> /// Writes a <see cref="Nullable{Single}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param> public override void WriteValue(float? value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.Float); WriteValueInternal(JsonConvert.ToString(value.Value, FloatFormatHandling, QuoteChar, true), JsonToken.Float); } } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public override void WriteValue(double value) { InternalWriteValue(JsonToken.Float); WriteValueInternal(JsonConvert.ToString(value, FloatFormatHandling, QuoteChar, false), JsonToken.Float); } /// <summary> /// Writes a <see cref="Nullable{Double}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param> public override void WriteValue(double? value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.Float); WriteValueInternal(JsonConvert.ToString(value.Value, FloatFormatHandling, QuoteChar, true), JsonToken.Float); } } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public override void WriteValue(bool value) { InternalWriteValue(JsonToken.Boolean); WriteValueInternal(JsonConvert.ToString(value), JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public override void WriteValue(short value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(ushort value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public override void WriteValue(char value) { InternalWriteValue(JsonToken.String); WriteValueInternal(JsonConvert.ToString(value), JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public override void WriteValue(byte value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public override void WriteValue(sbyte value) { InternalWriteValue(JsonToken.Integer); WriteIntegerValue(value); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public override void WriteValue(decimal value) { InternalWriteValue(JsonToken.Float); WriteValueInternal(JsonConvert.ToString(value), JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public override void WriteValue(DateTime value) { InternalWriteValue(JsonToken.Date); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); if (string.IsNullOrEmpty(DateFormatString)) { EnsureWriteBuffer(); int pos = 0; _writeBuffer[pos++] = _quoteChar; pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, value, null, value.Kind, DateFormatHandling); _writeBuffer[pos++] = _quoteChar; _writer.Write(_writeBuffer, 0, pos); } else { _writer.Write(_quoteChar); _writer.Write(value.ToString(DateFormatString, Culture)); _writer.Write(_quoteChar); } } /// <summary> /// Writes a <see cref="T:Byte[]"/> value. /// </summary> /// <param name="value">The <see cref="T:Byte[]"/> value to write.</param> public override void WriteValue(byte[] value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.Bytes); _writer.Write(_quoteChar); Base64Encoder.Encode(value, 0, value.Length); Base64Encoder.Flush(); _writer.Write(_quoteChar); } } #if !NET20 /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public override void WriteValue(DateTimeOffset value) { InternalWriteValue(JsonToken.Date); if (string.IsNullOrEmpty(DateFormatString)) { EnsureWriteBuffer(); int pos = 0; _writeBuffer[pos++] = _quoteChar; pos = DateTimeUtils.WriteDateTimeString(_writeBuffer, pos, (DateFormatHandling == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, DateFormatHandling); _writeBuffer[pos++] = _quoteChar; _writer.Write(_writeBuffer, 0, pos); } else { _writer.Write(_quoteChar); _writer.Write(value.ToString(DateFormatString, Culture)); _writer.Write(_quoteChar); } } #endif /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public override void WriteValue(Guid value) { InternalWriteValue(JsonToken.String); WriteValueInternal(JsonConvert.ToString(value, _quoteChar), JsonToken.String); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public override void WriteValue(TimeSpan value) { InternalWriteValue(JsonToken.String); WriteValueInternal(JsonConvert.ToString(value, _quoteChar), JsonToken.String); } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public override void WriteValue(Uri value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.String); WriteValueInternal(JsonConvert.ToString(value, _quoteChar), JsonToken.String); } } #endregion /// <summary> /// Writes out a comment <code>/*...*/</code> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public override void WriteComment(string text) { InternalWriteComment(); _writer.Write("/*"); _writer.Write(text); _writer.Write("*/"); } /// <summary> /// Writes out the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public override void WriteWhitespace(string ws) { InternalWriteWhitespace(ws); _writer.Write(ws); } private void EnsureWriteBuffer() { if (_writeBuffer == null) _writeBuffer = new char[64]; } private void WriteIntegerValue(long value) { EnsureWriteBuffer(); if (value >= 0 && value <= 9) { _writer.Write((char)('0' + value)); } else { ulong uvalue = (value < 0) ? (ulong)-value : (ulong)value; if (value < 0) _writer.Write('-'); WriteIntegerValue(uvalue); } } private void WriteIntegerValue(ulong uvalue) { EnsureWriteBuffer(); if (uvalue <= 9) { _writer.Write((char)('0' + uvalue)); } else { int totalLength = MathUtils.IntLength(uvalue); int length = 0; do { _writeBuffer[totalLength - ++length] = (char)('0' + (uvalue % 10)); uvalue /= 10; } while (uvalue != 0); _writer.Write(_writeBuffer, 0, length); } } } }
// 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.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class Http3TimeoutTests : Http3TestBase { [Fact] public async Task HEADERS_IncompleteFrameReceivedWithinRequestHeadersTimeout_StreamError() { var now = _serviceContext.MockSystemClock.UtcNow; var limits = _serviceContext.ServerOptions.Limits; var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(_noopApplication).DefaultTimeout(); var controlStream = await Http3Api.GetInboundControlStream().DefaultTimeout(); await controlStream.ExpectSettingsAsync().DefaultTimeout(); await requestStream.OnStreamCreatedTask.DefaultTimeout(); var serverRequestStream = Http3Api.Connection._streams[requestStream.StreamId]; await requestStream.SendHeadersPartialAsync().DefaultTimeout(); Http3Api.TriggerTick(now); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout); Assert.Equal((now + limits.RequestHeadersTimeout).Ticks, serverRequestStream.StreamTimeoutTicks); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout + TimeSpan.FromTicks(1)); await requestStream.WaitForStreamErrorAsync( Http3ErrorCode.RequestRejected, AssertExpectedErrorMessages, CoreStrings.BadRequest_RequestHeadersTimeout); } [Fact] public async Task HEADERS_HeaderFrameReceivedWithinRequestHeadersTimeout_Success() { var now = _serviceContext.MockSystemClock.UtcNow; var limits = _serviceContext.ServerOptions.Limits; var headers = new[] { new KeyValuePair<string, string>(HeaderNames.Method, "Custom"), new KeyValuePair<string, string>(HeaderNames.Path, "/"), new KeyValuePair<string, string>(HeaderNames.Scheme, "http"), new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"), }; var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(_noopApplication).DefaultTimeout(); var controlStream = await Http3Api.GetInboundControlStream().DefaultTimeout(); await controlStream.ExpectSettingsAsync().DefaultTimeout(); await requestStream.OnStreamCreatedTask.DefaultTimeout(); var serverRequestStream = Http3Api.Connection._streams[requestStream.StreamId]; Http3Api.TriggerTick(now); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout); Assert.Equal((now + limits.RequestHeadersTimeout).Ticks, serverRequestStream.StreamTimeoutTicks); await requestStream.SendHeadersAsync(headers).DefaultTimeout(); await requestStream.OnHeaderReceivedTask.DefaultTimeout(); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout + TimeSpan.FromTicks(1)); await requestStream.SendDataAsync(Memory<byte>.Empty, endStream: true); await requestStream.ExpectHeadersAsync(); await requestStream.ExpectReceiveEndOfStream(); } [Fact] public async Task ControlStream_HeaderNotReceivedWithinRequestHeadersTimeout_StreamError() { var now = _serviceContext.MockSystemClock.UtcNow; var limits = _serviceContext.ServerOptions.Limits; var headers = new[] { new KeyValuePair<string, string>(HeaderNames.Method, "Custom"), new KeyValuePair<string, string>(HeaderNames.Path, "/"), new KeyValuePair<string, string>(HeaderNames.Scheme, "http"), new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"), }; await Http3Api.InitializeConnectionAsync(_noopApplication).DefaultTimeout(); var controlStream = await Http3Api.GetInboundControlStream().DefaultTimeout(); await controlStream.ExpectSettingsAsync().DefaultTimeout(); var outboundControlStream = await Http3Api.CreateControlStream(id: null); await outboundControlStream.OnStreamCreatedTask.DefaultTimeout(); var serverInboundControlStream = Http3Api.Connection._streams[outboundControlStream.StreamId]; Http3Api.TriggerTick(now); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout); Assert.Equal((now + limits.RequestHeadersTimeout).Ticks, serverInboundControlStream.StreamTimeoutTicks); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout + TimeSpan.FromTicks(1)); await outboundControlStream.WaitForStreamErrorAsync( Http3ErrorCode.StreamCreationError, AssertExpectedErrorMessages, CoreStrings.Http3ControlStreamHeaderTimeout); } [Fact] public async Task ControlStream_HeaderReceivedWithinRequestHeadersTimeout_StreamError() { var now = _serviceContext.MockSystemClock.UtcNow; var limits = _serviceContext.ServerOptions.Limits; var headers = new[] { new KeyValuePair<string, string>(HeaderNames.Method, "Custom"), new KeyValuePair<string, string>(HeaderNames.Path, "/"), new KeyValuePair<string, string>(HeaderNames.Scheme, "http"), new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"), }; await Http3Api.InitializeConnectionAsync(_noopApplication).DefaultTimeout(); var controlStream = await Http3Api.GetInboundControlStream().DefaultTimeout(); await controlStream.ExpectSettingsAsync().DefaultTimeout(); var outboundControlStream = await Http3Api.CreateControlStream(id: null); await outboundControlStream.OnStreamCreatedTask.DefaultTimeout(); Http3Api.TriggerTick(now); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout); await outboundControlStream.WriteStreamIdAsync(id: 0); await outboundControlStream.OnHeaderReceivedTask.DefaultTimeout(); Http3Api.TriggerTick(now + limits.RequestHeadersTimeout + TimeSpan.FromTicks(1)); } [Fact] public async Task ControlStream_RequestHeadersTimeoutMaxValue_ExpirationIsMaxValue() { var now = _serviceContext.MockSystemClock.UtcNow; var limits = _serviceContext.ServerOptions.Limits; limits.RequestHeadersTimeout = TimeSpan.MaxValue; var headers = new[] { new KeyValuePair<string, string>(HeaderNames.Method, "Custom"), new KeyValuePair<string, string>(HeaderNames.Path, "/"), new KeyValuePair<string, string>(HeaderNames.Scheme, "http"), new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"), }; await Http3Api.InitializeConnectionAsync(_noopApplication).DefaultTimeout(); var controlStream = await Http3Api.GetInboundControlStream().DefaultTimeout(); await controlStream.ExpectSettingsAsync().DefaultTimeout(); var outboundControlStream = await Http3Api.CreateControlStream(id: null); await outboundControlStream.OnStreamCreatedTask.DefaultTimeout(); var serverInboundControlStream = Http3Api.Connection._streams[outboundControlStream.StreamId]; Http3Api.TriggerTick(now); Assert.Equal(TimeSpan.MaxValue.Ticks, serverInboundControlStream.StreamTimeoutTicks); } [Fact] public async Task DATA_Received_TooSlowlyOnSmallRead_AbortsConnectionAfterGracePeriod() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(_readRateApplication); var inboundControlStream = await Http3Api.GetInboundControlStream(); await inboundControlStream.ExpectSettingsAsync(); // _helloWorldBytes is 12 bytes, and 12 bytes / 240 bytes/sec = .05 secs which is far below the grace period. await requestStream.SendHeadersAsync(ReadRateRequestHeaders(_helloWorldBytes.Length), endStream: false); await requestStream.SendDataAsync(_helloWorldBytes, endStream: false); await requestStream.ExpectHeadersAsync(); await requestStream.ExpectDataAsync(); // Don't send any more data and advance just to and then past the grace period. Http3Api.AdvanceClock(limits.MinRequestBodyDataRate.GracePeriod); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromTicks(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once); await Http3Api.WaitForConnectionErrorAsync<ConnectionAbortedException>( ignoreNonGoAwayFrames: false, expectedLastStreamId: 4, Http3ErrorCode.InternalError, null); _mockTimeoutHandler.VerifyNoOtherCalls(); } [Fact] public async Task ResponseDrain_SlowerThanMinimumDataRate_AbortsConnection() { var now = _serviceContext.MockSystemClock.UtcNow; var limits = _serviceContext.ServerOptions.Limits; var mockSystemClock = _serviceContext.MockSystemClock; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); await Http3Api.InitializeConnectionAsync(_noopApplication); var inboundControlStream = await Http3Api.GetInboundControlStream(); await inboundControlStream.ExpectSettingsAsync(); var requestStream = await Http3Api.CreateRequestStream(); requestStream.StartStreamDisposeTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await requestStream.SendHeadersAsync(new[] { new KeyValuePair<string, string>(HeaderNames.Path, "/"), new KeyValuePair<string, string>(HeaderNames.Scheme, "http"), new KeyValuePair<string, string>(HeaderNames.Method, "GET"), new KeyValuePair<string, string>(HeaderNames.Authority, "localhost:80"), }, endStream: true); await requestStream.OnDisposingTask.DefaultTimeout(); Http3Api.TriggerTick(now); Assert.Null(requestStream.StreamContext._error); Http3Api.TriggerTick(now + TimeSpan.FromTicks(1)); Assert.Null(requestStream.StreamContext._error); Http3Api.TriggerTick(now + limits.MinResponseDataRate.GracePeriod + TimeSpan.FromTicks(1)); requestStream.StartStreamDisposeTcs.TrySetResult(); await Http3Api.WaitForConnectionErrorAsync<ConnectionAbortedException>( ignoreNonGoAwayFrames: false, expectedLastStreamId: 4, Http3ErrorCode.InternalError, expectedErrorMessage: CoreStrings.ConnectionTimedBecauseResponseMininumDataRateNotSatisfied); Assert.Contains(TestSink.Writes, w => w.EventId.Name == "ResponseMinimumDataRateNotSatisfied"); } private class EchoAppWithNotification { private readonly TaskCompletionSource _writeStartedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); public Task WriteStartedTask => _writeStartedTcs.Task; public async Task RunApp(HttpContext context) { await context.Response.Body.FlushAsync(); var buffer = new byte[16 * 1024]; int received; while ((received = await context.Request.Body.ReadAsync(buffer, 0, buffer.Length)) > 0) { var writeTask = context.Response.Body.WriteAsync(buffer, 0, received); _writeStartedTcs.TrySetResult(); await writeTask; } } } [Fact] public async Task DATA_Sent_TooSlowlyDueToSocketBackPressureOnSmallWrite_AbortsConnectionAfterGracePeriod() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); // Disable response buffering so "socket" backpressure is observed immediately. limits.MaxResponseBufferSize = 0; Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); var app = new EchoAppWithNotification(); var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(app.RunApp); await requestStream.SendHeadersAsync(_browserRequestHeaders, endStream: false); await requestStream.SendDataAsync(_helloWorldBytes, endStream: true); await requestStream.ExpectHeadersAsync(); await app.WriteStartedTask.DefaultTimeout(); // Complete timing of the request body so we don't induce any unexpected request body rate timeouts. Http3Api._timeoutControl.Tick(mockSystemClock.UtcNow); // Don't read data frame to induce "socket" backpressure. Http3Api.AdvanceClock(TimeSpan.FromSeconds((requestStream.BytesReceived + _helloWorldBytes.Length) / limits.MinResponseDataRate.BytesPerSecond) + limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5)); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromSeconds(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once); // The "hello, world" bytes are buffered from before the timeout, but not an END_STREAM data frame. var data = await requestStream.ExpectDataAsync(); Assert.Equal(_helloWorldBytes.Length, data.Length); _mockTimeoutHandler.VerifyNoOtherCalls(); } [Fact] public async Task DATA_Sent_TooSlowlyDueToSocketBackPressureOnLargeWrite_AbortsConnectionAfterRateTimeout() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinResponseDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); // Disable response buffering so "socket" backpressure is observed immediately. limits.MaxResponseBufferSize = 0; Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); var app = new EchoAppWithNotification(); var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(app.RunApp); await requestStream.SendHeadersAsync(_browserRequestHeaders, endStream: false); await requestStream.SendDataAsync(_maxData, endStream: true); await requestStream.ExpectHeadersAsync(); await app.WriteStartedTask.DefaultTimeout(); // Complete timing of the request body so we don't induce any unexpected request body rate timeouts. Http3Api._timeoutControl.Tick(mockSystemClock.UtcNow); var timeToWriteMaxData = TimeSpan.FromSeconds((requestStream.BytesReceived + _maxData.Length) / limits.MinResponseDataRate.BytesPerSecond) + limits.MinResponseDataRate.GracePeriod + Heartbeat.Interval - TimeSpan.FromSeconds(.5); // Don't read data frame to induce "socket" backpressure. Http3Api.AdvanceClock(timeToWriteMaxData); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromSeconds(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.WriteDataRate), Times.Once); // The _maxData bytes are buffered from before the timeout, but not an END_STREAM data frame. await requestStream.ExpectDataAsync(); _mockTimeoutHandler.VerifyNoOtherCalls(); } [Fact] public async Task DATA_Received_TooSlowlyOnLargeRead_AbortsConnectionAfterRateTimeout() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(_readRateApplication); var inboundControlStream = await Http3Api.GetInboundControlStream(); await inboundControlStream.ExpectSettingsAsync(); // _maxData is 16 KiB, and 16 KiB / 240 bytes/sec ~= 68 secs which is far above the grace period. await requestStream.SendHeadersAsync(ReadRateRequestHeaders(_maxData.Length), endStream: false); await requestStream.SendDataAsync(_maxData, endStream: false); await requestStream.ExpectHeadersAsync(); await requestStream.ExpectDataAsync(); // Due to the imprecision of floating point math and the fact that TimeoutControl derives rate from elapsed // time for reads instead of vice versa like for writes, use a half-second instead of single-tick cushion. var timeToReadMaxData = TimeSpan.FromSeconds(_maxData.Length / limits.MinRequestBodyDataRate.BytesPerSecond) - TimeSpan.FromSeconds(.5); // Don't send any more data and advance just to and then past the rate timeout. Http3Api.AdvanceClock(timeToReadMaxData); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromSeconds(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once); await Http3Api.WaitForConnectionErrorAsync<ConnectionAbortedException>( ignoreNonGoAwayFrames: false, expectedLastStreamId: null, Http3ErrorCode.InternalError, null); _mockTimeoutHandler.VerifyNoOtherCalls(); } [Fact] public async Task DATA_Received_TooSlowlyOnMultipleStreams_AbortsConnectionAfterAdditiveRateTimeout() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); await Http3Api.InitializeConnectionAsync(_readRateApplication); var inboundControlStream = await Http3Api.GetInboundControlStream(); await inboundControlStream.ExpectSettingsAsync(); var requestStream1 = await Http3Api.CreateRequestStream(); // _maxData is 16 KiB, and 16 KiB / 240 bytes/sec ~= 68 secs which is far above the grace period. await requestStream1.SendHeadersAsync(ReadRateRequestHeaders(_maxData.Length), endStream: false); await requestStream1.SendDataAsync(_maxData, endStream: false); await requestStream1.ExpectHeadersAsync(); await requestStream1.ExpectDataAsync(); var requestStream2 = await Http3Api.CreateRequestStream(); await requestStream2.SendHeadersAsync(ReadRateRequestHeaders(_maxData.Length), endStream: false); await requestStream2.SendDataAsync(_maxData, endStream: false); await requestStream2.ExpectHeadersAsync(); await requestStream2.ExpectDataAsync(); var timeToReadMaxData = TimeSpan.FromSeconds(_maxData.Length / limits.MinRequestBodyDataRate.BytesPerSecond); // Double the timeout for the second stream. timeToReadMaxData += timeToReadMaxData; // Due to the imprecision of floating point math and the fact that TimeoutControl derives rate from elapsed // time for reads instead of vice versa like for writes, use a half-second instead of single-tick cushion. timeToReadMaxData -= TimeSpan.FromSeconds(.5); // Don't send any more data and advance just to and then past the rate timeout. Http3Api.AdvanceClock(timeToReadMaxData); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromSeconds(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once); await Http3Api.WaitForConnectionErrorAsync<ConnectionAbortedException>( ignoreNonGoAwayFrames: false, expectedLastStreamId: null, Http3ErrorCode.InternalError, null); _mockTimeoutHandler.VerifyNoOtherCalls(); } [Fact] public async Task DATA_Received_TooSlowlyOnSecondStream_AbortsConnectionAfterNonAdditiveRateTimeout() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); await Http3Api.InitializeConnectionAsync(_readRateApplication); var inboundControlStream = await Http3Api.GetInboundControlStream(); await inboundControlStream.ExpectSettingsAsync(); Logger.LogInformation("Sending first request"); var requestStream1 = await Http3Api.CreateRequestStream(); // _maxData is 16 KiB, and 16 KiB / 240 bytes/sec ~= 68 secs which is far above the grace period. await requestStream1.SendHeadersAsync(ReadRateRequestHeaders(_maxData.Length), endStream: false); await requestStream1.SendDataAsync(_maxData, endStream: true); await requestStream1.ExpectHeadersAsync(); await requestStream1.ExpectDataAsync(); await requestStream1.ExpectReceiveEndOfStream(); Logger.LogInformation("Sending second request"); var requestStream2 = await Http3Api.CreateRequestStream(); await requestStream2.SendHeadersAsync(ReadRateRequestHeaders(_maxData.Length), endStream: false); await requestStream2.SendDataAsync(_maxData, endStream: false); await requestStream2.ExpectHeadersAsync(); await requestStream2.ExpectDataAsync(); // Due to the imprecision of floating point math and the fact that TimeoutControl derives rate from elapsed // time for reads instead of vice versa like for writes, use a half-second instead of single-tick cushion. var timeToReadMaxData = TimeSpan.FromSeconds(_maxData.Length / limits.MinRequestBodyDataRate.BytesPerSecond) - TimeSpan.FromSeconds(.5); // Don't send any more data and advance just to and then past the rate timeout. Http3Api.AdvanceClock(timeToReadMaxData); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromSeconds(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(TimeoutReason.ReadDataRate), Times.Once); await Http3Api.WaitForConnectionErrorAsync<ConnectionAbortedException>( ignoreNonGoAwayFrames: false, expectedLastStreamId: null, Http3ErrorCode.InternalError, null); _mockTimeoutHandler.VerifyNoOtherCalls(); } [Fact] public async Task DATA_Received_SlowlyWhenRateLimitDisabledPerRequest_DoesNotAbortConnection() { var mockSystemClock = _serviceContext.MockSystemClock; var limits = _serviceContext.ServerOptions.Limits; // Use non-default value to ensure the min request and response rates aren't mixed up. limits.MinRequestBodyDataRate = new MinDataRate(480, TimeSpan.FromSeconds(2.5)); Http3Api._timeoutControl.Initialize(mockSystemClock.UtcNow.Ticks); var requestStream = await Http3Api.InitializeConnectionAndStreamsAsync(context => { // Completely disable rate limiting for this stream. context.Features.Get<IHttpMinRequestBodyDataRateFeature>().MinDataRate = null; return _readRateApplication(context); }); var inboundControlStream = await Http3Api.GetInboundControlStream(); await inboundControlStream.ExpectSettingsAsync(); // _helloWorldBytes is 12 bytes, and 12 bytes / 240 bytes/sec = .05 secs which is far below the grace period. await requestStream.SendHeadersAsync(ReadRateRequestHeaders(_helloWorldBytes.Length), endStream: false); await requestStream.SendDataAsync(_helloWorldBytes, endStream: false); await requestStream.ExpectHeadersAsync(); await requestStream.ExpectDataAsync(); // Don't send any more data and advance just to and then past the grace period. Http3Api.AdvanceClock(limits.MinRequestBodyDataRate.GracePeriod); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); Http3Api.AdvanceClock(TimeSpan.FromTicks(1)); _mockTimeoutHandler.Verify(h => h.OnTimeout(It.IsAny<TimeoutReason>()), Times.Never); await requestStream.SendDataAsync(_helloWorldBytes, endStream: true); await requestStream.ExpectReceiveEndOfStream(); _mockTimeoutHandler.VerifyNoOtherCalls(); } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyLinnCoUkUpdate1 : ICpProxy, IDisposable { void SyncPushManifest(String aUri); void BeginPushManifest(String aUri, CpProxy.CallbackAsyncComplete aCallback); void EndPushManifest(IntPtr aAsyncHandle); void SyncSetUpdateFeedParams(String aTopic, String aChannel); void BeginSetUpdateFeedParams(String aTopic, String aChannel, CpProxy.CallbackAsyncComplete aCallback); void EndSetUpdateFeedParams(IntPtr aAsyncHandle); void SyncGetUpdateFeedParams(out String aTopic, out String aChannel); void BeginGetUpdateFeedParams(CpProxy.CallbackAsyncComplete aCallback); void EndGetUpdateFeedParams(IntPtr aAsyncHandle, out String aTopic, out String aChannel); void SyncGetUpdateStatus(out String aUpdateStatus); void BeginGetUpdateStatus(CpProxy.CallbackAsyncComplete aCallback); void EndGetUpdateStatus(IntPtr aAsyncHandle, out String aUpdateStatus); void SyncApply(); void BeginApply(CpProxy.CallbackAsyncComplete aCallback); void EndApply(IntPtr aAsyncHandle); void SyncRestore(); void BeginRestore(CpProxy.CallbackAsyncComplete aCallback); void EndRestore(IntPtr aAsyncHandle); void SetPropertyUpdateStatusChanged(System.Action aUpdateStatusChanged); String PropertyUpdateStatus(); void SetPropertyUpdateTopicChanged(System.Action aUpdateTopicChanged); String PropertyUpdateTopic(); void SetPropertyUpdateChannelChanged(System.Action aUpdateChannelChanged); String PropertyUpdateChannel(); } internal class SyncPushManifestLinnCoUkUpdate1 : SyncProxyAction { private CpProxyLinnCoUkUpdate1 iService; public SyncPushManifestLinnCoUkUpdate1(CpProxyLinnCoUkUpdate1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndPushManifest(aAsyncHandle); } }; internal class SyncSetUpdateFeedParamsLinnCoUkUpdate1 : SyncProxyAction { private CpProxyLinnCoUkUpdate1 iService; public SyncSetUpdateFeedParamsLinnCoUkUpdate1(CpProxyLinnCoUkUpdate1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndSetUpdateFeedParams(aAsyncHandle); } }; internal class SyncGetUpdateFeedParamsLinnCoUkUpdate1 : SyncProxyAction { private CpProxyLinnCoUkUpdate1 iService; private String iTopic; private String iChannel; public SyncGetUpdateFeedParamsLinnCoUkUpdate1(CpProxyLinnCoUkUpdate1 aProxy) { iService = aProxy; } public String Topic() { return iTopic; } public String Channel() { return iChannel; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndGetUpdateFeedParams(aAsyncHandle, out iTopic, out iChannel); } }; internal class SyncGetUpdateStatusLinnCoUkUpdate1 : SyncProxyAction { private CpProxyLinnCoUkUpdate1 iService; private String iUpdateStatus; public SyncGetUpdateStatusLinnCoUkUpdate1(CpProxyLinnCoUkUpdate1 aProxy) { iService = aProxy; } public String UpdateStatus() { return iUpdateStatus; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndGetUpdateStatus(aAsyncHandle, out iUpdateStatus); } }; internal class SyncApplyLinnCoUkUpdate1 : SyncProxyAction { private CpProxyLinnCoUkUpdate1 iService; public SyncApplyLinnCoUkUpdate1(CpProxyLinnCoUkUpdate1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndApply(aAsyncHandle); } }; internal class SyncRestoreLinnCoUkUpdate1 : SyncProxyAction { private CpProxyLinnCoUkUpdate1 iService; public SyncRestoreLinnCoUkUpdate1(CpProxyLinnCoUkUpdate1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndRestore(aAsyncHandle); } }; /// <summary> /// Proxy for the linn.co.uk:Update:1 UPnP service /// </summary> public class CpProxyLinnCoUkUpdate1 : CpProxy, IDisposable, ICpProxyLinnCoUkUpdate1 { private OpenHome.Net.Core.Action iActionPushManifest; private OpenHome.Net.Core.Action iActionSetUpdateFeedParams; private OpenHome.Net.Core.Action iActionGetUpdateFeedParams; private OpenHome.Net.Core.Action iActionGetUpdateStatus; private OpenHome.Net.Core.Action iActionApply; private OpenHome.Net.Core.Action iActionRestore; private PropertyString iUpdateStatus; private PropertyString iUpdateTopic; private PropertyString iUpdateChannel; private System.Action iUpdateStatusChanged; private System.Action iUpdateTopicChanged; private System.Action iUpdateChannelChanged; private Mutex iPropertyLock; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyLinnCoUkUpdate1(ICpDevice aDevice) : base("linn-co-uk", "Update", 1, aDevice) { OpenHome.Net.Core.Parameter param; List<String> allowedValues = new List<String>(); iActionPushManifest = new OpenHome.Net.Core.Action("PushManifest"); param = new ParameterString("Uri", allowedValues); iActionPushManifest.AddInputParameter(param); iActionSetUpdateFeedParams = new OpenHome.Net.Core.Action("SetUpdateFeedParams"); param = new ParameterString("Topic", allowedValues); iActionSetUpdateFeedParams.AddInputParameter(param); allowedValues.Add("release"); allowedValues.Add("beta"); allowedValues.Add("development"); allowedValues.Add("nightly"); param = new ParameterString("Channel", allowedValues); iActionSetUpdateFeedParams.AddInputParameter(param); allowedValues.Clear(); iActionGetUpdateFeedParams = new OpenHome.Net.Core.Action("GetUpdateFeedParams"); param = new ParameterString("Topic", allowedValues); iActionGetUpdateFeedParams.AddOutputParameter(param); allowedValues.Add("release"); allowedValues.Add("beta"); allowedValues.Add("development"); allowedValues.Add("nightly"); param = new ParameterString("Channel", allowedValues); iActionGetUpdateFeedParams.AddOutputParameter(param); allowedValues.Clear(); iActionGetUpdateStatus = new OpenHome.Net.Core.Action("GetUpdateStatus"); param = new ParameterString("UpdateStatus", allowedValues); iActionGetUpdateStatus.AddOutputParameter(param); iActionApply = new OpenHome.Net.Core.Action("Apply"); iActionRestore = new OpenHome.Net.Core.Action("Restore"); iUpdateStatus = new PropertyString("UpdateStatus", UpdateStatusPropertyChanged); AddProperty(iUpdateStatus); iUpdateTopic = new PropertyString("UpdateTopic", UpdateTopicPropertyChanged); AddProperty(iUpdateTopic); iUpdateChannel = new PropertyString("UpdateChannel", UpdateChannelPropertyChanged); AddProperty(iUpdateChannel); iPropertyLock = new Mutex(); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aUri"></param> public void SyncPushManifest(String aUri) { SyncPushManifestLinnCoUkUpdate1 sync = new SyncPushManifestLinnCoUkUpdate1(this); BeginPushManifest(aUri, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndPushManifest().</remarks> /// <param name="aUri"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginPushManifest(String aUri, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionPushManifest, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionPushManifest.InputParameter(inIndex++), aUri)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndPushManifest(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aTopic"></param> /// <param name="aChannel"></param> public void SyncSetUpdateFeedParams(String aTopic, String aChannel) { SyncSetUpdateFeedParamsLinnCoUkUpdate1 sync = new SyncSetUpdateFeedParamsLinnCoUkUpdate1(this); BeginSetUpdateFeedParams(aTopic, aChannel, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndSetUpdateFeedParams().</remarks> /// <param name="aTopic"></param> /// <param name="aChannel"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginSetUpdateFeedParams(String aTopic, String aChannel, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionSetUpdateFeedParams, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionSetUpdateFeedParams.InputParameter(inIndex++), aTopic)); invocation.AddInput(new ArgumentString((ParameterString)iActionSetUpdateFeedParams.InputParameter(inIndex++), aChannel)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndSetUpdateFeedParams(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aTopic"></param> /// <param name="aChannel"></param> public void SyncGetUpdateFeedParams(out String aTopic, out String aChannel) { SyncGetUpdateFeedParamsLinnCoUkUpdate1 sync = new SyncGetUpdateFeedParamsLinnCoUkUpdate1(this); BeginGetUpdateFeedParams(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aTopic = sync.Topic(); aChannel = sync.Channel(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndGetUpdateFeedParams().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginGetUpdateFeedParams(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionGetUpdateFeedParams, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionGetUpdateFeedParams.OutputParameter(outIndex++))); invocation.AddOutput(new ArgumentString((ParameterString)iActionGetUpdateFeedParams.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aTopic"></param> /// <param name="aChannel"></param> public void EndGetUpdateFeedParams(IntPtr aAsyncHandle, out String aTopic, out String aChannel) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aTopic = Invocation.OutputString(aAsyncHandle, index++); aChannel = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aUpdateStatus"></param> public void SyncGetUpdateStatus(out String aUpdateStatus) { SyncGetUpdateStatusLinnCoUkUpdate1 sync = new SyncGetUpdateStatusLinnCoUkUpdate1(this); BeginGetUpdateStatus(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aUpdateStatus = sync.UpdateStatus(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndGetUpdateStatus().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginGetUpdateStatus(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionGetUpdateStatus, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionGetUpdateStatus.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aUpdateStatus"></param> public void EndGetUpdateStatus(IntPtr aAsyncHandle, out String aUpdateStatus) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aUpdateStatus = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> public void SyncApply() { SyncApplyLinnCoUkUpdate1 sync = new SyncApplyLinnCoUkUpdate1(this); BeginApply(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndApply().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginApply(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionApply, aCallback); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndApply(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> public void SyncRestore() { SyncRestoreLinnCoUkUpdate1 sync = new SyncRestoreLinnCoUkUpdate1(this); BeginRestore(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndRestore().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginRestore(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionRestore, aCallback); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndRestore(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Set a delegate to be run when the UpdateStatus state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyLinnCoUkUpdate1 instance will not overlap.</remarks> /// <param name="aUpdateStatusChanged">The delegate to run when the state variable changes</param> public void SetPropertyUpdateStatusChanged(System.Action aUpdateStatusChanged) { lock (iPropertyLock) { iUpdateStatusChanged = aUpdateStatusChanged; } } private void UpdateStatusPropertyChanged() { lock (iPropertyLock) { ReportEvent(iUpdateStatusChanged); } } /// <summary> /// Set a delegate to be run when the UpdateTopic state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyLinnCoUkUpdate1 instance will not overlap.</remarks> /// <param name="aUpdateTopicChanged">The delegate to run when the state variable changes</param> public void SetPropertyUpdateTopicChanged(System.Action aUpdateTopicChanged) { lock (iPropertyLock) { iUpdateTopicChanged = aUpdateTopicChanged; } } private void UpdateTopicPropertyChanged() { lock (iPropertyLock) { ReportEvent(iUpdateTopicChanged); } } /// <summary> /// Set a delegate to be run when the UpdateChannel state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyLinnCoUkUpdate1 instance will not overlap.</remarks> /// <param name="aUpdateChannelChanged">The delegate to run when the state variable changes</param> public void SetPropertyUpdateChannelChanged(System.Action aUpdateChannelChanged) { lock (iPropertyLock) { iUpdateChannelChanged = aUpdateChannelChanged; } } private void UpdateChannelPropertyChanged() { lock (iPropertyLock) { ReportEvent(iUpdateChannelChanged); } } /// <summary> /// Query the value of the UpdateStatus property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the UpdateStatus property</returns> public String PropertyUpdateStatus() { PropertyReadLock(); String val; try { val = iUpdateStatus.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the UpdateTopic property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the UpdateTopic property</returns> public String PropertyUpdateTopic() { PropertyReadLock(); String val; try { val = iUpdateTopic.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the UpdateChannel property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the UpdateChannel property</returns> public String PropertyUpdateChannel() { PropertyReadLock(); String val; try { val = iUpdateChannel.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionPushManifest.Dispose(); iActionSetUpdateFeedParams.Dispose(); iActionGetUpdateFeedParams.Dispose(); iActionGetUpdateStatus.Dispose(); iActionApply.Dispose(); iActionRestore.Dispose(); iUpdateStatus.Dispose(); iUpdateTopic.Dispose(); iUpdateChannel.Dispose(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.Runtime; using System.ServiceModel.Diagnostics; using System.Xml; using System.IO; using System.Runtime.Diagnostics; using SMTD = System.ServiceModel.Diagnostics.Application.TD; using System.Diagnostics; class ByteStreamMessageEncoder : MessageEncoder, IStreamedMessageEncoder, IWebMessageEncoderHelper, ITraceSourceStringProvider { string traceSourceString; string maxReceivedMessageSizeExceededResourceString; string maxSentMessageSizeExceededResourceString; XmlDictionaryReaderQuotas quotas; XmlDictionaryReaderQuotas bufferedReadReaderQuotas; /// <summary> /// Specifies if this encoder produces Messages that provide a body reader (with the Message.GetReaderAtBodyContents() method) positioned on content. /// See the comments on 'IWebMessageEncoderHelper' for more info. /// </summary> bool moveBodyReaderToContent = false; // false because we want the ByteStreamMessageEncoder to be compatible with previous releases public ByteStreamMessageEncoder(XmlDictionaryReaderQuotas quotas) { this.quotas = new XmlDictionaryReaderQuotas(); quotas.CopyTo(this.quotas); this.bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(this.quotas); this.maxSentMessageSizeExceededResourceString = SR.MaxSentMessageSizeExceeded("{0}"); this.maxReceivedMessageSizeExceededResourceString = SR.MaxReceivedMessageSizeExceeded("{0}"); } void IWebMessageEncoderHelper.EnableBodyReaderMoveToContent() { this.moveBodyReaderToContent = true; } public override string ContentType { get { return null; } } public override string MediaType { get { return null; } } public override MessageVersion MessageVersion { get { return MessageVersion.None; } } public override bool IsContentTypeSupported(string contentType) { return true; } public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) { if (stream == null) { throw FxTrace.Exception.ArgumentNull("stream"); } if (TD.ByteStreamMessageDecodingStartIsEnabled()) { TD.ByteStreamMessageDecodingStart(); } Message message = ByteStreamMessage.CreateMessage(stream, this.quotas, this.moveBodyReaderToContent); message.Properties.Encoder = this; if (SMTD.StreamedMessageReadByEncoderIsEnabled()) { SMTD.StreamedMessageReadByEncoder(EventTraceActivityHelper.TryExtractActivity(message, true)); } if (MessageLogger.LogMessagesAtTransportLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive); } return message; } public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType) { if (buffer.Array == null) { throw FxTrace.Exception.ArgumentNull("buffer.Array"); } if (bufferManager == null) { throw FxTrace.Exception.ArgumentNull("bufferManager"); } if (TD.ByteStreamMessageDecodingStartIsEnabled()) { TD.ByteStreamMessageDecodingStart(); } ByteStreamBufferedMessageData messageData = new ByteStreamBufferedMessageData(buffer, bufferManager); Message message = ByteStreamMessage.CreateMessage(messageData, this.bufferedReadReaderQuotas, this.moveBodyReaderToContent); message.Properties.Encoder = this; if (SMTD.MessageReadByEncoderIsEnabled()) { SMTD.MessageReadByEncoder( EventTraceActivityHelper.TryExtractActivity(message, true), buffer.Count, this); } if (MessageLogger.LogMessagesAtTransportLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive); } return message; } public override void WriteMessage(Message message, Stream stream) { if (message == null) { throw FxTrace.Exception.ArgumentNull("message"); } if (stream == null) { throw FxTrace.Exception.ArgumentNull("stream"); } ThrowIfMismatchedMessageVersion(message); EventTraceActivity eventTraceActivity = null; if (TD.ByteStreamMessageEncodingStartIsEnabled()) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.ByteStreamMessageEncodingStart(eventTraceActivity); } message.Properties.Encoder = this; if (MessageLogger.LogMessagesAtTransportLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend); } using (XmlWriter writer = new XmlByteStreamWriter(stream, false)) { message.WriteMessage(writer); writer.Flush(); } if (SMTD.StreamedMessageWrittenByEncoderIsEnabled()) { SMTD.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message)); } } public override IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state) { if (message == null) { throw FxTrace.Exception.ArgumentNull("message"); } if (stream == null) { throw FxTrace.Exception.ArgumentNull("stream"); } ThrowIfMismatchedMessageVersion(message); message.Properties.Encoder = this; if (MessageLogger.LogMessagesAtTransportLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend); } return new WriteMessageAsyncResult(message, stream, callback, state); } public override void EndWriteMessage(IAsyncResult result) { WriteMessageAsyncResult.End(result); } public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { if (message == null) { throw FxTrace.Exception.ArgumentNull("message"); } if (bufferManager == null) { throw FxTrace.Exception.ArgumentNull("bufferManager"); } if (maxMessageSize < 0) { throw FxTrace.Exception.ArgumentOutOfRange("maxMessageSize", maxMessageSize, SR.ArgumentOutOfMinRange(0)); } if (messageOffset < 0) { throw FxTrace.Exception.ArgumentOutOfRange("messageOffset", messageOffset, SR.ArgumentOutOfMinRange(0)); } EventTraceActivity eventTraceActivity = null; if (TD.ByteStreamMessageEncodingStartIsEnabled()) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.ByteStreamMessageEncodingStart(eventTraceActivity); } ThrowIfMismatchedMessageVersion(message); message.Properties.Encoder = this; ArraySegment<byte> messageBuffer; int size; using (BufferManagerOutputStream stream = new BufferManagerOutputStream(maxSentMessageSizeExceededResourceString, 0, maxMessageSize, bufferManager)) { stream.Skip(messageOffset); using (XmlWriter writer = new XmlByteStreamWriter(stream, true)) { message.WriteMessage(writer); writer.Flush(); byte[] bytes = stream.ToArray(out size); messageBuffer = new ArraySegment<byte>(bytes, messageOffset, size - messageOffset); } } if (SMTD.MessageWrittenByEncoderIsEnabled()) { SMTD.MessageWrittenByEncoder( eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message), messageBuffer.Count, this); } if (MessageLogger.LogMessagesAtTransportLevel) { // DevDiv#486728 // Don't pass in a buffer manager to avoid returning 'messageBuffer" to the bufferManager twice. ByteStreamBufferedMessageData messageData = new ByteStreamBufferedMessageData(messageBuffer, null); using (XmlReader reader = new XmlBufferedByteStreamReader(messageData, this.quotas)) { MessageLogger.LogMessage(ref message, reader, MessageLoggingSource.TransportSend); } } return messageBuffer; } public override string ToString() { return ByteStreamMessageUtility.EncoderName; } public Stream GetResponseMessageStream(Message message) { if (message == null) { throw FxTrace.Exception.ArgumentNull("message"); } ThrowIfMismatchedMessageVersion(message); if (!ByteStreamMessage.IsInternalByteStreamMessage(message)) { return null; } return message.GetBody<Stream>(); } string ITraceSourceStringProvider.GetSourceString() { // Other MessageEncoders use base.GetTraceSourceString but that would require a public api change in MessageEncoder // as ByteStreamMessageEncoder is in a different assemly. The same logic is reimplemented here. if (this.traceSourceString == null) { this.traceSourceString = DiagnosticTraceBase.CreateDefaultSourceString(this); } return this.traceSourceString; } class WriteMessageAsyncResult : AsyncResult { Message message; Stream stream; static Action<IAsyncResult, Exception> onCleanup; XmlByteStreamWriter writer; EventTraceActivity eventTraceActivity; public WriteMessageAsyncResult(Message message, Stream stream, AsyncCallback callback, object state) : base(callback, state) { this.message = message; this.stream = stream; this.writer = new XmlByteStreamWriter(stream, false); if (onCleanup == null) { onCleanup = new Action<IAsyncResult, Exception>(Cleanup); } this.OnCompleting += onCleanup; Exception completionException = null; bool completeSelf = false; this.eventTraceActivity = null; if (TD.ByteStreamMessageEncodingStartIsEnabled()) { this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.ByteStreamMessageEncodingStart(this.eventTraceActivity); } try { IAsyncResult result = message.BeginWriteMessage(writer, PrepareAsyncCompletion(HandleWriteMessage), this); completeSelf = SyncContinue(result); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } completeSelf = true; completionException = ex; } if (completeSelf) { this.Complete(true, completionException); } } static bool HandleWriteMessage(IAsyncResult result) { WriteMessageAsyncResult thisPtr = (WriteMessageAsyncResult)result.AsyncState; thisPtr.message.EndWriteMessage(result); thisPtr.writer.Flush(); if (SMTD.MessageWrittenAsynchronouslyByEncoderIsEnabled()) { SMTD.MessageWrittenAsynchronouslyByEncoder( thisPtr.eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(thisPtr.message)); } return true; } static void Cleanup(IAsyncResult result, Exception ex) { WriteMessageAsyncResult thisPtr = (WriteMessageAsyncResult)result; bool success = false; try { thisPtr.writer.Close(); success = true; } finally { if (!success) { FxTrace.Exception.TraceHandledException(ex, TraceEventType.Information); } } } public static void End(IAsyncResult result) { AsyncResult.End<WriteMessageAsyncResult>(result); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Hydra.Framework.Mapping.CoordinateSystems { // // ********************************************************************** /// <summary> /// A 2D cartographic coordinate system. /// </summary> // ********************************************************************** // public class ProjectedCoordinateSystem : AbstractHorizontalCoordinateSystem, IProjectedCoordinateSystem { #region Private Member Variables // // ********************************************************************** /// <summary> /// Geographic Coordinate System /// </summary> // ********************************************************************** // private IGeographicCoordinateSystem m_GeographicCoordinateSystem; // // ********************************************************************** /// <summary> /// Linear Unit /// </summary> // ********************************************************************** // private ILinearUnit m_LinearUnit; // // ********************************************************************** /// <summary> /// Projection /// </summary> // ********************************************************************** // private IProjection m_Projection; #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new instance of a projected coordinate system /// </summary> /// <param name="datum">Horizontal datum</param> /// <param name="geographicCoordinateSystem">Geographic coordinate system</param> /// <param name="linearUnit">Linear unit</param> /// <param name="projection">Projection</param> /// <param name="axisInfo">Axis info</param> /// <param name="name">StateName</param> /// <param name="authority">Authority name</param> /// <param name="code">Authority-specific identification code.</param> /// <param name="alias">Alias</param> /// <param name="remarks">Provider-supplied remarks</param> /// <param name="abbreviation">Abbreviation</param> // ********************************************************************** // internal ProjectedCoordinateSystem(IHorizontalDatum datum, IGeographicCoordinateSystem geographicCoordinateSystem, ILinearUnit linearUnit, IProjection projection, List<AxisInfo> axisInfo, string name, string authority, long code, string alias, string remarks, string abbreviation) : base(datum, axisInfo, name, authority, code, alias, abbreviation, remarks) { m_GeographicCoordinateSystem = geographicCoordinateSystem; m_LinearUnit = linearUnit; m_Projection = projection; } #endregion #region IProjectedCoordinateSystem Implementation // // ********************************************************************** /// <summary> /// Gets or sets the GeographicCoordinateSystem. /// </summary> /// <value></value> // ********************************************************************** // public IGeographicCoordinateSystem GeographicCoordinateSystem { get { return m_GeographicCoordinateSystem; } set { m_GeographicCoordinateSystem = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the <see cref="LinearUnit">LinearUnits</see>. The linear unit must be the same as the <see cref="AbstractCoordinateSystem"/> units. /// </summary> /// <value></value> // ********************************************************************** // public ILinearUnit LinearUnit { get { return m_LinearUnit; } set { m_LinearUnit = value; } } // // ********************************************************************** /// <summary> /// Gets units for dimension within coordinate system. Each dimension in /// the coordinate system has corresponding units. /// </summary> /// <param name="dimension">Dimension</param> /// <returns>Unit</returns> // ********************************************************************** // public override IUnit GetUnits(int dimension) { return m_LinearUnit; } // // ********************************************************************** /// <summary> /// Gets or sets the projection /// </summary> /// <value></value> // ********************************************************************** // public IProjection Projection { get { return m_Projection; } set { m_Projection = value; } } // // ********************************************************************** /// <summary> /// Returns the Well-known text for this object /// as defined in the simple features specification. /// </summary> /// <value></value> // ********************************************************************** // public override string WKT { get { StringBuilder sb = new StringBuilder(); sb.AppendFormat("PROJCS[\"{0}\", {1}, {2}", Name, GeographicCoordinateSystem.WKT, Projection.WKT); for (int i = 0; i < Projection.NumParameters; i++) sb.AppendFormat(Hydra.Framework.Mapping.Map.numberFormat_EnUS, ", {0}", Projection.GetParameter(i).WKT); sb.AppendFormat(", {0}", LinearUnit.WKT); // // Skip axis info if they contain default values // if (AxisInfo.Count != 2 || AxisInfo[0].Name != "X" || AxisInfo[0].Orientation != AxisOrientationEnum.East || AxisInfo[1].Name != "Y" || AxisInfo[1].Orientation != AxisOrientationEnum.North) { for (int i = 0; i < AxisInfo.Count; i++) sb.AppendFormat(", {0}", GetAxis(i).WKT); } if (!String.IsNullOrEmpty(Authority) && AuthorityCode > 0) sb.AppendFormat(", AUTHORITY[\"{0}\", \"{1}\"]", Authority, AuthorityCode); sb.Append("]"); return sb.ToString(); } } // // ********************************************************************** /// <summary> /// Gets an XML representation of this object. /// </summary> /// <value></value> // ********************************************************************** // public override string XML { get { StringBuilder sb = new StringBuilder(); sb.AppendFormat(Hydra.Framework.Mapping.Map.numberFormat_EnUS, "<CS_CoordinateSystem Dimension=\"{0}\"><CS_ProjectedCoordinateSystem>{1}", this.Dimension, InfoXml); foreach (AxisInfo ai in this.AxisInfo) sb.Append(ai.XML); sb.AppendFormat("{0}{1}{2}</CS_ProjectedCoordinateSystem></CS_CoordinateSystem>", GeographicCoordinateSystem.XML, LinearUnit.XML, Projection.XML); return sb.ToString(); } } // // ********************************************************************** /// <summary> /// Checks whether the values of this instance is equal to the values of another instance. /// Only parameters used for coordinate system are used for comparison. /// StateName, abbreviation, authority, alias and remarks are ignored in the comparison. /// </summary> /// <param name="obj"></param> /// <returns>True if equal</returns> // ********************************************************************** // public override bool EqualParams(object obj) { if (!(obj is ProjectedCoordinateSystem)) return false; ProjectedCoordinateSystem pcs = obj as ProjectedCoordinateSystem; if (pcs.Dimension != this.Dimension) return false; for (int i = 0; i < pcs.Dimension; i++) { if (pcs.GetAxis(i).Orientation != this.GetAxis(i).Orientation) return false; if (!pcs.GetUnits(i).EqualParams(this.GetUnits(i))) return false; } return pcs.GeographicCoordinateSystem.EqualParams(this.GeographicCoordinateSystem) && pcs.HorizontalDatum.EqualParams(this.HorizontalDatum) && pcs.LinearUnit.EqualParams(this.LinearUnit) && pcs.Projection.EqualParams(this.Projection); } #endregion } }
// 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.Threading.Tasks; using Microsoft.AspNetCore.Internal; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Testing; using Xunit; namespace Microsoft.AspNetCore.SignalR.Tests { public class HubFilterTests : VerifiableLoggedTest { [Fact] public async Task GlobalHubFilterByType_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter<VerifyMethodFilter>(); }); services.AddSingleton(tcsService); }, LoggerFactory); await AssertMethodsCalled(serviceProvider, tcsService); } } [Fact] public async Task GlobalHubFilterByInstance_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter(new VerifyMethodFilter(tcsService)); }); }, LoggerFactory); await AssertMethodsCalled(serviceProvider, tcsService); } } [Fact] public async Task PerHubFilterByInstance_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR().AddHubOptions<MethodHub>(options => { options.AddFilter(new VerifyMethodFilter(tcsService)); }); }, LoggerFactory); await AssertMethodsCalled(serviceProvider, tcsService); } } [Fact] public async Task PerHubFilterByCompileTimeType_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR().AddHubOptions<MethodHub>(options => { options.AddFilter<VerifyMethodFilter>(); }); services.AddSingleton(tcsService); }, LoggerFactory); await AssertMethodsCalled(serviceProvider, tcsService); } } [Fact] public async Task PerHubFilterByRuntimeType_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR().AddHubOptions<MethodHub>(options => { options.AddFilter(typeof(VerifyMethodFilter)); }); services.AddSingleton(tcsService); }, LoggerFactory); await AssertMethodsCalled(serviceProvider, tcsService); } } private async Task AssertMethodsCalled(IServiceProvider serviceProvider, TcsService tcsService) { var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await tcsService.StartedMethod.Task.DefaultTimeout(); await client.Connected.DefaultTimeout(); await tcsService.EndMethod.Task.DefaultTimeout(); tcsService.Reset(); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); await tcsService.EndMethod.Task.DefaultTimeout(); tcsService.Reset(); Assert.Null(message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); await tcsService.EndMethod.Task.DefaultTimeout(); } } [Fact] public async Task HubFilterDoesNotNeedToImplementMethods() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR().AddHubOptions<DynamicTestHub>(options => { options.AddFilter(typeof(EmptyFilter)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<DynamicTestHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await client.Connected.DefaultTimeout(); var completion = await client.InvokeAsync(nameof(DynamicTestHub.Echo), "hello"); Assert.Null(completion.Error); Assert.Equal("hello", completion.Result); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task MutlipleFilters_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService1 = new TcsService(); var tcsService2 = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter(new VerifyMethodFilter(tcsService1)); options.AddFilter(new VerifyMethodFilter(tcsService2)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await tcsService1.StartedMethod.Task.DefaultTimeout(); await tcsService2.StartedMethod.Task.DefaultTimeout(); await client.Connected.DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); tcsService1.Reset(); tcsService2.Reset(); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); tcsService1.Reset(); tcsService2.Reset(); Assert.Null(message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); } } } [Fact] public async Task MixingTypeAndInstanceGlobalFilters_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService1 = new TcsService(); var tcsService2 = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter(new VerifyMethodFilter(tcsService1)); options.AddFilter<VerifyMethodFilter>(); }); services.AddSingleton(tcsService2); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await tcsService1.StartedMethod.Task.DefaultTimeout(); await tcsService2.StartedMethod.Task.DefaultTimeout(); await client.Connected.DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); tcsService1.Reset(); tcsService2.Reset(); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); tcsService1.Reset(); tcsService2.Reset(); Assert.Null(message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); } } } [Fact] public async Task MixingTypeAndInstanceHubSpecificFilters_MethodsAreCalled() { using (StartVerifiableLog()) { var tcsService1 = new TcsService(); var tcsService2 = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR() .AddHubOptions<MethodHub>(options => { options.AddFilter(new VerifyMethodFilter(tcsService1)); options.AddFilter<VerifyMethodFilter>(); }); services.AddSingleton(tcsService2); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await tcsService1.StartedMethod.Task.DefaultTimeout(); await tcsService2.StartedMethod.Task.DefaultTimeout(); await client.Connected.DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); tcsService1.Reset(); tcsService2.Reset(); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); tcsService1.Reset(); tcsService2.Reset(); Assert.Null(message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); await tcsService1.EndMethod.Task.DefaultTimeout(); await tcsService2.EndMethod.Task.DefaultTimeout(); } } } [Fact] public async Task GlobalFiltersRunInOrder() { using (StartVerifiableLog()) { var syncPoint1 = SyncPoint.Create(3, out var syncPoints1); var syncPoint2 = SyncPoint.Create(3, out var syncPoints2); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter(new SyncPointFilter(syncPoints1)); options.AddFilter(new SyncPointFilter(syncPoints2)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await syncPoints1[0].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[0].WaitForSyncPoint().IsCompleted); syncPoints1[0].Continue(); await syncPoints2[0].WaitForSyncPoint().DefaultTimeout(); syncPoints2[0].Continue(); await client.Connected.DefaultTimeout(); var invokeTask = client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!"); await syncPoints1[1].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[1].WaitForSyncPoint().IsCompleted); syncPoints1[1].Continue(); await syncPoints2[1].WaitForSyncPoint().DefaultTimeout(); syncPoints2[1].Continue(); var message = await invokeTask.DefaultTimeout(); Assert.Null(message.Error); client.Dispose(); await syncPoints1[2].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[2].WaitForSyncPoint().IsCompleted); syncPoints1[2].Continue(); await syncPoints2[2].WaitForSyncPoint().DefaultTimeout(); syncPoints2[2].Continue(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task HubSpecificFiltersRunInOrder() { using (StartVerifiableLog()) { var syncPoint1 = SyncPoint.Create(3, out var syncPoints1); var syncPoint2 = SyncPoint.Create(3, out var syncPoints2); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR() .AddHubOptions<MethodHub>(options => { options.AddFilter(new SyncPointFilter(syncPoints1)); options.AddFilter(new SyncPointFilter(syncPoints2)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await syncPoints1[0].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[0].WaitForSyncPoint().IsCompleted); syncPoints1[0].Continue(); await syncPoints2[0].WaitForSyncPoint().DefaultTimeout(); syncPoints2[0].Continue(); await client.Connected.DefaultTimeout(); var invokeTask = client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!"); await syncPoints1[1].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[1].WaitForSyncPoint().IsCompleted); syncPoints1[1].Continue(); await syncPoints2[1].WaitForSyncPoint().DefaultTimeout(); syncPoints2[1].Continue(); var message = await invokeTask.DefaultTimeout(); Assert.Null(message.Error); client.Dispose(); await syncPoints1[2].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[2].WaitForSyncPoint().IsCompleted); syncPoints1[2].Continue(); await syncPoints2[2].WaitForSyncPoint().DefaultTimeout(); syncPoints2[2].Continue(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task GlobalFiltersRunBeforeHubSpecificFilters() { using (StartVerifiableLog()) { var syncPoint1 = SyncPoint.Create(3, out var syncPoints1); var syncPoint2 = SyncPoint.Create(3, out var syncPoints2); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter(new SyncPointFilter(syncPoints1)); }) .AddHubOptions<MethodHub>(options => { options.AddFilter(new SyncPointFilter(syncPoints2)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await syncPoints1[0].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[0].WaitForSyncPoint().IsCompleted); syncPoints1[0].Continue(); await syncPoints2[0].WaitForSyncPoint().DefaultTimeout(); syncPoints2[0].Continue(); await client.Connected.DefaultTimeout(); var invokeTask = client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!"); await syncPoints1[1].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[1].WaitForSyncPoint().IsCompleted); syncPoints1[1].Continue(); await syncPoints2[1].WaitForSyncPoint().DefaultTimeout(); syncPoints2[1].Continue(); var message = await invokeTask.DefaultTimeout(); Assert.Null(message.Error); client.Dispose(); await syncPoints1[2].WaitForSyncPoint().DefaultTimeout(); // Second filter wont run yet because first filter is waiting on SyncPoint Assert.False(syncPoints2[2].WaitForSyncPoint().IsCompleted); syncPoints1[2].Continue(); await syncPoints2[2].WaitForSyncPoint().DefaultTimeout(); syncPoints2[2].Continue(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task FilterCanBeResolvedFromDI() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter<VerifyMethodFilter>(); }); // If this instance wasn't resolved, then the tcsService.StartedMethod waits would never trigger and fail the test services.AddSingleton(new VerifyMethodFilter(tcsService)); }, LoggerFactory); await AssertMethodsCalled(serviceProvider, tcsService); } } [Fact] public async Task FiltersHaveTransientScopeByDefault() { using (StartVerifiableLog()) { var counter = new FilterCounter(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter<CounterFilter>(); }); services.AddSingleton(counter); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await client.Connected.DefaultTimeout(); // Filter is transient, so these counts are reset every time the filter is created Assert.Equal(1, counter.OnConnectedAsyncCount); Assert.Equal(0, counter.InvokeMethodAsyncCount); Assert.Equal(0, counter.OnDisconnectedAsyncCount); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); // Filter is transient, so these counts are reset every time the filter is created Assert.Equal(0, counter.OnConnectedAsyncCount); Assert.Equal(1, counter.InvokeMethodAsyncCount); Assert.Equal(0, counter.OnDisconnectedAsyncCount); Assert.Null(message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); // Filter is transient, so these counts are reset every time the filter is created Assert.Equal(0, counter.OnConnectedAsyncCount); Assert.Equal(0, counter.InvokeMethodAsyncCount); Assert.Equal(1, counter.OnDisconnectedAsyncCount); } } } [Fact] public async Task FiltersCanBeSingletonIfAddedToDI() { using (StartVerifiableLog()) { var counter = new FilterCounter(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter<CounterFilter>(); }); services.AddSingleton<CounterFilter>(); services.AddSingleton(counter); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await client.Connected.DefaultTimeout(); Assert.Equal(1, counter.OnConnectedAsyncCount); Assert.Equal(0, counter.InvokeMethodAsyncCount); Assert.Equal(0, counter.OnDisconnectedAsyncCount); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); Assert.Equal(1, counter.OnConnectedAsyncCount); Assert.Equal(1, counter.InvokeMethodAsyncCount); Assert.Equal(0, counter.OnDisconnectedAsyncCount); Assert.Null(message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); Assert.Equal(1, counter.OnConnectedAsyncCount); Assert.Equal(1, counter.InvokeMethodAsyncCount); Assert.Equal(1, counter.OnDisconnectedAsyncCount); } } } [Fact] public async Task ConnectionContinuesIfOnConnectedAsyncThrowsAndFilterDoesNot() { using (StartVerifiableLog()) { var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter<NoExceptionFilter>(); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<OnConnectedThrowsHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); // Verify connection still connected, can't invoke a method if the connection is disconnected var message = await client.InvokeAsync("Method"); Assert.Equal("Failed to invoke 'Method' due to an error on the server. HubException: Method does not exist.", message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task ConnectionContinuesIfOnConnectedAsyncNotCalledByFilter() { using (StartVerifiableLog()) { var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter(new SkipNextFilter(skipOnConnected: true)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); // Verify connection still connected, can't invoke a method if the connection is disconnected var message = await client.InvokeAsync("Method"); Assert.Equal("Failed to invoke 'Method' due to an error on the server. HubException: Method does not exist.", message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task FilterCanSkipCallingHubMethod() { using (StartVerifiableLog()) { var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.AddFilter(new SkipNextFilter(skipInvoke: true)); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); await client.Connected.DefaultTimeout(); var message = await client.InvokeAsync(nameof(MethodHub.Echo), "Hello world!").DefaultTimeout(); Assert.Null(message.Error); Assert.Null(message.Result); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task FiltersWithIDisposableAreDisposed() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter<DisposableFilter>(); }); services.AddSingleton(tcsService); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); // OnConnectedAsync creates and destroys the filter await tcsService.StartedMethod.Task.DefaultTimeout(); tcsService.Reset(); var message = await client.InvokeAsync("Echo", "Hello"); Assert.Equal("Hello", message.Result); await tcsService.StartedMethod.Task.DefaultTimeout(); tcsService.Reset(); client.Dispose(); // OnDisconnectedAsync creates and destroys the filter await tcsService.StartedMethod.Task.DefaultTimeout(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task InstanceFiltersWithIDisposableAreNotDisposed() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter(new DisposableFilter(tcsService)); }); services.AddSingleton(tcsService); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); var message = await client.InvokeAsync("Echo", "Hello"); Assert.Equal("Hello", message.Result); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); Assert.False(tcsService.StartedMethod.Task.IsCompleted); } } } [Fact] public async Task FiltersWithIAsyncDisposableAreDisposed() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter<AsyncDisposableFilter>(); }); services.AddSingleton(tcsService); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); // OnConnectedAsync creates and destroys the filter await tcsService.StartedMethod.Task.DefaultTimeout(); tcsService.Reset(); var message = await client.InvokeAsync("Echo", "Hello"); Assert.Equal("Hello", message.Result); await tcsService.StartedMethod.Task.DefaultTimeout(); tcsService.Reset(); client.Dispose(); // OnDisconnectedAsync creates and destroys the filter await tcsService.StartedMethod.Task.DefaultTimeout(); await connectionHandlerTask.DefaultTimeout(); } } } [Fact] public async Task InstanceFiltersWithIAsyncDisposableAreNotDisposed() { using (StartVerifiableLog()) { var tcsService = new TcsService(); var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter(new AsyncDisposableFilter(tcsService)); }); services.AddSingleton(tcsService); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); var message = await client.InvokeAsync("Echo", "Hello"); Assert.Equal("Hello", message.Result); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); Assert.False(tcsService.StartedMethod.Task.IsCompleted); } } } [Fact] public async Task InvokeFailsWhenFilterCallsNonExistantMethod() { bool ExpectedErrors(WriteContext writeContext) { return writeContext.LoggerName == "Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher" && writeContext.EventId.Name == "FailedInvokingHubMethod"; } using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { var serviceProvider = HubConnectionHandlerTestUtils.CreateServiceProvider(services => { services.AddSignalR(options => { options.EnableDetailedErrors = true; options.AddFilter<ChangeMethodFilter>(); }); }, LoggerFactory); var connectionHandler = serviceProvider.GetService<HubConnectionHandler<MethodHub>>(); using (var client = new TestClient()) { var connectionHandlerTask = await client.ConnectAsync(connectionHandler); var message = await client.InvokeAsync("Echo", "Hello"); Assert.Equal("An unexpected error occurred invoking 'Echo' on the server. HubException: Unknown hub method 'BaseMethod'", message.Error); client.Dispose(); await connectionHandlerTask.DefaultTimeout(); } } } } }
using Lucene.Net.Support; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace Lucene.Net.Index { /* * 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. */ /// <summary> /// An <seealso cref="CompositeReader"/> which reads multiple, parallel indexes. Each index added /// must have the same number of documents, and exactly the same hierarchical subreader structure, /// but typically each contains different fields. Deletions are taken from the first reader. /// Each document contains the union of the fields of all /// documents with the same document number. When searching, matches for a /// query term are from the first index added that has the field. /// /// <p>this is useful, e.g., with collections that have large fields which /// change rarely and small fields that change more frequently. The smaller /// fields may be re-indexed in a new index and both indexes may be searched /// together. /// /// <p><strong>Warning:</strong> It is up to you to make sure all indexes /// are created and modified the same way. For example, if you add /// documents to one index, you need to add the same documents in the /// same order to the other indexes. <em>Failure to do so will result in /// undefined behavior</em>. /// A good strategy to create suitable indexes with <seealso cref="IndexWriter"/> is to use /// <seealso cref="LogDocMergePolicy"/>, as this one does not reorder documents /// during merging (like {@code TieredMergePolicy}) and triggers merges /// by number of documents per segment. If you use different <seealso cref="MergePolicy"/>s /// it might happen that the segment structure of your index is no longer predictable. /// </summary> public class ParallelCompositeReader : BaseCompositeReader<IndexReader> { private readonly bool CloseSubReaders; private readonly ISet<IndexReader> CompleteReaderSet = new IdentityHashSet<IndexReader>(); /// <summary> /// Create a ParallelCompositeReader based on the provided /// readers; auto-closes the given readers on <seealso cref="#close()"/>. /// </summary> public ParallelCompositeReader(params CompositeReader[] readers) : this(true, readers) { } /// <summary> /// Create a ParallelCompositeReader based on the provided /// readers. /// </summary> public ParallelCompositeReader(bool closeSubReaders, params CompositeReader[] readers) : this(closeSubReaders, readers, readers) { } /// <summary> /// Expert: create a ParallelCompositeReader based on the provided /// readers and storedFieldReaders; when a document is /// loaded, only storedFieldsReaders will be used. /// </summary> public ParallelCompositeReader(bool closeSubReaders, CompositeReader[] readers, CompositeReader[] storedFieldReaders) : base(PrepareSubReaders(readers, storedFieldReaders)) { this.CloseSubReaders = closeSubReaders; CollectionsHelper.AddAll(CompleteReaderSet, readers); CollectionsHelper.AddAll(CompleteReaderSet, storedFieldReaders); // update ref-counts (like MultiReader): if (!closeSubReaders) { foreach (IndexReader reader in CompleteReaderSet) { reader.IncRef(); } } // finally add our own synthetic readers, so we close or decRef them, too (it does not matter what we do) CollectionsHelper.AddAll(CompleteReaderSet, GetSequentialSubReaders()); } private static IndexReader[] PrepareSubReaders(CompositeReader[] readers, CompositeReader[] storedFieldsReaders) { if (readers.Length == 0) { if (storedFieldsReaders.Length > 0) { throw new System.ArgumentException("There must be at least one main reader if storedFieldsReaders are used."); } return new IndexReader[0]; } else { IList<IndexReader> firstSubReaders = readers[0].GetSequentialSubReaders(); // check compatibility: int maxDoc = readers[0].MaxDoc, noSubs = firstSubReaders.Count; int[] childMaxDoc = new int[noSubs]; bool[] childAtomic = new bool[noSubs]; for (int i = 0; i < noSubs; i++) { IndexReader r = firstSubReaders[i]; childMaxDoc[i] = r.MaxDoc; childAtomic[i] = r is AtomicReader; } Validate(readers, maxDoc, childMaxDoc, childAtomic); Validate(storedFieldsReaders, maxDoc, childMaxDoc, childAtomic); // hierarchically build the same subreader structure as the first CompositeReader with Parallel*Readers: IndexReader[] subReaders = new IndexReader[noSubs]; for (int i = 0; i < subReaders.Length; i++) { if (firstSubReaders[i] is AtomicReader) { AtomicReader[] atomicSubs = new AtomicReader[readers.Length]; for (int j = 0; j < readers.Length; j++) { atomicSubs[j] = (AtomicReader)readers[j].GetSequentialSubReaders()[i]; } AtomicReader[] storedSubs = new AtomicReader[storedFieldsReaders.Length]; for (int j = 0; j < storedFieldsReaders.Length; j++) { storedSubs[j] = (AtomicReader)storedFieldsReaders[j].GetSequentialSubReaders()[i]; } // We pass true for closeSubs and we prevent closing of subreaders in doClose(): // By this the synthetic throw-away readers used here are completely invisible to ref-counting subReaders[i] = new ParallelAtomicReaderAnonymousInnerClassHelper(atomicSubs, storedSubs); } else { Debug.Assert(firstSubReaders[i] is CompositeReader); CompositeReader[] compositeSubs = new CompositeReader[readers.Length]; for (int j = 0; j < readers.Length; j++) { compositeSubs[j] = (CompositeReader)readers[j].GetSequentialSubReaders()[i]; } CompositeReader[] storedSubs = new CompositeReader[storedFieldsReaders.Length]; for (int j = 0; j < storedFieldsReaders.Length; j++) { storedSubs[j] = (CompositeReader)storedFieldsReaders[j].GetSequentialSubReaders()[i]; } // We pass true for closeSubs and we prevent closing of subreaders in doClose(): // By this the synthetic throw-away readers used here are completely invisible to ref-counting subReaders[i] = new ParallelCompositeReaderAnonymousInnerClassHelper(compositeSubs, storedSubs); } } return subReaders; } } private class ParallelAtomicReaderAnonymousInnerClassHelper : ParallelAtomicReader { public ParallelAtomicReaderAnonymousInnerClassHelper(Lucene.Net.Index.AtomicReader[] atomicSubs, Lucene.Net.Index.AtomicReader[] storedSubs) : base(true, atomicSubs, storedSubs) { } protected internal override void DoClose() { } } private class ParallelCompositeReaderAnonymousInnerClassHelper : ParallelCompositeReader { public ParallelCompositeReaderAnonymousInnerClassHelper(Lucene.Net.Index.CompositeReader[] compositeSubs, Lucene.Net.Index.CompositeReader[] storedSubs) : base(true, compositeSubs, storedSubs) { } protected internal override void DoClose() { } } private static void Validate(CompositeReader[] readers, int maxDoc, int[] childMaxDoc, bool[] childAtomic) { for (int i = 0; i < readers.Length; i++) { CompositeReader reader = readers[i]; IList<IndexReader> subs = reader.GetSequentialSubReaders(); if (reader.MaxDoc != maxDoc) { throw new System.ArgumentException("All readers must have same maxDoc: " + maxDoc + "!=" + reader.MaxDoc); } int noSubs = subs.Count; if (noSubs != childMaxDoc.Length) { throw new System.ArgumentException("All readers must have same number of subReaders"); } for (int subIDX = 0; subIDX < noSubs; subIDX++) { IndexReader r = subs[subIDX]; if (r.MaxDoc != childMaxDoc[subIDX]) { throw new System.ArgumentException("All readers must have same corresponding subReader maxDoc"); } if (!(childAtomic[subIDX] ? (r is AtomicReader) : (r is CompositeReader))) { throw new System.ArgumentException("All readers must have same corresponding subReader types (atomic or composite)"); } } } } protected internal override void DoClose() { lock (this) { IOException ioe = null; foreach (IndexReader reader in CompleteReaderSet) { try { if (CloseSubReaders) { reader.Dispose(); } else { reader.DecRef(); } } catch (IOException e) { if (ioe == null) { ioe = e; } } } // throw the first exception if (ioe != null) { throw ioe; } } } } }
namespace RibbonAndNavigatorAndWorkspace { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.radioSparkleOrange = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.panelFill = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kryptonWorkspace = new ComponentFactory.Krypton.Workspace.KryptonWorkspace(); this.kryptonWorkspaceCell1 = new ComponentFactory.Krypton.Workspace.KryptonWorkspaceCell(); this.kryptonPage1 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLinkLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLinkLabel(); this.kryptonCheckBox2 = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kryptonCheckBox1 = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kryptonRadioButton3 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonRadioButton2 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonRadioButton1 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonPage3 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPage2 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPage7 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonWorkspaceSequence1 = new ComponentFactory.Krypton.Workspace.KryptonWorkspaceSequence(); this.kryptonWorkspaceCell3 = new ComponentFactory.Krypton.Workspace.KryptonWorkspaceCell(); this.kryptonPage4 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPage5 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPage10 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonWorkspaceCell4 = new ComponentFactory.Krypton.Workspace.KryptonWorkspaceCell(); this.kryptonPage6 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPage11 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.navigatorOutlook = new ComponentFactory.Krypton.Navigator.KryptonNavigator(); this.buttonSpecExpandCollapse = new ComponentFactory.Krypton.Navigator.ButtonSpecNavigator(); this.pageGlobalPalettes = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.radioOffice2010Black = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioSparklePurple = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2010Blue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2010Silver = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioSparkleBlue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioSystem = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2003 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2007Black = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2007Silver = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.radioOffice2007Blue = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonDisplayMode = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.buttonRibbonTabs = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.buttonStack = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.buttonHeaderBar = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.buttonHeaderGroup = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.buttonCheckButtons = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.buttonTabs = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.checkSetDocMode = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components); this.kryptonRibbon = new ComponentFactory.Krypton.Ribbon.KryptonRibbon(); this.qatAlbania = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatAruba = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatBenin = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatBrunei = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatCapeVerde = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatEthiopia = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatGuam = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatHaiti = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatLaos = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatMali = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatMozambique = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatPanama = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.qatQatar = new ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton(); this.kryptonContextMenuItem1 = new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem(); this.kryptonRibbonTab1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.kryptonRibbonGroup1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupTriple4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton10 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupSeparator1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator(); this.kryptonRibbonGroupTriple3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton7 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton8 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton9 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonTab2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.kryptonRibbonGroup3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton11 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton12 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton13 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup5 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple8 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton18 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupLines1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines(); this.kryptonRibbonGroupButton19 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton20 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup4 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple6 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton14 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupTriple7 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton15 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton16 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton17 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonPage8 = new ComponentFactory.Krypton.Navigator.KryptonPage(); this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLinkLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLinkLabel(); this.kryptonRadioButton4 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonRadioButton5 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonRadioButton6 = new ComponentFactory.Krypton.Toolkit.KryptonRadioButton(); this.kryptonCheckBox4 = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kryptonCheckBox5 = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kryptonCheckBox6 = new ComponentFactory.Krypton.Toolkit.KryptonCheckBox(); this.kryptonPage9 = new ComponentFactory.Krypton.Navigator.KryptonPage(); ((System.ComponentModel.ISupportInitialize)(this.panelFill)).BeginInit(); this.panelFill.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspace)).BeginInit(); this.kryptonWorkspace.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspaceCell1)).BeginInit(); this.kryptonWorkspaceCell1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage1)).BeginInit(); this.kryptonPage1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspaceCell3)).BeginInit(); this.kryptonWorkspaceCell3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage10)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspaceCell4)).BeginInit(); this.kryptonWorkspaceCell4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage11)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.navigatorOutlook)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pageGlobalPalettes)).BeginInit(); this.pageGlobalPalettes.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonDisplayMode)).BeginInit(); this.kryptonDisplayMode.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.checkSetDocMode)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage8)).BeginInit(); this.kryptonPage8.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage9)).BeginInit(); this.SuspendLayout(); // // radioSparkleOrange // this.radioSparkleOrange.Location = new System.Drawing.Point(13, 205); this.radioSparkleOrange.Name = "radioSparkleOrange"; this.radioSparkleOrange.Size = new System.Drawing.Size(110, 19); this.radioSparkleOrange.TabIndex = 8; this.radioSparkleOrange.Values.Text = "Sparkle - Orange"; this.radioSparkleOrange.CheckedChanged += new System.EventHandler(this.radioSparkleOrange_CheckedChanged); // // panelFill // this.panelFill.Controls.Add(this.kryptonWorkspace); this.panelFill.Controls.Add(this.kryptonPanel1); this.panelFill.Controls.Add(this.navigatorOutlook); this.panelFill.Dock = System.Windows.Forms.DockStyle.Fill; this.panelFill.Location = new System.Drawing.Point(0, 141); this.panelFill.Margin = new System.Windows.Forms.Padding(7); this.panelFill.Name = "panelFill"; this.panelFill.Padding = new System.Windows.Forms.Padding(7); this.panelFill.Size = new System.Drawing.Size(638, 454); this.panelFill.TabIndex = 1; // // kryptonWorkspace // this.kryptonWorkspace.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonWorkspace.Location = new System.Drawing.Point(162, 7); this.kryptonWorkspace.Name = "kryptonWorkspace"; // // // this.kryptonWorkspace.Root.Children.AddRange(new System.ComponentModel.Component[] { this.kryptonWorkspaceCell1, this.kryptonWorkspaceSequence1}); this.kryptonWorkspace.Root.Orientation = System.Windows.Forms.Orientation.Vertical; this.kryptonWorkspace.Root.UniqueName = "03CE3DB6856D4BE671B66A4FB4EF68C3"; this.kryptonWorkspace.SeparatorStyle = ComponentFactory.Krypton.Toolkit.SeparatorStyle.HighProfile; this.kryptonWorkspace.Size = new System.Drawing.Size(469, 440); this.kryptonWorkspace.TabIndex = 3; this.kryptonWorkspace.TabStop = true; this.kryptonWorkspace.WorkspaceCellAdding += new System.EventHandler<ComponentFactory.Krypton.Workspace.WorkspaceCellEventArgs>(this.OnWorkspaceCellAdding); // // kryptonWorkspaceCell1 // this.kryptonWorkspaceCell1.AllowPageDrag = true; this.kryptonWorkspaceCell1.AllowTabFocus = false; this.kryptonWorkspaceCell1.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.kryptonWorkspaceCell1.Button.ContextButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.kryptonWorkspaceCell1.Name = "kryptonWorkspaceCell1"; this.kryptonWorkspaceCell1.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] { this.kryptonPage1, this.kryptonPage3, this.kryptonPage2, this.kryptonPage7}); this.kryptonWorkspaceCell1.SelectedIndex = 0; this.kryptonWorkspaceCell1.UniqueName = "B6BB7B2230CD4B6CDBB3C3D3ECA3CE84"; // // kryptonPage1 // this.kryptonPage1.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage1.Controls.Add(this.kryptonLabel1); this.kryptonPage1.Controls.Add(this.kryptonLinkLabel1); this.kryptonPage1.Controls.Add(this.kryptonCheckBox2); this.kryptonPage1.Controls.Add(this.kryptonCheckBox1); this.kryptonPage1.Controls.Add(this.kryptonRadioButton3); this.kryptonPage1.Controls.Add(this.kryptonRadioButton2); this.kryptonPage1.Controls.Add(this.kryptonRadioButton1); this.kryptonPage1.Flags = 65534; this.kryptonPage1.LastVisibleSet = true; this.kryptonPage1.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage1.Name = "kryptonPage1"; this.kryptonPage1.Size = new System.Drawing.Size(467, 191); this.kryptonPage1.Text = "Page 1"; this.kryptonPage1.TextDescription = "Page 1 Description"; this.kryptonPage1.TextTitle = "Page 1 Title"; this.kryptonPage1.ToolTipTitle = "Page ToolTip"; this.kryptonPage1.UniqueName = "6BBD1FFBC4424D2F6BBD1FFBC4424D2F"; // // kryptonLabel1 // this.kryptonLabel1.Location = new System.Drawing.Point(180, 87); this.kryptonLabel1.Name = "kryptonLabel1"; this.kryptonLabel1.Size = new System.Drawing.Size(62, 19); this.kryptonLabel1.TabIndex = 6; this.kryptonLabel1.Values.Text = "Label Text"; // // kryptonLinkLabel1 // this.kryptonLinkLabel1.Location = new System.Drawing.Point(180, 63); this.kryptonLinkLabel1.Name = "kryptonLinkLabel1"; this.kryptonLinkLabel1.Size = new System.Drawing.Size(61, 19); this.kryptonLinkLabel1.TabIndex = 5; this.kryptonLinkLabel1.Values.Text = "Link Label"; // // kryptonCheckBox2 // this.kryptonCheckBox2.Location = new System.Drawing.Point(185, 15); this.kryptonCheckBox2.Name = "kryptonCheckBox2"; this.kryptonCheckBox2.Size = new System.Drawing.Size(83, 19); this.kryptonCheckBox2.TabIndex = 3; this.kryptonCheckBox2.Values.Text = "CheckBox 1"; // // kryptonCheckBox1 // this.kryptonCheckBox1.Location = new System.Drawing.Point(185, 39); this.kryptonCheckBox1.Name = "kryptonCheckBox1"; this.kryptonCheckBox1.Size = new System.Drawing.Size(83, 19); this.kryptonCheckBox1.TabIndex = 4; this.kryptonCheckBox1.Values.Text = "CheckBox 2"; // // kryptonRadioButton3 // this.kryptonRadioButton3.Location = new System.Drawing.Point(18, 63); this.kryptonRadioButton3.Name = "kryptonRadioButton3"; this.kryptonRadioButton3.Size = new System.Drawing.Size(99, 19); this.kryptonRadioButton3.TabIndex = 2; this.kryptonRadioButton3.Values.Text = "Radio Button 3"; // // kryptonRadioButton2 // this.kryptonRadioButton2.Location = new System.Drawing.Point(18, 39); this.kryptonRadioButton2.Name = "kryptonRadioButton2"; this.kryptonRadioButton2.Size = new System.Drawing.Size(99, 19); this.kryptonRadioButton2.TabIndex = 1; this.kryptonRadioButton2.Values.Text = "Radio Button 2"; // // kryptonRadioButton1 // this.kryptonRadioButton1.Location = new System.Drawing.Point(18, 15); this.kryptonRadioButton1.Name = "kryptonRadioButton1"; this.kryptonRadioButton1.Size = new System.Drawing.Size(99, 19); this.kryptonRadioButton1.TabIndex = 0; this.kryptonRadioButton1.Values.Text = "Radio Button 1"; // // kryptonPage3 // this.kryptonPage3.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage3.Flags = 65534; this.kryptonPage3.LastVisibleSet = true; this.kryptonPage3.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage3.Name = "kryptonPage3"; this.kryptonPage3.Size = new System.Drawing.Size(392, 147); this.kryptonPage3.Text = "Page 2"; this.kryptonPage3.TextDescription = "Page 2 Description"; this.kryptonPage3.TextTitle = "Page 2 Title"; this.kryptonPage3.ToolTipTitle = "Page ToolTip"; this.kryptonPage3.UniqueName = "A11EDA543BCD4892A11EDA543BCD4892"; // // kryptonPage2 // this.kryptonPage2.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage2.Flags = 65534; this.kryptonPage2.LastVisibleSet = true; this.kryptonPage2.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage2.Name = "kryptonPage2"; this.kryptonPage2.Size = new System.Drawing.Size(100, 100); this.kryptonPage2.Text = "Page 3"; this.kryptonPage2.TextDescription = "Page 3 Description"; this.kryptonPage2.TextTitle = "Page 3 Title"; this.kryptonPage2.ToolTipTitle = "Page ToolTip"; this.kryptonPage2.UniqueName = "2421DFC88D71464D2421DFC88D71464D"; // // kryptonPage7 // this.kryptonPage7.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage7.Flags = 65534; this.kryptonPage7.LastVisibleSet = true; this.kryptonPage7.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage7.Name = "kryptonPage7"; this.kryptonPage7.Size = new System.Drawing.Size(100, 100); this.kryptonPage7.Text = "Page 4"; this.kryptonPage7.TextDescription = "Page 4 Description"; this.kryptonPage7.TextTitle = "Page 4 Title"; this.kryptonPage7.ToolTipTitle = "Page ToolTip"; this.kryptonPage7.UniqueName = "07A8AEAF8A294D7307A8AEAF8A294D73"; // // kryptonWorkspaceSequence1 // this.kryptonWorkspaceSequence1.Children.AddRange(new System.ComponentModel.Component[] { this.kryptonWorkspaceCell3, this.kryptonWorkspaceCell4}); this.kryptonWorkspaceSequence1.UniqueName = "E0BD868474F749821686DA2047A1B41C"; // // kryptonWorkspaceCell3 // this.kryptonWorkspaceCell3.AllowPageDrag = true; this.kryptonWorkspaceCell3.AllowTabFocus = false; this.kryptonWorkspaceCell3.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.kryptonWorkspaceCell3.Button.ContextButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.kryptonWorkspaceCell3.Name = "kryptonWorkspaceCell3"; this.kryptonWorkspaceCell3.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] { this.kryptonPage4, this.kryptonPage5, this.kryptonPage10}); this.kryptonWorkspaceCell3.SelectedIndex = 0; this.kryptonWorkspaceCell3.UniqueName = "D6C2C815C07F40DA9786E81899BDF116"; // // kryptonPage4 // this.kryptonPage4.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage4.Flags = 65534; this.kryptonPage4.LastVisibleSet = true; this.kryptonPage4.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage4.Name = "kryptonPage4"; this.kryptonPage4.Size = new System.Drawing.Size(229, 192); this.kryptonPage4.Text = "Page 5"; this.kryptonPage4.TextDescription = "Page 5 Description"; this.kryptonPage4.TextTitle = "Page 5 Title"; this.kryptonPage4.ToolTipTitle = "Page ToolTip"; this.kryptonPage4.UniqueName = "51BA9BE4E9B64B9E51BA9BE4E9B64B9E"; // // kryptonPage5 // this.kryptonPage5.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage5.Flags = 65534; this.kryptonPage5.LastVisibleSet = true; this.kryptonPage5.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage5.Name = "kryptonPage5"; this.kryptonPage5.Size = new System.Drawing.Size(192, 148); this.kryptonPage5.Text = "Page 6"; this.kryptonPage5.TextDescription = "Page 6 Description"; this.kryptonPage5.TextTitle = "Page 6 Title"; this.kryptonPage5.ToolTipTitle = "Page ToolTip"; this.kryptonPage5.UniqueName = "F0E8346BF896419DF0E8346BF896419D"; // // kryptonPage10 // this.kryptonPage10.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage10.Flags = 65534; this.kryptonPage10.LastVisibleSet = true; this.kryptonPage10.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage10.Name = "kryptonPage10"; this.kryptonPage10.Size = new System.Drawing.Size(100, 100); this.kryptonPage10.Text = "Page 7"; this.kryptonPage10.TextDescription = "Page 7 Description"; this.kryptonPage10.TextTitle = "Page 7 Title"; this.kryptonPage10.ToolTipTitle = "Page ToolTip"; this.kryptonPage10.UniqueName = "3A748AD5F777479F3A748AD5F777479F"; // // kryptonWorkspaceCell4 // this.kryptonWorkspaceCell4.AllowPageDrag = true; this.kryptonWorkspaceCell4.AllowTabFocus = false; this.kryptonWorkspaceCell4.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.kryptonWorkspaceCell4.Button.ContextButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.kryptonWorkspaceCell4.Name = "kryptonWorkspaceCell4"; this.kryptonWorkspaceCell4.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] { this.kryptonPage6, this.kryptonPage11}); this.kryptonWorkspaceCell4.SelectedIndex = 0; this.kryptonWorkspaceCell4.UniqueName = "60088AB11A8D41DC5DA877C07264119D"; // // kryptonPage6 // this.kryptonPage6.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage6.Flags = 65534; this.kryptonPage6.LastVisibleSet = true; this.kryptonPage6.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage6.Name = "kryptonPage6"; this.kryptonPage6.Size = new System.Drawing.Size(231, 192); this.kryptonPage6.Text = "Page 8"; this.kryptonPage6.TextDescription = "Page 8 Description"; this.kryptonPage6.TextTitle = "Page 8 Title"; this.kryptonPage6.ToolTipTitle = "Page ToolTip"; this.kryptonPage6.UniqueName = "15D511E80A1D4E9515D511E80A1D4E95"; // // kryptonPage11 // this.kryptonPage11.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage11.Flags = 65534; this.kryptonPage11.LastVisibleSet = true; this.kryptonPage11.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage11.Name = "kryptonPage11"; this.kryptonPage11.Size = new System.Drawing.Size(100, 100); this.kryptonPage11.Text = "Page 9"; this.kryptonPage11.TextDescription = "Page 9 Description"; this.kryptonPage11.TextTitle = "Page 9 Title"; this.kryptonPage11.ToolTipTitle = "Page ToolTip"; this.kryptonPage11.UniqueName = "6D99A7C237EA45C26D99A7C237EA45C2"; // // kryptonPanel1 // this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Left; this.kryptonPanel1.Location = new System.Drawing.Point(155, 7); this.kryptonPanel1.Name = "kryptonPanel1"; this.kryptonPanel1.Size = new System.Drawing.Size(7, 440); this.kryptonPanel1.TabIndex = 2; // // navigatorOutlook // this.navigatorOutlook.AutoSize = true; this.navigatorOutlook.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.navigatorOutlook.Button.ButtonDisplayLogic = ComponentFactory.Krypton.Navigator.ButtonDisplayLogic.None; this.navigatorOutlook.Button.ButtonSpecs.AddRange(new ComponentFactory.Krypton.Navigator.ButtonSpecNavigator[] { this.buttonSpecExpandCollapse}); this.navigatorOutlook.Button.CloseButtonDisplay = ComponentFactory.Krypton.Navigator.ButtonDisplay.Hide; this.navigatorOutlook.Dock = System.Windows.Forms.DockStyle.Left; this.navigatorOutlook.Header.HeaderValuesPrimary.MapImage = ComponentFactory.Krypton.Navigator.MapKryptonPageImage.None; this.navigatorOutlook.Location = new System.Drawing.Point(7, 7); this.navigatorOutlook.Name = "navigatorOutlook"; this.navigatorOutlook.NavigatorMode = ComponentFactory.Krypton.Navigator.NavigatorMode.OutlookFull; this.navigatorOutlook.Pages.AddRange(new ComponentFactory.Krypton.Navigator.KryptonPage[] { this.pageGlobalPalettes, this.kryptonDisplayMode}); this.navigatorOutlook.SelectedIndex = 0; this.navigatorOutlook.Size = new System.Drawing.Size(148, 440); this.navigatorOutlook.TabIndex = 0; this.navigatorOutlook.Text = "kryptonNavigator1"; // // buttonSpecExpandCollapse // this.buttonSpecExpandCollapse.Type = ComponentFactory.Krypton.Toolkit.PaletteButtonSpecStyle.ArrowLeft; this.buttonSpecExpandCollapse.TypeRestricted = ComponentFactory.Krypton.Navigator.PaletteNavButtonSpecStyle.ArrowLeft; this.buttonSpecExpandCollapse.UniqueName = "22C3A3B1DC494B5F22C3A3B1DC494B5F"; this.buttonSpecExpandCollapse.Click += new System.EventHandler(this.buttonSpecExpandCollapse_Click); // // pageGlobalPalettes // this.pageGlobalPalettes.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.pageGlobalPalettes.Controls.Add(this.radioOffice2010Black); this.pageGlobalPalettes.Controls.Add(this.radioSparklePurple); this.pageGlobalPalettes.Controls.Add(this.radioOffice2010Blue); this.pageGlobalPalettes.Controls.Add(this.radioOffice2010Silver); this.pageGlobalPalettes.Controls.Add(this.radioSparkleOrange); this.pageGlobalPalettes.Controls.Add(this.radioSparkleBlue); this.pageGlobalPalettes.Controls.Add(this.radioSystem); this.pageGlobalPalettes.Controls.Add(this.radioOffice2003); this.pageGlobalPalettes.Controls.Add(this.radioOffice2007Black); this.pageGlobalPalettes.Controls.Add(this.radioOffice2007Silver); this.pageGlobalPalettes.Controls.Add(this.radioOffice2007Blue); this.pageGlobalPalettes.Flags = 65534; this.pageGlobalPalettes.ImageSmall = ((System.Drawing.Image)(resources.GetObject("pageGlobalPalettes.ImageSmall"))); this.pageGlobalPalettes.LastVisibleSet = true; this.pageGlobalPalettes.MinimumSize = new System.Drawing.Size(145, 50); this.pageGlobalPalettes.Name = "pageGlobalPalettes"; this.pageGlobalPalettes.Padding = new System.Windows.Forms.Padding(10); this.pageGlobalPalettes.Size = new System.Drawing.Size(146, 336); this.pageGlobalPalettes.Text = "Palettes"; this.pageGlobalPalettes.TextDescription = "Palettes"; this.pageGlobalPalettes.TextTitle = "Palettes"; this.pageGlobalPalettes.ToolTipTitle = "Page ToolTip"; this.pageGlobalPalettes.UniqueName = "64378E1F7C03429B64378E1F7C03429B"; // // radioOffice2010Black // this.radioOffice2010Black.Location = new System.Drawing.Point(13, 61); this.radioOffice2010Black.Name = "radioOffice2010Black"; this.radioOffice2010Black.Size = new System.Drawing.Size(119, 19); this.radioOffice2010Black.TabIndex = 2; this.radioOffice2010Black.Values.Text = "Office 2010 - Black"; this.radioOffice2010Black.CheckedChanged += new System.EventHandler(this.radioOffice2010Black_CheckedChanged); // // radioSparklePurple // this.radioSparklePurple.Location = new System.Drawing.Point(13, 229); this.radioSparklePurple.Name = "radioSparklePurple"; this.radioSparklePurple.Size = new System.Drawing.Size(104, 19); this.radioSparklePurple.TabIndex = 9; this.radioSparklePurple.Values.Text = "Sparkle - Purple"; this.radioSparklePurple.CheckedChanged += new System.EventHandler(this.radioSparklePurple_CheckedChanged); // // radioOffice2010Blue // this.radioOffice2010Blue.Checked = true; this.radioOffice2010Blue.Location = new System.Drawing.Point(13, 13); this.radioOffice2010Blue.Name = "radioOffice2010Blue"; this.radioOffice2010Blue.Size = new System.Drawing.Size(114, 19); this.radioOffice2010Blue.TabIndex = 0; this.radioOffice2010Blue.Values.Text = "Office 2010 - Blue"; this.radioOffice2010Blue.CheckedChanged += new System.EventHandler(this.radioOffice2010Blue_CheckedChanged); // // radioOffice2010Silver // this.radioOffice2010Silver.Location = new System.Drawing.Point(13, 37); this.radioOffice2010Silver.Name = "radioOffice2010Silver"; this.radioOffice2010Silver.Size = new System.Drawing.Size(120, 19); this.radioOffice2010Silver.TabIndex = 1; this.radioOffice2010Silver.Values.Text = "Office 2010 - Silver"; this.radioOffice2010Silver.CheckedChanged += new System.EventHandler(this.radioOffice2010Silver_CheckedChanged); // // radioSparkleBlue // this.radioSparkleBlue.Location = new System.Drawing.Point(13, 181); this.radioSparkleBlue.Name = "radioSparkleBlue"; this.radioSparkleBlue.Size = new System.Drawing.Size(93, 19); this.radioSparkleBlue.TabIndex = 7; this.radioSparkleBlue.Values.Text = "Sparkle - Blue"; this.radioSparkleBlue.CheckedChanged += new System.EventHandler(this.radioSparkleBlue_CheckedChanged); // // radioSystem // this.radioSystem.Location = new System.Drawing.Point(13, 253); this.radioSystem.Name = "radioSystem"; this.radioSystem.Size = new System.Drawing.Size(59, 19); this.radioSystem.TabIndex = 10; this.radioSystem.Values.Text = "System"; this.radioSystem.CheckedChanged += new System.EventHandler(this.radioSystem_CheckedChanged); // // radioOffice2003 // this.radioOffice2003.Location = new System.Drawing.Point(13, 157); this.radioOffice2003.Name = "radioOffice2003"; this.radioOffice2003.Size = new System.Drawing.Size(81, 19); this.radioOffice2003.TabIndex = 6; this.radioOffice2003.Values.Text = "Office 2003"; this.radioOffice2003.CheckedChanged += new System.EventHandler(this.radioOffice2003_CheckedChanged); // // radioOffice2007Black // this.radioOffice2007Black.Location = new System.Drawing.Point(13, 133); this.radioOffice2007Black.Name = "radioOffice2007Black"; this.radioOffice2007Black.Size = new System.Drawing.Size(119, 19); this.radioOffice2007Black.TabIndex = 5; this.radioOffice2007Black.Values.Text = "Office 2007 - Black"; this.radioOffice2007Black.CheckedChanged += new System.EventHandler(this.radioOffice2007Black_CheckedChanged); // // radioOffice2007Silver // this.radioOffice2007Silver.Location = new System.Drawing.Point(13, 109); this.radioOffice2007Silver.Name = "radioOffice2007Silver"; this.radioOffice2007Silver.Size = new System.Drawing.Size(120, 19); this.radioOffice2007Silver.TabIndex = 4; this.radioOffice2007Silver.Values.Text = "Office 2007 - Silver"; this.radioOffice2007Silver.CheckedChanged += new System.EventHandler(this.radioOffice2007Silver_CheckedChanged); // // radioOffice2007Blue // this.radioOffice2007Blue.Location = new System.Drawing.Point(13, 85); this.radioOffice2007Blue.Name = "radioOffice2007Blue"; this.radioOffice2007Blue.Size = new System.Drawing.Size(114, 19); this.radioOffice2007Blue.TabIndex = 3; this.radioOffice2007Blue.Values.Text = "Office 2007 - Blue"; this.radioOffice2007Blue.CheckedChanged += new System.EventHandler(this.radioOffice2007Blue_CheckedChanged); // // kryptonDisplayMode // this.kryptonDisplayMode.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonDisplayMode.Controls.Add(this.buttonRibbonTabs); this.kryptonDisplayMode.Controls.Add(this.buttonStack); this.kryptonDisplayMode.Controls.Add(this.buttonHeaderBar); this.kryptonDisplayMode.Controls.Add(this.buttonHeaderGroup); this.kryptonDisplayMode.Controls.Add(this.buttonCheckButtons); this.kryptonDisplayMode.Controls.Add(this.buttonTabs); this.kryptonDisplayMode.Flags = 65534; this.kryptonDisplayMode.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonDisplayMode.ImageSmall"))); this.kryptonDisplayMode.LastVisibleSet = true; this.kryptonDisplayMode.MinimumSize = new System.Drawing.Size(145, 50); this.kryptonDisplayMode.Name = "kryptonDisplayMode"; this.kryptonDisplayMode.Padding = new System.Windows.Forms.Padding(10); this.kryptonDisplayMode.Size = new System.Drawing.Size(151, 247); this.kryptonDisplayMode.Text = "Display Mode"; this.kryptonDisplayMode.TextDescription = "Display Mode"; this.kryptonDisplayMode.TextTitle = "Display Mode"; this.kryptonDisplayMode.ToolTipTitle = "Page ToolTip"; this.kryptonDisplayMode.UniqueName = "24D4FC840D914CC024D4FC840D914CC0"; // // buttonRibbonTabs // this.buttonRibbonTabs.Location = new System.Drawing.Point(19, 41); this.buttonRibbonTabs.Name = "buttonRibbonTabs"; this.buttonRibbonTabs.Size = new System.Drawing.Size(108, 25); this.buttonRibbonTabs.TabIndex = 14; this.buttonRibbonTabs.Values.Text = "RibbonTabs"; // // buttonStack // this.buttonStack.Location = new System.Drawing.Point(19, 165); this.buttonStack.Name = "buttonStack"; this.buttonStack.Size = new System.Drawing.Size(108, 25); this.buttonStack.TabIndex = 13; this.buttonStack.Values.Text = "Stack"; // // buttonHeaderBar // this.buttonHeaderBar.Location = new System.Drawing.Point(19, 134); this.buttonHeaderBar.Name = "buttonHeaderBar"; this.buttonHeaderBar.Size = new System.Drawing.Size(108, 25); this.buttonHeaderBar.TabIndex = 12; this.buttonHeaderBar.Values.Text = "HeaderBar"; // // buttonHeaderGroup // this.buttonHeaderGroup.Location = new System.Drawing.Point(19, 103); this.buttonHeaderGroup.Name = "buttonHeaderGroup"; this.buttonHeaderGroup.Size = new System.Drawing.Size(108, 25); this.buttonHeaderGroup.TabIndex = 11; this.buttonHeaderGroup.Values.Text = "HeaderGroup"; // // buttonCheckButtons // this.buttonCheckButtons.Location = new System.Drawing.Point(19, 72); this.buttonCheckButtons.Name = "buttonCheckButtons"; this.buttonCheckButtons.Size = new System.Drawing.Size(108, 25); this.buttonCheckButtons.TabIndex = 10; this.buttonCheckButtons.Values.Text = "CheckButtons"; // // buttonTabs // this.buttonTabs.Checked = true; this.buttonTabs.Location = new System.Drawing.Point(19, 10); this.buttonTabs.Name = "buttonTabs"; this.buttonTabs.Size = new System.Drawing.Size(108, 25); this.buttonTabs.TabIndex = 9; this.buttonTabs.Values.Text = "Tabs"; // // checkSetDocMode // this.checkSetDocMode.CheckButtons.Add(this.buttonTabs); this.checkSetDocMode.CheckButtons.Add(this.buttonCheckButtons); this.checkSetDocMode.CheckButtons.Add(this.buttonHeaderGroup); this.checkSetDocMode.CheckButtons.Add(this.buttonHeaderBar); this.checkSetDocMode.CheckButtons.Add(this.buttonStack); this.checkSetDocMode.CheckButtons.Add(this.buttonRibbonTabs); this.checkSetDocMode.CheckedButton = this.buttonTabs; this.checkSetDocMode.CheckedButtonChanged += new System.EventHandler(this.OnDocumentModeChanged); // // kryptonRibbon // this.kryptonRibbon.Name = "kryptonRibbon"; this.kryptonRibbon.QATButtons.AddRange(new System.ComponentModel.Component[] { this.qatAlbania, this.qatAruba, this.qatBenin, this.qatBrunei, this.qatCapeVerde, this.qatEthiopia, this.qatGuam, this.qatHaiti, this.qatLaos, this.qatMali, this.qatMozambique, this.qatPanama, this.qatQatar}); this.kryptonRibbon.QATLocation = ComponentFactory.Krypton.Ribbon.QATLocation.Below; this.kryptonRibbon.RibbonAppButton.AppButtonMenuItems.AddRange(new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItemBase[] { this.kryptonContextMenuItem1}); this.kryptonRibbon.RibbonAppButton.AppButtonShowRecentDocs = false; this.kryptonRibbon.RibbonTabs.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab[] { this.kryptonRibbonTab1, this.kryptonRibbonTab2}); this.kryptonRibbon.SelectedContext = null; this.kryptonRibbon.SelectedTab = this.kryptonRibbonTab1; this.kryptonRibbon.Size = new System.Drawing.Size(638, 141); this.kryptonRibbon.TabIndex = 0; // // qatAlbania // this.qatAlbania.Image = ((System.Drawing.Image)(resources.GetObject("qatAlbania.Image"))); this.qatAlbania.Text = "Albania"; // // qatAruba // this.qatAruba.Image = ((System.Drawing.Image)(resources.GetObject("qatAruba.Image"))); this.qatAruba.Text = "Aruba"; // // qatBenin // this.qatBenin.Image = ((System.Drawing.Image)(resources.GetObject("qatBenin.Image"))); this.qatBenin.Text = "Benin"; // // qatBrunei // this.qatBrunei.Image = ((System.Drawing.Image)(resources.GetObject("qatBrunei.Image"))); this.qatBrunei.Text = "Brunei"; // // qatCapeVerde // this.qatCapeVerde.Image = ((System.Drawing.Image)(resources.GetObject("qatCapeVerde.Image"))); this.qatCapeVerde.Text = "Cape Verde"; // // qatEthiopia // this.qatEthiopia.Image = ((System.Drawing.Image)(resources.GetObject("qatEthiopia.Image"))); this.qatEthiopia.Text = "Ethiopia"; // // qatGuam // this.qatGuam.Image = ((System.Drawing.Image)(resources.GetObject("qatGuam.Image"))); this.qatGuam.Text = "Guam"; // // qatHaiti // this.qatHaiti.Image = ((System.Drawing.Image)(resources.GetObject("qatHaiti.Image"))); this.qatHaiti.Text = "Haiti"; // // qatLaos // this.qatLaos.Image = ((System.Drawing.Image)(resources.GetObject("qatLaos.Image"))); this.qatLaos.Text = "Laos"; // // qatMali // this.qatMali.Image = ((System.Drawing.Image)(resources.GetObject("qatMali.Image"))); this.qatMali.Text = "Mali"; // // qatMozambique // this.qatMozambique.Image = ((System.Drawing.Image)(resources.GetObject("qatMozambique.Image"))); this.qatMozambique.Text = "Mozambique"; // // qatPanama // this.qatPanama.Image = ((System.Drawing.Image)(resources.GetObject("qatPanama.Image"))); this.qatPanama.Text = "Panama"; // // qatQatar // this.qatQatar.Image = ((System.Drawing.Image)(resources.GetObject("qatQatar.Image"))); this.qatQatar.Text = "Qatar"; // // kryptonContextMenuItem1 // this.kryptonContextMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonContextMenuItem1.Image"))); this.kryptonContextMenuItem1.Text = "E&xit"; this.kryptonContextMenuItem1.Click += new System.EventHandler(this.OnExit); // // kryptonRibbonTab1 // this.kryptonRibbonTab1.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] { this.kryptonRibbonGroup1, this.kryptonRibbonGroup2}); this.kryptonRibbonTab1.KeyTip = "H"; this.kryptonRibbonTab1.Text = "Home"; // // kryptonRibbonGroup1 // this.kryptonRibbonGroup1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup1.Image"))); this.kryptonRibbonGroup1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple1, this.kryptonRibbonGroupTriple4}); this.kryptonRibbonGroup1.KeyTipDialogLauncher = "LB"; this.kryptonRibbonGroup1.KeyTipGroup = "B"; this.kryptonRibbonGroup1.TextLine1 = "Bookmarks"; // // kryptonRibbonGroupTriple1 // this.kryptonRibbonGroupTriple1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton1}); this.kryptonRibbonGroupTriple1.MinimumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Large; // // kryptonRibbonGroupButton1 // this.kryptonRibbonGroupButton1.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton1.ImageLarge"))); this.kryptonRibbonGroupButton1.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton1.ImageSmall"))); this.kryptonRibbonGroupButton1.KeyTip = "BM"; this.kryptonRibbonGroupButton1.TextLine1 = "Bookmarks"; // // kryptonRibbonGroupTriple4 // this.kryptonRibbonGroupTriple4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton2, this.kryptonRibbonGroupButton3, this.kryptonRibbonGroupButton10}); this.kryptonRibbonGroupTriple4.MaximumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Medium; // // kryptonRibbonGroupButton2 // this.kryptonRibbonGroupButton2.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton2.ImageLarge"))); this.kryptonRibbonGroupButton2.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton2.ImageSmall"))); this.kryptonRibbonGroupButton2.KeyTip = "BA"; this.kryptonRibbonGroupButton2.TextLine1 = "Add"; // // kryptonRibbonGroupButton3 // this.kryptonRibbonGroupButton3.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton3.ImageLarge"))); this.kryptonRibbonGroupButton3.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton3.ImageSmall"))); this.kryptonRibbonGroupButton3.KeyTip = "BD"; this.kryptonRibbonGroupButton3.TextLine1 = "Delete"; // // kryptonRibbonGroupButton10 // this.kryptonRibbonGroupButton10.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton10.ImageLarge"))); this.kryptonRibbonGroupButton10.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton10.ImageSmall"))); this.kryptonRibbonGroupButton10.KeyTip = "BP"; this.kryptonRibbonGroupButton10.TextLine1 = "Preference"; // // kryptonRibbonGroup2 // this.kryptonRibbonGroup2.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup2.Image"))); this.kryptonRibbonGroup2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple2, this.kryptonRibbonGroupSeparator1, this.kryptonRibbonGroupTriple3}); this.kryptonRibbonGroup2.KeyTipDialogLauncher = "LD"; this.kryptonRibbonGroup2.KeyTipGroup = "D"; this.kryptonRibbonGroup2.TextLine1 = "Data"; // // kryptonRibbonGroupTriple2 // this.kryptonRibbonGroupTriple2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton4, this.kryptonRibbonGroupButton5, this.kryptonRibbonGroupButton6}); // // kryptonRibbonGroupButton4 // this.kryptonRibbonGroupButton4.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton4.ImageLarge"))); this.kryptonRibbonGroupButton4.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton4.ImageSmall"))); this.kryptonRibbonGroupButton4.KeyTip = "DC"; this.kryptonRibbonGroupButton4.TextLine1 = "Data"; this.kryptonRibbonGroupButton4.TextLine2 = "Copy"; // // kryptonRibbonGroupButton5 // this.kryptonRibbonGroupButton5.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton5.ImageLarge"))); this.kryptonRibbonGroupButton5.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton5.ImageSmall"))); this.kryptonRibbonGroupButton5.KeyTip = "DA"; this.kryptonRibbonGroupButton5.TextLine1 = "Data"; this.kryptonRibbonGroupButton5.TextLine2 = "Add"; // // kryptonRibbonGroupButton6 // this.kryptonRibbonGroupButton6.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton6.ImageLarge"))); this.kryptonRibbonGroupButton6.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton6.ImageSmall"))); this.kryptonRibbonGroupButton6.KeyTip = "DD"; this.kryptonRibbonGroupButton6.TextLine1 = "Data"; this.kryptonRibbonGroupButton6.TextLine2 = "Delete"; // // kryptonRibbonGroupTriple3 // this.kryptonRibbonGroupTriple3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton7, this.kryptonRibbonGroupButton8, this.kryptonRibbonGroupButton9}); // // kryptonRibbonGroupButton7 // this.kryptonRibbonGroupButton7.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton7.ImageLarge"))); this.kryptonRibbonGroupButton7.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton7.ImageSmall"))); this.kryptonRibbonGroupButton7.KeyTip = "DF"; this.kryptonRibbonGroupButton7.TextLine1 = "Data"; this.kryptonRibbonGroupButton7.TextLine2 = "Find"; // // kryptonRibbonGroupButton8 // this.kryptonRibbonGroupButton8.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton8.ImageLarge"))); this.kryptonRibbonGroupButton8.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton8.ImageSmall"))); this.kryptonRibbonGroupButton8.KeyTip = "DE"; this.kryptonRibbonGroupButton8.TextLine1 = "Data"; this.kryptonRibbonGroupButton8.TextLine2 = "Edit"; // // kryptonRibbonGroupButton9 // this.kryptonRibbonGroupButton9.ButtonType = ComponentFactory.Krypton.Ribbon.GroupButtonType.Check; this.kryptonRibbonGroupButton9.Checked = true; this.kryptonRibbonGroupButton9.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton9.ImageLarge"))); this.kryptonRibbonGroupButton9.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton9.ImageSmall"))); this.kryptonRibbonGroupButton9.KeyTip = "DL"; this.kryptonRibbonGroupButton9.TextLine1 = "Data"; this.kryptonRibbonGroupButton9.TextLine2 = "Lock"; // // kryptonRibbonTab2 // this.kryptonRibbonTab2.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] { this.kryptonRibbonGroup3, this.kryptonRibbonGroup5, this.kryptonRibbonGroup4}); this.kryptonRibbonTab2.KeyTip = "O"; this.kryptonRibbonTab2.Text = "Objects"; // // kryptonRibbonGroup3 // this.kryptonRibbonGroup3.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup3.Image"))); this.kryptonRibbonGroup3.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple5}); this.kryptonRibbonGroup3.KeyTipDialogLauncher = "LD"; this.kryptonRibbonGroup3.KeyTipGroup = "D"; this.kryptonRibbonGroup3.TextLine1 = "Disks"; // // kryptonRibbonGroupTriple5 // this.kryptonRibbonGroupTriple5.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton11, this.kryptonRibbonGroupButton12, this.kryptonRibbonGroupButton13}); // // kryptonRibbonGroupButton11 // this.kryptonRibbonGroupButton11.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton11.ImageLarge"))); this.kryptonRibbonGroupButton11.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton11.ImageSmall"))); this.kryptonRibbonGroupButton11.KeyTip = "DG"; this.kryptonRibbonGroupButton11.TextLine1 = "Green"; // // kryptonRibbonGroupButton12 // this.kryptonRibbonGroupButton12.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton12.ImageLarge"))); this.kryptonRibbonGroupButton12.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton12.ImageSmall"))); this.kryptonRibbonGroupButton12.KeyTip = "DR"; this.kryptonRibbonGroupButton12.TextLine1 = "Red"; // // kryptonRibbonGroupButton13 // this.kryptonRibbonGroupButton13.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton13.ImageLarge"))); this.kryptonRibbonGroupButton13.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton13.ImageSmall"))); this.kryptonRibbonGroupButton13.KeyTip = "DY"; this.kryptonRibbonGroupButton13.TextLine1 = "Yellow"; // // kryptonRibbonGroup5 // this.kryptonRibbonGroup5.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup5.Image"))); this.kryptonRibbonGroup5.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple8, this.kryptonRibbonGroupLines1}); this.kryptonRibbonGroup5.KeyTipDialogLauncher = "LB"; this.kryptonRibbonGroup5.KeyTipGroup = "B"; this.kryptonRibbonGroup5.TextLine1 = "Blocks"; // // kryptonRibbonGroupTriple8 // this.kryptonRibbonGroupTriple8.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton18}); this.kryptonRibbonGroupTriple8.MinimumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Large; // // kryptonRibbonGroupButton18 // this.kryptonRibbonGroupButton18.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton18.ImageLarge"))); this.kryptonRibbonGroupButton18.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton18.ImageSmall"))); this.kryptonRibbonGroupButton18.KeyTip = "S"; this.kryptonRibbonGroupButton18.TextLine1 = "Blocks"; // // kryptonRibbonGroupLines1 // this.kryptonRibbonGroupLines1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton19, this.kryptonRibbonGroupButton20}); this.kryptonRibbonGroupLines1.MinimumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Large; // // kryptonRibbonGroupButton19 // this.kryptonRibbonGroupButton19.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton19.ImageLarge"))); this.kryptonRibbonGroupButton19.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton19.ImageSmall"))); this.kryptonRibbonGroupButton19.TextLine1 = "Blue"; this.kryptonRibbonGroupButton19.TextLine2 = "Block"; // // kryptonRibbonGroupButton20 // this.kryptonRibbonGroupButton20.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton20.ImageLarge"))); this.kryptonRibbonGroupButton20.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton20.ImageSmall"))); this.kryptonRibbonGroupButton20.KeyTip = "Y"; this.kryptonRibbonGroupButton20.TextLine1 = "Yellow"; this.kryptonRibbonGroupButton20.TextLine2 = "Block"; // // kryptonRibbonGroup4 // this.kryptonRibbonGroup4.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup4.Image"))); this.kryptonRibbonGroup4.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple6, this.kryptonRibbonGroupTriple7}); this.kryptonRibbonGroup4.KeyTipDialogLauncher = "LCP"; this.kryptonRibbonGroup4.KeyTipGroup = "CP"; this.kryptonRibbonGroup4.TextLine1 = "Cups"; // // kryptonRibbonGroupTriple6 // this.kryptonRibbonGroupTriple6.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton14}); this.kryptonRibbonGroupTriple6.MinimumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Large; // // kryptonRibbonGroupButton14 // this.kryptonRibbonGroupButton14.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton14.ImageLarge"))); this.kryptonRibbonGroupButton14.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton14.ImageSmall"))); this.kryptonRibbonGroupButton14.KeyTip = "CR"; this.kryptonRibbonGroupButton14.TextLine1 = "Red"; // // kryptonRibbonGroupTriple7 // this.kryptonRibbonGroupTriple7.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton15, this.kryptonRibbonGroupButton16, this.kryptonRibbonGroupButton17}); // // kryptonRibbonGroupButton15 // this.kryptonRibbonGroupButton15.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton15.ImageLarge"))); this.kryptonRibbonGroupButton15.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton15.ImageSmall"))); this.kryptonRibbonGroupButton15.KeyTip = "CG"; this.kryptonRibbonGroupButton15.TextLine1 = "Green"; // // kryptonRibbonGroupButton16 // this.kryptonRibbonGroupButton16.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton16.ImageLarge"))); this.kryptonRibbonGroupButton16.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton16.ImageSmall"))); this.kryptonRibbonGroupButton16.KeyTip = "CB"; this.kryptonRibbonGroupButton16.TextLine1 = "Blue"; // // kryptonRibbonGroupButton17 // this.kryptonRibbonGroupButton17.ImageLarge = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton17.ImageLarge"))); this.kryptonRibbonGroupButton17.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton17.ImageSmall"))); this.kryptonRibbonGroupButton17.KeyTip = "CY"; this.kryptonRibbonGroupButton17.TextLine1 = "Yellow"; // // kryptonPage8 // this.kryptonPage8.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage8.Controls.Add(this.kryptonLabel2); this.kryptonPage8.Controls.Add(this.kryptonLinkLabel2); this.kryptonPage8.Controls.Add(this.kryptonRadioButton4); this.kryptonPage8.Controls.Add(this.kryptonRadioButton5); this.kryptonPage8.Controls.Add(this.kryptonRadioButton6); this.kryptonPage8.Controls.Add(this.kryptonCheckBox4); this.kryptonPage8.Controls.Add(this.kryptonCheckBox5); this.kryptonPage8.Controls.Add(this.kryptonCheckBox6); this.kryptonPage8.Flags = 65534; this.kryptonPage8.LastVisibleSet = true; this.kryptonPage8.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage8.Name = "kryptonPage8"; this.kryptonPage8.Size = new System.Drawing.Size(392, 147); this.kryptonPage8.Text = "kryptonPage8"; this.kryptonPage8.ToolTipTitle = "Page ToolTip"; this.kryptonPage8.UniqueName = "3A56A17B0EAE42533A56A17B0EAE4253"; // // kryptonLabel2 // this.kryptonLabel2.Location = new System.Drawing.Point(166, 44); this.kryptonLabel2.Name = "kryptonLabel2"; this.kryptonLabel2.Size = new System.Drawing.Size(76, 19); this.kryptonLabel2.TabIndex = 15; this.kryptonLabel2.Values.Text = "Simple Label"; // // kryptonLinkLabel2 // this.kryptonLinkLabel2.Location = new System.Drawing.Point(166, 19); this.kryptonLinkLabel2.Name = "kryptonLinkLabel2"; this.kryptonLinkLabel2.Size = new System.Drawing.Size(61, 19); this.kryptonLinkLabel2.TabIndex = 14; this.kryptonLinkLabel2.Values.Text = "Link Label"; // // kryptonRadioButton4 // this.kryptonRadioButton4.Location = new System.Drawing.Point(13, 165); this.kryptonRadioButton4.Name = "kryptonRadioButton4"; this.kryptonRadioButton4.Size = new System.Drawing.Size(135, 19); this.kryptonRadioButton4.TabIndex = 13; this.kryptonRadioButton4.Values.Text = "RadioButton Option 3"; // // kryptonRadioButton5 // this.kryptonRadioButton5.Checked = true; this.kryptonRadioButton5.Location = new System.Drawing.Point(13, 139); this.kryptonRadioButton5.Name = "kryptonRadioButton5"; this.kryptonRadioButton5.Size = new System.Drawing.Size(135, 19); this.kryptonRadioButton5.TabIndex = 12; this.kryptonRadioButton5.Values.Text = "RadioButton Option 2"; // // kryptonRadioButton6 // this.kryptonRadioButton6.Location = new System.Drawing.Point(13, 113); this.kryptonRadioButton6.Name = "kryptonRadioButton6"; this.kryptonRadioButton6.Size = new System.Drawing.Size(135, 19); this.kryptonRadioButton6.TabIndex = 11; this.kryptonRadioButton6.Values.Text = "RadioButton Option 1"; // // kryptonCheckBox4 // this.kryptonCheckBox4.Checked = true; this.kryptonCheckBox4.CheckState = System.Windows.Forms.CheckState.Indeterminate; this.kryptonCheckBox4.Location = new System.Drawing.Point(13, 71); this.kryptonCheckBox4.Name = "kryptonCheckBox4"; this.kryptonCheckBox4.Size = new System.Drawing.Size(122, 19); this.kryptonCheckBox4.TabIndex = 10; this.kryptonCheckBox4.Values.Text = "CheckBox Option 3"; // // kryptonCheckBox5 // this.kryptonCheckBox5.Checked = true; this.kryptonCheckBox5.CheckState = System.Windows.Forms.CheckState.Checked; this.kryptonCheckBox5.Location = new System.Drawing.Point(13, 45); this.kryptonCheckBox5.Name = "kryptonCheckBox5"; this.kryptonCheckBox5.Size = new System.Drawing.Size(122, 19); this.kryptonCheckBox5.TabIndex = 9; this.kryptonCheckBox5.Values.Text = "CheckBox Option 2"; // // kryptonCheckBox6 // this.kryptonCheckBox6.Location = new System.Drawing.Point(13, 19); this.kryptonCheckBox6.Name = "kryptonCheckBox6"; this.kryptonCheckBox6.Size = new System.Drawing.Size(122, 19); this.kryptonCheckBox6.TabIndex = 8; this.kryptonCheckBox6.Values.Text = "CheckBox Option 1"; // // kryptonPage9 // this.kryptonPage9.AutoHiddenSlideSize = new System.Drawing.Size(200, 200); this.kryptonPage9.Flags = 65534; this.kryptonPage9.LastVisibleSet = true; this.kryptonPage9.MinimumSize = new System.Drawing.Size(50, 50); this.kryptonPage9.Name = "kryptonPage9"; this.kryptonPage9.Size = new System.Drawing.Size(100, 100); this.kryptonPage9.Text = "kryptonPage9"; this.kryptonPage9.ToolTipTitle = "Page ToolTip"; this.kryptonPage9.UniqueName = "D7E39F0CF3924149D7E39F0CF3924149"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(638, 595); this.Controls.Add(this.panelFill); this.Controls.Add(this.kryptonRibbon); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(400, 525); this.Name = "Form1"; this.Text = "Ribbon + Navigator + Workspace"; ((System.ComponentModel.ISupportInitialize)(this.panelFill)).EndInit(); this.panelFill.ResumeLayout(false); this.panelFill.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspace)).EndInit(); this.kryptonWorkspace.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspaceCell1)).EndInit(); this.kryptonWorkspaceCell1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage1)).EndInit(); this.kryptonPage1.ResumeLayout(false); this.kryptonPage1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspaceCell3)).EndInit(); this.kryptonWorkspaceCell3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage10)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonWorkspaceCell4)).EndInit(); this.kryptonWorkspaceCell4.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage11)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.navigatorOutlook)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pageGlobalPalettes)).EndInit(); this.pageGlobalPalettes.ResumeLayout(false); this.pageGlobalPalettes.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonDisplayMode)).EndInit(); this.kryptonDisplayMode.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.checkSetDocMode)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage8)).EndInit(); this.kryptonPage8.ResumeLayout(false); this.kryptonPage8.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPage9)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager; private ComponentFactory.Krypton.Ribbon.KryptonRibbon kryptonRibbon; private ComponentFactory.Krypton.Toolkit.KryptonPanel panelFill; private ComponentFactory.Krypton.Navigator.KryptonNavigator navigatorOutlook; private ComponentFactory.Krypton.Navigator.KryptonPage pageGlobalPalettes; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonDisplayMode; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab kryptonRibbonTab1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupSeparator kryptonRibbonGroupSeparator1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton8; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton9; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab kryptonRibbonTab2; private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton10; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup3; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton11; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton12; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton13; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup4; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple6; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton14; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton15; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton16; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton17; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup5; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple8; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton18; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupLines kryptonRibbonGroupLines1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton19; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton20; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonStack; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonHeaderBar; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonHeaderGroup; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonCheckButtons; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonTabs; private ComponentFactory.Krypton.Toolkit.KryptonCheckSet checkSetDocMode; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatAlbania; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatAruba; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatBenin; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatBrunei; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatCapeVerde; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatEthiopia; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatGuam; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatHaiti; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatLaos; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatMali; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatMozambique; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatPanama; private ComponentFactory.Krypton.Ribbon.KryptonRibbonQATButton qatQatar; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton buttonRibbonTabs; private ComponentFactory.Krypton.Navigator.ButtonSpecNavigator buttonSpecExpandCollapse; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2007Blue; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSystem; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2003; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2007Black; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2007Silver; private ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem kryptonContextMenuItem1; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSparkleBlue; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSparklePurple; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioSparkleOrange; private ComponentFactory.Krypton.Workspace.KryptonWorkspace kryptonWorkspace; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage8; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel2; private ComponentFactory.Krypton.Toolkit.KryptonLinkLabel kryptonLinkLabel2; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonRadioButton4; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonRadioButton5; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonRadioButton6; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kryptonCheckBox4; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kryptonCheckBox5; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kryptonCheckBox6; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage9; private ComponentFactory.Krypton.Workspace.KryptonWorkspaceCell kryptonWorkspaceCell1; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage1; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage3; private ComponentFactory.Krypton.Workspace.KryptonWorkspaceSequence kryptonWorkspaceSequence1; private ComponentFactory.Krypton.Workspace.KryptonWorkspaceCell kryptonWorkspaceCell3; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage4; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage5; private ComponentFactory.Krypton.Workspace.KryptonWorkspaceCell kryptonWorkspaceCell4; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage6; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage2; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage7; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage10; private ComponentFactory.Krypton.Navigator.KryptonPage kryptonPage11; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kryptonCheckBox2; private ComponentFactory.Krypton.Toolkit.KryptonCheckBox kryptonCheckBox1; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonRadioButton3; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonRadioButton2; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton kryptonRadioButton1; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel1; private ComponentFactory.Krypton.Toolkit.KryptonLinkLabel kryptonLinkLabel1; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2010Black; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2010Blue; private ComponentFactory.Krypton.Toolkit.KryptonRadioButton radioOffice2010Silver; } }
#if !SILVERLIGHT using System.Windows.Forms; #endif using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace DevExpress.Mvvm.UI { [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public abstract class FileDialogServiceBase : ServiceBase, IFileDialogServiceBase { #if !SILVERLIGHT public static readonly DependencyProperty CheckFileExistsProperty = DependencyProperty.Register("CheckFileExists", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false)); public static readonly DependencyProperty AddExtensionProperty = DependencyProperty.Register("AddExtension", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true)); public static readonly DependencyProperty AutoUpgradeEnabledProperty = DependencyProperty.Register("AutoUpgradeEnabled", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true)); public static readonly DependencyProperty CheckPathExistsProperty = DependencyProperty.Register("CheckPathExists", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true)); public static readonly DependencyProperty DereferenceLinksProperty = DependencyProperty.Register("DereferenceLinks", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true)); public static readonly DependencyProperty InitialDirectoryProperty = DependencyProperty.Register("InitialDirectory", typeof(string), typeof(FileDialogServiceBase), new PropertyMetadata(string.Empty)); public static readonly DependencyProperty RestoreDirectoryProperty = DependencyProperty.Register("RestoreDirectory", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false)); public static readonly DependencyProperty ShowHelpProperty = DependencyProperty.Register("ShowHelp", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false)); public static readonly DependencyProperty SupportMultiDottedExtensionsProperty = DependencyProperty.Register("SupportMultiDottedExtensions", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(false)); public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(FileDialogServiceBase), new PropertyMetadata(string.Empty)); public static readonly DependencyProperty ValidateNamesProperty = DependencyProperty.Register("ValidateNames", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true)); public static readonly DependencyProperty RestorePreviouslySelectedDirectoryProperty = DependencyProperty.Register("RestorePreviouslySelectedDirectory", typeof(bool), typeof(FileDialogServiceBase), new PropertyMetadata(true)); public static readonly DependencyProperty FileOkCommandProperty = DependencyProperty.Register("FileOkCommand", typeof(ICommand), typeof(FileDialogServiceBase), new PropertyMetadata(null)); public static readonly DependencyProperty HelpRequestCommandProperty = DependencyProperty.Register("HelpRequestCommand", typeof(ICommand), typeof(FileDialogServiceBase), new PropertyMetadata(null)); public bool CheckFileExists { get { return (bool)GetValue(CheckFileExistsProperty); } set { SetValue(CheckFileExistsProperty, value); } } public bool AddExtension { get { return (bool)GetValue(AddExtensionProperty); } set { SetValue(AddExtensionProperty, value); } } public bool AutoUpgradeEnabled { get { return (bool)GetValue(AutoUpgradeEnabledProperty); } set { SetValue(AutoUpgradeEnabledProperty, value); } } public bool CheckPathExists { get { return (bool)GetValue(CheckPathExistsProperty); } set { SetValue(CheckPathExistsProperty, value); } } public bool DereferenceLinks { get { return (bool)GetValue(DereferenceLinksProperty); } set { SetValue(DereferenceLinksProperty, value); } } public string InitialDirectory { get { return (string)GetValue(InitialDirectoryProperty); } set { SetValue(InitialDirectoryProperty, value); } } public bool RestoreDirectory { get { return (bool)GetValue(RestoreDirectoryProperty); } set { SetValue(RestoreDirectoryProperty, value); } } public bool ShowHelp { get { return (bool)GetValue(ShowHelpProperty); } set { SetValue(ShowHelpProperty, value); } } public bool SupportMultiDottedExtensions { get { return (bool)GetValue(SupportMultiDottedExtensionsProperty); } set { SetValue(SupportMultiDottedExtensionsProperty, value); } } public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } public bool ValidateNames { get { return (bool)GetValue(ValidateNamesProperty); } set { SetValue(ValidateNamesProperty, value); } } public bool RestorePreviouslySelectedDirectory { get { return (bool)GetValue(RestorePreviouslySelectedDirectoryProperty); } set { SetValue(RestorePreviouslySelectedDirectoryProperty, value); } } public ICommand FileOkCommand { get { return (ICommand)GetValue(FileOkCommandProperty); } set { SetValue(FileOkCommandProperty, value); } } public ICommand HelpRequestCommand { get { return (ICommand)GetValue(HelpRequestCommandProperty); } set { SetValue(HelpRequestCommandProperty, value); } } public event CancelEventHandler FileOk { add { FileDialog dialog = (FileDialog)FileDialog; dialog.FileOk += value; } remove { FileDialog dialog = (FileDialog)FileDialog; dialog.FileOk -= value; } } public event EventHandler HelpRequest { add { FileDialog dialog = (FileDialog)FileDialog; dialog.HelpRequest += value; } remove { FileDialog dialog = (FileDialog)FileDialog; dialog.HelpRequest -= value; } } #endif object FileDialog; IEnumerable<FileInfoWrapper> FilesCore; public FileDialogServiceBase() { FileDialog = CreateFileDialog(); FilesCore = new List<FileInfoWrapper>(); #if !SILVERLIGHT FileOk += (d, e) => { if(FileOkCommand != null && FileOkCommand.CanExecute(e)) FileOkCommand.Execute(e); }; HelpRequest += (d, e) => { if(HelpRequestCommand != null && HelpRequestCommand.CanExecute(e)) HelpRequestCommand.Execute(e); }; #endif } protected abstract object CreateFileDialog(); protected abstract void InitFileDialog(); protected abstract List<FileInfoWrapper> GetFileInfos(); void InitFileDialogCore() { #if !SILVERLIGHT FileDialog dialog = (FileDialog)FileDialog; dialog.CheckFileExists = CheckFileExists; dialog.AddExtension = AddExtension; dialog.AutoUpgradeEnabled = AutoUpgradeEnabled; dialog.CheckPathExists = CheckPathExists; dialog.DereferenceLinks = DereferenceLinks; dialog.InitialDirectory = InitialDirectory; dialog.RestoreDirectory = RestoreDirectory; dialog.ShowHelp = ShowHelp; dialog.SupportMultiDottedExtensions = SupportMultiDottedExtensions; dialog.Title = Title; dialog.ValidateNames = ValidateNames; if(RestorePreviouslySelectedDirectory && FilesCore.Count() > 0) dialog.InitialDirectory = FilesCore.First().FileInfo.DirectoryName; else dialog.InitialDirectory = InitialDirectory; #endif } void UpdateFiles(bool dialogResult) { ((IList)FilesCore).Clear(); if(!dialogResult) return; var fileInfos = GetFileInfos(); foreach(FileInfoWrapper fileInfo in fileInfos) ((IList)FilesCore).Add(fileInfo); } #if SILVERLIGHT bool ConvertDialogResultToBoolean(bool? result) { return result.Value; } #else bool ConvertDialogResultToBoolean(DialogResult result) { if(result == DialogResult.OK) return true; if(result == DialogResult.Cancel) return false; throw new InvalidOperationException("The Dialog has returned a not supported value"); } #endif protected object GetFileDialog() { return FileDialog; } protected IEnumerable<FileInfoWrapper> GetFiles() { return FilesCore; } protected bool Show() { InitFileDialogCore(); InitFileDialog(); #if !SILVERLIGHT DialogResult result = ((FileDialog)FileDialog).ShowDialog(); #else bool? result = null; if(FileDialog is OpenFileDialog) result = ((OpenFileDialog)FileDialog).ShowDialog(); if(FileDialog is SaveFileDialog) result = ((SaveFileDialog)FileDialog).ShowDialog(); #endif bool res = ConvertDialogResultToBoolean(result); UpdateFiles(res); return res; } #if !SILVERLIGHT void IFileDialogServiceBase.Reset() { ((FileDialog)FileDialog).Reset(); } #endif } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public class FileInfoWrapper : IFileInfo { public static FileInfoWrapper Create(string fileName) { return new FileInfoWrapper(new FileInfo(fileName)); } public FileInfo FileInfo { get; private set; } public FileInfoWrapper(FileInfo fileInfo) { FileInfo = fileInfo; } StreamWriter IFileInfo.AppendText() { return FileInfo.AppendText(); } FileInfo IFileInfo.CopyTo(string destFileName, bool overwrite) { return FileInfo.CopyTo(destFileName, overwrite); } FileInfo IFileInfo.CopyTo(string destFileName) { return FileInfo.CopyTo(destFileName); } FileStream IFileInfo.Create() { return FileInfo.Create(); } StreamWriter IFileInfo.CreateText() { return FileInfo.CreateText(); } void IFileInfo.Delete() { FileInfo.Delete(); } string IFileInfo.DirectoryName { get { return FileInfo.DirectoryName; } } bool IFileInfo.Exists { get { return FileInfo.Exists; } } long IFileInfo.Length { get { return FileInfo.Length; } } void IFileInfo.MoveTo(string destFileName) { FileInfo.MoveTo(destFileName); } string IFileInfo.Name { get { return FileInfo.Name; } } FileStream IFileInfo.Open(FileMode mode, FileAccess access, FileShare share) { return FileInfo.Open(mode, access, share); } FileStream IFileInfo.Open(FileMode mode, FileAccess access) { return FileInfo.Open(mode, access); } FileStream IFileInfo.Open(FileMode mode) { return FileInfo.Open(mode); } FileStream IFileInfo.OpenRead() { return FileInfo.OpenRead(); } StreamReader IFileInfo.OpenText() { return FileInfo.OpenText(); } FileStream IFileInfo.OpenWrite() { return FileInfo.OpenWrite(); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; namespace Encog.Util { /// <summary> /// A very simple text parser. /// </summary> public class SimpleParser { /// <summary> /// The current position. /// </summary> private int _currentPosition; /// <summary> /// The marked position. /// </summary> private int _marked; /// <summary> /// Construct the object for the specified line. /// </summary> /// <param name="line">The line to parse.</param> public SimpleParser(String line) { Line = line; } /// <summary> /// The line being parsed. /// </summary> public String Line { get; set; } /// <summary> /// The number of characters remaining. /// </summary> /// <returns>The number of characters remaining.</returns> public int Remaining() { return Math.Max(Line.Length - _currentPosition, 0); } /// <summary> /// Parse through a comma. /// </summary> /// <returns>True, if the comma was found.</returns> public bool ParseThroughComma() { EatWhiteSpace(); if (!EOL()) { if (Peek() == ',') { Advance(); return true; } } return false; } /// <summary> /// CHeck to see if the next character is an identifier. /// </summary> /// <returns>True, if the next char is an identifier.</returns> public bool IsIdentifier() { if (EOL()) return false; return char.IsLetterOrDigit(Peek()) || Peek() == '_'; } /// <summary> /// Peek ahead to see the next character. But do not advance beyond it. /// </summary> /// <returns>The next character.</returns> public char Peek() { if (EOL()) return (char) 0; if (_currentPosition >= Line.Length) return (char) 0; return Line[_currentPosition]; } /// <summary> /// Advance beyond the next character. /// </summary> public void Advance() { if (_currentPosition < Line.Length) { _currentPosition++; } } /// <summary> /// Returns true if the next character is a white space. /// </summary> /// <returns>True, if the next character is a white space.</returns> public bool IsWhiteSpace() { return " \t\n\r".IndexOf(Peek()) != -1; } /// <summary> /// Returns true of there are no more characters to read. /// </summary> /// <returns>True, if we have reached end of line.</returns> public bool EOL() { return (_currentPosition >= Line.Length); } /// <summary> /// Strip any white space from the current position. /// </summary> public void EatWhiteSpace() { while (!EOL() && IsWhiteSpace()) Advance(); } /// <summary> /// Read the next character. /// </summary> /// <returns>The next character.</returns> public char ReadChar() { if (EOL()) return (char) 0; char ch = Peek(); Advance(); return ch; } /// <summary> /// Read text up to the next white space. /// </summary> /// <returns>The text read up to the next white space.</returns> public String ReadToWhiteSpace() { var result = new StringBuilder(); while (!IsWhiteSpace() && !EOL()) { result.Append(ReadChar()); } return result.ToString(); } /// <summary> /// Look ahead to see if the specified string is present. /// </summary> /// <param name="str">The string searching for.</param> /// <param name="ignoreCase">True if case is to be ignored.</param> /// <returns>True if the string is present.</returns> public bool LookAhead(String str, bool ignoreCase) { if (Remaining() < str.Length) return false; for (int i = 0; i < str.Length; i++) { char c1 = str[i]; char c2 = Line[_currentPosition + i]; if (ignoreCase) { c1 = char.ToLower(c1); c2 = char.ToLower(c2); } if (c1 != c2) return false; } return true; } /// <summary> /// Advance the specified number of characters. /// </summary> /// <param name="p">The number of characters to advance.</param> public void Advance(int p) { _currentPosition = Math.Min(Line.Length, _currentPosition + p); } /// <summary> /// Mark the current position. /// </summary> public void Mark() { _marked = _currentPosition; } /// <summary> /// Reset back to the marked position. /// </summary> public void Reset() { _currentPosition = _marked; } /// <summary> /// Read a quoted string. /// </summary> /// <returns>The string that was read.</returns> public String ReadQuotedString() { if (Peek() != '\"') return ""; var result = new StringBuilder(); Advance(); while (Peek() != '\"' && !EOL()) { result.Append(ReadChar()); } Advance(); return result.ToString(); } /// <summary> /// Read forward to the specified characters. /// </summary> /// <param name="chs">The characters to stop at.</param> /// <returns>The string that was read.</returns> public String ReadToChars(String chs) { StringBuilder result = new StringBuilder(); while (chs.IndexOf(this.Peek()) == -1 && !EOL()) { result.Append(ReadChar()); } return result.ToString(); } } }
//#define ASTAR_POOL_DEBUG //Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly. using UnityEngine; using System.Collections; using Pathfinding; using System.Collections.Generic; namespace Pathfinding { /** Base class for all path types */ public abstract class Path { #if ASTAR_POOL_DEBUG private string pathTraceInfo = ""; private List<string> claimInfo = new List<string>(); ~Path() { Debug.Log ("Destroying " + GetType().Name + " instance"); if (claimed.Count > 0) { Debug.LogWarning ("Pool Is Leaking. See list of claims:\n" + "Each message below will list what objects are currently claiming the path." + " These objects have removed their reference to the path object but has not called .Release on it (which is bad).\n" + pathTraceInfo+"\n"); for (int i=0;i<claimed.Count;i++) { Debug.LogWarning ("- Claim "+ (i+1) + " is by a " + claimed[i].GetType().Name + "\n"+claimInfo[i]); } } else { Debug.Log ("Some scripts are not using pooling.\n" + pathTraceInfo + "\n"); } } #endif /** Data for the thread calculating this path */ public PathHandler pathHandler; /** Callback to call when the path is complete. * This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path */ public OnPathDelegate callback; #if !ASTAR_LOCK_FREE_PATH_STATE private PathState state; private System.Object stateLock = new object(); #else private int state; #endif /** Current state of the path. * \see #CompleteState */ private PathCompleteState pathCompleteState; /** Current state of the path */ public PathCompleteState CompleteState { get { return pathCompleteState; } protected set { pathCompleteState = value; } } /** If the path failed, this is true. * \see #errorLog */ public bool error { get { return CompleteState == PathCompleteState.Error; }} /** Additional info on what went wrong. * \see #error */ private string _errorLog = ""; /** Log messages with info about eventual errors. */ public string errorLog { get { return _errorLog; } } private GraphNode[] _path; private Vector3[] _vectorPath; /** Holds the path as a Node array. All nodes the path traverses. This might not be the same as all nodes the smoothed path traverses. */ public List<GraphNode> path; /** Holds the (perhaps post processed) path as a Vector3 array */ public List<Vector3> vectorPath; /** The max number of milliseconds per iteration (frame, in case of non-multithreading) */ protected float maxFrameTime; /** The node currently being processed */ protected PathNode currentR; public float duration; /**< The duration of this path in ms. How long it took to calculate the path */ /**< The number of frames/iterations this path has executed. * This is the number of frames when not using multithreading. * When using multithreading, this value is quite irrelevant */ public int searchIterations = 0; public int searchedNodes; /**< Number of nodes this path has searched */ /** When the call was made to start the pathfinding for this path */ public System.DateTime callTime; /* True if the path has been calculated (even if it had an error). * Used by the multithreaded pathfinder to signal that this path object is safe to return. */ //public bool processed = false; /** True if the path is currently recycled (i.e in the path pool). * Do not set this value. Only read. It is used internally. */ public bool recycled = false; /** True if the Reset function has been called. * Used to allert users when they are doing it wrong. */ protected bool hasBeenReset = false; /** Constraint for how to search for nodes */ public NNConstraint nnConstraint = PathNNConstraint.Default; /** The next path to be searched. * Linked list implementation. * \warning You should never change this if you do not know what you are doing */ public Path next; //These are variables which different scripts and custom graphs can use to get a bit more info about What is searching //Not all are used in the standard graph types //These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary) //Note: These variables needs to be filled in by an external script to be usable /** Radius for the unit searching for the path. * \note Not used by any built-in pathfinders. * These common name variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary). * Or having to cast to another path type for acess. */ public int radius; /** A mask for defining what type of ground a unit can traverse, not used in any default standard graph. \see #enabledTags * \note Not used by any built-in pathfinders. * These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary) */ public int walkabilityMask = -1; /** Height of the character. Not used currently */ public int height; /** Turning radius of the character. Not used currently */ public int turnRadius; /** Speed of the character. Not used currently */ public int speed; /* To store additional data. Note: this is SLOW. About 10-100 times slower than using the fields above. * \since Removed in 3.0.8 * Currently not used */ //public Dictionary<string,int> customData = null;//new Dictionary<string,int>(); /** Determines which heuristic to use */ public Heuristic heuristic; /** Scale of the heuristic values */ public float heuristicScale = 1F; /** ID of this path. Used to distinguish between different paths */ #if ASTAR_MORE_PATH_IDS public uint pathID; #else public ushort pathID; #endif protected Int3 hTarget; /**< Target to use for H score calculations. \see Pathfinding.Node.H */ /** Which graph tags are traversable. * This is a bitmask so -1 = all bits set = all tags traversable. * For example, to set bit 5 to true, you would do * \code myPath.enabledTags |= 1 << 5; \endcode * To set it to false, you would do * \code myPath.enabledTags &= ~(1 << 5); \endcode * * The Seeker has a popup field where you can set which tags to use. * \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. * So you need to change the Seeker value via script, not set this value if you want to change it via script. * * \see CanTraverse */ public int enabledTags = -1; /** Penalties for each tag. */ protected int[] _tagPenalties = new int[0]; /** Penalties for each tag. * Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. * These should only be positive values since the A* algorithm cannot handle negative penalties. * \note This array will never be null. If you try to set it to null or with a lenght which is not 32. It will be set to "new int[0]". * * \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. * So you need to change the Seeker value via script, not set this value if you want to change it via script. * * \see Seeker.tagPenalties */ public int[] tagPenalties { get { return _tagPenalties; } set { if (value == null || value.Length != 32) _tagPenalties = new int[0]; else _tagPenalties = value; } } /** Total Length of the path. * Calculates the total length of the #vectorPath. * Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value. * \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned. */ public float GetTotalLength () { if (vectorPath == null) return float.PositiveInfinity; float tot = 0; for (int i=0;i<vectorPath.Count-1;i++) tot += Vector3.Distance (vectorPath[i],vectorPath[i+1]); return tot; } /** Waits until this path has been calculated and returned. * Allows for very easy scripting. \code //In an IEnumerator function Path p = Seeker.StartPath (transform.position, transform.position + Vector3.forward * 10); yield return StartCoroutine (p.WaitForPath ()); //The path is calculated at this stage \endcode * \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated * while AstarPath.WaitForPath will halt all operations until the path has been calculated. * * \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function. * * \see AstarPath.WaitForPath */ public IEnumerator WaitForPath () { if (GetState () == PathState.Created) throw new System.InvalidOperationException ("This path has not been started yet"); while (GetState () != PathState.Returned) yield return null; } public uint CalculateHScore (GraphNode node) { switch (heuristic) { case Heuristic.Euclidean: return (uint)(((GetHTarget () - node.position).costMagnitude)*heuristicScale); case Heuristic.Manhattan: Int3 p2 = node.position; return (uint)((System.Math.Abs (hTarget.x-p2.x) + System.Math.Abs (hTarget.y-p2.y) + System.Math.Abs (hTarget.z-p2.z))*heuristicScale); case Heuristic.DiagonalManhattan: Int3 p = GetHTarget () - node.position; p.x = System.Math.Abs (p.x); p.y = System.Math.Abs (p.y); p.z = System.Math.Abs (p.z); int diag = System.Math.Min (p.x,p.z); int diag2 = System.Math.Max (p.x,p.z); return (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale); } return 0U; } /** Returns penalty for the given tag. * \param tag A value between 0 (inclusive) and 31 (inclusive). */ public uint GetTagPenalty (int tag) { return tag < _tagPenalties.Length ? (uint)_tagPenalties[tag] : 0; } public Int3 GetHTarget () { return hTarget; } /** Returns if the node can be traversed. * This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */ #if ConfigureTagsAsMultiple public bool CanTraverse (GraphNode node) { return node.walkable && (node.tags & enabledTags) != 0; } #else public bool CanTraverse (GraphNode node) { unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; } } #endif public uint GetTraversalCost (GraphNode node) { unchecked { return GetTagPenalty ((int)node.Tag ) + node.Penalty; } } /** May be called by graph nodes to get a special cost for some connections. * Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have * a very large area can be marked on the start and end nodes, this method will be called * to get the actual cost for moving from the start position to its neighbours instead * of as would otherwise be the case, from the start node's position to its neighbours. * The position of a node and the actual start point on the node can vary quite a lot. * * The default behaviour of this method is to return the previous cost of the connection, * essentiall making no change at all. * * This method should return the same regardless of the order of a and b. * That is f(a,b) == f(b,a) should hold. * * \param a Moving from this node * \param b Moving to this node * \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return. */ public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) { return currentCost; } /** Returns if this path is done calculating. * \returns If CompleteState is not PathCompleteState.NotCalculated. * * \note The path might not have been returned yet. * * \since Added in 3.0.8 * * \see Seeker.IsDone */ public bool IsDone () { return CompleteState != PathCompleteState.NotCalculated; } /** Threadsafe increment of the state */ #if !ASTAR_LOCK_FREE_PATH_STATE public void AdvanceState (PathState s) { lock (stateLock) { state = (PathState)System.Math.Max ((int)state, (int)s); } } #else public void AdvanceState () { System.Threading.Interlocked.Increment (ref state); } #endif /** Returns the state of the path in the pathfinding pipeline */ public PathState GetState () { return (PathState)state; } /** Appends \a msg to #errorLog and logs \a msg to the console. * Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame. * Consider calling Error() along with this call. */ // Ugly Code Inc. wrote the below code :D // What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled // since the DISABLED define will never be enabled // Ugly way of writing Conditional("!ASTAR_NO_LOGGING") #if ASTAR_NO_LOGGING [System.Diagnostics.Conditional("DISABLED")] #endif public void LogError (string msg) { // Optimize for release builds if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) { _errorLog += msg; } if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) { Debug.LogWarning (msg); } } /** Logs an error and calls Error() to true. * This is called only if something is very wrong or the user is doing something he/she really should not be doing. */ public void ForceLogError (string msg) { Error(); _errorLog += msg; Debug.LogError (msg); } /** Appends a message to the #errorLog. * Nothing is logged to the console. * * \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization. */ public void Log (string msg) { // Optimize for release builds if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) { _errorLog += msg; } } /** Aborts the path because of an error. * Sets #error to true. * This function is called when an error has ocurred (e.g a valid path could not be found). * \see LogError */ public void Error () { CompleteState = PathCompleteState.Error; } /** Does some error checking. * Makes sure the user isn't using old code paths and that no major errors have been done. * * \throws An exception if any errors are found */ private void ErrorCheck () { if (!hasBeenReset) throw new System.Exception ("The path has never been reset. Use pooling API or call Reset() after creating the path with the default constructor."); if (recycled) throw new System.Exception ("The path is currently in a path pool. Are you sending the path for calculation twice?"); if (pathHandler == null) throw new System.Exception ("Field pathHandler is not set. Please report this bug."); if (GetState() > PathState.Processing) throw new System.Exception ("This path has already been processed. Do not request a path with the same path object twice."); } /** Called when the path enters the pool. * This method should release e.g pooled lists and other pooled resources * The base version of this method releases vectorPath and path lists. * Reset() will be called after this function, not before. * \warning Do not call this function manually. */ public virtual void OnEnterPool () { if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release (vectorPath); if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release (path); vectorPath = null; path = null; } /** Reset all values to their default values. * * \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to * override this function, resetting ALL their variables to enable recycling of paths. * If this is not done, trying to use that path type for pooling might result in weird behaviour. * The best way is to reset to default values the variables declared in the extended path type and then * call this base function in inheriting types with base.Reset (). * * \warning This function should not be called manually. */ public virtual void Reset () { #if ASTAR_POOL_DEBUG pathTraceInfo = "This path was got from the pool or created from here (stacktrace):\n"; pathTraceInfo += System.Environment.StackTrace; #endif if (AstarPath.active == null) throw new System.NullReferenceException ("No AstarPath object found in the scene. " + "Make sure there is one or do not create paths in Awake"); hasBeenReset = true; state = (int)PathState.Created; releasedNotSilent = false; pathHandler = null; callback = null; _errorLog = ""; pathCompleteState = PathCompleteState.NotCalculated; path = Pathfinding.Util.ListPool<GraphNode>.Claim(); vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim(); currentR = null; duration = 0; searchIterations = 0; searchedNodes = 0; //calltime nnConstraint = PathNNConstraint.Default; next = null; radius = 0; walkabilityMask = -1; height = 0; turnRadius = 0; speed = 0; //heuristic = (Heuristic)0; //heuristicScale = 1F; heuristic = AstarPath.active.heuristic; heuristicScale = AstarPath.active.heuristicScale; pathID = 0; enabledTags = -1; tagPenalties = null; callTime = System.DateTime.UtcNow; pathID = AstarPath.active.GetNextPathID (); hTarget = Int3.zero; } protected bool HasExceededTime (int searchedNodes, long targetTime) { return System.DateTime.UtcNow.Ticks >= targetTime; } /** Recycle the path. * Calling this means that the path and any variables on it are not needed anymore and the path can be pooled. * All path data will be reset. * Implement this in inheriting path types to support recycling of paths. \code public override void Recycle () { //Recycle the Path (<Path> should be replaced by the path type it is implemented in) PathPool<Path>.Recycle (this); } \endcode * * \warning Do not call this function directly, instead use the #Claim and #Release functions. * \see Pathfinding.PathPool * \see Reset * \see Claim * \see Release */ protected abstract void Recycle ();// { // PathPool<Path>.Recycle (this); //} /** List of claims on this path with reference objects */ private List<System.Object> claimed = new List<System.Object>(); /** True if the path has been released with a non-silent call yet. * * \see Release * \see ReleaseSilent * \see Claim */ private bool releasedNotSilent = false; /** Claim this path. * A claim on a path will ensure that it is not recycled. * If you are using a path, you will want to claim it when you first get it and then release it when you will not * use it anymore. When there are no claims on the path, it will be recycled and put in a pool. * * \see Release * \see Recycle */ public void Claim (System.Object o) { if (o == null) throw new System.ArgumentNullException ("o"); if (claimed.Contains (o)) { throw new System.ArgumentException ("You have already claimed the path with that object ("+o.ToString()+"). Are you claiming the path with the same object twice?"); } claimed.Add (o); #if ASTAR_POOL_DEBUG claimInfo.Add (o.ToString () + "\n\nClaimed from:\n" + System.Environment.StackTrace); #endif } /** Releases the path silently. * This will remove the claim by the specified object, but the path will not be recycled if the claim count reches zero unless a Release call (not silent) has been made earlier. * This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not recycle paths. * This enables users to skip the claim/release calls if they want without the path being recycled by the Seeker or AstarPath. */ public void ReleaseSilent (System.Object o) { if (o == null) throw new System.ArgumentNullException ("o"); for (int i=0;i<claimed.Count;i++) { if (claimed[i] == o) { claimed.RemoveAt (i); #if ASTAR_POOL_DEBUG claimInfo.RemoveAt (i); #endif if (releasedNotSilent && claimed.Count == 0) { Recycle (); } return; } } if (claimed.Count == 0) { throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " + "Are you releasing the path with the same object ("+o.ToString()+") twice?"); } else { throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " + "Are you releasing the path with the same object twice?"); } } /** Releases a path claim. * Removes the claim of the path by the specified object. * When the claim count reaches zero, the path will be recycled, all variables will be cleared and the path will be put in a pool to be used again. * This is great for memory since less allocations are made. * \see Claim */ public void Release (System.Object o) { if (o == null) throw new System.ArgumentNullException ("o"); for (int i=0;i<claimed.Count;i++) { if (claimed[i] == o) { claimed.RemoveAt (i); #if ASTAR_POOL_DEBUG claimInfo.RemoveAt (i); #endif releasedNotSilent = true; if (claimed.Count == 0) { Recycle (); } return; } } if (claimed.Count == 0) { throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " + "Are you releasing the path with the same object ("+o.ToString()+") twice?"); } else { throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " + "Are you releasing the path with the same object twice?"); } } /** Traces the calculated path from the end node to the start. * This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions. * Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path). */ protected virtual void Trace (PathNode from) { int count = 0; PathNode c = from; while (c != null) { c = c.parent; count++; if (count > 1024) { Debug.LogWarning ("Inifinity loop? >1024 node path. Remove this message if you really have that long paths (Path.cs, Trace function)"); break; } } //Ensure capacities for lists AstarProfiler.StartProfile ("Check List Capacities"); if (path.Capacity < count) path.Capacity = count; if (vectorPath.Capacity < count) vectorPath.Capacity = count; AstarProfiler.EndProfile (); c = from; for (int i = 0;i<count;i++) { path.Add (c.node); c = c.parent; } int half = count/2; for (int i=0;i<half;i++) { GraphNode tmp = path[i]; path[i] = path[count-i-1]; path[count - i - 1] = tmp; } for (int i=0;i<count;i++) { vectorPath.Add ((Vector3)path[i].position); } } /** Returns a debug string for this path. */ public virtual string DebugString (PathLog logMode) { if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) { return ""; } //debugStringBuilder.Length = 0; System.Text.StringBuilder text = pathHandler.DebugStringBuilder; text.Length = 0; text.Append (error ? "Path Failed : " : "Path Completed : "); text.Append ("Computation Time "); text.Append ((duration).ToString (logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms ")); text.Append ("Searched Nodes "); text.Append (searchedNodes); if (!error) { text.Append (" Path Length "); text.Append (path == null ? "Null" : path.Count.ToString ()); if (logMode == PathLog.Heavy) { text.Append ("\nSearch Iterations "+searchIterations); //text.Append ("\nBinary Heap size at complete: "); // -2 because numberOfItems includes the next item to be added and item zero is not used //text.Append (pathHandler.open == null ? "null" : (pathHandler.open.numberOfItems-2).ToString ()); } /*"\nEnd node\n G = "+p.endNode.g+"\n H = "+p.endNode.h+"\n F = "+p.endNode.f+"\n Point "+p.endPoint +"\nStart Point = "+p.startPoint+"\n"+"Start Node graph: "+p.startNode.graphIndex+" End Node graph: "+p.endNode.graphIndex+ "\nBinary Heap size at completion: "+(p.open == null ? "Null" : p.open.numberOfItems.ToString ())*/ } if (error) { text.Append ("\nError: "); text.Append (errorLog); } if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading ) { text.Append ("\nCallback references "); if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine(); else text.AppendLine ("NULL"); } text.Append ("\nPath Number "); text.Append (pathID); return text.ToString (); } /** Calls callback to return the calculated path. \see #callback */ public virtual void ReturnPath () { if (callback != null) { callback (this); } } /** Prepares low level path variables for calculation. * Called before a path search will take place. * Always called before the Prepare, Initialize and CalculateStep functions */ public void PrepareBase (PathHandler pathHandler) { //Path IDs have overflowed 65K, cleanup is needed //Since pathIDs are handed out sequentially, we can do this if (pathHandler.PathID > pathID) { pathHandler.ClearPathIDs (); } //Make sure the path has a reference to the pathHandler this.pathHandler = pathHandler; //Assign relevant path data to the pathHandler pathHandler.InitializeForPath (this); try { ErrorCheck (); } catch (System.Exception e) { ForceLogError ("Exception in path "+pathID+"\n"+e.ToString()); } } public abstract void Prepare (); /** Always called after the path has been calculated. * Guaranteed to be called before other paths have been calculated on * the same thread. * Use for cleaning up things like node tagging and similar. */ public virtual void Cleanup () {} /** Initializes the path. * Sets up the open list and adds the first node to it */ public abstract void Initialize (); /** Calculates the path until time has gone past \a targetTick */ public abstract void CalculateStep (long targetTick); } }
using System; using GuruComponents.CodeEditor.CodeEditor.Syntax; using System.ComponentModel; namespace GuruComponents.CodeEditor.CodeEditor { /// <summary> /// Selection class used by the SyntaxBoxControl /// </summary> public class Selection { /// <summary> /// Event fired when the selection has changed. /// </summary> public event EventHandler Change = null; #region Instance constructors /// <summary> /// Selection Constructor. /// </summary> /// <param name="control">Control that will use this selection</param> public Selection(EditViewControl control) { Control = control; this.Bounds = new TextRange(); } #endregion Instance constructors #region Public instance properties /// <summary> /// Gets the text of the active selection /// </summary> public String Text { get { if (!this.IsValid) { return ""; } else { return Control.Document.GetRange(this.LogicalBounds); } } set { if (this.Text == value) return; //selection text bug fix // //selection gets too short if \n is used instead of newline string tmp = value.Replace(Environment.NewLine, "\n"); tmp = tmp.Replace("\n", Environment.NewLine); value = tmp; //--- TextPoint oCaretPos = Control.Caret.Position; int nCaretX = oCaretPos.X; int nCaretY = oCaretPos.Y; this.Control.Document.StartUndoCapture(); this.DeleteSelection(); this.Control.Document.InsertText(value, oCaretPos.X, oCaretPos.Y); this.SelLength = value.Length; if (nCaretX != oCaretPos.X || nCaretY != oCaretPos.Y) { this.Control.Caret.Position = new TextPoint(this.Bounds.LastColumn, this.Bounds.LastRow); } this.Control.Document.EndUndoCapture(); this.Control.Document.InvokeChange(); } } /// <summary> /// Returns the normalized positions of the selection. /// Swapping start and end values if the selection is reversed. /// </summary> public TextRange LogicalBounds { get { TextRange r = new TextRange(); if (this.Bounds.FirstRow < this.Bounds.LastRow) { return this.Bounds; } else if (this.Bounds.FirstRow == this.Bounds.LastRow && this.Bounds.FirstColumn < this.Bounds.LastColumn) { return this.Bounds; } else { r.FirstColumn = this.Bounds.LastColumn; r.FirstRow = this.Bounds.LastRow; r.LastColumn = this.Bounds.FirstColumn; r.LastRow = this.Bounds.FirstRow; return r; } } } /// <summary> /// Returns true if the selection contains One or more chars /// </summary> public bool IsValid { get { return (this.LogicalBounds.FirstColumn != this.LogicalBounds.LastColumn || this.LogicalBounds.FirstRow != this.LogicalBounds.LastRow); } } /// <summary> /// gets or sets the length of the selection in chars /// </summary> public int SelLength { get { TextPoint p1 = new TextPoint(this.Bounds.FirstColumn, this.Bounds.FirstRow); TextPoint p2 = new TextPoint(this.Bounds.LastColumn, this.Bounds.LastRow); int i1 = this.Control.Document.PointToIntPos(p1); int i2 = this.Control.Document.PointToIntPos(p2); return i2 - i1; } set { this.SelEnd = this.SelStart + value; } } /// <summary> /// Gets or Sets the Selection end as an index in the document text. /// </summary> public int SelEnd { get { TextPoint p = new TextPoint(this.Bounds.LastColumn, this.Bounds.LastRow); return this.Control.Document.PointToIntPos(p); } set { TextPoint p = this.Control.Document.IntPosToPoint(value); this.Bounds.LastColumn = p.X; this.Bounds.LastRow = p.Y; } } /// <summary> /// Gets or Sets the Selection start as an index in the document text. /// </summary> public int SelStart { get { TextPoint p = new TextPoint(this.Bounds.FirstColumn, this.Bounds.FirstRow); return this.Control.Document.PointToIntPos(p); } set { TextPoint p = this.Control.Document.IntPosToPoint(value); this.Bounds.FirstColumn = p.X; this.Bounds.FirstRow = p.Y; } } /// <summary> /// Gets or Sets the logical Selection start as an index in the document text. /// </summary> public int LogicalSelStart { get { TextPoint p = new TextPoint(this.LogicalBounds.FirstColumn, this.LogicalBounds.FirstRow); return this.Control.Document.PointToIntPos(p); } set { TextPoint p = this.Control.Document.IntPosToPoint(value); this.Bounds.FirstColumn = p.X; this.Bounds.FirstRow = p.Y; } } #endregion Public instance properties #region Public instance methods /// <summary> /// Indent the active selection one step. /// </summary> public void Indent() { if (!this.IsValid) return; Row xtr = null; UndoBlockCollection ActionGroup = new UndoBlockCollection(); for (int i = this.LogicalBounds.FirstRow; i <= this.LogicalBounds.LastRow; i++) { xtr = Control.Document[i]; xtr.Text = "\t" + xtr.Text; UndoBlock b = new UndoBlock(); b.Action = UndoAction.InsertRange; b.Text = "\t"; b.Position.X = 0; b.Position.Y = i; ActionGroup.Add(b); } if (ActionGroup.Count > 0) Control.Document.AddToUndoList(ActionGroup); this.Bounds = this.LogicalBounds; this.Bounds.FirstColumn = 0; this.Bounds.LastColumn = xtr.Text.Length; Control.Caret.Position.X = this.LogicalBounds.LastColumn; Control.Caret.Position.Y = this.LogicalBounds.LastRow; } /// <summary> /// Outdent the active selection one step /// </summary> public void Outdent() { if (!this.IsValid) return; Row xtr = null; UndoBlockCollection ActionGroup = new UndoBlockCollection(); for (int i = this.LogicalBounds.FirstRow; i <= this.LogicalBounds.LastRow; i++) { xtr = Control.Document[i]; UndoBlock b = new UndoBlock(); b.Action = UndoAction.DeleteRange; b.Position.X = 0; b.Position.Y = i; ActionGroup.Add(b); string s = xtr.Text; if (s.StartsWith("\t")) { b.Text = s.Substring(0, 1); s = s.Substring(1); } if (s.StartsWith(" ")) { b.Text = s.Substring(0, 4); s = s.Substring(4); } xtr.Text = s; } if (ActionGroup.Count > 0) Control.Document.AddToUndoList(ActionGroup); this.Bounds = this.LogicalBounds; this.Bounds.FirstColumn = 0; this.Bounds.LastColumn = xtr.Text.Length; Control.Caret.Position.X = this.LogicalBounds.LastColumn; Control.Caret.Position.Y = this.LogicalBounds.LastRow; } public void Indent(string Pattern) { if (!this.IsValid) return; Row xtr = null; UndoBlockCollection ActionGroup = new UndoBlockCollection(); for (int i = this.LogicalBounds.FirstRow; i <= this.LogicalBounds.LastRow; i++) { xtr = Control.Document[i]; xtr.Text = Pattern + xtr.Text; UndoBlock b = new UndoBlock(); b.Action = UndoAction.InsertRange; b.Text = Pattern; b.Position.X = 0; b.Position.Y = i; ActionGroup.Add(b); } if (ActionGroup.Count > 0) Control.Document.AddToUndoList(ActionGroup); this.Bounds = this.LogicalBounds; this.Bounds.FirstColumn = 0; this.Bounds.LastColumn = xtr.Text.Length; Control.Caret.Position.X = this.LogicalBounds.LastColumn; Control.Caret.Position.Y = this.LogicalBounds.LastRow; } /// <summary> /// Outdent the active selection one step /// </summary> public void Outdent(string Pattern) { if (!this.IsValid) return; Row xtr = null; UndoBlockCollection ActionGroup = new UndoBlockCollection(); for (int i = this.LogicalBounds.FirstRow; i <= this.LogicalBounds.LastRow; i++) { xtr = Control.Document[i]; UndoBlock b = new UndoBlock(); b.Action = UndoAction.DeleteRange; b.Position.X = 0; b.Position.Y = i; ActionGroup.Add(b); string s = xtr.Text; if (s.StartsWith(Pattern)) { b.Text = s.Substring(0, Pattern.Length); s = s.Substring(Pattern.Length); } xtr.Text = s; } if (ActionGroup.Count > 0) Control.Document.AddToUndoList(ActionGroup); this.Bounds = this.LogicalBounds; this.Bounds.FirstColumn = 0; this.Bounds.LastColumn = xtr.Text.Length; Control.Caret.Position.X = this.LogicalBounds.LastColumn; Control.Caret.Position.Y = this.LogicalBounds.LastRow; } /// <summary> /// Delete the active selection. /// <seealso cref="ClearSelection"/> /// </summary> public void DeleteSelection() { TextRange r = this.LogicalBounds; int x = r.FirstColumn; int y = r.FirstRow; Control.Document.DeleteRange(r); Control.Caret.Position.X = x; Control.Caret.Position.Y = y; ClearSelection(); Control.ScrollIntoView(); } /// <summary> /// Clear the active selection /// <seealso cref="DeleteSelection"/> /// </summary> public void ClearSelection() { Bounds.FirstColumn = Control.Caret.Position.X; Bounds.FirstRow = Control.Caret.Position.Y; Bounds.LastColumn = Control.Caret.Position.X; Bounds.LastRow = Control.Caret.Position.Y; } /// <summary> /// Make a selection from the current selection start to the position of the caret /// </summary> public void MakeSelection() { Bounds.LastColumn = Control.Caret.Position.X; Bounds.LastRow = Control.Caret.Position.Y; } /// <summary> /// Select all text. /// </summary> public void SelectAll() { Bounds.FirstColumn = 0; Bounds.FirstRow = 0; Bounds.LastColumn = Control.Document[Control.Document.Count - 1].Text.Length; Bounds.LastRow = Control.Document.Count - 1; Control.Caret.Position.X = Bounds.LastColumn; Control.Caret.Position.Y = Bounds.LastRow; Control.ScrollIntoView(); } #endregion Public instance methods #region Public instance fields /// <summary> /// The bounds of the selection /// </summary> /// private TextRange _Bounds; public TextRange Bounds { get { return _Bounds; } set { if (_Bounds != null) { _Bounds.Change -= new EventHandler(this.Bounds_Change); } _Bounds = value; _Bounds.Change += new EventHandler(this.Bounds_Change); OnChange(); } } private void Bounds_Change(object s, EventArgs e) { OnChange(); } #endregion Public instance fields #region Protected instance fields private EditViewControl Control; #endregion Protected instance fields private void PositionChange(object s, EventArgs e) { OnChange(); } private void OnChange() { if (Change != null) Change(this, null); } } }
using System; using Overflow.Extensibility; using Overflow.Test.Fakes; using Overflow.Test.TestingInfrastructure; using Xunit; namespace Overflow.Test { public class SimpleOperationResolverTests { [Theory, AutoMoqData] public void The_simple_resolver_can_resolve_operations_without_any_dependencies(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); var result = sut.Resolve<SimpleTestOperation>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void The_simple_resolver_can_resolve_operations_with_registered_dependencies(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); var result = sut.Resolve<OperationWithDependencies>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void The_simple_resolver_can_resolve_operations_with_registered_instance_dependencies(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependencyInstance(new SimpleDependency()); var result = sut.Resolve<OperationWithDependencies>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void You_can_register_the_same_dependency_more_than_once(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); var result = sut.Resolve<OperationWithDependencies>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void You_can_register_the_same_instance_dependency_more_than_once(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependencyInstance(new SimpleDependency()); sut.RegisterOperationDependencyInstance(new SimpleDependency()); var result = sut.Resolve<OperationWithDependencies>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void Dependencies_registered_as_instances_are_preferred_over_instances_registered_as_types(WorkflowConfiguration configuration, SimpleDependency instance) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); sut.RegisterOperationDependencyInstance(instance); var result = (OperationWithDependencies)sut.Resolve<OperationWithDependencies>(configuration); Assert.Equal(instance, result.Dependency); } [Theory, AutoMoqData] public void The_simple_resolver_can_resolve_operations_with_nested_dependencies(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); sut.RegisterOperationDependency<ComplexDependency, ComplexDependency>(); var result = sut.Resolve<OperationWithComplexDependencies>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void The_simple_resolver_cannot_resolve_operations_with_unregistered_dependencies(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); Assert.Throws<InvalidOperationException>(() => sut.Resolve<OperationWithDependencies>(configuration)); } [Theory, AutoMoqData] public void The_simple_resolver_cannot_resolve_operations_with_unregistered_sub_dependencies(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<ComplexDependency, ComplexDependency>(); Assert.Throws<InvalidOperationException>(() => sut.Resolve<OperationWithComplexDependencies>(configuration)); } [Theory, AutoMoqData] public void Resolving_the_same_operation_twice_returns_two_different_instances(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); var result1 = sut.Resolve<SimpleTestOperation>(configuration); var result2 = sut.Resolve<SimpleTestOperation>(configuration); Assert.NotSame(result1, result2); } [Theory, AutoMoqData] public void Dependencies_are_resolved_as_new_instances_every_time(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); var result1 = sut.Resolve<OperationWithDependencies>(configuration) as OperationWithDependencies; var result2 = sut.Resolve<OperationWithDependencies>(configuration) as OperationWithDependencies; Assert.NotSame(result1.Dependency, result2.Dependency); } [Theory, AutoMoqData] public void Operations_having_more_than_one_constructor_cannot_be_resolved(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); Assert.Throws<InvalidOperationException>(() => sut.Resolve<OperationWithTwoConstructors>(configuration)); } [Theory, AutoMoqData] public void Operations_with_dependencies_having_more_than_one_constructor_cannot_be_resolved(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); sut.RegisterOperationDependency<DependencyWithTwoConstructors, DependencyWithTwoConstructors>(); Assert.Throws<InvalidOperationException>(() => sut.Resolve<OperationWithDualConstructorDependency>(configuration)); } [Theory, AutoMoqData] public void Dependencies_can_be_registered_as_implementations(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<IDependency, SimpleDependency>(); var result = sut.Resolve<OperationWithInterfaceDependency>(configuration); Assert.NotNull(result); } [Theory, AutoMoqData] public void The_last_registered_dependency_of_a_given_type_wins(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); sut.RegisterOperationDependency<SimpleDependency, SimpleDependency>(); sut.RegisterOperationDependency<IDependency, SimpleDependency>(); sut.RegisterOperationDependency<IDependency, ComplexDependency>(); var result = sut.Resolve<OperationWithInterfaceDependency>(configuration) as OperationWithInterfaceDependency; Assert.IsType<ComplexDependency>(result.Dependency); } [Theory, AutoMoqData] public void Resolving_operations_creates_and_applies_behaviors_to_the_created_operations(WorkflowConfiguration configuration) { var sut = new SimpleOperationResolver(); var factory = new FakeOperationBehaviorFactory(); factory.OperationBehaviors.Add(new FakeOperationBehavior { SetPrecedence = BehaviorPrecedence.StateRecovery }); var workflow = configuration.WithBehaviorFactory(factory); var result = sut.Resolve<SimpleTestOperation>(workflow); Assert.IsType<FakeOperationBehavior>(result); Assert.IsType<SimpleTestOperation>((result as OperationBehavior).InnerOperation); } #region Dependencies private class SimpleTestOperation : Operation { } private class OperationWithDependencies : Operation { public SimpleDependency Dependency { get; } public OperationWithDependencies(SimpleDependency dependency) { if (dependency == null) throw new ArgumentException(); Dependency = dependency; } } private interface IDependency { } public class SimpleDependency : IDependency { } private class OperationWithComplexDependencies : Operation { public ComplexDependency Dependency { get; private set; } public OperationWithComplexDependencies(ComplexDependency dependency) { if (dependency == null) throw new ArgumentException(); Dependency = dependency; } } private class ComplexDependency : IDependency { public SimpleDependency Dependency { get; private set; } public ComplexDependency(SimpleDependency dependency) { if (dependency == null) throw new ArgumentException(); Dependency = dependency; } } private class OperationWithDualConstructorDependency : Operation { public OperationWithDualConstructorDependency(DependencyWithTwoConstructors dependency) { if (dependency == null) throw new ArgumentException(); } } private class DependencyWithTwoConstructors : IDependency { public DependencyWithTwoConstructors() { } public DependencyWithTwoConstructors(SimpleDependency dependency) { } } private class OperationWithTwoConstructors : Operation { public OperationWithTwoConstructors() { } public OperationWithTwoConstructors(SimpleDependency dependency) { } } private class OperationWithInterfaceDependency : Operation { public IDependency Dependency { get; } public OperationWithInterfaceDependency(IDependency dependency) { if (dependency == null) throw new ArgumentException(); Dependency = dependency; } } #endregion } }
// Copyright 2016-2017 Confluent Inc., 2015-2016 Andreas Heider // // 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. // // Derived from: rdkafka-dotnet, licensed under the 2-clause BSD License. // // Refer to LICENSE for more information. namespace Confluent.Kafka { /// <summary> /// Enumeration of local and broker generated error codes. /// </summary> /// <remarks> /// Error codes that relate to locally produced errors in /// librdkafka are prefixed with Local_ /// </remarks> public enum ErrorCode { /// <summary> /// Received message is incorrect /// </summary> Local_BadMsg = -199, /// <summary> /// Bad/unknown compression /// </summary> Local_BadCompression = -198, /// <summary> /// Broker is going away /// </summary> Local_Destroy = -197, /// <summary> /// Generic failure /// </summary> Local_Fail = -196, /// <summary> /// Broker transport failure /// </summary> Local_Transport = -195, /// <summary> /// Critical system resource /// </summary> Local_CritSysResource = -194, /// <summary> /// Failed to resolve broker /// </summary> Local_Resolve = -193, /// <summary> /// Produced message timed out /// </summary> Local_MsgTimedOut = -192, /// <summary> /// Reached the end of the topic+partition queue on the broker. Not really an error. /// </summary> Local_PartitionEOF = -191, /// <summary> /// Permanent: Partition does not exist in cluster. /// </summary> Local_UnknownPartition = -190, /// <summary> /// File or filesystem error /// </summary> Local_FS = -189, /// <summary> /// Permanent: Topic does not exist in cluster. /// </summary> Local_UnknownTopic = -188, /// <summary> /// All broker connections are down. /// </summary> Local_AllBrokersDown = -187, /// <summary> /// Invalid argument, or invalid configuration /// </summary> Local_InvalidArg = -186, /// <summary> /// Operation timed out /// </summary> Local_TimedOut = -185, /// <summary> /// Queue is full /// </summary> Local_QueueFull = -184, /// <summary> /// ISR count &lt; required.acks /// </summary> Local_IsrInsuff = -183, /// <summary> /// Broker node update /// </summary> Local_NodeUpdate = -182, /// <summary> /// SSL error /// </summary> Local_Ssl = -181, /// <summary> /// Waiting for coordinator to become available. /// </summary> Local_WaitCoord = -180, /// <summary> /// Unknown client group /// </summary> Local_UnknownGroup = -179, /// <summary> /// Operation in progress /// </summary> Local_InProgress = -178, /// <summary> /// Previous operation in progress, wait for it to finish. /// </summary> Local_PrevInProgress = -177, /// <summary> /// This operation would interfere with an existing subscription /// </summary> Local_ExistingSubscription = -176, /// <summary> /// Assigned partitions (rebalance_cb) /// </summary> Local_AssignPartitions= -175, /// <summary> /// Revoked partitions (rebalance_cb) /// </summary> Local_RevokePartitions = -174, /// <summary> /// Conflicting use /// </summary> Local_Conflict = -173, /// <summary> /// Wrong state /// </summary> Local_State = -172, /// <summary> /// Unknown protocol /// </summary> Local_UnknownProtocol = -171, /// <summary> /// Not implemented /// </summary> Local_NotImplemented = -170, /// <summary> /// Authentication failure /// </summary> Local_Authentication = -169, /// <summary> /// No stored offset /// </summary> Local_NoOffset = -168, /// <summary> /// Outdated /// </summary> Local_Outdated = -167, /// <summary> /// Timed out in queue /// </summary> Local_TimedOutQueue = -166, /// <summary> /// Feature not supported by broker /// </summary> Local_UnsupportedFeature = -165, /// <summary> /// Awaiting cache update /// </summary> Local_WaitCache = -164, /// <summary> /// Operation interrupted /// </summary> Local_Intr = -163, /// <summary> /// Key serialization error /// </summary> Local_KeySerialization = -162, /// <summary> /// Value serialization error /// </summary> Local_ValueSerialization = -161, /// <summary> /// Key deserialization error /// </summary> Local_KeyDeserialization = -160, /// <summary> /// Value deserialization error /// </summary> Local_ValueDeserialization = -159, /// <summary> /// Unknown broker error /// </summary> Unknown = -1, /// <summary> /// Success /// </summary> NoError = 0, /// <summary> /// Offset out of range /// </summary> OffsetOutOfRange = 1, /// <summary> /// Invalid message /// </summary> InvalidMsg = 2, /// <summary> /// Unknown topic or partition /// </summary> UnknownTopicOrPart = 3, /// <summary> /// Invalid message size /// </summary> InvalidMsgSize = 4, /// <summary> /// Leader not available /// </summary> LeaderNotAvailable = 5, /// <summary> /// Not leader for partition /// </summary> NotLeaderForPartition = 6, /// <summary> /// Request timed out /// </summary> RequestTimedOut = 7, /// <summary> /// Broker not available /// </summary> BrokerNotAvailable = 8, /// <summary> /// Replica not available /// </summary> ReplicaNotAvailable = 9, /// <summary> /// Message size too large /// </summary> MsgSizeTooLarge = 10, /// <summary> /// StaleControllerEpochCode /// </summary> StaleCtrlEpoch = 11, /// <summary> /// Offset metadata string too large /// </summary> OffsetMetadataTooLarge = 12, /// <summary> /// Broker disconnected before response received /// </summary> NetworkException = 13, /// <summary> /// Group coordinator load in progress /// </summary> GroupLoadInProress = 14, /// <summary> /// Group coordinator not available /// </summary> GroupCoordinatorNotAvailable = 15, /// <summary> /// Not coordinator for group /// </summary> NotCoordinatorForGroup = 16, /// <summary> /// Invalid topic /// </summary> TopicException = 17, /// <summary> /// Message batch larger than configured server segment size /// </summary> RecordListTooLarge = 18, /// <summary> /// Not enough in-sync replicas /// </summary> NotEnoughReplicas = 19, /// <summary> /// Message(s) written to insufficient number of in-sync replicas /// </summary> NotEnoughReplicasAfterAppend = 20, /// <summary> /// Invalid required acks value /// </summary> InvalidRequiredAcks = 21, /// <summary> /// Specified group generation id is not valid /// </summary> IllegalGeneration = 22, /// <summary> /// Inconsistent group protocol /// </summary> InconsistentGroupProtocol = 23, /// <summary> /// Invalid group.id /// </summary> InvalidGroupId = 24, /// <summary> /// Unknown member /// </summary> UnknownMemberId = 25, /// <summary> /// Invalid session timeout /// </summary> InvalidSessionTimeout = 26, /// <summary> /// Group rebalance in progress /// </summary> RebalanceInProgress = 27, /// <summary> /// Commit offset data size is not valid /// </summary> InvalidCommitOffsetSize = 28, /// <summary> /// Topic authorization failed /// </summary> TopicAuthorizationFailed = 29, /// <summary> /// Group authorization failed /// </summary> GroupAuthorizationFailed = 30, /// <summary> /// Cluster authorization failed /// </summary> ClusterAuthorizationFailed = 31, /// <summary> /// Invalid timestamp /// </summary> InvalidTimestamp = 32, /// <summary> /// Unsupported SASL mechanism /// </summary> UnsupportedSaslMechanism = 33, /// <summary> /// Illegal SASL state /// </summary> IllegalSaslState = 34, /// <summary> /// Unuspported version /// </summary> UnsupportedVersion = 35 }; /// <summary> /// Provides extension methods on the ErrorCode enumeration. /// </summary> public static class ErrorCodeExtensions { /// <summary> /// Returns the static error string associated with /// the particular ErrorCode value. /// </summary> public static string GetReason(this ErrorCode code) { return Internal.Util.Marshal.PtrToStringUTF8(Impl.LibRdKafka.err2str(code)); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for NetworkSecurityGroupsOperations. /// </summary> public static partial class NetworkSecurityGroupsOperationsExtensions { /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> public static void Delete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName) { operations.DeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> public static NetworkSecurityGroup Get(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string)) { return operations.GetAsync(resourceGroupName, networkSecurityGroupName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> GetAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> public static NetworkSecurityGroup CreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> CreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network security groups in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NetworkSecurityGroup> ListAll(this INetworkSecurityGroupsOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all network security groups in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkSecurityGroup>> ListAllAsync(this INetworkSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network security groups in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<NetworkSecurityGroup> List(this INetworkSecurityGroupsOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets all network security groups in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkSecurityGroup>> ListAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> public static void BeginDelete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName) { operations.BeginDeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified network security group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> public static NetworkSecurityGroup BeginCreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a network security group in the specified resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update network security group /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> BeginCreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network security groups in a subscription. /// </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<NetworkSecurityGroup> ListAllNext(this INetworkSecurityGroupsOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all network security groups in a subscription. /// </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<NetworkSecurityGroup>> ListAllNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all network security groups in a resource group. /// </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<NetworkSecurityGroup> ListNext(this INetworkSecurityGroupsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all network security groups in a resource group. /// </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<NetworkSecurityGroup>> ListNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.Network; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the client /// root certificates for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for /// more information) /// </summary> internal partial class ClientRootCertificateOperations : IServiceOperations<NetworkManagementClient>, IClientRootCertificateOperations { /// <summary> /// Initializes a new instance of the ClientRootCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ClientRootCertificateOperations(NetworkManagementClient client) { this._client = client; } private NetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient. /// </summary> public NetworkManagementClient Client { get { return this._client; } } /// <summary> /// The Upload Client Root Certificate operation is used to upload a /// new client root certificate to Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205129.aspx /// for more information) /// </summary> /// <param name='networkName'> /// Required. The name of the virtual network for this gateway. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Upload Client Root Certificate /// Virtual Network Gateway operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<GatewayOperationResponse> CreateAsync(string networkName, ClientRootCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (networkName == null) { throw new ArgumentNullException("networkName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Certificate == null) { throw new ArgumentNullException("parameters.Certificate"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("networkName", networkName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/"; url = url + Uri.EscapeDataString(networkName); url = url + "/gateway/clientrootcertificates"; 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Certificate; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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.Accepted) { 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 GatewayOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GatewayOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } } 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> /// The Delete Client Root Certificate operation deletes a previously /// uploaded client root certificate from Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205128.aspx /// for more information) /// </summary> /// <param name='networkName'> /// Required. The name of the virtual network for this gateway. /// </param> /// <param name='certificateThumbprint'> /// Required. The X509 certificate thumbprint. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<GatewayOperationResponse> DeleteAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken) { // Validate if (networkName == null) { throw new ArgumentNullException("networkName"); } if (certificateThumbprint == null) { throw new ArgumentNullException("certificateThumbprint"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("networkName", networkName); tracingParameters.Add("certificateThumbprint", certificateThumbprint); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/"; url = url + Uri.EscapeDataString(networkName); url = url + "/gateway/clientrootcertificates/"; url = url + Uri.EscapeDataString(certificateThumbprint); 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 httpRequest.Headers.Add("x-ms-version", "2016-03-01"); // 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 GatewayOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GatewayOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } } 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> /// The Get Client Root Certificate operation returns the public /// portion of a previously uploaded client root certificate in a /// base-64-encoded format from Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205127.aspx /// for more information) /// </summary> /// <param name='networkName'> /// Required. The name of the virtual network for this gateway. /// </param> /// <param name='certificateThumbprint'> /// Required. The X509 certificate thumbprint. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response to the Get Client Root Certificate operation. /// </returns> public async Task<ClientRootCertificateGetResponse> GetAsync(string networkName, string certificateThumbprint, CancellationToken cancellationToken) { // Validate if (networkName == null) { throw new ArgumentNullException("networkName"); } if (certificateThumbprint == null) { throw new ArgumentNullException("certificateThumbprint"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("networkName", networkName); tracingParameters.Add("certificateThumbprint", certificateThumbprint); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/"; url = url + Uri.EscapeDataString(networkName); url = url + "/gateway/clientrootcertificates/"; url = url + Uri.EscapeDataString(certificateThumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-03-01"); // 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 ClientRootCertificateGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ClientRootCertificateGetResponse(); result.Certificate = responseContent; } 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> /// The List Client Root Certificates operation returns a list of all /// the client root certificates that are associated with the /// specified virtual network in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx /// for more information) /// </summary> /// <param name='networkName'> /// Required. The name of the virtual network for this gateway. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response for the List Client Root Certificates operation. /// </returns> public async Task<ClientRootCertificateListResponse> ListAsync(string networkName, CancellationToken cancellationToken) { // Validate if (networkName == null) { throw new ArgumentNullException("networkName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("networkName", networkName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/"; url = url + Uri.EscapeDataString(networkName); url = url + "/gateway/clientrootcertificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-03-01"); // 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 ClientRootCertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ClientRootCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement clientRootCertificatesSequenceElement = responseDoc.Element(XName.Get("ClientRootCertificates", "http://schemas.microsoft.com/windowsazure")); if (clientRootCertificatesSequenceElement != null) { foreach (XElement clientRootCertificatesElement in clientRootCertificatesSequenceElement.Elements(XName.Get("ClientRootCertificate", "http://schemas.microsoft.com/windowsazure"))) { ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate(); result.ClientRootCertificates.Add(clientRootCertificateInstance); XElement expirationTimeElement = clientRootCertificatesElement.Element(XName.Get("ExpirationTime", "http://schemas.microsoft.com/windowsazure")); if (expirationTimeElement != null) { DateTime expirationTimeInstance = DateTime.Parse(expirationTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); clientRootCertificateInstance.ExpirationTime = expirationTimeInstance; } XElement subjectElement = clientRootCertificatesElement.Element(XName.Get("Subject", "http://schemas.microsoft.com/windowsazure")); if (subjectElement != null) { string subjectInstance = subjectElement.Value; clientRootCertificateInstance.Subject = subjectInstance; } XElement thumbprintElement = clientRootCertificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure")); if (thumbprintElement != null) { string thumbprintInstance = thumbprintElement.Value; clientRootCertificateInstance.Thumbprint = thumbprintInstance; } } } } 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(); } } } } }
using UnityEditor; using UnityEngine; using Noesis; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Reflection; public class NoesisSettings : EditorWindow { public static string[] ActivePlatforms { get { var platforms = new List<string>(); int mask = ReadSettings(); if ((mask & DX9Platform) > 0) { platforms.Add("dx9"); } if ((mask & DX11Platform) > 0) { platforms.Add("dx11"); } if ((mask & GLPlatform) > 0) { platforms.Add("gl"); } if ((mask & IOSPlatform) > 0) { platforms.Add("ios"); } if ((mask & AndroidPlatform) > 0) { platforms.Add("android"); } return platforms.ToArray(); } } private static int GetNumAssets() { int numAssets = BuildToolKernel.ReadAssets().Count; if (numAssets == 0) { // approximate with number of xamls files numAssets = Directory.GetFiles( UnityEngine.Application.dataPath, "*.xaml", SearchOption.AllDirectories).Length; } return numAssets; } public static void RebuildActivePlatforms(string progressTitle) { try { string[] activePlatforms = ActivePlatforms; string platform = ""; float platformProgress = 0.0f; float platformDelta = 1.0f / (GetNumAssets() * (activePlatforms.Length + 1)); float progress = 0.0f; float deltaProgress = 1.0f / (activePlatforms.Length + 1); EditorUtility.DisplayProgressBar(progressTitle, "Cleaning...", 0.0f); BuildToolKernel.BuildBegin(); BuildToolKernel.Clean(); Action<String> action = s => { EditorUtility.DisplayProgressBar(progressTitle, "[" + platform + "] " + s + "...", progress + platformProgress); platformProgress = Math.Min(platformProgress + platformDelta, deltaProgress); }; BuildToolKernel.BuildEvent += action; foreach (string activePlatform in activePlatforms) { platformProgress = 0.0f; progress += deltaProgress; platform = activePlatform; Build(platform); } BuildToolKernel.BuildEvent -= action; EditorUtility.DisplayProgressBar(progressTitle, "Done.", 1.0f); } finally { EditorUtility.ClearProgressBar(); } } public static void ClearLog() { Assembly assembly = Assembly.GetAssembly(typeof(SceneView)); System.Type type = assembly.GetType("UnityEditorInternal.LogEntries"); MethodInfo method = type.GetMethod("Clear"); method.Invoke(new object(), null); } private static int DX9Platform = 1; private static int GLPlatform = 2; private static int IOSPlatform = 4; private static int AndroidPlatform = 8; private static int DX11Platform = 16; private static string DX9Field = "NoesisDX9"; private static string DX11Field = "NoesisDX11"; private static string GLField = "NoesisGL"; private static string AndroidField = "NoesisAndroid"; private static string IOSField = "NoesisIOS"; private static int ReadSettings() { int activePlatforms = 0; bool isWindows = UnityEngine.Application.platform == UnityEngine.RuntimePlatform.WindowsEditor; bool isOSX = !isWindows; if (PlayerPrefs.GetInt(DX9Field, 0) > 0) { activePlatforms |= DX9Platform; } if (PlayerPrefs.GetInt(DX11Field, isWindows ? 1 : 0) > 0) { activePlatforms |= DX11Platform; } if (PlayerPrefs.GetInt(GLField, isOSX ? 1 : 0) > 0) { activePlatforms |= GLPlatform; } if (PlayerPrefs.GetInt(IOSField, 0) > 0) { activePlatforms |= IOSPlatform; } if (PlayerPrefs.GetInt(AndroidField, 0) > 0) { activePlatforms |= AndroidPlatform; } return activePlatforms; } private static void WriteSettings(int activePlatforms) { PlayerPrefs.SetInt(DX9Field, (activePlatforms & DX9Platform) > 0 ? 1 : 0); PlayerPrefs.SetInt(DX11Field, (activePlatforms & DX11Platform) > 0 ? 1 : 0); PlayerPrefs.SetInt(GLField, (activePlatforms & GLPlatform) > 0 ? 1 : 0); PlayerPrefs.SetInt(IOSField, (activePlatforms & IOSPlatform) > 0 ? 1 : 0); PlayerPrefs.SetInt(AndroidField, (activePlatforms & AndroidPlatform) > 0 ? 1 : 0); PlayerPrefs.Save(); using (StreamWriter file = new StreamWriter(UnityEngine.Application.dataPath + "/Editor/NoesisGUI/Platform_.cs")) { file.WriteLine("// This file is automatically generated"); file.WriteLine(); if ((activePlatforms & DX9Platform) == 0 && (activePlatforms & DX11Platform) == 0) { file.WriteLine("#if UNITY_STANDALONE_WIN"); file.WriteLine("# error DirectX is not active! Please, activate it in Tools -> NoesisGUI -> Settings"); file.WriteLine("#endif"); } if ((activePlatforms & GLPlatform) == 0) { file.WriteLine("#if UNITY_STANDALONE_OSX"); file.WriteLine("# error GL is not active! Please, activate it in Tools -> NoesisGUI -> Settings"); file.WriteLine("#endif"); } if ((activePlatforms & IOSPlatform) == 0) { file.WriteLine("#if UNITY_IPHONE"); file.WriteLine("# error iOS is not active! Please, activate it in Tools -> NoesisGUI -> Settings"); file.WriteLine("#endif"); } if ((activePlatforms & AndroidPlatform) == 0) { file.WriteLine("#if UNITY_ANDROID"); file.WriteLine("# error Android is not active! Please, activate it in Tools -> NoesisGUI -> Settings"); file.WriteLine("#endif"); } } AssetDatabase.ImportAsset("Assets/Editor/NoesisGUI/Platform_.cs"); } private int activePlatforms_; [UnityEditor.MenuItem("Tools/NoesisGUI/About NoesisGUI...", false, 30000)] static void OpenAbout() { GetWindow(typeof(NoesisAbout), true, "About NoesisGUI"); } [UnityEditor.MenuItem("Tools/NoesisGUI/Settings...", false, 30050)] static void OpenSettings() { GetWindow(typeof(NoesisSettings), false, "NoesisGUI"); } [UnityEditor.MenuItem("Tools/NoesisGUI/Welcome Screen...", false, 30100)] static void OpenWelcome() { GetWindow(typeof(NoesisWelcome), true, "Welcome to NoesisGUI!"); } [UnityEditor.MenuItem("Tools/NoesisGUI/Video Tutorials", false, 30102)] static void OpenVideoTutorial() { UnityEngine.Application.OpenURL("https://vimeo.com/groups/264371"); } [UnityEditor.MenuItem("Tools/NoesisGUI/Documentation", false, 30103)] static void OpenDocumentation() { string docPath = Application.dataPath + "/../NoesisDoc/index.html"; if (File.Exists(docPath)) { UnityEngine.Application.OpenURL("file://" + docPath); } else { UnityEngine.Application.OpenURL("http://www.noesisengine.com/docs"); } } [UnityEditor.MenuItem("Tools/NoesisGUI/Forums", false, 30104)] static void OpenForum() { UnityEngine.Application.OpenURL("http://forums.noesisengine.com/"); } [UnityEditor.MenuItem("Tools/NoesisGUI/Review...", false, 30105)] static void OpenReview() { EditorWindow.GetWindow(typeof(NoesisReview), true, "Support our development"); } [UnityEditor.MenuItem("Tools/NoesisGUI/Release Notes", false, 30150)] static public void OpenReleaseNotes() { string docPath = Application.dataPath + "/../NoesisDoc/Doc/Gui.Core.Changelog.html"; if (File.Exists(docPath)) { UnityEngine.Application.OpenURL("file://" + docPath); } else { UnityEngine.Application.OpenURL("http://www.noesisengine.com/docs/Gui.Core.Changelog.html"); } } [UnityEditor.MenuItem("Tools/NoesisGUI/Report a bug", false, 30151)] static void OpenReportBug() { UnityEngine.Application.OpenURL("http://bugs.noesisengine.com/"); } void Awake() { activePlatforms_ = ReadSettings(); } void OnGUI() { bool isCompiling = EditorApplication.isCompiling; GUI.enabled = !isCompiling; GUIStyle titleStyle = new GUIStyle(EditorStyles.whiteLabel); titleStyle.alignment = TextAnchor.MiddleCenter; titleStyle.fontStyle = UnityEngine.FontStyle.Bold; titleStyle.fontSize = 12; GUILayout.Label("NoesisGUI Settings", titleStyle); GUILayout.Label("Build Platforms", EditorStyles.boldLabel); int activePlatforms = 0; int numActivePlatforms = 0; GUILayout.BeginHorizontal(); bool isWindows = UnityEngine.Application.platform == UnityEngine.RuntimePlatform.WindowsEditor; if (!isWindows) { GUI.enabled = false; } if (GUILayout.Toggle((activePlatforms_ & DX9Platform) > 0, "DX9")) { activePlatforms |= DX9Platform; numActivePlatforms++; } if (GUILayout.Toggle((activePlatforms_ & DX11Platform) > 0, "DX11")) { activePlatforms |= DX11Platform; numActivePlatforms++; } GUI.enabled = !isCompiling; if (GUILayout.Toggle((activePlatforms_ & GLPlatform) > 0, "GL")) { activePlatforms |= GLPlatform; numActivePlatforms++; } if (GUILayout.Toggle((activePlatforms_ & IOSPlatform) > 0, "iOS")) { activePlatforms |= IOSPlatform; numActivePlatforms++; } if (GUILayout.Toggle((activePlatforms_ & AndroidPlatform) > 0, "Android")) { activePlatforms |= AndroidPlatform; numActivePlatforms++; } GUILayout.EndHorizontal(); int delta = activePlatforms ^ activePlatforms_; if (delta > 0) { activePlatforms_ = activePlatforms; WriteSettings(activePlatforms_); } GUILayout.Space(15.0f); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(isCompiling ? "Unity is compiling scripts..." : "Rebuild", GUILayout.MinWidth(100))) { RebuildActivePlatforms("Building Resources"); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUI.enabled = true; } private static void Build(string platform) { using (BuildToolKernel builder = new BuildToolKernel(platform)) { builder.BuildAll(); } } }
/* * 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.Linq; using System.Threading; using System.Threading.Tasks; using NodaTime; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.DataFeeds.Enumerators; using QuantConnect.Logging; using QuantConnect.Securities; using QuantConnect.Securities.Equity; using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; using QuantConnect.Util; namespace QuantConnect.Tests.Engine.DataFeeds { [TestFixture, Parallelizable(ParallelScope.All)] public class SubscriptionCollectionTests { [Test] public void EnumerationWhileUpdatingDoesNotThrow() { var cts = new CancellationTokenSource(); var subscriptions = new SubscriptionCollection(); var start = DateTime.UtcNow; var end = start.AddSeconds(10); var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, DateTimeZone.Utc, DateTimeZone.Utc, true, false, false); var security = new Equity( Symbols.SPY, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); var timeZoneOffsetProvider = new TimeZoneOffsetProvider(DateTimeZone.Utc, start, end); var enumerator = new EnqueueableEnumerator<BaseData>(); var subscriptionDataEnumerator = new SubscriptionDataEnumerator(config, security.Exchange.Hours, timeZoneOffsetProvider, enumerator); var subscriptionRequest = new SubscriptionRequest(false, null, security, config, start, end); var subscription = new Subscription(subscriptionRequest, subscriptionDataEnumerator, timeZoneOffsetProvider); var addTask = Task.Factory.StartNew(() => { Log.Trace("Add task started"); while (DateTime.UtcNow < end) { if (!subscriptions.Contains(config)) { subscriptions.TryAdd(subscription); } Thread.Sleep(1); } Log.Trace("Add task ended"); }, cts.Token); var removeTask = Task.Factory.StartNew(() => { Log.Trace("Remove task started"); while (DateTime.UtcNow < end) { Subscription removed; subscriptions.TryRemove(config, out removed); Thread.Sleep(1); } Log.Trace("Remove task ended"); }, cts.Token); var readTask = Task.Factory.StartNew(() => { Log.Trace("Read task started"); while (DateTime.UtcNow < end) { foreach (var sub in subscriptions) { } Thread.Sleep(1); } Log.Trace("Read task ended"); }, cts.Token); Task.WaitAll(addTask, removeTask, readTask); subscription.Dispose(); } [Test] public void DefaultFillForwardResolution() { var subscriptionColletion = new SubscriptionCollection(); var defaultFillForwardResolutio = subscriptionColletion.UpdateAndGetFillForwardResolution(); Assert.AreEqual(defaultFillForwardResolutio.Value, new TimeSpan(0, 1, 0)); } [Test] public void UpdatesFillForwardResolutionOverridesDefaultWhenNotAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Daily); var fillForwardResolutio = subscriptionColletion.UpdateAndGetFillForwardResolution(subscription.Configuration); Assert.AreEqual(fillForwardResolutio.Value, new TimeSpan(1, 0, 0, 0)); subscription.Dispose(); } [Test] public void UpdatesFillForwardResolutionSuccessfullyWhenNotAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var fillForwardResolutio = subscriptionColletion.UpdateAndGetFillForwardResolution(subscription.Configuration); Assert.AreEqual(fillForwardResolutio.Value, new TimeSpan(0, 0, 1)); subscription.Dispose(); } [Test] public void UpdatesFillForwardResolutionSuccessfullyWhenAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); } [Test] public void UpdatesFillForwardResolutionSuccessfullyOverridesDefaultWhenAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Daily); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(1, 0, 0, 0)); subscription.Dispose(); } [Test] public void DoesNotUpdateFillForwardResolutionWhenAddingBiggerResolution() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var subscription2 = CreateSubscription(Resolution.Minute); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscription.Dispose(); subscription2.Dispose(); } [Test] public void UpdatesFillForwardResolutionWhenRemoving() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var subscription2 = CreateSubscription(Resolution.Daily); subscriptionColletion.TryAdd(subscription); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(1, 0, 0, 0)); subscriptionColletion.TryRemove(subscription2.Configuration, out subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscription.Dispose(); subscription2.Dispose(); } [Test] public void FillForwardResolutionIgnoresTick() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Tick); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscription.Dispose(); } [Test] public void FillForwardResolutionIgnoresInternalFeed() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, "AAPL", true); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscription.Dispose(); } [Test] public void DoesNotUpdateFillForwardResolutionWhenRemovingDuplicateResolution() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 0, 1)); subscriptionColletion.TryRemove(subscription2.Configuration, out subscription2); Assert.AreEqual(subscriptionColletion.UpdateAndGetFillForwardResolution().Value, new TimeSpan(0, 1, 0)); subscription.Dispose(); subscription2.Dispose(); } [Test] public void SubscriptionsAreSortedWhenAdding() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, Futures.Metals.Gold, false, SecurityType.Future); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); var subscription3 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option); var subscription4 = CreateSubscription(Resolution.Second, "EURGBP"); var subscription5 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option, TickType.OpenInterest); var subscription6 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option, TickType.Quote); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription }); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription2, subscription }); subscriptionColletion.TryAdd(subscription3); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription2, subscription3, subscription }); subscriptionColletion.TryAdd(subscription4); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription }); subscriptionColletion.TryAdd(subscription5); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription5, subscription }); subscriptionColletion.TryAdd(subscription6); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription6, subscription5, subscription }); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Equity, SecurityType.Option, SecurityType.Option, SecurityType.Option, SecurityType.Future }); subscription.Dispose(); subscription2.Dispose(); subscription3.Dispose(); subscription4.Dispose(); subscription5.Dispose(); subscription6.Dispose(); } [Test] public void SubscriptionsAreSortedWhenAdding2() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, Futures.Metals.Gold, false, SecurityType.Future); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); var subscription3 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option); var subscription4 = CreateSubscription(Resolution.Second, "EURGBP"); subscriptionColletion.TryAdd(subscription); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription }); subscriptionColletion.TryAdd(subscription2); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription2, subscription }); subscriptionColletion.TryAdd(subscription3); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription2, subscription3, subscription }); subscriptionColletion.TryAdd(subscription4); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription }); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Equity, SecurityType.Option, SecurityType.Future }); subscription.Dispose(); subscription2.Dispose(); subscription3.Dispose(); subscription4.Dispose(); } [Test] public void SubscriptionsAreSortedWhenRemoving() { var subscriptionColletion = new SubscriptionCollection(); var subscription = CreateSubscription(Resolution.Second, Futures.Metals.Gold, false, SecurityType.Future); var subscription2 = CreateSubscription(Resolution.Second, "SPY"); var subscription3 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option); var subscription4 = CreateSubscription(Resolution.Second, "EURGBP"); var subscription5 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option, TickType.OpenInterest); var subscription6 = CreateSubscription(Resolution.Second, "AAPL", false, SecurityType.Option, TickType.Quote); subscriptionColletion.TryAdd(subscription); subscriptionColletion.TryAdd(subscription2); subscriptionColletion.TryAdd(subscription3); subscriptionColletion.TryAdd(subscription4); subscriptionColletion.TryAdd(subscription5); subscriptionColletion.TryAdd(subscription6); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription2, subscription3, subscription6, subscription5, subscription }); subscriptionColletion.TryRemove(subscription2.Configuration, out subscription2); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option, SecurityType.Option, SecurityType.Option, SecurityType.Future }); subscriptionColletion.TryRemove(subscription3.Configuration, out subscription3); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option, SecurityType.Option, SecurityType.Future }); subscriptionColletion.TryRemove(subscription.Configuration, out subscription); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option, SecurityType.Option }); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription6, subscription5 }); subscriptionColletion.TryRemove(subscription6.Configuration, out subscription6); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] { SecurityType.Equity, SecurityType.Option }); Assert.AreEqual(subscriptionColletion.ToList(), new[] { subscription4, subscription5 }); subscriptionColletion.TryRemove(subscription5.Configuration, out subscription5); Assert.AreEqual(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList(), new[] {SecurityType.Equity}); subscriptionColletion.TryRemove(subscription4.Configuration, out subscription4); Assert.IsTrue(subscriptionColletion.Select(x => x.Configuration.SecurityType).ToList().IsNullOrEmpty()); subscription.Dispose(); subscription2.Dispose(); subscription3.Dispose(); subscription4.Dispose(); subscription5.Dispose(); subscription6.Dispose(); } private Subscription CreateSubscription(Resolution resolution, string symbol = "AAPL", bool isInternalFeed = false, SecurityType type = SecurityType.Equity, TickType tickType = TickType.Trade) { var start = DateTime.UtcNow; var end = start.AddSeconds(10); Security security; Symbol _symbol; if (type == SecurityType.Equity) { _symbol = new Symbol(SecurityIdentifier.GenerateEquity(DateTime.Now, symbol, Market.USA), symbol); security = new Equity( _symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); } else if (type == SecurityType.Option) { _symbol = Symbol.CreateOption( new Symbol(SecurityIdentifier.GenerateEquity(DateTime.Now, symbol, Market.USA), symbol), Market.USA, OptionStyle.American, OptionRight.Call, 0m, DateTime.Now ); security = new Option( _symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache(), null ); } else if (type == SecurityType.Future) { _symbol = new Symbol(SecurityIdentifier.GenerateFuture(DateTime.Now, symbol, Market.COMEX), symbol); security = new Future( _symbol, SecurityExchangeHours.AlwaysOpen(DateTimeZone.Utc), new Cash(Currencies.USD, 0, 1), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); } else { throw new Exception("SecurityType not implemented"); } var config = new SubscriptionDataConfig(typeof(TradeBar), _symbol, resolution, DateTimeZone.Utc, DateTimeZone.Utc, true, false, isInternalFeed, false, tickType); var timeZoneOffsetProvider = new TimeZoneOffsetProvider(DateTimeZone.Utc, start, end); var enumerator = new EnqueueableEnumerator<BaseData>(); var subscriptionDataEnumerator = new SubscriptionDataEnumerator(config, security.Exchange.Hours, timeZoneOffsetProvider, enumerator); var subscriptionRequest = new SubscriptionRequest(false, null, security, config, start, end); return new Subscription(subscriptionRequest, subscriptionDataEnumerator, timeZoneOffsetProvider); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Collections.Generic; using System.Text; namespace WebsitePanel.Providers.Mail { public class AmsMailbox { private TreeNode userConfig; private Tree accountConfig; private Tree deliveryConfig; private string mailboxName; public TreeNode UserConfig { get { return userConfig; } } public Tree AccountConfig { get { return accountConfig; } /*set { accountConfig = value; }*/ } public Tree DeliveryConfig { get { return deliveryConfig; } /*set { deliveryConfig = value; }*/ } public AmsMailbox(string mailboxName) { this.mailboxName = mailboxName; this.accountConfig = new Tree(); this.deliveryConfig = new Tree(); this.userConfig = new TreeNode(); } public bool Load(Tree userConfig) { string account = GetAccountName(mailboxName); string domain = GetDomainName(mailboxName); foreach (TreeNode node in userConfig.ChildNodes) { string amsUser = node["user"]; string amsDomain = node["domain"]; if (string.Compare(amsUser, account, true) == 0 && string.Compare(amsDomain, domain, true) == 0) { this.userConfig = node; return true; } } return false; } public bool Load(TreeNode configNode) { string account = GetAccountName(mailboxName); string domain = GetDomainName(mailboxName); string amsUser = configNode["user"]; string amsDomain = configNode["domain"]; if (string.Compare(amsUser, account, true) == 0 && string.Compare(amsDomain, domain, true) == 0) { this.userConfig = configNode; return true; } return false; } public void LoadAccountConfig() { this.accountConfig = AMSHelper.GetAccountConfig(mailboxName); this.deliveryConfig = AMSHelper.GetAccountDelivery(mailboxName); } public bool Save(Tree config) { if (!config.ChildNodes.Contains(userConfig)) { userConfig["dir"] = Path.Combine(AMSHelper.AMSLocation, string.Format(@"{0}\{1}\", GetDomainName(mailboxName), GetAccountName(mailboxName))); config.ChildNodes.Add(userConfig); } return AMSHelper.SetUsersConfig(config) && AMSHelper.SetAccountConfig(accountConfig, mailboxName) && AMSHelper.SetAccountDelivery(deliveryConfig, mailboxName); } public bool Delete(Tree config) { if (config.ChildNodes.Contains(userConfig)) config.ChildNodes.Remove(userConfig); return AMSHelper.RemoveAccount(mailboxName) && AMSHelper.SetUsersConfig(config); } public MailAccount ToMailAccount() { MailAccount account = new MailAccount(); account.Name = string.Concat(userConfig["user"], "@", userConfig["domain"]); account.Enabled = userConfig["enabled"] == "1" ? true : false; account.Password = userConfig["pass"]; // read forwardings TreeNode redirection = deliveryConfig.ChildNodes["redirection"]; if (redirection != null) { TreeNode redirections = redirection.ChildNodes["redirections"]; if (redirections != null) { List<string> list = new List<string>(); foreach (TreeNode node in redirections.ChildNodes) list.Add(node.NodeValue); account.ForwardingAddresses = list.ToArray(); } } // read autoresponder TreeNode autoresponses = deliveryConfig.ChildNodes["autoresponses"]; if (autoresponses != null) { account.ResponderEnabled = autoresponses["enabled"] == "1" ? true : false; account.ResponderSubject = autoresponses["subject"]; account.ResponderMessage = autoresponses["body"]; if (autoresponses["usereplyto"] == "1") account.ReplyTo = autoresponses["replyto"]; } return account; } public MailGroup ToMailGroup() { MailGroup group = new MailGroup(); group.Name = mailboxName; group.Enabled = userConfig["enabled"] == "1" ? true : false; TreeNode redirection = deliveryConfig.ChildNodes["redirection"]; if (redirection != null) { TreeNode redirections = redirection.ChildNodes["redirections"]; if (redirections != null) { List<string> list = new List<string>(); foreach (TreeNode node in redirections.ChildNodes) list.Add(node.NodeValue); group.Members = list.ToArray(); } } return group; } public void Read(MailAccount mailbox) { userConfig["domain"] = GetDomainName(mailbox.Name); userConfig["enabled"] = mailbox.Enabled ? "1" : "0"; userConfig["user"] = GetAccountName(mailbox.Name); userConfig["pass"] = mailbox.Password; // forwardings if (mailbox.ForwardingAddresses != null) AddForwardingInfo(mailbox.ForwardingAddresses, mailbox.DeleteOnForward); AddAutoResponderInfo(mailbox); } private void AddAutoResponderInfo(MailAccount mailbox) { TreeNode autoresponses = deliveryConfig.ChildNodes["autoresponses"]; if (autoresponses == null) { autoresponses = new TreeNode(); autoresponses.NodeName = "autoresponses"; deliveryConfig.ChildNodes.Add(autoresponses); } autoresponses["enabled"] = mailbox.ResponderEnabled ? "1" : "0"; if (mailbox.ResponderEnabled) { autoresponses["subject"] = mailbox.ResponderSubject; autoresponses["body"] = mailbox.ResponderMessage; if (!string.IsNullOrEmpty(mailbox.ReplyTo)) { autoresponses["usereplyto"] = "1"; autoresponses["replyto"] = mailbox.ReplyTo; } else { autoresponses["usereplyto"] = "0"; autoresponses["replyto"] = string.Empty; } } else { autoresponses["subject"] = string.Empty; autoresponses["body"] = string.Empty; } } private void AddForwardingInfo(string[] forwardings, bool removeCopies) { TreeNode redirection = deliveryConfig.ChildNodes["redirection"]; if (redirection == null) { redirection = new TreeNode(); redirection.NodeName = "redirection"; deliveryConfig.ChildNodes.Add(redirection); } if (forwardings.Length > 0) { redirection["enabled"] = "1"; redirection["stilldeliver"] = removeCopies ? "0" : "1"; TreeNode redirections = redirection.ChildNodes["redirections"]; if (redirections == null) { redirections = new TreeNode(redirection); redirections.NodeName = "redirections"; redirection.ChildNodes.Add(redirections); } redirections.ChildNodes.Clear(); foreach (string forwarding in forwardings) { TreeNode node = new TreeNode(redirections); node.NodeValue = forwarding; redirections.ChildNodes.Add(node); } } } public void Read(MailGroup group) { userConfig["domain"] = GetDomainName(group.Name); userConfig["enabled"] = group.Enabled ? "1" : "0"; userConfig["user"] = GetAccountName(group.Name); AddForwardingInfo(group.Members, true); } public bool IsMailGroup() { TreeNode redirection = deliveryConfig.ChildNodes["redirection"]; if (redirection != null) if (redirection["stilldeliver"] == "0") return true; return false; } public static AmsMailbox[] GetMailboxes(Tree config, string domainName) { List<AmsMailbox> list = new List<AmsMailbox>(); foreach (TreeNode node in config.ChildNodes) { string account = node["user"]; string amsDomain = node["domain"]; if (string.Compare(amsDomain, domainName, true) == 0) { AmsMailbox mb = new AmsMailbox(string.Concat(account, "@", amsDomain)); mb.Load(node); mb.LoadAccountConfig(); list.Add(mb); } } return list.ToArray(); } public static AmsMailbox[] GetMailGroups(Tree config, string domainName) { List<AmsMailbox> groups = new List<AmsMailbox>(); foreach (TreeNode node in config.ChildNodes) { string account = node["user"]; string amsDomain = node["domain"]; if (string.Compare(amsDomain, domainName, true) == 0) { AmsMailbox mb = new AmsMailbox(string.Concat(account, "@", amsDomain)); mb.Load(node); mb.LoadAccountConfig(); if (mb.IsMailGroup()) groups.Add(mb); } } return groups.ToArray(); } public static string GetAccountName(string email) { if (email.IndexOf("@") == -1) return email; return email.Substring(0, email.IndexOf("@")); } public static string GetDomainName(string email) { return email.Substring(email.IndexOf("@") + 1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security; using System.Security.AccessControl; /* Note on transaction support: Eventually we will want to add support for NT's transactions to our RegistryKey API's. When we do this, here's the list of API's we need to make transaction-aware: RegCreateKeyEx RegDeleteKey RegDeleteValue RegEnumKeyEx RegEnumValue RegOpenKeyEx RegQueryInfoKey RegQueryValueEx RegSetValueEx We can ignore RegConnectRegistry (remote registry access doesn't yet have transaction support) and RegFlushKey. RegCloseKey doesn't require any additional work. */ /* Note on ACL support: The key thing to note about ACL's is you set them on a kernel object like a registry key, then the ACL only gets checked when you construct handles to them. So if you set an ACL to deny read access to yourself, you'll still be able to read with that handle, but not with new handles. Another peculiarity is a Terminal Server app compatibility hack. The OS will second guess your attempt to open a handle sometimes. If a certain combination of Terminal Server app compat registry keys are set, then the OS will try to reopen your handle with lesser permissions if you couldn't open it in the specified mode. So on some machines, we will see handles that may not be able to read or write to a registry key. It's very strange. But the real test of these handles is attempting to read or set a value in an affected registry key. For reference, at least two registry keys must be set to particular values for this behavior: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1. HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1 There might possibly be an interaction with yet a third registry key as well. */ namespace Microsoft.Win32 { public sealed partial class RegistryKey : MarshalByRefObject, IDisposable { private void ClosePerfDataKey() { // System keys should never be closed. However, we want to call RegCloseKey // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources // (i.e. when disposing is true) so that we release the PERFLIB cache and cause it // to be refreshed (by re-reading the registry) when accessed subsequently. // This is the only way we can see the just installed perf counter. // NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race in closing // the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources // in this situation the down level OSes are not. We have a small window of race between // the dispose below and usage elsewhere (other threads). This is By Design. // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary. Interop.Advapi32.RegCloseKey(HKEY_PERFORMANCE_DATA); } private void FlushCore() { if (_hkey != null && IsDirty()) { Interop.Advapi32.RegFlushKey(_hkey); } } private unsafe RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); int disposition = 0; // By default, the new key will be writable. SafeRegistryHandle result = null; int ret = Interop.Advapi32.RegCreateKeyEx(_hkey, subkey, 0, null, (int)registryOptions /* specifies if the key is volatile */, GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree) | (int)_regView, ref secAttrs, out result, out disposition); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, _remoteKey, false, _regView); key._checkMode = permissionCheck; if (subkey.Length == 0) { key._keyName = _keyName; } else { key._keyName = _keyName + "\\" + subkey; } return key; } else if (ret != 0) // syscall failed, ret is an error code. { Win32Error(ret, _keyName + "\\" + subkey); // Access denied? } Debug.Fail("Unexpected code path in RegistryKey::CreateSubKey"); return null; } private void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey) { int ret = Interop.Advapi32.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0); if (ret != 0) { if (ret == Interop.Errors.ERROR_FILE_NOT_FOUND) { if (throwOnMissingSubKey) { throw new ArgumentException(SR.Arg_RegSubKeyAbsent); } } else { Win32Error(ret, null); } } } private void DeleteSubKeyTreeCore(string subkey) { int ret = Interop.Advapi32.RegDeleteKeyEx(_hkey, subkey, (int)_regView, 0); if (ret != 0) { Win32Error(ret, null); } } private void DeleteValueCore(string name, bool throwOnMissingValue) { int errorCode = Interop.Advapi32.RegDeleteValue(_hkey, name); // // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE // This still means the name doesn't exist. We need to be consistent with previous OS. // if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_FILENAME_EXCED_RANGE) { if (throwOnMissingValue) { throw new ArgumentException(SR.Arg_RegSubKeyValueAbsent); } else { // Otherwise, reset and just return giving no indication to the user. // (For compatibility) errorCode = 0; } } // We really should throw an exception here if errorCode was bad, // but we can't for compatibility reasons. Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode); } /// <summary> /// Retrieves a new RegistryKey that represents the requested key. Valid /// values are: /// HKEY_CLASSES_ROOT, /// HKEY_CURRENT_USER, /// HKEY_LOCAL_MACHINE, /// HKEY_USERS, /// HKEY_PERFORMANCE_DATA, /// HKEY_CURRENT_CONFIG. /// </summary> /// <param name="hKeyHive">HKEY_* to open.</param> /// <returns>The RegistryKey requested.</returns> private static RegistryKey OpenBaseKeyCore(RegistryHive hKeyHive, RegistryView view) { IntPtr hKey = (IntPtr)((int)hKeyHive); int index = ((int)hKey) & 0x0FFFFFFF; Debug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!"); Debug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!"); bool isPerf = hKey == HKEY_PERFORMANCE_DATA; // only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA. SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf); RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view); key._checkMode = RegistryKeyPermissionCheck.Default; key._keyName = s_hkeyNames[index]; return key; } private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view) { int index = (int)hKey & 0x0FFFFFFF; if (index < 0 || index >= s_hkeyNames.Length || ((int)hKey & 0xFFFFFFF0) != 0x80000000) { throw new ArgumentException(SR.Arg_RegKeyOutOfRange); } // connect to the specified remote registry SafeRegistryHandle foreignHKey = null; int ret = Interop.Advapi32.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), false), out foreignHKey); if (ret == Interop.Errors.ERROR_DLL_INIT_FAILED) { // return value indicates an error occurred throw new ArgumentException(SR.Arg_DllInitFailure); } if (ret != 0) { Win32ErrorStatic(ret, null); } if (foreignHKey.IsInvalid) { // return value indicates an error occurred throw new ArgumentException(SR.Format(SR.Arg_RegKeyNoRemoteConnect, machineName)); } RegistryKey key = new RegistryKey(foreignHKey, true, false, true, ((IntPtr)hKey) == HKEY_PERFORMANCE_DATA, view); key._checkMode = RegistryKeyPermissionCheck.Default; key._keyName = s_hkeyNames[index]; return key; } private RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights) { SafeRegistryHandle result = null; int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (rights | (int)_regView), out result); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, _remoteKey, false, _regView); key._keyName = _keyName + "\\" + name; key._checkMode = permissionCheck; return key; } if (ret == Interop.Errors.ERROR_ACCESS_DENIED || ret == Interop.Errors.ERROR_BAD_IMPERSONATION_LEVEL) { // We need to throw SecurityException here for compatibility reason, // although UnauthorizedAccessException will make more sense. throw new SecurityException(SR.Security_RegistryPermission); } // Return null if we didn't find the key. return null; } private RegistryKey InternalOpenSubKeyCore(string name, bool writable) { SafeRegistryHandle result = null; int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (GetRegistryKeyAccess(writable) | (int)_regView), out result); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, writable, false, _remoteKey, false, _regView); key._checkMode = GetSubKeyPermissionCheck(writable); key._keyName = _keyName + "\\" + name; return key; } if (ret == Interop.Errors.ERROR_ACCESS_DENIED || ret == Interop.Errors.ERROR_BAD_IMPERSONATION_LEVEL) { // We need to throw SecurityException here for compatibility reasons, // although UnauthorizedAccessException will make more sense. throw new SecurityException(SR.Security_RegistryPermission); } // Return null if we didn't find the key. return null; } internal RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable) { SafeRegistryHandle result = null; int ret = Interop.Advapi32.RegOpenKeyEx(_hkey, name, 0, (GetRegistryKeyAccess(writable) | (int)_regView), out result); if (ret == 0 && !result.IsInvalid) { RegistryKey key = new RegistryKey(result, writable, false, _remoteKey, false, _regView); key._keyName = _keyName + "\\" + name; return key; } return null; } private SafeRegistryHandle SystemKeyHandle { get { Debug.Assert(IsSystemKey()); int ret = Interop.Errors.ERROR_INVALID_HANDLE; IntPtr baseKey = (IntPtr)0; switch (_keyName) { case "HKEY_CLASSES_ROOT": baseKey = HKEY_CLASSES_ROOT; break; case "HKEY_CURRENT_USER": baseKey = HKEY_CURRENT_USER; break; case "HKEY_LOCAL_MACHINE": baseKey = HKEY_LOCAL_MACHINE; break; case "HKEY_USERS": baseKey = HKEY_USERS; break; case "HKEY_PERFORMANCE_DATA": baseKey = HKEY_PERFORMANCE_DATA; break; case "HKEY_CURRENT_CONFIG": baseKey = HKEY_CURRENT_CONFIG; break; default: Win32Error(ret, null); break; } // open the base key so that RegistryKey.Handle will return a valid handle SafeRegistryHandle result; ret = Interop.Advapi32.RegOpenKeyEx(baseKey, null, 0, GetRegistryKeyAccess(IsWritable()) | (int)_regView, out result); if (ret == 0 && !result.IsInvalid) { return result; } else { Win32Error(ret, null); throw new IOException(Interop.Kernel32.GetMessage(ret), ret); } } } private int InternalSubKeyCountCore() { int subkeys = 0; int junk = 0; int ret = Interop.Advapi32.RegQueryInfoKey(_hkey, null, null, IntPtr.Zero, ref subkeys, // subkeys null, null, ref junk, // values null, null, null, null); if (ret != 0) { Win32Error(ret, null); } return subkeys; } private string[] InternalGetSubKeyNamesCore(int subkeys) { var names = new List<string>(subkeys); char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1); try { int result; int nameLength = name.Length; while ((result = Interop.Advapi32.RegEnumKeyEx( _hkey, names.Count, name, ref nameLength, null, null, null, null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { switch (result) { case Interop.Errors.ERROR_SUCCESS: names.Add(new string(name, 0, nameLength)); nameLength = name.Length; break; default: // Throw the error Win32Error(result, null); break; } } } finally { ArrayPool<char>.Shared.Return(name); } return names.ToArray(); } private int InternalValueCountCore() { int values = 0; int junk = 0; int ret = Interop.Advapi32.RegQueryInfoKey(_hkey, null, null, IntPtr.Zero, ref junk, // subkeys null, null, ref values, // values null, null, null, null); if (ret != 0) { Win32Error(ret, null); } return values; } /// <summary>Retrieves an array of strings containing all the value names.</summary> /// <returns>All value names.</returns> private unsafe string[] GetValueNamesCore(int values) { var names = new List<string>(values); // Names in the registry aren't usually very long, although they can go to as large // as 16383 characters (MaxValueLength). // // Every call to RegEnumValue will allocate another buffer to get the data from // NtEnumerateValueKey before copying it back out to our passed in buffer. This can // add up quickly- we'll try to keep the memory pressure low and grow the buffer // only if needed. char[] name = ArrayPool<char>.Shared.Rent(100); try { int result; int nameLength = name.Length; while ((result = Interop.Advapi32.RegEnumValue( _hkey, names.Count, name, ref nameLength, IntPtr.Zero, null, null, null)) != Interop.Errors.ERROR_NO_MORE_ITEMS) { switch (result) { // The size is only ever reported back correctly in the case // of ERROR_SUCCESS. It will almost always be changed, however. case Interop.Errors.ERROR_SUCCESS: names.Add(new string(name, 0, nameLength)); break; case Interop.Errors.ERROR_MORE_DATA: if (IsPerfDataKey()) { // Enumerating the values for Perf keys always returns // ERROR_MORE_DATA, but has a valid name. Buffer does need // to be big enough however. 8 characters is the largest // known name. The size isn't returned, but the string is // null terminated. fixed (char* c = &name[0]) { names.Add(new string(c)); } } else { char[] oldName = name; int oldLength = oldName.Length; name = null; ArrayPool<char>.Shared.Return(oldName); name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2)); } break; default: // Throw the error Win32Error(result, null); break; } // Always set the name length back to the buffer size nameLength = name.Length; } } finally { if (name != null) ArrayPool<char>.Shared.Return(name); } return names.ToArray(); } private object InternalGetValueCore(string name, object defaultValue, bool doNotExpand) { object data = defaultValue; int type = 0; int datasize = 0; int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); if (ret != 0) { if (IsPerfDataKey()) { int size = 65000; int sizeInput = size; int r; byte[] blob = new byte[size]; while (Interop.Errors.ERROR_MORE_DATA == (r = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput))) { if (size == int.MaxValue) { // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue Win32Error(r, name); } else if (size > (int.MaxValue / 2)) { // at this point in the loop "size * 2" would cause an overflow size = int.MaxValue; } else { size *= 2; } sizeInput = size; blob = new byte[size]; } if (r != 0) { Win32Error(r, name); } return blob; } else { // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data). // Some OS's returned ERROR_MORE_DATA even in success cases, so we // want to continue on through the function. if (ret != Interop.Errors.ERROR_MORE_DATA) { return data; } } } if (datasize < 0) { // unexpected code path Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize"); datasize = 0; } switch (type) { case Interop.Advapi32.RegistryValues.REG_NONE: case Interop.Advapi32.RegistryValues.REG_DWORD_BIG_ENDIAN: case Interop.Advapi32.RegistryValues.REG_BINARY: { byte[] blob = new byte[datasize]; ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); data = blob; } break; case Interop.Advapi32.RegistryValues.REG_QWORD: { // also REG_QWORD_LITTLE_ENDIAN if (datasize > 8) { // prevent an AV in the edge case that datasize is larger than sizeof(long) goto case Interop.Advapi32.RegistryValues.REG_BINARY; } long blob = 0; Debug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; case Interop.Advapi32.RegistryValues.REG_DWORD: { // also REG_DWORD_LITTLE_ENDIAN if (datasize > 4) { // prevent an AV in the edge case that datasize is larger than sizeof(int) goto case Interop.Advapi32.RegistryValues.REG_QWORD; } int blob = 0; Debug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } break; case Interop.Advapi32.RegistryValues.REG_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new string(blob, 0, blob.Length - 1); } else { // in the very unlikely case the data is missing null termination, // pass in the whole char[] to prevent truncating a character data = new string(blob); } } break; case Interop.Advapi32.RegistryValues.REG_EXPAND_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new string(blob, 0, blob.Length - 1); } else { // in the very unlikely case the data is missing null termination, // pass in the whole char[] to prevent truncating a character data = new string(blob); } if (!doNotExpand) { data = Environment.ExpandEnvironmentVariables((string)data); } } break; case Interop.Advapi32.RegistryValues.REG_MULTI_SZ: { if (datasize % 2 == 1) { // handle the case where the registry contains an odd-byte length (corrupt data?) try { datasize = checked(datasize + 1); } catch (OverflowException e) { throw new IOException(SR.Arg_RegGetOverflowBug, e); } } char[] blob = new char[datasize / 2]; ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); // make sure the string is null terminated before processing the data if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) { Array.Resize(ref blob, blob.Length + 1); } string[] strings = Array.Empty<string>(); int stringsCount = 0; int cur = 0; int len = blob.Length; while (ret == 0 && cur < len) { int nextNull = cur; while (nextNull < len && blob[nextNull] != (char)0) { nextNull++; } string toAdd = null; if (nextNull < len) { Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0"); if (nextNull - cur > 0) { toAdd = new string(blob, cur, nextNull - cur); } else { // we found an empty string. But if we're at the end of the data, // it's just the extra null terminator. if (nextNull != len - 1) { toAdd = string.Empty; } } } else { toAdd = new string(blob, cur, len - cur); } cur = nextNull + 1; if (toAdd != null) { if (strings.Length == stringsCount) { Array.Resize(ref strings, stringsCount > 0 ? stringsCount * 2 : 4); } strings[stringsCount++] = toAdd; } } Array.Resize(ref strings, stringsCount); data = strings; } break; case Interop.Advapi32.RegistryValues.REG_LINK: default: break; } return data; } private RegistryValueKind GetValueKindCore(string name) { int type = 0; int datasize = 0; int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); if (ret != 0) { Win32Error(ret, null); } return type == Interop.Advapi32.RegistryValues.REG_NONE ? RegistryValueKind.None : !Enum.IsDefined(typeof(RegistryValueKind), type) ? RegistryValueKind.Unknown : (RegistryValueKind)type; } private unsafe void SetValueCore(string name, object value, RegistryValueKind valueKind) { int ret = 0; try { switch (valueKind) { case RegistryValueKind.ExpandString: case RegistryValueKind.String: { string data = value.ToString(); ret = Interop.Advapi32.RegSetValueEx(_hkey, name, 0, (int)valueKind, data, checked(data.Length * 2 + 2)); break; } case RegistryValueKind.MultiString: { // Other thread might modify the input array after we calculate the buffer length. // Make a copy of the input array to be safe. string[] dataStrings = (string[])(((string[])value).Clone()); // First determine the size of the array // // Format is null terminator between strings and final null terminator at the end. // e.g. str1\0str2\0str3\0\0 // int sizeInChars = 1; // no matter what, we have the final null terminator. for (int i = 0; i < dataStrings.Length; i++) { if (dataStrings[i] == null) { throw new ArgumentException(SR.Arg_RegSetStrArrNull); } sizeInChars = checked(sizeInChars + (dataStrings[i].Length + 1)); } int sizeInBytes = checked(sizeInChars * sizeof(char)); // Write out the strings... // char[] dataChars = new char[sizeInChars]; int destinationIndex = 0; for (int i = 0; i < dataStrings.Length; i++) { int length = dataStrings[i].Length; dataStrings[i].CopyTo(0, dataChars, destinationIndex, length); destinationIndex += (length + 1); // +1 for null terminator, which is already zero-initialized in new array. } ret = Interop.Advapi32.RegSetValueEx(_hkey, name, 0, Interop.Advapi32.RegistryValues.REG_MULTI_SZ, dataChars, sizeInBytes); break; } case RegistryValueKind.None: case RegistryValueKind.Binary: byte[] dataBytes = (byte[])value; ret = Interop.Advapi32.RegSetValueEx(_hkey, name, 0, (valueKind == RegistryValueKind.None ? Interop.Advapi32.RegistryValues.REG_NONE : Interop.Advapi32.RegistryValues.REG_BINARY), dataBytes, dataBytes.Length); break; case RegistryValueKind.DWord: { // We need to use Convert here because we could have a boxed type cannot be // unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail. int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture); ret = Interop.Advapi32.RegSetValueEx(_hkey, name, 0, Interop.Advapi32.RegistryValues.REG_DWORD, ref data, 4); break; } case RegistryValueKind.QWord: { long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture); ret = Interop.Advapi32.RegSetValueEx(_hkey, name, 0, Interop.Advapi32.RegistryValues.REG_QWORD, ref data, 8); break; } } } catch (Exception exc) when (exc is OverflowException || exc is InvalidOperationException || exc is FormatException || exc is InvalidCastException) { throw new ArgumentException(SR.Arg_RegSetMismatchedKind); } if (ret == 0) { SetDirty(); } else { Win32Error(ret, null); } } /// <summary> /// After calling GetLastWin32Error(), it clears the last error field, /// so you must save the HResult and pass it to this method. This method /// will determine the appropriate exception to throw dependent on your /// error, and depending on the error, insert a string into the message /// gotten from the ResourceManager. /// </summary> private void Win32Error(int errorCode, string str) { switch (errorCode) { case Interop.Errors.ERROR_ACCESS_DENIED: throw str != null ? new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) : new UnauthorizedAccessException(); case Interop.Errors.ERROR_INVALID_HANDLE: // For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException. // However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the // SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues // in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception // on reentrant calls because of this error code path in RegistryKey // // Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this, // however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on // this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of // having serialized access). if (!IsPerfDataKey()) { _hkey.SetHandleAsInvalid(); _hkey = null; } goto default; case Interop.Errors.ERROR_FILE_NOT_FOUND: throw new IOException(SR.Arg_RegKeyNotFound, errorCode); default: throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode); } } private static void Win32ErrorStatic(int errorCode, string str) { switch (errorCode) { case Interop.Errors.ERROR_ACCESS_DENIED: throw str != null ? new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str)) : new UnauthorizedAccessException(); default: throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode); } } private static int GetRegistryKeyAccess(bool isWritable) { int winAccess; if (!isWritable) { winAccess = Interop.Advapi32.RegistryOperations.KEY_READ; } else { winAccess = Interop.Advapi32.RegistryOperations.KEY_READ | Interop.Advapi32.RegistryOperations.KEY_WRITE; } return winAccess; } private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) { int winAccess = 0; switch (mode) { case RegistryKeyPermissionCheck.ReadSubTree: case RegistryKeyPermissionCheck.Default: winAccess = Interop.Advapi32.RegistryOperations.KEY_READ; break; case RegistryKeyPermissionCheck.ReadWriteSubTree: winAccess = Interop.Advapi32.RegistryOperations.KEY_READ | Interop.Advapi32.RegistryOperations.KEY_WRITE; break; default: Debug.Fail("unexpected code path"); break; } return winAccess; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Agent.InternetRelayClientView.Server { public delegate void OnIRCClientReadyDelegate(IRCClientView cv); public class IRCClientView : IClientAPI, IClientCore, IClientIPEndpoint { public event OnIRCClientReadyDelegate OnIRCReady; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly TcpClient m_client; private readonly Scene m_scene; private UUID m_agentID = UUID.Random(); private string m_username; private string m_nick; private bool m_hasNick = false; private bool m_hasUser = false; private bool m_connected = true; public IRCClientView(TcpClient client, Scene scene) { m_client = client; m_scene = scene; Watchdog.StartThread(InternalLoop, "IRCClientView", ThreadPriority.Normal, false); } private void SendServerCommand(string command) { SendCommand(":opensimircd " + command); } private void SendCommand(string command) { m_log.Info("[IRCd] Sending >>> " + command); byte[] buf = Util.UTF8.GetBytes(command + "\r\n"); m_client.GetStream().BeginWrite(buf, 0, buf.Length, SendComplete, null); } private void SendComplete(IAsyncResult result) { m_log.Info("[IRCd] Send Complete."); } private string IrcRegionName { // I know &Channel is more technically correct, but people are used to seeing #Channel // Dont shoot me! get { return "#" + m_scene.RegionInfo.RegionName.Replace(" ", "-"); } } private void InternalLoop() { try { string strbuf = String.Empty; while (m_connected && m_client.Connected) { byte[] buf = new byte[8]; // RFC1459 defines max message size as 512. int count = m_client.GetStream().Read(buf, 0, buf.Length); string line = Util.UTF8.GetString(buf, 0, count); strbuf += line; string message = ExtractMessage(strbuf); if (message != null) { // Remove from buffer strbuf = strbuf.Remove(0, message.Length); m_log.Info("[IRCd] Recieving <<< " + message); message = message.Trim(); // Extract command sequence string command = ExtractCommand(message); ProcessInMessage(message, command); } else { //m_log.Info("[IRCd] Recieved data, but not enough to make a message. BufLen is " + strbuf.Length + // "[" + strbuf + "]"); if (strbuf.Length == 0) { m_connected = false; m_log.Info("[IRCd] Buffer zero, closing..."); if (OnDisconnectUser != null) OnDisconnectUser(); } } Thread.Sleep(0); Watchdog.UpdateThread(); } } catch (IOException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } catch (SocketException) { if (OnDisconnectUser != null) OnDisconnectUser(); m_log.Warn("[IRCd] Disconnected client."); } Watchdog.RemoveThread(); } private void ProcessInMessage(string message, string command) { m_log.Info("[IRCd] Processing [MSG:" + message + "] [COM:" + command + "]"); if (command != null) { switch (command) { case "ADMIN": case "AWAY": case "CONNECT": case "DIE": case "ERROR": case "INFO": case "INVITE": case "ISON": case "KICK": case "KILL": case "LINKS": case "LUSERS": case "OPER": case "PART": case "REHASH": case "SERVICE": case "SERVLIST": case "SERVER": case "SQUERY": case "SQUIT": case "STATS": case "SUMMON": case "TIME": case "TRACE": case "VERSION": case "WALLOPS": case "WHOIS": case "WHOWAS": SendServerCommand("421 " + command + " :Command unimplemented"); break; // Connection Commands case "PASS": break; // Ignore for now. I want to implement authentication later however. case "JOIN": IRC_SendReplyJoin(); break; case "MODE": IRC_SendReplyModeChannel(); break; case "USER": IRC_ProcessUser(message); IRC_Ready(); break; case "USERHOST": string[] userhostArgs = ExtractParameters(message); if (userhostArgs[0] == ":" + m_nick) { SendServerCommand("302 :" + m_nick + "=+" + m_nick + "@" + ((IPEndPoint) m_client.Client.RemoteEndPoint).Address); } break; case "NICK": IRC_ProcessNick(message); IRC_Ready(); break; case "TOPIC": IRC_SendReplyTopic(); break; case "USERS": IRC_SendReplyUsers(); break; case "LIST": break; // TODO case "MOTD": IRC_SendMOTD(); break; case "NOTICE": // TODO break; case "WHO": // TODO IRC_SendNamesReply(); IRC_SendWhoReply(); break; case "PING": IRC_ProcessPing(message); break; // Special case, ignore this completely. case "PONG": break; case "QUIT": if (OnDisconnectUser != null) OnDisconnectUser(); break; case "NAMES": IRC_SendNamesReply(); break; case "PRIVMSG": IRC_ProcessPrivmsg(message); break; default: SendServerCommand("421 " + command + " :Unknown command"); break; } } } private void IRC_Ready() { if (m_hasUser && m_hasNick) { SendServerCommand("001 " + m_nick + " :Welcome to OpenSimulator IRCd"); SendServerCommand("002 " + m_nick + " :Running OpenSimVersion"); SendServerCommand("003 " + m_nick + " :This server was created over 9000 years ago"); SendServerCommand("004 " + m_nick + " :opensimirc r1 aoOirw abeiIklmnoOpqrstv"); SendServerCommand("251 " + m_nick + " :There are 0 users and 0 services on 1 servers"); SendServerCommand("252 " + m_nick + " 0 :operators online"); SendServerCommand("253 " + m_nick + " 0 :unknown connections"); SendServerCommand("254 " + m_nick + " 1 :channels formed"); SendServerCommand("255 " + m_nick + " :I have 1 users, 0 services and 1 servers"); SendCommand(":" + m_nick + " MODE " + m_nick + " :+i"); SendCommand(":" + m_nick + " JOIN :" + IrcRegionName); // Rename to 'Real Name' SendCommand(":" + m_nick + " NICK :" + m_username.Replace(" ", "")); m_nick = m_username.Replace(" ", ""); IRC_SendReplyJoin(); IRC_SendChannelPrivmsg("System", "Welcome to OpenSimulator."); IRC_SendChannelPrivmsg("System", "You are in a maze of twisty little passages, all alike."); IRC_SendChannelPrivmsg("System", "It is pitch black. You are likely to be eaten by a grue."); if (OnIRCReady != null) OnIRCReady(this); } } private void IRC_SendReplyJoin() { IRC_SendReplyTopic(); IRC_SendNamesReply(); } private void IRC_SendReplyModeChannel() { SendServerCommand("324 " + m_nick + " " + IrcRegionName + " +n"); //SendCommand(":" + IrcRegionName + " MODE +n"); } private void IRC_ProcessUser(string message) { string[] userArgs = ExtractParameters(message); // TODO: unused: string username = userArgs[0]; // TODO: unused: string hostname = userArgs[1]; // TODO: unused: string servername = userArgs[2]; string realname = userArgs[3].Replace(":", ""); m_username = realname; m_hasUser = true; } private void IRC_ProcessNick(string message) { string[] nickArgs = ExtractParameters(message); string nickname = nickArgs[0].Replace(":",""); m_nick = nickname; m_hasNick = true; } private void IRC_ProcessPing(string message) { string[] pingArgs = ExtractParameters(message); string pingHost = pingArgs[0]; SendCommand("PONG " + pingHost); } private void IRC_ProcessPrivmsg(string message) { string[] privmsgArgs = ExtractParameters(message); if (privmsgArgs[0] == IrcRegionName) { if (OnChatFromClient != null) { OSChatMessage msg = new OSChatMessage(); msg.Sender = this; msg.Channel = 0; msg.From = this.Name; msg.Message = privmsgArgs[1].Replace(":", ""); msg.Position = Vector3.Zero; msg.Scene = m_scene; msg.SenderObject = null; msg.SenderUUID = this.AgentId; msg.Type = ChatTypeEnum.Say; OnChatFromClient(this, msg); } } else { // Handle as an IM, later. } } private void IRC_SendNamesReply() { List<EntityBase> users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { SendServerCommand("353 " + m_nick + " = " + IrcRegionName + " :" + user.Name.Replace(" ", "")); } SendServerCommand("366 " + IrcRegionName + " :End of /NAMES list"); } private void IRC_SendWhoReply() { List<EntityBase> users = m_scene.Entities.GetAllByType<ScenePresence>(); foreach (EntityBase user in users) { /*SendServerCommand(String.Format("352 {0} {1} {2} {3} {4} {5} :0 {6}", IrcRegionName, user.Name.Replace(" ", ""), "nohost.com", "opensimircd", user.Name.Replace(" ", ""), 'H', user.Name));*/ SendServerCommand("352 " + m_nick + " " + IrcRegionName + " n=" + user.Name.Replace(" ", "") + " fakehost.com " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); //SendServerCommand("352 " + IrcRegionName + " " + user.Name.Replace(" ", "") + " nohost.com irc.opensimulator " + user.Name.Replace(" ", "") + " H " + ":0 " + user.Name); } SendServerCommand("315 " + m_nick + " " + IrcRegionName + " :End of /WHO list"); } private void IRC_SendMOTD() { SendServerCommand("375 :- OpenSimulator Message of the day -"); SendServerCommand("372 :- Hiya!"); SendServerCommand("376 :End of /MOTD command"); } private void IRC_SendReplyTopic() { SendServerCommand("332 " + IrcRegionName + " :OpenSimulator IRC Server"); } private void IRC_SendReplyUsers() { List<EntityBase> users = m_scene.Entities.GetAllByType<ScenePresence>(); SendServerCommand("392 :UserID Terminal Host"); if (users.Count == 0) { SendServerCommand("395 :Nobody logged in"); return; } foreach (EntityBase user in users) { char[] nom = new char[8]; char[] term = "terminal_".ToCharArray(); char[] host = "hostname".ToCharArray(); string userName = user.Name.Replace(" ",""); for (int i = 0; i < nom.Length; i++) { if (userName.Length < i) nom[i] = userName[i]; else nom[i] = ' '; } SendServerCommand("393 :" + nom + " " + term + " " + host + ""); } SendServerCommand("394 :End of users"); } private static string ExtractMessage(string buffer) { int pos = buffer.IndexOf("\r\n"); if (pos == -1) return null; string command = buffer.Substring(0, pos + 2); return command; } private static string ExtractCommand(string msg) { string[] msgs = msg.Split(' '); if (msgs.Length < 2) { m_log.Warn("[IRCd] Dropped msg: " + msg); return null; } if (msgs[0].StartsWith(":")) return msgs[1]; return msgs[0]; } private static string[] ExtractParameters(string msg) { string[] msgs = msg.Split(' '); List<string> parms = new List<string>(msgs.Length); bool foundCommand = false; string command = ExtractCommand(msg); for (int i=0;i<msgs.Length;i++) { if (msgs[i] == command) { foundCommand = true; continue; } if (foundCommand != true) continue; if (i != 0 && msgs[i].StartsWith(":")) { List<string> tmp = new List<string>(); for (int j=i;j<msgs.Length;j++) { tmp.Add(msgs[j]); } parms.Add(string.Join(" ", tmp.ToArray())); break; } parms.Add(msgs[i]); } return parms.ToArray(); } #region Implementation of IClientAPI public Vector3 StartPos { get { return new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 50); } set { } } public bool TryGet<T>(out T iface) { iface = default(T); return false; } public T Get<T>() { return default(T); } public UUID AgentId { get { return m_agentID; } } public void Disconnect(string reason) { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue. (" + reason + ")"); m_connected = false; m_client.Close(); } public void Disconnect() { IRC_SendChannelPrivmsg("System", "You have been eaten by a grue."); m_connected = false; m_client.Close(); } public UUID SessionId { get { return m_agentID; } } public UUID SecureSessionId { get { return m_agentID; } } public UUID ActiveGroupId { get { return UUID.Zero; } } public string ActiveGroupName { get { return "IRCd User"; } } public ulong ActiveGroupPowers { get { return 0; } } public ulong GetGroupPowers(UUID groupID) { return 0; } public bool IsGroupMember(UUID GroupID) { return false; } public string FirstName { get { string[] names = m_username.Split(' '); return names[0]; } } public string LastName { get { string[] names = m_username.Split(' '); if (names.Length > 1) return names[1]; return names[0]; } } public IScene Scene { get { return m_scene; } } public int NextAnimationSequenceNumber { get { return 0; } } public string Name { get { return m_username; } } public bool IsActive { get { return true; } set { if (!value) Disconnect("IsActive Disconnected?"); } } public bool IsLoggingOut { get { return false; } set { } } public bool SendLogoutPacketWhenClosing { set { } } public uint CircuitCode { get { return (uint)Util.RandomClass.Next(0,int.MaxValue); } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint)m_client.Client.RemoteEndPoint; } } #pragma warning disable 67 public event GenericMessage OnGenericMessage; public event ImprovedInstantMessage OnInstantMessage; public event ChatMessage OnChatFromClient; public event TextureRequest OnRequestTexture; public event RezObject OnRezObject; public event ModifyTerrain OnModifyTerrain; public event BakeTerrain OnBakeTerrain; public event EstateChangeInfo OnEstateChangeInfo; public event SetAppearance OnSetAppearance; public event AvatarNowWearing OnAvatarNowWearing; public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv; public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv; public event UUIDNameRequest OnDetachAttachmentIntoInv; public event ObjectAttach OnObjectAttach; public event ObjectDeselect OnObjectDetach; public event ObjectDrop OnObjectDrop; public event StartAnim OnStartAnim; public event StopAnim OnStopAnim; public event LinkObjects OnLinkObjects; public event DelinkObjects OnDelinkObjects; public event RequestMapBlocks OnRequestMapBlocks; public event RequestMapName OnMapNameRequest; public event TeleportLocationRequest OnTeleportLocationRequest; public event DisconnectUser OnDisconnectUser; public event RequestAvatarProperties OnRequestAvatarProperties; public event SetAlwaysRun OnSetAlwaysRun; public event TeleportLandmarkRequest OnTeleportLandmarkRequest; public event DeRezObject OnDeRezObject; public event Action<IClientAPI> OnRegionHandShakeReply; public event GenericCall2 OnRequestWearables; public event GenericCall1 OnCompleteMovementToRegion; public event UpdateAgent OnPreAgentUpdate; public event UpdateAgent OnAgentUpdate; public event AgentRequestSit OnAgentRequestSit; public event AgentSit OnAgentSit; public event AvatarPickerRequest OnAvatarPickerRequest; public event Action<IClientAPI> OnRequestAvatarsData; public event AddNewPrim OnAddPrim; public event FetchInventory OnAgentDataUpdateRequest; public event TeleportLocationRequest OnSetStartLocationRequest; public event RequestGodlikePowers OnRequestGodlikePowers; public event GodKickUser OnGodKickUser; public event ObjectDuplicate OnObjectDuplicate; public event ObjectDuplicateOnRay OnObjectDuplicateOnRay; public event GrabObject OnGrabObject; public event DeGrabObject OnDeGrabObject; public event MoveObject OnGrabUpdate; public event SpinStart OnSpinStart; public event SpinObject OnSpinUpdate; public event SpinStop OnSpinStop; public event UpdateShape OnUpdatePrimShape; public event ObjectExtraParams OnUpdateExtraParams; public event ObjectRequest OnObjectRequest; public event ObjectSelect OnObjectSelect; public event ObjectDeselect OnObjectDeselect; public event GenericCall7 OnObjectDescription; public event GenericCall7 OnObjectName; public event GenericCall7 OnObjectClickAction; public event GenericCall7 OnObjectMaterial; public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily; public event UpdatePrimFlags OnUpdatePrimFlags; public event UpdatePrimTexture OnUpdatePrimTexture; public event UpdateVector OnUpdatePrimGroupPosition; public event UpdateVector OnUpdatePrimSinglePosition; public event UpdatePrimRotation OnUpdatePrimGroupRotation; public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation; public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition; public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation; public event UpdateVector OnUpdatePrimScale; public event UpdateVector OnUpdatePrimGroupScale; public event StatusChange OnChildAgentStatus; public event GenericCall2 OnStopMovement; public event Action<UUID> OnRemoveAvatar; public event ObjectPermissions OnObjectPermissions; public event CreateNewInventoryItem OnCreateNewInventoryItem; public event LinkInventoryItem OnLinkInventoryItem; public event CreateInventoryFolder OnCreateNewInventoryFolder; public event UpdateInventoryFolder OnUpdateInventoryFolder; public event MoveInventoryFolder OnMoveInventoryFolder; public event FetchInventoryDescendents OnFetchInventoryDescendents; public event PurgeInventoryDescendents OnPurgeInventoryDescendents; public event FetchInventory OnFetchInventory; public event RequestTaskInventory OnRequestTaskInventory; public event UpdateInventoryItem OnUpdateInventoryItem; public event CopyInventoryItem OnCopyInventoryItem; public event MoveInventoryItem OnMoveInventoryItem; public event RemoveInventoryFolder OnRemoveInventoryFolder; public event RemoveInventoryItem OnRemoveInventoryItem; public event UDPAssetUploadRequest OnAssetUploadRequest; public event XferReceive OnXferReceive; public event RequestXfer OnRequestXfer; public event ConfirmXfer OnConfirmXfer; public event AbortXfer OnAbortXfer; public event RezScript OnRezScript; public event UpdateTaskInventory OnUpdateTaskInventory; public event MoveTaskInventory OnMoveTaskItem; public event RemoveTaskInventory OnRemoveTaskItem; public event RequestAsset OnRequestAsset; public event UUIDNameRequest OnNameFromUUIDRequest; public event ParcelAccessListRequest OnParcelAccessListRequest; public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest; public event ParcelPropertiesRequest OnParcelPropertiesRequest; public event ParcelDivideRequest OnParcelDivideRequest; public event ParcelJoinRequest OnParcelJoinRequest; public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest; public event ParcelSelectObjects OnParcelSelectObjects; public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest; public event ParcelAbandonRequest OnParcelAbandonRequest; public event ParcelGodForceOwner OnParcelGodForceOwner; public event ParcelReclaim OnParcelReclaim; public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest; public event ParcelDeedToGroup OnParcelDeedToGroup; public event RegionInfoRequest OnRegionInfoRequest; public event EstateCovenantRequest OnEstateCovenantRequest; public event FriendActionDelegate OnApproveFriendRequest; public event FriendActionDelegate OnDenyFriendRequest; public event FriendshipTermination OnTerminateFriendship; public event GrantUserFriendRights OnGrantUserRights; public event MoneyTransferRequest OnMoneyTransferRequest; public event EconomyDataRequest OnEconomyDataRequest; public event MoneyBalanceRequest OnMoneyBalanceRequest; public event UpdateAvatarProperties OnUpdateAvatarProperties; public event ParcelBuy OnParcelBuy; public event RequestPayPrice OnRequestPayPrice; public event ObjectSaleInfo OnObjectSaleInfo; public event ObjectBuy OnObjectBuy; public event BuyObjectInventory OnBuyObjectInventory; public event RequestTerrain OnRequestTerrain; public event RequestTerrain OnUploadTerrain; public event ObjectIncludeInSearch OnObjectIncludeInSearch; public event UUIDNameRequest OnTeleportHomeRequest; public event ScriptAnswer OnScriptAnswer; public event AgentSit OnUndo; public event AgentSit OnRedo; public event LandUndo OnLandUndo; public event ForceReleaseControls OnForceReleaseControls; public event GodLandStatRequest OnLandStatRequest; public event DetailedEstateDataRequest OnDetailedEstateDataRequest; public event SetEstateFlagsRequest OnSetEstateFlagsRequest; public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture; public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture; public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights; public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest; public event SetRegionTerrainSettings OnSetRegionTerrainSettings; public event EstateRestartSimRequest OnEstateRestartSimRequest; public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest; public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest; public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest; public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest; public event EstateDebugRegionRequest OnEstateDebugRegionRequest; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; public event UUIDNameRequest OnUUIDGroupNameRequest; public event RegionHandleRequest OnRegionHandleRequest; public event ParcelInfoRequest OnParcelInfoRequest; public event RequestObjectPropertiesFamily OnObjectGroupRequest; public event ScriptReset OnScriptReset; public event GetScriptRunning OnGetScriptRunning; public event SetScriptRunning OnSetScriptRunning; public event UpdateVector OnAutoPilotGo; public event TerrainUnacked OnUnackedTerrain; public event ActivateGesture OnActivateGesture; public event DeactivateGesture OnDeactivateGesture; public event ObjectOwner OnObjectOwner; public event DirPlacesQuery OnDirPlacesQuery; public event DirFindQuery OnDirFindQuery; public event DirLandQuery OnDirLandQuery; public event DirPopularQuery OnDirPopularQuery; public event DirClassifiedQuery OnDirClassifiedQuery; public event EventInfoRequest OnEventInfoRequest; public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime; public event MapItemRequest OnMapItemRequest; public event OfferCallingCard OnOfferCallingCard; public event AcceptCallingCard OnAcceptCallingCard; public event DeclineCallingCard OnDeclineCallingCard; public event SoundTrigger OnSoundTrigger; public event StartLure OnStartLure; public event TeleportLureRequest OnTeleportLureRequest; public event NetworkStats OnNetworkStatsUpdate; public event ClassifiedInfoRequest OnClassifiedInfoRequest; public event ClassifiedInfoUpdate OnClassifiedInfoUpdate; public event ClassifiedDelete OnClassifiedDelete; public event ClassifiedDelete OnClassifiedGodDelete; public event EventNotificationAddRequest OnEventNotificationAddRequest; public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest; public event EventGodDelete OnEventGodDelete; public event ParcelDwellRequest OnParcelDwellRequest; public event UserInfoRequest OnUserInfoRequest; public event UpdateUserInfo OnUpdateUserInfo; public event RetrieveInstantMessages OnRetrieveInstantMessages; public event PickDelete OnPickDelete; public event PickGodDelete OnPickGodDelete; public event PickInfoUpdate OnPickInfoUpdate; public event AvatarNotesUpdate OnAvatarNotesUpdate; public event MuteListRequest OnMuteListRequest; public event AvatarInterestUpdate OnAvatarInterestUpdate; public event PlacesQuery OnPlacesQuery; public event FindAgentUpdate OnFindAgent; public event TrackAgentUpdate OnTrackAgent; public event NewUserReport OnUserReport; public event SaveStateHandler OnSaveState; public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest; public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest; public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest; public event FreezeUserUpdate OnParcelFreezeUser; public event EjectUserUpdate OnParcelEjectUser; public event ParcelBuyPass OnParcelBuyPass; public event ParcelGodMark OnParcelGodMark; public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest; public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest; public event SimWideDeletesDelegate OnSimWideDeletes; public event SendPostcard OnSendPostcard; public event MuteListEntryUpdate OnUpdateMuteListEntry; public event MuteListEntryRemove OnRemoveMuteListEntry; public event GodlikeMessage onGodlikeMessage; public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate; #pragma warning restore 67 public void SetDebugPacketLevel(int newDebug) { } public void InPacket(object NewPack) { } public void ProcessInPacket(Packet NewPack) { } public void Close() { Disconnect(); } public void Kick(string message) { Disconnect(message); } public void Start() { Scene.AddNewClient(this); // Mimicking LLClientView which gets always set appearance from client. Scene scene = (Scene)Scene; AvatarAppearance appearance; scene.GetAvatarAppearance(this, out appearance); OnSetAppearance(appearance.Texture, (byte[])appearance.VisualParams.Clone()); } public void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args) { m_log.Info("[IRCd ClientStack] Completing Handshake to Region"); if (OnRegionHandShakeReply != null) { OnRegionHandShakeReply(this); } if (OnCompleteMovementToRegion != null) { OnCompleteMovementToRegion(this); } } public void Stop() { Disconnect(); } public void SendWearables(AvatarWearable[] wearables, int serial) { } public void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry) { } public void SendStartPingCheck(byte seq) { } public void SendKillObject(ulong regionHandle, uint localID) { } public void SendAnimations(UUID[] animID, int[] seqs, UUID sourceAgentId, UUID[] objectIDs) { } public void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName, UUID fromAgentID, byte source, byte audible) { if (audible > 0 && message.Length > 0) IRC_SendChannelPrivmsg(fromName, message); } private void IRC_SendChannelPrivmsg(string fromName, string message) { SendCommand(":" + fromName.Replace(" ", "") + " PRIVMSG " + IrcRegionName + " :" + message); } public void SendInstantMessage(GridInstantMessage im) { // TODO } public void SendGenericMessage(string method, List<string> message) { } public void SendGenericMessage(string method, List<byte[]> message) { } public void SendLayerData(float[] map) { } public void SendLayerData(int px, int py, float[] map) { } public void SendWindData(Vector2[] windSpeeds) { } public void SendCloudData(float[] cloudCover) { } public void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look) { } public void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint) { } public AgentCircuitData RequestClientInfo() { return new AgentCircuitData(); } public void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL) { } public void SendMapBlock(List<MapBlockData> mapBlocks, uint flag) { } public void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags) { } public void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL) { } public void SendTeleportFailed(string reason) { } public void SendTeleportLocationStart() { } public void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance) { } public void SendPayPrice(UUID objectID, int[] payPrice) { } public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) { } public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID) { } public void SendAvatarDataImmediate(ISceneEntity avatar) { } public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags) { } public void ReprioritizeUpdates() { } public void FlushPrimUpdates() { } public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems) { } public void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item) { } public void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackId) { } public void SendRemoveInventoryItem(UUID itemID) { } public void SendTakeControls(int controls, bool passToAgent, bool TakeControls) { } public void SendTaskInventory(UUID taskID, short serial, byte[] fileName) { } public void SendBulkUpdateInventory(InventoryNodeBase node) { } public void SendXferPacket(ulong xferID, uint packet, byte[] data) { } public void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit, int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor, int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay, int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent) { } public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data) { } public void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle) { } public void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID) { } public void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain, byte flags) { } public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain) { } public void SendAttachedSoundGainChange(UUID objectID, float gain) { } public void SendNameReply(UUID profileId, string firstname, string lastname) { } public void SendAlertMessage(string message) { IRC_SendChannelPrivmsg("Alert",message); } public void SendAgentAlertMessage(string message, bool modal) { } public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message, string url) { IRC_SendChannelPrivmsg(objectname,url); } public void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) { } public bool AddMoney(int debit) { return true; } public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong CurrentTime, uint SecondsPerSunCycle, uint SecondsPerYear, float OrbitalPosition) { } public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks) { } public void SendViewerTime(int phase) { } public UUID GetDefaultAnimation(string name) { return UUID.Zero; } public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, byte[] charterMember, string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL, UUID partnerID) { } public void SendScriptQuestion(UUID taskID, string taskName, string ownerName, UUID itemID, int question) { } public void SendHealth(float health) { } public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID) { } public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID) { } public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args) { } public void SendEstateCovenantInformation(UUID covenant) { } public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner) { } public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags) { } public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID) { } public void SendForceClientSelectObjects(List<uint> objectIDs) { } public void SendCameraConstraint(Vector4 ConstraintPlane) { } public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount) { } public void SendLandParcelOverlay(byte[] data, int sequence_id) { } public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time) { } public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType, string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop) { } public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID) { } public void SendConfirmXfer(ulong xferID, uint PacketID) { } public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName) { } public void SendInitiateDownload(string simFileName, string clientFileName) { } public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec) { } public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData) { } public void SendImageNotFound(UUID imageid) { } public void SendShutdownConnectionNotice() { // TODO } public void SendSimStats(SimStats stats) { } public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description) { } public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice) { } public void SendAgentOffline(UUID[] agentIDs) { } public void SendAgentOnline(UUID[] agentIDs) { } public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot, Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook) { } public void SendAdminResponse(UUID Token, uint AdminLevel) { } public void SendGroupMembership(GroupMembershipData[] GroupMembership) { } public void SendGroupNameReply(UUID groupLLUID, string GroupName) { } public void SendJoinGroupReply(UUID groupID, bool success) { } public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool success) { } public void SendLeaveGroupReply(UUID groupID, bool success) { } public void SendCreateGroupReply(UUID groupID, bool success, string message) { } public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia) { } public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running) { } public void SendAsset(AssetRequestToClient req) { } public void SendTexture(AssetBase TextureAsset) { } public virtual void SetChildAgentThrottle(byte[] throttle) { } public byte[] GetThrottlesPacked(float multiplier) { return new byte[0]; } public event ViewerEffectEventHandler OnViewerEffect; public event Action<IClientAPI> OnLogout; public event Action<IClientAPI> OnConnectionClosed; public void SendBlueBoxMessage(UUID FromAvatarID, string FromAvatarName, string Message) { IRC_SendChannelPrivmsg(FromAvatarName, Message); } public void SendLogoutPacket() { Disconnect(); } public EndPoint GetClientEP() { return null; } public ClientInfo GetClientInfo() { return new ClientInfo(); } public void SetClientInfo(ClientInfo info) { } public void SetClientOption(string option, string value) { } public string GetClientOption(string option) { return String.Empty; } public void Terminate() { Disconnect(); } public void SendSetFollowCamProperties(UUID objectID, SortedDictionary<int, float> parameters) { } public void SendClearFollowCamProperties(UUID objectID) { } public void SendRegionHandle(UUID regoinID, ulong handle) { } public void SendParcelInfo(RegionInfo info, LandData land, UUID parcelID, uint x, uint y) { } public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt) { } public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data) { } public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data) { } public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data) { } public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data) { } public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data) { } public void SendDirLandReply(UUID queryID, DirLandReplyData[] data) { } public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data) { } public void SendEventInfoReply(EventData info) { } public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags) { } public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data) { } public void SendOfferCallingCard(UUID srcID, UUID transactionID) { } public void SendAcceptCallingCard(UUID transactionID) { } public void SendDeclineCallingCard(UUID transactionID) { } public void SendTerminateFriend(UUID exFriendID) { } public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name) { } public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price) { } public void SendAgentDropGroup(UUID groupID) { } public void RefreshGroupMembership() { } public void SendAvatarNotesReply(UUID targetID, string text) { } public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks) { } public void SendPickInfoReply(UUID pickID, UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled) { } public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds) { } public void SendAvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { } public void SendParcelDwellReply(int localID, UUID parcelID, float dwell) { } public void SendUserInfoReply(bool imViaEmail, bool visible, string email) { } public void SendUseCachedMuteList() { } public void SendMuteListUpdate(string filename) { } public void KillEndDone() { } public bool AddGenericPacketHandler(string MethodName, GenericMessage handler) { return true; } #endregion #region Implementation of IClientIPEndpoint public IPAddress EndPoint { get { return ((IPEndPoint) m_client.Client.RemoteEndPoint).Address; } } #endregion public void SendRebakeAvatarTextures(UUID textureID) { } public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages) { } public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt) { } public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier) { } public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt) { } public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes) { } public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals) { } public void SendChangeUserRights(UUID agentID, UUID friendID, int rights) { } public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) { } public void StopFlying(ISceneEntity presence) { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; /// <summary> /// Version: 1.2 /// ------------------------------------------------------------------------- /// Simon Pucher 2016 /// Christian Kovar 2016 /// ------------------------------------------------------------------------- /// Description: https://en.wikipedia.org/wiki/Algorithmic_trading#Mean_reversion /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this indicator without any error you also need access to the utility indicator to use these global source code elements. /// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { [Description("The mean reversion is the theory suggesting that prices and returns eventually move back towards the mean or average.")] public class Mean_Reversion_Strategy : UserStrategy, IMean_Reversion { //interface private bool _IsShortEnabled = false; private bool _IsLongEnabled = true; private bool _WarningOccured = false; private bool _ErrorOccured = false; private int _Bollinger_Period = 20; private double _Bollinger_Standard_Deviation = 2; private int _Momentum_Period = 100; private int _RSI_Period = 14; private int _RSI_Smooth = 3; private int _RSI_Level_Low = 30; private int _RSI_Level_High = 70; private int _Momentum_Level_Low = -1; private int _Momentum_Level_High = 1; //input private bool _send_email = false; private bool _autopilot = true; //todo //private bool _statisticbacktesting = false; //output //internal private IOrder _orderenterlong; private IOrder _orderentershort; private Mean_Reversion_Indicator _Mean_Reversion_Indicator = null; //todo //private StatisticContainer _StatisticContainer = null; protected override void OnInit() { //We need at least xy bars this.RequiredBarsCount = 130; } protected override void OnStart() { base.OnStart(); //Print("OnStartUp" + Bars[0].Timestamp); //Init our indicator to get code access this._Mean_Reversion_Indicator = new Mean_Reversion_Indicator(); ////todo Initalize statistic data list if this feature is enabled //if (this.StatisticBacktesting) //{ // this._StatisticContainer = new StatisticContainer(); //} this.ErrorOccured = false; this.WarningOccured = false; } protected override void OnDispose() { base.OnDispose(); ////Print("OnTermination" + Bars[0].Timestamp); //IAccount account = this.Core.AccountManager.GetAccount(this.Instrument, true); //double counti = this.Core.TradingManager.GetExecutions(account, this.Backtesting.Settings.DateTimeRange.Lower, this.Backtesting.Settings.DateTimeRange.Upper).Count(); //IEnumerable<ExecutionHistory> data = this.Backtesting.TradingProcessor.GetExecutions(this.Backtesting.TradingProcessor.Accounts.First(), this.Backtesting.Settings.DateTimeRange.Lower, this.Backtesting.Settings.DateTimeRange.Upper); //foreach (ExecutionHistory item in data) //{ // item.Ex //} ////todo Close statistic data list if this feature is enabled //if (this.StatisticBacktesting) //{ // //get the statistic data // this._StatisticContainer.copyToClipboard(); //} } protected override void OnCalculate() { //Set automated during configuration in input dialog at strategy escort in chart this.IsAutoConfirmOrder = this.Autopilot; //calculate data ResultValue returnvalue = this._Mean_Reversion_Indicator.calculate(InSeries, Open, High, _orderenterlong, _orderentershort, this.Bollinger_Period, this.Bollinger_Standard_Deviation, this.Momentum_Period, this.RSI_Period, this.RSI_Smooth, this.RSI_Level_Low, this.RSI_Level_High, this.Momentum_Level_Low, this.Momentum_Level_High); //If the calculate method was not finished we need to stop and show an alert message to the user. if (returnvalue.ErrorOccured) { //Display error just one time if (!this.ErrorOccured) { Log(this.DisplayName + ": " + Const.DefaultStringErrorDuringCalculation, InfoLogLevel.AlertLog); this.ErrorOccured = true; } return; } //Entry if (returnvalue.Entry.HasValue) { switch (returnvalue.Entry) { case OrderDirection.Buy: this.DoEnterLong(); break; case OrderDirection.Sell: this.DoEnterShort(); break; } } //Exit if (returnvalue.Exit.HasValue) { switch (returnvalue.Exit) { case OrderDirection.Buy: this.DoExitShort(); break; case OrderDirection.Sell: this.DoExitLong(); break; } } //todo move stop of long order // SetUpTrailStop(CalculationMode.Ticks, 30); } /// <summary> /// OnExecution of orders /// </summary> /// <param name="execution"></param> protected override void OnOrderExecution(IExecution execution) { ////todo Create statistic for execution //if (this.StatisticBacktesting) //{ // this._StatisticContainer.Add(this.Root.Core.TradingManager, this.DisplayName, execution); //} //send email if (this.Send_email) { this.SendEmail(Core.Settings.MailDefaultFromAddress, Core.PreferenceManager.DefaultEmailAddress, GlobalUtilities.GetEmailSubject(execution), GlobalUtilities.GetEmailText(execution, this.GetType().Name)); } } /// <summary> /// Create LONG order. /// </summary> private void DoEnterLong() { if (_orderenterlong == null) { _orderenterlong = SubmitOrder(new StrategyOrderParameters {Direction = OrderDirection.Buy, Type = OrderType.Market, Quantity = GlobalUtilities.AdjustPositionToRiskManagement(this.Root.Core.AccountManager, this.Root.Core.PreferenceManager, this.Instrument, Bars[0].Close), SignalName = this.DisplayName + "_" + OrderDirection.Buy + "_" + this.Instrument.Symbol + "_" + Bars[0].Time.Ticks.ToString(), Instrument = this.Instrument, TimeFrame = this.TimeFrame}); SetUpStopLoss(_orderenterlong.Name, CalculationMode.Price, Bars[0].Close * 0.97, false); //SetUpProfitTarget(_orderenterlong.Name, CalculationMode.Price, this._orb_indicator.TargetLong); } } /// <summary> /// Create SHORT order. /// </summary> private void DoEnterShort() { if (_orderentershort == null) { _orderentershort = SubmitOrder(new StrategyOrderParameters {Direction = OrderDirection.Sell, Type = OrderType.Market, Quantity = GlobalUtilities.AdjustPositionToRiskManagement(this.Root.Core.AccountManager, this.Root.Core.PreferenceManager, this.Instrument, Bars[0].Close), SignalName = this.DisplayName + "_" + OrderDirection.Sell + "_" + this.Instrument.Symbol + "_" + Bars[0].Time.Ticks.ToString(), Instrument = this.Instrument, TimeFrame = this.TimeFrame}); //SetUpStopLoss(_orderentershort.Name, CalculationMode.Price, this._orb_indicator.RangeHigh, false); //SetUpProfitTarget(_orderentershort.Name, CalculationMode.Price, this._orb_indicator.TargetShort); } } /// <summary> /// Exit the LONG position. /// </summary> private void DoExitLong() { if (this._orderenterlong != null) { CloseLongTrade(new StrategyOrderParameters {Type = OrderType.Market, Quantity = this._orderenterlong.Quantity }); this._orderenterlong = null; } } /// <summary> /// Fill the SHORT position. /// </summary> private void DoExitShort() { if (this._orderentershort != null) { CloseShortTrade(new StrategyOrderParameters {Type = OrderType.Market, Quantity = this._orderentershort.Quantity}); this._orderentershort = null; } } #region Properties #region Interface /// <summary> /// </summary> [Description("If true it is allowed to create long positions.")] [InputParameter] [DisplayName("Allow Long")] public bool IsLongEnabled { get { return _IsLongEnabled; } set { _IsLongEnabled = value; } } /// <summary> /// </summary> [Description("If true it is allowed to create short positions.")] [InputParameter] [DisplayName("Allow Short")] public bool IsShortEnabled { get { return _IsShortEnabled; } set { _IsShortEnabled = value; } } [Browsable(false)] [XmlIgnore()] public bool ErrorOccured { get { return _ErrorOccured; } set { _ErrorOccured = value; } } [Browsable(false)] [XmlIgnore()] public bool WarningOccured { get { return _WarningOccured; } set { _WarningOccured = value; } } [Description("Period of the Bollinger Band.")] [InputParameter] [DisplayName("BB Period")] public int Bollinger_Period { get { return _Bollinger_Period; } set { _Bollinger_Period = value; } } [Description("Standard Deviation of the Bollinger Band.")] [InputParameter] [DisplayName("BB StdDev")] public double Bollinger_Standard_Deviation { get { return _Bollinger_Standard_Deviation; } set { _Bollinger_Standard_Deviation = value; } } [Description("Period of the Momentum.")] [InputParameter] [DisplayName("MOM Period")] public int Momentum_Period { get { return _Momentum_Period; } set { _Momentum_Period = value; } } [Description("Period of the RSI.")] [InputParameter] [DisplayName("RSI Period")] public int RSI_Period { get { return _RSI_Period; } set { _RSI_Period = value; } } [Description("Smooth Period of the RSI.")] [InputParameter] [DisplayName("RSI Smooth Period")] public int RSI_Smooth { get { return _RSI_Smooth; } set { _RSI_Smooth = value; } } [Description("We trade long below this RSI level.")] [InputParameter] [DisplayName("RSI Level Low")] public int RSI_Level_Low { get { return _RSI_Level_Low; } set { _RSI_Level_Low = value; } } [Description("We trade short above this RSI level.")] [InputParameter] [DisplayName("RSI Level High")] public int RSI_Level_High { get { return _RSI_Level_High; } set { _RSI_Level_High = value; } } [Description("We trade long if momentum is above this level.")] [InputParameter] [DisplayName("MOM Level Low")] public int Momentum_Level_Low { get { return _Momentum_Level_Low; } set { _Momentum_Level_Low = value; } } [Description("We trade short if momentum is below this level.")] [InputParameter] [DisplayName("MOM Level High")] public int Momentum_Level_High { get { return _Momentum_Level_High; } set { _Momentum_Level_High = value; } } #endregion #region Internal [Description("If true an email will be send on order execution and on other important issues")] [Category("Safety first!")] [DisplayName("Send email")] public bool Send_email { get { return _send_email; } set { _send_email = value; } } [Description("If true the strategy will handle everything. It will create buy orders, sell orders, stop loss orders, targets fully automatically")] [Category("Safety first!")] [DisplayName("Autopilot")] public bool Autopilot { get { return _autopilot; } set { _autopilot = value; } } //todo //[Description("If true the strategy will create statistic data during the backtesting process")] //[Category("Safety first!")] //[DisplayName("Statistic Backtesting")] //public bool StatisticBacktesting //{ // get { return _statisticbacktesting; } // set { _statisticbacktesting = value; } //} #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; public struct ValX0 { } public struct ValY0 { } public struct ValX1<T> { } public struct ValY1<T> { } public struct ValX2<T, U> { } public struct ValY2<T, U> { } public struct ValX3<T, U, V> { } public struct ValY3<T, U, V> { } public class RefX0 { } public class RefY0 { } public class RefX1<T> { } public class RefY1<T> { } public class RefX2<T, U> { } public class RefY2<T, U> { } public class RefX3<T, U, V> { } public class RefY3<T, U, V> { } public class GenException<T> : Exception { } public class Gen<T> { public bool ExceptionTest(bool throwException) { if (throwException) { throw new GenException<T>(); } else { return true; } } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } counter++; } public static int Main() { int cLabel = 0; while (cLabel < 50) { try { switch (cLabel) { case 0: cLabel++; new Gen<int>().ExceptionTest(true); break; case 1: cLabel++; new Gen<double>().ExceptionTest(true); break; case 2: cLabel++; new Gen<string>().ExceptionTest(true); break; case 3: cLabel++; new Gen<object>().ExceptionTest(true); break; case 4: cLabel++; new Gen<Guid>().ExceptionTest(true); break; case 5: cLabel++; new Gen<int[]>().ExceptionTest(true); break; case 6: cLabel++; new Gen<double[,]>().ExceptionTest(true); break; case 7: cLabel++; new Gen<string[][][]>().ExceptionTest(true); break; case 8: cLabel++; new Gen<object[, , ,]>().ExceptionTest(true); break; case 9: cLabel++; new Gen<Guid[][, , ,][]>().ExceptionTest(true); break; case 10: cLabel++; new Gen<RefX1<int>[]>().ExceptionTest(true); break; case 11: cLabel++; new Gen<RefX1<double>[,]>().ExceptionTest(true); break; case 12: cLabel++; new Gen<RefX1<string>[][][]>().ExceptionTest(true); break; case 13: cLabel++; new Gen<RefX1<object>[, , ,]>().ExceptionTest(true); break; case 14: cLabel++; new Gen<RefX1<Guid>[][, , ,][]>().ExceptionTest(true); break; case 15: cLabel++; new Gen<RefX2<int, int>[]>().ExceptionTest(true); break; case 16: cLabel++; new Gen<RefX2<double, double>[,]>().ExceptionTest(true); break; case 17: cLabel++; new Gen<RefX2<string, string>[][][]>().ExceptionTest(true); break; case 18: cLabel++; new Gen<RefX2<object, object>[, , ,]>().ExceptionTest(true); break; case 19: cLabel++; new Gen<RefX2<Guid, Guid>[][, , ,][]>().ExceptionTest(true); break; case 20: cLabel++; new Gen<ValX1<int>[]>().ExceptionTest(true); break; case 21: cLabel++; new Gen<ValX1<double>[,]>().ExceptionTest(true); break; case 22: cLabel++; new Gen<ValX1<string>[][][]>().ExceptionTest(true); break; case 23: cLabel++; new Gen<ValX1<object>[, , ,]>().ExceptionTest(true); break; case 24: cLabel++; new Gen<ValX1<Guid>[][, , ,][]>().ExceptionTest(true); break; case 25: cLabel++; new Gen<ValX2<int, int>[]>().ExceptionTest(true); break; case 26: cLabel++; new Gen<ValX2<double, double>[,]>().ExceptionTest(true); break; case 27: cLabel++; new Gen<ValX2<string, string>[][][]>().ExceptionTest(true); break; case 28: cLabel++; new Gen<ValX2<object, object>[, , ,]>().ExceptionTest(true); break; case 29: cLabel++; new Gen<ValX2<Guid, Guid>[][, , ,][]>().ExceptionTest(true); break; case 30: cLabel++; new Gen<RefX1<int>>().ExceptionTest(true); break; case 31: cLabel++; new Gen<RefX1<ValX1<int>>>().ExceptionTest(true); break; case 32: cLabel++; new Gen<RefX2<int, string>>().ExceptionTest(true); break; case 33: cLabel++; new Gen<RefX3<int, string, Guid>>().ExceptionTest(true); break; case 34: cLabel++; new Gen<RefX1<RefX1<int>>>().ExceptionTest(true); break; case 35: cLabel++; new Gen<RefX1<RefX1<RefX1<string>>>>().ExceptionTest(true); break; case 36: cLabel++; new Gen<RefX1<RefX1<RefX1<RefX1<Guid>>>>>().ExceptionTest(true); break; case 37: cLabel++; new Gen<RefX1<RefX2<int, string>>>().ExceptionTest(true); break; case 38: cLabel++; new Gen<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>().ExceptionTest(true); break; case 39: cLabel++; new Gen<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>().ExceptionTest(true); break; case 40: cLabel++; new Gen<ValX1<int>>().ExceptionTest(true); break; case 41: cLabel++; new Gen<ValX1<RefX1<int>>>().ExceptionTest(true); break; case 42: cLabel++; new Gen<ValX2<int, string>>().ExceptionTest(true); break; case 43: cLabel++; new Gen<ValX3<int, string, Guid>>().ExceptionTest(true); break; case 44: cLabel++; new Gen<ValX1<ValX1<int>>>().ExceptionTest(true); break; case 45: cLabel++; new Gen<ValX1<ValX1<ValX1<string>>>>().ExceptionTest(true); break; case 46: cLabel++; new Gen<ValX1<ValX1<ValX1<ValX1<Guid>>>>>().ExceptionTest(true); break; case 47: cLabel++; new Gen<ValX1<ValX2<int, string>>>().ExceptionTest(true); break; case 48: cLabel++; new Gen<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>().ExceptionTest(true); break; case 49: cLabel++; new Gen<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>().ExceptionTest(true); break; } } catch (GenException<int>) { Eval(cLabel == 1); } catch (GenException<double>) { Eval(cLabel == 2); } catch (GenException<string>) { Eval(cLabel == 3); } catch (GenException<object>) { Eval(cLabel == 4); } catch (GenException<Guid>) { Eval(cLabel == 5); } catch (GenException<int[]>) { Eval(cLabel == 6); } catch (GenException<double[,]>) { Eval(cLabel == 7); } catch (GenException<string[][][]>) { Eval(cLabel == 8); } catch (GenException<object[, , ,]>) { Eval(cLabel == 9); } catch (GenException<Guid[][, , ,][]>) { Eval(cLabel == 10); } catch (GenException<RefX1<int>[]>) { Eval(cLabel == 11); } catch (GenException<RefX1<double>[,]>) { Eval(cLabel == 12); } catch (GenException<RefX1<string>[][][]>) { Eval(cLabel == 13); } catch (GenException<RefX1<object>[, , ,]>) { Eval(cLabel == 14); } catch (GenException<RefX1<Guid>[][, , ,][]>) { Eval(cLabel == 15); } catch (GenException<RefX2<int, int>[]>) { Eval(cLabel == 16); } catch (GenException<RefX2<double, double>[,]>) { Eval(cLabel == 17); } catch (GenException<RefX2<string, string>[][][]>) { Eval(cLabel == 18); } catch (GenException<RefX2<object, object>[, , ,]>) { Eval(cLabel == 19); } catch (GenException<RefX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 20); } catch (GenException<ValX1<int>[]>) { Eval(cLabel == 21); } catch (GenException<ValX1<double>[,]>) { Eval(cLabel == 22); } catch (GenException<ValX1<string>[][][]>) { Eval(cLabel == 23); } catch (GenException<ValX1<object>[, , ,]>) { Eval(cLabel == 24); } catch (GenException<ValX1<Guid>[][, , ,][]>) { Eval(cLabel == 25); } catch (GenException<ValX2<int, int>[]>) { Eval(cLabel == 26); } catch (GenException<ValX2<double, double>[,]>) { Eval(cLabel == 27); } catch (GenException<ValX2<string, string>[][][]>) { Eval(cLabel == 28); } catch (GenException<ValX2<object, object>[, , ,]>) { Eval(cLabel == 29); } catch (GenException<ValX2<Guid, Guid>[][, , ,][]>) { Eval(cLabel == 30); } catch (GenException<RefX1<int>>) { Eval(cLabel == 31); } catch (GenException<RefX1<ValX1<int>>>) { Eval(cLabel == 32); } catch (GenException<RefX2<int, string>>) { Eval(cLabel == 33); } catch (GenException<RefX3<int, string, Guid>>) { Eval(cLabel == 34); } catch (GenException<RefX1<RefX1<int>>>) { Eval(cLabel == 35); } catch (GenException<RefX1<RefX1<RefX1<string>>>>) { Eval(cLabel == 36); } catch (GenException<RefX1<RefX1<RefX1<RefX1<Guid>>>>>) { Eval(cLabel == 37); } catch (GenException<RefX1<RefX2<int, string>>>) { Eval(cLabel == 38); } catch (GenException<RefX2<RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>, RefX2<RefX1<int>, RefX3<int, string, RefX1<RefX2<int, string>>>>>>) { Eval(cLabel == 39); } catch (GenException<RefX3<RefX1<int[][, , ,]>, RefX2<object[, , ,][][], Guid[][][]>, RefX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 40); } catch (GenException<ValX1<int>>) { Eval(cLabel == 41); } catch (GenException<ValX1<RefX1<int>>>) { Eval(cLabel == 42); } catch (GenException<ValX2<int, string>>) { Eval(cLabel == 43); } catch (GenException<ValX3<int, string, Guid>>) { Eval(cLabel == 44); } catch (GenException<ValX1<ValX1<int>>>) { Eval(cLabel == 45); } catch (GenException<ValX1<ValX1<ValX1<string>>>>) { Eval(cLabel == 46); } catch (GenException<ValX1<ValX1<ValX1<ValX1<Guid>>>>>) { Eval(cLabel == 47); } catch (GenException<ValX1<ValX2<int, string>>>) { Eval(cLabel == 48); } catch (GenException<ValX2<ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>, ValX2<ValX1<int>, ValX3<int, string, ValX1<ValX2<int, string>>>>>>) { Eval(cLabel == 49); } catch (GenException<ValX3<ValX1<int[][, , ,]>, ValX2<object[, , ,][][], Guid[][][]>, ValX3<double[, , , , , , , , , ,], Guid[][][][, , , ,][, , , ,][][][], string[][][][][][][][][][][]>>>) { Eval(cLabel == 50); } } if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // Used when working with SSPI APIs, like SafeSspiAuthDataHandle(). Holds the pointer to the auth data blob. // #if DEBUG internal sealed class SafeSspiAuthDataHandle : DebugSafeHandle { #else internal sealed class SafeSspiAuthDataHandle : SafeHandleZeroOrMinusOneIsInvalid { #endif public SafeSspiAuthDataHandle() : base(true) { } protected override bool ReleaseHandle() { return Interop.Secur32.SspiFreeAuthIdentity(handle) == Interop.SecurityStatus.OK; } } // // A set of Safe Handles that depend on native FreeContextBuffer finalizer // #if DEBUG internal abstract class SafeFreeContextBuffer : DebugSafeHandle { #else internal abstract class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { #endif protected SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; SafeFreeContextBuffer_SECURITY pkgArray_SECURITY = null; res = Interop.Secur32.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0 && pkgArray != null) { pkgArray.SetHandleAsInvalid(); } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer_SECURITY(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public unsafe static int QueryContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle); } private unsafe static int QueryContextAttributes_SECURITY( SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { int status = (int)Interop.SecurityStatus.InvalidHandle; try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.Secur32.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } public static int SetContextAttributes( SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, byte[] buffer) { return SetContextAttributes_SECURITY(phContext, contextAttribute, buffer); } private static int SetContextAttributes_SECURITY( SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, byte[] buffer) { try { bool ignore = false; phContext.DangerousAddRef(ref ignore); return Interop.Secur32.SetContextAttributesW(ref phContext._handle, contextAttribute, buffer, buffer.Length); } finally { phContext.DangerousRelease(); } } } internal sealed class SafeFreeContextBuffer_SECURITY : SafeFreeContextBuffer { internal SafeFreeContextBuffer_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.Secur32.FreeContextBuffer(handle) == 0; } } // // Implementation of handles required CertFreeCertificateContext // #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { #endif internal SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file. internal void Set(IntPtr value) { this.handle = value; } private const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040; protected override bool ReleaseHandle() { Interop.Crypt32.CertFreeCertificateContext(handle); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal abstract class SafeFreeCredentials : DebugSafeHandle { #else internal abstract class SafeFreeCredentials : SafeHandle { #endif internal Interop.Secur32.SSPIHandle _handle; //should be always used as by ref in PInvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = new Interop.Secur32.SSPIHandle(); } #if TRACE_VERBOSE public override string ToString() { return "0x" + _handle.ToString(); } #endif public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } #if DEBUG public new IntPtr DangerousGetHandle() { Debug.Fail("This method should never be called for this type"); throw NotImplemented.ByDesign; } #endif #if false //TODO if not used in Nego Stream as well, please remove it. public unsafe static int AcquireCredentialsHandle( string package, Interop.Secur32.CredentialUse intent, ref Interop.Secur32.AuthIdentity authdata, out SafeFreeCredentials outCredential) { GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#1(" + package + ", " + intent + ", " + authdata + ")"); int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.Secur32.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x" + String.Format("{0:x}", errorCode) + ", handle = " + outCredential.ToString()); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public unsafe static int AcquireDefaultCredential( string package, Interop.Secur32.CredentialUse intent, out SafeFreeCredentials outCredential) { GlobalLog.Print("SafeFreeCredentials::AcquireDefaultCredential(" + package + ", " + intent + ")"); int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.Secur32.AcquireCredentialsHandleW( null, package, (int)intent, null, IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp); #if TRACE_VERBOSE GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x" + errorCode.ToString("x") + ", handle = " + outCredential.ToString()); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } public unsafe static int AcquireCredentialsHandle( string package, Interop.Secur32.CredentialUse intent, ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.Secur32.AcquireCredentialsHandleW( null, package, (int)intent, null, authdata, null, null, ref outCredential._handle, out timeStamp); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } #endif public unsafe static int AcquireCredentialsHandle( string package, Interop.Secur32.CredentialUse intent, ref Interop.Secur32.SecureCredential authdata, out SafeFreeCredentials outCredential) { GlobalLog.Print("SafeFreeCredentials::AcquireCredentialsHandle#2(" + package + ", " + intent + ", " + authdata + ")"); int errorCode = -1; long timeStamp; // If there is a certificate, wrap it into an array. // Not threadsafe. IntPtr copiedPtr = authdata.certContextArray; try { IntPtr certArrayPtr = new IntPtr(&copiedPtr); if (copiedPtr != IntPtr.Zero) { authdata.certContextArray = certArrayPtr; } outCredential = new SafeFreeCredential_SECURITY(); errorCode = Interop.Secur32.AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp); } finally { authdata.certContextArray = copiedPtr; } #if TRACE_VERBOSE GlobalLog.Print("Unmanaged::AcquireCredentialsHandle() returns 0x" + errorCode.ToString("x") + ", handle = " + outCredential.ToString()); #endif if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } return errorCode; } } // // This is a class holding a Credential handle reference, used for static handles cache // #if DEBUG internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid { #else internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid { #endif // // Static cache will return the target handle if found the reference in the table. // internal SafeFreeCredentials Target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) { return null; } return result; } private SafeCredentialReference(SafeFreeCredentials target) : base() { // Bumps up the refcount on Target to signify that target handle is statically cached so // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); Target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; if (target != null) { target.DangerousRelease(); } Target = null; return true; } } internal sealed class SafeFreeCredential_SECURITY : SafeFreeCredentials { public SafeFreeCredential_SECURITY() : base() { } protected override bool ReleaseHandle() { return Interop.Secur32.FreeCredentialsHandle(ref _handle) == 0; } } // // Implementation of handles that are dependent on DeleteSecurityContext // #if DEBUG internal abstract class SafeDeleteContext : DebugSafeHandle { #else internal abstract class SafeDeleteContext : SafeHandle { #endif private const string dummyStr = " "; private static readonly byte[] s_dummyBytes = new byte[] { 0 }; // // ATN: _handle is internal since it is used on PInvokes by other wrapper methods. // However all such wrappers MUST manually and reliably adjust refCounter of SafeDeleteContext handle. // internal Interop.Secur32.SSPIHandle _handle; protected SafeFreeCredentials _EffectiveCredential; protected SafeDeleteContext() : base(IntPtr.Zero, true) { _handle = new Interop.Secur32.SSPIHandle(); } public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } public override string ToString() { return _handle.ToString(); } #if DEBUG //This method should never be called for this type public new IntPtr DangerousGetHandle() { throw new InvalidOperationException(); } #endif //------------------------------------------------------------------- internal unsafe static int InitializeSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.Secur32.ContextFlags outFlags) { #if TRACE_VERBOSE GlobalLog.Enter("SafeDeleteContext::InitializeSecurityContext"); GlobalLog.Print(" credential = " + inCredentials.ToString()); GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext)); GlobalLog.Print(" targetName = " + targetName); GlobalLog.Print(" inFlags = " + inFlags); GlobalLog.Print(" reservedI = 0x0"); GlobalLog.Print(" endianness = " + endianness); if (inSecBuffers == null) { GlobalLog.Print(" inSecBuffers = (null)"); } else { GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); } #endif GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::InitializeSecurityContext()|outSecBuffer != null"); GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::InitializeSecurityContext()|inSecBuffer == null || inSecBuffers == null"); if (inCredentials == null) { throw new ArgumentNullException("inCredentials"); } Interop.Secur32.SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length); } Interop.Secur32.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.Secur32.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); Interop.Secur32.SecurityBufferStruct[] inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); #endif } } } Interop.Secur32.SecurityBufferStruct[] outUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } fixed (char* namePtr = targetName) { errorCode = MustRunInitializeSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, inSecurityBufferDescriptor, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); } GlobalLog.Print("SafeDeleteContext:InitializeSecurityContext Marshalling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } GlobalLog.Leave("SafeDeleteContext::InitializeSecurityContext() unmanaged InitializeSecurityContext()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext)); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, Interop.Secur32.SecurityBufferDescriptor inputBuffer, SafeDeleteContext outContext, Interop.Secur32.SecurityBufferDescriptor outputBuffer, ref Interop.Secur32.ContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SecurityStatus.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.Secur32.SSPIHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.Secur32.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.Secur32.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; } //------------------------------------------------------------------- internal unsafe static int AcceptSecurityContext( ref SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref Interop.Secur32.ContextFlags outFlags) { #if TRACE_VERBOSE GlobalLog.Enter("SafeDeleteContext::AcceptSecurityContex"); GlobalLog.Print(" credential = " + inCredentials.ToString()); GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext)); GlobalLog.Print(" inFlags = " + inFlags); if (inSecBuffers == null) { GlobalLog.Print(" inSecBuffers = (null)"); } else { GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); } #endif GlobalLog.Assert(outSecBuffer != null, "SafeDeleteContext::AcceptSecurityContext()|outSecBuffer != null"); GlobalLog.Assert(inSecBuffer == null || inSecBuffers == null, "SafeDeleteContext::AcceptSecurityContext()|inSecBuffer == null || inSecBuffers == null"); if (inCredentials == null) { throw new ArgumentNullException("inCredentials"); } Interop.Secur32.SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length); } Interop.Secur32.SecurityBufferDescriptor outSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(1); // Actually, this is returned in outFlags. bool isSspiAllocated = (inFlags & Interop.Secur32.ContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // Optional output buffer that may need to be freed. SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); var inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder. inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); #endif } } } var outUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder. outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } errorCode = MustRunAcceptSecurityContext_SECURITY( ref inCredentials, contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor, inFlags, endianness, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer); GlobalLog.Print("SafeDeleteContext:AcceptSecurityContext Marshalling OUT buffer"); // Get unmanaged buffer with index 0 as the only one passed into PInvoke. outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = new byte[outSecBuffer.size]; Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Dispose(); } } GlobalLog.Leave("SafeDeleteContext::AcceptSecurityContex() unmanaged AcceptSecurityContex()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext)); return errorCode; } // // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned. // private static unsafe int MustRunAcceptSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, Interop.Secur32.SecurityBufferDescriptor inputBuffer, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, SafeDeleteContext outContext, Interop.Secur32.SecurityBufferDescriptor outputBuffer, ref Interop.Secur32.ContextFlags outFlags, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SecurityStatus.InvalidHandle; // Run the body of this method as a non-interruptible block. try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.Secur32.SSPIHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.Secur32.AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, outputBuffer, ref outFlags, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle. if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes. handleTemplate.Set(((Interop.Secur32.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // An error on the first call, need to set the out handle to invalid value. outContext._handle.SetToInvalid(); } return errorCode; } internal unsafe static int CompleteAuthToken( ref SafeDeleteContext refContext, SecurityBuffer[] inSecBuffers) { GlobalLog.Enter("SafeDeleteContext::CompleteAuthToken"); GlobalLog.Print(" refContext = " + Logging.ObjectToString(refContext)); #if TRACE_VERBOSE GlobalLog.Print(" inSecBuffers[] = length:" + inSecBuffers.Length); #endif GlobalLog.Assert(inSecBuffers != null, "SafeDeleteContext::CompleteAuthToken()|inSecBuffers == null"); var inSecurityBufferDescriptor = new Interop.Secur32.SecurityBufferDescriptor(inSecBuffers.Length); int errorCode = (int)Interop.SecurityStatus.InvalidHandle; // These are pinned user byte arrays passed along with SecurityBuffers. GCHandle[] pinnedInBytes = null; var inUnmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers. inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffers[index]; if (securityBuffer != null) { inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // Use the unmanaged token if it's not null; otherwise use the managed buffer. if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } #if TRACE_VERBOSE GlobalLog.Print("SecBuffer: cbBuffer:" + securityBuffer.size + " BufferType:" + securityBuffer.type); #endif } } Interop.Secur32.SSPIHandle contextHandle = new Interop.Secur32.SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } try { if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext_SECURITY(); } try { bool ignore = false; refContext.DangerousAddRef(ref ignore); errorCode = Interop.Secur32.CompleteAuthToken(contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor); } finally { refContext.DangerousRelease(); } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } } } GlobalLog.Leave("SafeDeleteContext::CompleteAuthToken() unmanaged CompleteAuthToken()", "errorCode:0x" + errorCode.ToString("x8") + " refContext:" + Logging.ObjectToString(refContext)); return errorCode; } } internal sealed class SafeDeleteContext_SECURITY : SafeDeleteContext { internal SafeDeleteContext_SECURITY() : base() { } protected override bool ReleaseHandle() { if (this._EffectiveCredential != null) { this._EffectiveCredential.DangerousRelease(); } return Interop.Secur32.DeleteSecurityContext(ref _handle) == 0; } } // Based on SafeFreeContextBuffer. internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { private int _size; public override int Size { get { return _size; } } public override bool IsInvalid { get { return handle == new IntPtr(0) || handle == new IntPtr(-1); } } internal unsafe void Set(IntPtr value) { this.handle = value; } internal static SafeFreeContextBufferChannelBinding CreateEmptyHandle() { return new SafeFreeContextBufferChannelBinding_SECURITY(); } public unsafe static int QueryContextChannelBinding(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { return QueryContextChannelBinding_SECURITY(phContext, contextAttribute, buffer, refHandle); } private unsafe static int QueryContextChannelBinding_SECURITY(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, Bindings* buffer, SafeFreeContextBufferChannelBinding refHandle) { int status = (int)Interop.SecurityStatus.InvalidHandle; // SCHANNEL only supports SECPKG_ATTR_ENDPOINT_BINDINGS and SECPKG_ATTR_UNIQUE_BINDINGS which // map to our enum ChannelBindingKind.Endpoint and ChannelBindingKind.Unique. if (contextAttribute != Interop.Secur32.ContextAttribute.EndpointBindings && contextAttribute != Interop.Secur32.ContextAttribute.UniqueBindings) { return status; } try { bool ignore = false; phContext.DangerousAddRef(ref ignore); status = Interop.Secur32.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); } finally { phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { refHandle.Set((*buffer).pBindings); refHandle._size = (*buffer).BindingsLength; } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } return status; } } internal sealed class SafeFreeContextBufferChannelBinding_SECURITY : SafeFreeContextBufferChannelBinding { protected override bool ReleaseHandle() { return Interop.Secur32.FreeContextBuffer(handle) == 0; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using NUnit.Framework; using UnityEngine; using Object = UnityEngine.Object; using System.Text; using NUnit.Framework.Internal; using UnityEditor.ShaderGraph.Drawing; namespace UnityEditor.ShaderGraph.IntegrationTests { class ShaderGenerationTest { static readonly string s_Path = Path.Combine(Path.Combine(Path.Combine("" /*DefaultShaderIncludes.GetRepositoryPath()*/, "Testing"), "IntegrationTests"), "Graphs"); public struct TestInfo { public string name; public FileInfo info; public float threshold; public override string ToString() { return name; } } public static class CollectGraphs { public static IEnumerable graphs { get { var filePaths = Directory.GetFiles(s_Path, string.Format("*.{0}", ShaderGraphImporter.Extension), SearchOption.AllDirectories).Select(x => new FileInfo(x)); foreach (var p in filePaths) { var extension = Path.GetExtension(p.FullName); yield return new TestInfo { name = p.FullName.Replace(s_Path + Path.DirectorySeparatorChar, "").Replace(Path.DirectorySeparatorChar, '/').Replace(extension, ""), info = p, threshold = 0.05f }; } } } } private Shader m_Shader; private Material m_PreviewMaterial; private Texture2D m_Captured; private Texture2D m_FromDisk; [TearDown] public void CleanUp() { if (m_Shader != null) Object.DestroyImmediate(m_Shader); if (m_PreviewMaterial != null) Object.DestroyImmediate(m_PreviewMaterial); if (m_Captured != null) Object.DestroyImmediate(m_Captured); if (m_FromDisk != null) Object.DestroyImmediate(m_FromDisk); } // [Test, TestCaseSource(typeof(CollectGraphs), "graphs")] [Ignore("Not currently runable")] public void Graph(TestInfo testInfo) { var file = testInfo.info; var filePath = file.FullName; var textGraph = File.ReadAllText(filePath, Encoding.UTF8); var graph = JsonUtility.FromJson<GraphData>(textGraph); Assert.IsNotNull(graph.outputNode, "No master node in graph."); var rootPath = Path.Combine(Path.Combine("" /*DefaultShaderIncludes.GetRepositoryPath()*/, "Testing"), "IntegrationTests"); var shaderTemplatePath = Path.Combine(rootPath, ".ShaderTemplates"); var textTemplateFilePath = Path.Combine(shaderTemplatePath, string.Format("{0}.{1}", testInfo.name, "shader")); List<PropertyCollector.TextureInfo> configuredTextures = new List<PropertyCollector.TextureInfo>(); if (!File.Exists(textTemplateFilePath)) { Directory.CreateDirectory(Directory.GetParent(textTemplateFilePath).FullName); File.WriteAllText(textTemplateFilePath, ShaderGraphImporter.GetShaderText(filePath, out configuredTextures)); configuredTextures.Clear(); } // Generate the shader var shaderString = ShaderGraphImporter.GetShaderText(filePath, out configuredTextures); Directory.CreateDirectory(shaderTemplatePath); var textTemplate = File.ReadAllText(textTemplateFilePath); var textsAreEqual = string.Compare(shaderString, textTemplate, CultureInfo.CurrentCulture, CompareOptions.IgnoreSymbols); if (0 != textsAreEqual) { var failedPath = Path.Combine(rootPath, ".Failed"); var misMatchLocationResult = Path.Combine(failedPath, string.Format("{0}.{1}", testInfo.name, "shader")); var misMatchLocationTemplate = Path.Combine(failedPath, string.Format("{0}.template.{1}", testInfo.name, "shader")); Directory.CreateDirectory(Directory.GetParent(misMatchLocationResult).FullName); File.WriteAllText(misMatchLocationResult, shaderString); File.WriteAllText(misMatchLocationTemplate, textTemplate); Assert.Fail("Shader text from graph {0}, did not match .template file.", file); } m_Shader = ShaderUtil.CreateShaderAsset(shaderString); m_Shader.hideFlags = HideFlags.HideAndDontSave; Assert.IsNotNull(m_Shader, "Shader Generation Failed"); //Assert.IsFalse(AbstractMaterialNodeUI.ShaderHasError(m_Shader), "Shader has error"); m_PreviewMaterial = new Material(m_Shader) { hideFlags = HideFlags.HideAndDontSave }; foreach (var textureInfo in configuredTextures) { var texture = EditorUtility.InstanceIDToObject(textureInfo.textureId) as Texture; if (texture == null) continue; m_PreviewMaterial.SetTexture(textureInfo.name, texture); } Assert.IsNotNull(m_PreviewMaterial, "preview material could not be created"); const int res = 256; using (var generator = new MaterialGraphPreviewGenerator()) { var renderTexture = new RenderTexture(res, res, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }; generator.DoRenderPreview(renderTexture, m_PreviewMaterial, null, PreviewMode.Preview3D, true, 10); Assert.IsNotNull(renderTexture, "Render failed"); RenderTexture.active = renderTexture; m_Captured = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false); m_Captured.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); RenderTexture.active = null; //can help avoid errors Object.DestroyImmediate(renderTexture, true); // find the reference image var dumpFileLocation = Path.Combine(shaderTemplatePath, string.Format("{0}.{1}", testInfo.name, "png")); if (!File.Exists(dumpFileLocation)) { Directory.CreateDirectory(Directory.GetParent(dumpFileLocation).FullName); // no reference exists, create it var generated = m_Captured.EncodeToPNG(); File.WriteAllBytes(dumpFileLocation, generated); Assert.Fail("Image template file not found for {0}, creating it.", file); } var template = File.ReadAllBytes(dumpFileLocation); m_FromDisk = new Texture2D(2, 2); m_FromDisk.LoadImage(template, false); var rmse = CompareTextures(m_FromDisk, m_Captured); if (rmse > testInfo.threshold) { var failedPath = Path.Combine(rootPath, ".Failed"); var misMatchLocationResult = Path.Combine(failedPath, string.Format("{0}.{1}", testInfo.name, "png")); var misMatchLocationTemplate = Path.Combine(failedPath, string.Format("{0}.template.{1}", testInfo.name, "png")); var generated = m_Captured.EncodeToPNG(); Directory.CreateDirectory(Directory.GetParent(misMatchLocationResult).FullName); File.WriteAllBytes(misMatchLocationResult, generated); File.WriteAllBytes(misMatchLocationTemplate, template); Assert.Fail("Shader image from graph {0}, did not match .template file.", file); } } } // compare textures, use RMS for this private float CompareTextures(Texture2D fromDisk, Texture2D captured) { if (fromDisk == null || captured == null) return 1f; if (fromDisk.width != captured.width || fromDisk.height != captured.height) return 1f; var pixels1 = fromDisk.GetPixels(); var pixels2 = captured.GetPixels(); if (pixels1.Length != pixels2.Length) return 1f; int numberOfPixels = pixels1.Length; float sumOfSquaredColorDistances = 0; for (int i = 0; i < numberOfPixels; i++) { Color p1 = pixels1[i]; Color p2 = pixels2[i]; Color diff = p1 - p2; diff = diff * diff; sumOfSquaredColorDistances += (diff.r + diff.g + diff.b) / 3.0f; } float rmse = Mathf.Sqrt(sumOfSquaredColorDistances / numberOfPixels); return rmse; } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections.Generic; namespace Leap.Unity.Query { public partial struct QueryWrapper<QueryType, QueryOp> where QueryOp : IQueryOp<QueryType> { /// <summary> /// Returns true if all elements in the sequence satisfy the predicate. /// </summary> public bool All(Func<QueryType, bool> predicate) { var op = _op; QueryType obj; while (op.TryGetNext(out obj)) { if (!predicate(obj)) { return false; } } return true; } /// <summary> /// Returns true if all elements in the sequence are equal to the same value. /// Will always return true for sequences with one or zero elements. /// </summary> public bool AllEqual() { var op = _op; QueryType a; if (!op.TryGetNext(out a)) { return true; } QueryType b; while (op.TryGetNext(out b)) { if ((a == null) != (b == null)) { return false; } if (a == null && b == null) { continue; } if (!a.Equals(b)) { return false; } } return true; } /// <summary> /// Returns true if the sequence has any elements in it. /// </summary> public bool Any() { var op = _op; QueryType obj; return op.TryGetNext(out obj); } /// <summary> /// Returns true if any elements in the sequence satisfy the predicate. /// </summary> public bool Any(Func<QueryType, bool> predicate) { return Where(predicate).Any(); } /// <summary> /// Returns true if any element in the sequence is equal to a specific value. /// </summary> public bool Contains(QueryType instance) { var op = _op; QueryType obj; while (op.TryGetNext(out obj)) { if (obj.Equals(instance)) { return true; } } return false; } /// <summary> /// Returns the number of elements in the sequence. /// </summary> public int Count() { var op = _op; QueryType obj; int count = 0; while (op.TryGetNext(out obj)) { count++; } return count; } /// <summary> /// Returns the number of elements in the sequence that satisfy a predicate. /// </summary> public int Count(Func<QueryType, bool> predicate) { return Where(predicate).Count(); } /// <summary> /// Returns the element at a specific index in the sequence. Will throw an error /// if the sequence has no element at that index. /// </summary> public QueryType ElementAt(int index) { return Skip(index).First(); } /// <summary> /// Returns the element at a specific index in the sequence. Will return /// the default value if the sequence has no element at that index. /// </summary> public QueryType ElementAtOrDefault(int index) { return Skip(index).FirstOrDefault(); } /// <summary> /// Returns the first element in the sequence. Will throw an error if there are /// no elements in the sequence. /// </summary> public QueryType First() { var op = _op; QueryType obj; if (!op.TryGetNext(out obj)) { throw new InvalidOperationException("The source query is empty."); } return obj; } /// <summary> /// Returns the first element in the sequence that satisfies a predicate. Will /// throw an error if there is no such element. /// </summary> public QueryType First(Func<QueryType, bool> predicate) { return Where(predicate).First(); } /// <summary> /// Returns the first element in the sequence. Will return the default value /// if the sequence is empty. /// </summary> public QueryType FirstOrDefault() { var op = _op; QueryType obj; op.TryGetNext(out obj); return obj; } /// <summary> /// Returns the first element in the sequence that satisfies a predicate. Will return /// the default value if there is no such element. /// </summary> public QueryType FirstOrDefault(Func<QueryType, bool> predicate) { return Where(predicate).FirstOrDefault(); } /// <summary> /// Folds all of the elements in the sequence into a single element, using a fold function. /// Will throw an error if there are no elements in the sequence. /// /// The fold function takes in the current folded value, and the next item to fold in. /// It returns the result of folding the item into the current folded value. For example, /// you can use the Fold operation to implement a sum: /// /// var sum = numbers.Query().Fold((a,b) => a + b); /// </summary> public QueryType Fold(Func<QueryType, QueryType, QueryType> foldFunc) { var op = _op; QueryType value; if (!op.TryGetNext(out value)) { throw new InvalidOperationException(); } QueryType next; while (op.TryGetNext(out next)) { value = foldFunc(value, next); } return value; } /// <summary> /// Returns the index of the first element that is equal to a specific value. Will return /// a negative index if there is no such element. /// </summary> public int IndexOf(QueryType value) { var op = _op; QueryType obj; int index = 0; while (op.TryGetNext(out obj)) { if (obj.Equals(value)) { return index; } index++; } return -1; } /// <summary> /// Returns the index of the first element to satisfy a predicate. Will return a negative /// index if there is no such element. /// </summary> public int IndexOf(Func<QueryType, bool> predicate) { var op = _op; QueryType obj; int index = 0; while (op.TryGetNext(out obj)) { if (predicate(obj)) { return index; } index++; } return -1; } /// <summary> /// Returns the last element in the sequence. Will throw an error if the sequence is empty. /// </summary> public QueryType Last() { var op = _op; QueryType obj, temp; if (!op.TryGetNext(out obj)) { throw new InvalidOperationException("The source query is empty!"); } while (op.TryGetNext(out temp)) { obj = temp; } return obj; } /// <summary> /// Returns the last element in the sequence that satisfies a predicate. Will throw an error /// if there is no such element. /// </summary> public QueryType Last(Func<QueryType, bool> predicate) { return Where(predicate).Last(); } /// <summary> /// Returns the last element in the sequence. Will return the default value if the sequence is empty. /// </summary> public QueryType LastOrDefault() { var op = _op; QueryType obj = default(QueryType); while (op.TryGetNext(out obj)) { } return obj; } /// <summary> /// Returns the last element in the sequence that satisfies a predicate. Will return the default /// value if there is no such element. /// </summary> public QueryType LastOrDefault(Func<QueryType, bool> predicate) { return Where(predicate).LastOrDefault(); } /// <summary> /// Returns the first and only element in the sequence. Will throw an error if the length of the /// sequence is anything other than 1. /// </summary> public QueryType Single() { var op = _op; QueryType obj; if (!op.TryGetNext(out obj)) { throw new InvalidOperationException("The source query is empty!"); } QueryType dummy; if (op.TryGetNext(out dummy)) { throw new InvalidOperationException("The source query had more than a single elemeny!"); } return obj; } /// <summary> /// Returns the first and only element in the sequence that satisfies the predicate. Will throw /// an error if the number of such elements is anything other than 1. /// </summary> public QueryType Single(Func<QueryType, bool> predicate) { return Where(predicate).Single(); } private static List<QueryType> _utilityList = new List<QueryType>(); /// <summary> /// Converts the sequence into an array. /// </summary> public QueryType[] ToArray() { try { AppendList(_utilityList); return _utilityList.ToArray(); } finally { _utilityList.Clear(); } } /// <summary> /// Copies the elements of the sequence into an array. Can optionally specify the offset into the array /// where to copy. /// </summary> public void FillArray(QueryType[] array, int offset = 0) { var op = _op; QueryType obj; while (op.TryGetNext(out obj)) { array[offset++] = obj; } } /// <summary> /// Converts the sequence into a list. /// </summary> public List<QueryType> ToList() { List<QueryType> list = new List<QueryType>(); AppendList(list); return list; } /// <summary> /// Fills a given list with the elements in this sequence. The list is cleared before the fill happens. /// </summary> public void FillList(List<QueryType> list) { list.Clear(); AppendList(list); } /// <summary> /// Appends the elements in this sequence to the end of a given list. /// </summary> public void AppendList(List<QueryType> list) { var op = _op; QueryType obj; while (op.TryGetNext(out obj)) { list.Add(obj); } } public void FillHashSet(HashSet<QueryType> hashSet) { hashSet.Clear(); AppendHashSet(hashSet); } public void AppendHashSet(HashSet<QueryType> hashSet) { var op = _op; QueryType obj; while (op.TryGetNext(out obj)) { hashSet.Add(obj); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class UnaryArithmeticNegateCheckedNullableTests { #region Test methods [Fact] public static void CheckUnaryArithmeticNegateCheckedNullableByteTest() { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableByte(values[i]); } } [Fact] public static void CheckUnaryArithmeticNegateCheckedNullableCharTest() { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableChar(values[i]); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryArithmeticNegateCheckedNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableDecimal(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryArithmeticNegateCheckedNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableDouble(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryArithmeticNegateCheckedNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableFloat(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryArithmeticNegateCheckedNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryArithmeticNegateCheckedNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableLong(values[i], useInterpreter); } } [Fact] public static void CheckUnaryArithmeticNegateCheckedNullableSByteTest() { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableSByte(values[i]); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryArithmeticNegateCheckedNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyArithmeticNegateCheckedNullableShort(values[i], useInterpreter); } } #endregion #region Test verifiers private static void VerifyArithmeticNegateCheckedNullableByte(byte? value) { Assert.Throws<InvalidOperationException>(() => Expression.NegateChecked(Expression.Constant(value, typeof(byte?)))); } private static void VerifyArithmeticNegateCheckedNullableChar(char? value) { Assert.Throws<InvalidOperationException>(() => Expression.NegateChecked(Expression.Constant(value, typeof(char?)))); } private static void VerifyArithmeticNegateCheckedNullableDecimal(decimal? value, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.NegateChecked(Expression.Constant(value, typeof(decimal?))), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f = e.Compile(useInterpreter); Assert.Equal(-value, f()); } private static void VerifyArithmeticNegateCheckedNullableDouble(double? value, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.NegateChecked(Expression.Constant(value, typeof(double?))), Enumerable.Empty<ParameterExpression>()); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(-value, f()); } private static void VerifyArithmeticNegateCheckedNullableFloat(float? value, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.NegateChecked(Expression.Constant(value, typeof(float?))), Enumerable.Empty<ParameterExpression>()); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(-value, f()); } private static void VerifyArithmeticNegateCheckedNullableInt(int? value, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.NegateChecked(Expression.Constant(value, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); if (value == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(-value, f()); } private static void VerifyArithmeticNegateCheckedNullableLong(long? value, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.NegateChecked(Expression.Constant(value, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); if (value == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(-value, f()); } private static void VerifyArithmeticNegateCheckedNullableSByte(sbyte? value) { Assert.Throws<InvalidOperationException>(() => Expression.NegateChecked(Expression.Constant(value, typeof(sbyte?)))); } private static void VerifyArithmeticNegateCheckedNullableShort(short? value, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.NegateChecked(Expression.Constant(value, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); if (value == short.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(-value, f()); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Recognizers.Text.DataTypes.TimexExpression.Tests { [TestClass] public class TestTimexParsing { [TestMethod] public void DataTypes_Parsing_CompleteDate() { var timex = new TimexProperty("2017-05-29"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Definite, Constants.TimexTypes.Date }, timex.Types.ToList()); Assert.AreEqual(2017, timex.Year); Assert.AreEqual(5, timex.Month); Assert.AreEqual(29, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_MonthAndDayOfMonth() { var timex = new TimexProperty("XXXX-12-05"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.AreEqual(12, timex.Month); Assert.AreEqual(5, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DayOfWeek() { var timex = new TimexProperty("XXXX-WXX-3"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.AreEqual(timex.DayOfWeek, 3); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_HoursMinutesAndSeconds() { var timex = new TimexProperty("T17:30:05"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Time }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(17, timex.Hour); Assert.AreEqual(30, timex.Minute); Assert.AreEqual(5, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_HoursAndMinutes() { var timex = new TimexProperty("T17:30"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Time }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(17, timex.Hour); Assert.AreEqual(30, timex.Minute); Assert.AreEqual(0, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Hours() { var timex = new TimexProperty("T17"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Time }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(17, timex.Hour); Assert.AreEqual(0, timex.Minute); Assert.AreEqual(0, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Now() { var timex = new TimexProperty("PRESENT_REF"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Present, Constants.TimexTypes.Date, Constants.TimexTypes.Time, Constants.TimexTypes.DateTime }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.AreEqual(true, timex.Now); } [TestMethod] public void DataTypes_Parsing_FullDatetime() { var timex = new TimexProperty("1984-01-03T18:30:45"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Definite, Constants.TimexTypes.Date, Constants.TimexTypes.Time, Constants.TimexTypes.DateTime }, timex.Types.ToList()); Assert.AreEqual(1984, timex.Year); Assert.AreEqual(1, timex.Month); Assert.AreEqual(3, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(18, timex.Hour); Assert.AreEqual(30, timex.Minute); Assert.AreEqual(45, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_ParicularTimeOnParticularDayOfWeek() { var timex = new TimexProperty("XXXX-WXX-3T16"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Time, Constants.TimexTypes.Date, Constants.TimexTypes.DateTime }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.AreEqual(3, timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(16, timex.Hour); Assert.AreEqual(0, timex.Minute); Assert.AreEqual(0, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Year() { var timex = new TimexProperty("2016"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.AreEqual(2016, timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_SummerOf1999() { var timex = new TimexProperty("1999-SU"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.AreEqual(1999, timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.AreEqual("SU", timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_YearAndWeek() { var timex = new TimexProperty("2017-W37"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.AreEqual(2017, timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.AreEqual(37, timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_SeasonSummer() { var timex = new TimexProperty("SU"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.AreEqual("SU", timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_SeasonWinter() { var timex = new TimexProperty("WI"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.AreEqual("WI", timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_YearAndWeekend() { var timex = new TimexProperty("2017-W37-WE"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.AreEqual(2017, timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.AreEqual(37, timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.AreEqual(true, timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_May() { var timex = new TimexProperty("XXXX-05"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.AreEqual(5, timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_July2020() { var timex = new TimexProperty("2020-07"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.AreEqual(2020, timex.Year); Assert.AreEqual(7, timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_WeekOfMonth() { var timex = new TimexProperty("XXXX-01-W01"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.AreEqual(1, timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.AreEqual(1, timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_WednesdayToSaturday() { var timex = new TimexProperty("(XXXX-WXX-3,XXXX-WXX-6,P3D)"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date, Constants.TimexTypes.Duration, Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.AreEqual(3, timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.AreEqual(3, timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Jan1ToAug5() { var timex = new TimexProperty("(XXXX-01-01,XXXX-08-05,P216D)"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date, Constants.TimexTypes.Duration, Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.AreEqual(1, timex.Month); Assert.AreEqual(1, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.AreEqual(216, timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Jan1ToAug5Year2015() { var timex = new TimexProperty("(2015-01-01,2015-08-05,P216D)"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Definite, Constants.TimexTypes.Date, Constants.TimexTypes.Duration, Constants.TimexTypes.DateRange }, timex.Types.ToList()); Assert.AreEqual(2015, timex.Year); Assert.AreEqual(1, timex.Month); Assert.AreEqual(1, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.AreEqual(216, timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DayTime() { var timex = new TimexProperty("TDT"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.TimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("DT", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_NightTime() { var timex = new TimexProperty("TNI"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.TimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("NI", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Morning() { var timex = new TimexProperty("TMO"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.TimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("MO", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Afternoon() { var timex = new TimexProperty("TAF"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.TimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("AF", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Evening() { var timex = new TimexProperty("TEV"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.TimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("EV", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Timerange430pmTo445pm() { var timex = new TimexProperty("(T16:30,T16:45,PT15M)"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Time, Constants.TimexTypes.Duration, Constants.TimexTypes.TimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(16, timex.Hour); Assert.AreEqual(30, timex.Minute); Assert.AreEqual(0, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.AreEqual(15, timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DateTimeRange() { var timex = new TimexProperty("XXXX-WXX-5TEV"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date, Constants.TimexTypes.TimeRange, Constants.TimexTypes.DateTimeRange }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.AreEqual(5, timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("EV", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_LastNight() { var timex = new TimexProperty("2017-09-07TNI"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Definite, Constants.TimexTypes.Date, Constants.TimexTypes.TimeRange, Constants.TimexTypes.DateTimeRange }, timex.Types.ToList()); Assert.AreEqual(2017, timex.Year); Assert.AreEqual(9, timex.Month); Assert.AreEqual(7, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.AreEqual("NI", timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Last5Minutes() { var timex = new TimexProperty("(2017-09-08T21:19:29,2017-09-08T21:24:29,PT5M)"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date, Constants.TimexTypes.TimeRange, Constants.TimexTypes.DateTimeRange, Constants.TimexTypes.Time, Constants.TimexTypes.DateTime, Constants.TimexTypes.Duration, Constants.TimexTypes.DateRange, Constants.TimexTypes.Definite }, timex.Types.ToList()); Assert.AreEqual(2017, timex.Year); Assert.AreEqual(9, timex.Month); Assert.AreEqual(8, timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(21, timex.Hour); Assert.AreEqual(19, timex.Minute); Assert.AreEqual(29, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.AreEqual(5, timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_Wed4PMToSat3PM() { var timex = new TimexProperty("(XXXX-WXX-3T16,XXXX-WXX-6T15,PT71H)"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Date, Constants.TimexTypes.TimeRange, Constants.TimexTypes.DateTimeRange, Constants.TimexTypes.Time, Constants.TimexTypes.DateTime, Constants.TimexTypes.Duration, Constants.TimexTypes.DateRange, }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.AreEqual(3, timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.AreEqual(16, timex.Hour); Assert.AreEqual(0, timex.Minute); Assert.AreEqual(0, timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.AreEqual(71, timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationYears() { var timex = new TimexProperty("P2Y"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.AreEqual(2, timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationMonths() { var timex = new TimexProperty("P4M"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.AreEqual(4, timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationWeeks() { var timex = new TimexProperty("P6W"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.AreEqual(6, timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationWeeksFloatingPoint() { var timex = new TimexProperty("P2.5W"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.AreEqual(2.5m, timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationDays() { var timex = new TimexProperty("P1D"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.AreEqual(1, timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationHours() { var timex = new TimexProperty("PT5H"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.AreEqual(5, timex.Hours); Assert.IsNull(timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationMinutes() { var timex = new TimexProperty("PT30M"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.AreEqual(30, timex.Minutes); Assert.IsNull(timex.Seconds); Assert.IsNull(timex.Now); } [TestMethod] public void DataTypes_Parsing_DurationSeconds() { var timex = new TimexProperty("PT45S"); CollectionAssert.AreEquivalent(new[] { Constants.TimexTypes.Duration }, timex.Types.ToList()); Assert.IsNull(timex.Year); Assert.IsNull(timex.Month); Assert.IsNull(timex.DayOfMonth); Assert.IsNull(timex.DayOfWeek); Assert.IsNull(timex.WeekOfYear); Assert.IsNull(timex.WeekOfMonth); Assert.IsNull(timex.Season); Assert.IsNull(timex.Hour); Assert.IsNull(timex.Minute); Assert.IsNull(timex.Second); Assert.IsNull(timex.Weekend); Assert.IsNull(timex.PartOfDay); Assert.IsNull(timex.Years); Assert.IsNull(timex.Months); Assert.IsNull(timex.Weeks); Assert.IsNull(timex.Days); Assert.IsNull(timex.Hours); Assert.IsNull(timex.Minutes); Assert.AreEqual(45, timex.Seconds); Assert.IsNull(timex.Now); } } }
using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; namespace ModernRonin.PraeterArtem.Functional { /// <summary>Contains extension methods for <see cref="IEnumerable{T}"/> /// supporting a functional coding style.</summary> public static class EnumerableExtensions { /// <summary>More readable replacement for !Any{T}.</summary> public static bool IsEmpty<T>( [NotNull] this IEnumerable<T> enumerable) { return !enumerable.Any(); } /// <summary>Passes each argument of <paramref name="enumerable"/> to /// <paramref name="action"/>.</summary> public static void UseIn<T>([NotNull] this IEnumerable<T> enumerable, [NotNull] Action<T> action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (action == null) throw new ArgumentNullException("action"); foreach (var element in enumerable) action(element); } /// <summary> /// Calls each action contained in <paramref name="actions"/> with the /// argument <paramref name="argument"/> /// </summary> /// <typeparam name="T"></typeparam> public static void ExecuteOn<T>( [NotNull] this IEnumerable<Action<T>> actions, T argument) { if (actions == null) throw new ArgumentNullException("actions"); actions.UseIn(a => a(argument)); } /// <summary> /// Allows to easily pass single elements into functions expecting an /// IEnumerable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="element"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> ToEnumerable<T>(this T element) { if (element is IEnumerable<T>) return CastToEnumerable(element); return WrapAsEnumerable(element); } [NotNull] static IEnumerable<T> CastToEnumerable<T>(T singleElement) { return (IEnumerable<T>) singleElement; } [NotNull] static IEnumerable<T> WrapAsEnumerable<T>(T singleElement) { yield return singleElement; } /// <summary>Adds all element to <paramref name="destination"/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="destination"></param> public static void AddTo<T>([NotNull] this IEnumerable<T> enumerable, [NotNull] ICollection<T> destination) { enumerable.UseIn(destination.Add); } /// <summary>Returns all elements which are not null.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> ExceptNullValues<T>( [NotNull] this IEnumerable<T> enumerable) where T : class { return enumerable.Where(e => null != e); } /// <summary>Returns all elements except the first.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> ButFirst<T>( [NotNull] this IEnumerable<T> enumerable) { return enumerable.Skip(1); } /// <summary>Returns all elements except the last.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> ButLast<T>( [NotNull] this IEnumerable<T> enumerable) { var enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) yield break; var first = enumerator.Current; while (enumerator.MoveNext()) { yield return first; first = enumerator.Current; } } /// <summary>Returns all elements of <paramref name="enumerable"/> except /// <paramref name="value"/>/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="value"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> Except<T>( [NotNull] this IEnumerable<T> enumerable, T value) { return enumerable.Except(value.ToEnumerable()); } /// <summary>Returns all elements of <paramref name="enumerable"/> /// which are greater than <paramref name="limit"/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="limit"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> GreaterThan<T>( [NotNull] this IEnumerable<T> enumerable, T limit) where T : IComparable<T> { return enumerable.Where(e => 0 < e.CompareTo(limit)); } /// <summary>Returns all elements of <paramref name="enumerable"/> /// which are greater than or equal to <paramref name="limit"/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="limit"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> GreaterThanOrEqualTo<T>( [NotNull] this IEnumerable<T> enumerable, T limit) where T : IComparable<T> { return enumerable.Where(e => 0 <= e.CompareTo(limit)); } /// <summary>Returns all elements of <paramref name="enumerable"/> /// which are smaller than <paramref name="limit"/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="limit"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> SmallerThan<T>( [NotNull] this IEnumerable<T> enumerable, T limit) where T : IComparable<T> { return enumerable.Where(e => 0 > e.CompareTo(limit)); } /// <summary>Returns all elements of <paramref name="enumerable"/> /// which are smaller than or equal to<paramref name="limit"/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="limit"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> SmallerThanOrEqualTo<T>( [NotNull] this IEnumerable<T> enumerable, T limit) where T : IComparable<T> { return enumerable.Where(e => 0 >= e.CompareTo(limit)); } /// <summary> /// Returns all elements of <paramref name="enumerable"/> which are /// equal to <paramref name="check"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="check"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> EqualTo<T>( [NotNull] this IEnumerable<T> enumerable, T check) { return enumerable.Where(e => e.Equals(check)); } /// <summary>Returns all elements of <paramref name="enumerable"/> /// which are reference-equal to <paramref name="check"/>.</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="check"></param> /// <returns></returns> [NotNull] public static IEnumerable<T> SameAs<T>( [NotNull] this IEnumerable<T> enumerable, T check) { return enumerable.Where(e => ReferenceEquals(e, check)); } /// <summary> /// Returns the element of <paramref name="enumerable"/> /// with the smallest evaluation when passed to <paramref name="evaluator"/>. /// (In contrast to the BCL .Min() method which returns the minimal value, not /// the minimal element.) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="evaluator"></param> /// <returns></returns> public static T MinElement<T>( [NotNull] this IEnumerable<T> enumerable, [NotNull] Func<T, int> evaluator) { if (enumerable == null) throw new ArgumentNullException("enumerable"); if (evaluator == null) throw new ArgumentNullException("evaluator"); var minimumScore = Int32.MaxValue; var result = default(T); foreach (var element in enumerable) { var score = evaluator(element); if (score <= minimumScore) { minimumScore = score; result = element; } } return result; } /// <summary> /// Returns the element of <paramref name="enumerable"/> /// with the greatest evaluation when passed to <paramref name="evaluator"/>. /// (In contrast to the BCL .Max() method which returns the minimal value, not /// the minimal element.) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="evaluator"></param> /// <returns></returns> public static T MaxElement<T>( [NotNull] this IEnumerable<T> enumerable, [NotNull] Func<T, int> evaluator) { return enumerable.MinElement(e => -evaluator(e)); } /// <summary> /// Overload for the BCL .Min() method which allows to pass a value to /// be used in case /// <paramref name="enumerable"/> is empty. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="valueToReturnIfEmpty"></param> /// <returns></returns> public static T Min<T>([NotNull] this IEnumerable<T> enumerable, T valueToReturnIfEmpty) where T : IComparable<T> { var frozen = enumerable as T[] ?? enumerable.ToArray(); return frozen.Any() ? frozen.Min() : valueToReturnIfEmpty; } /// <summary> /// Overload for the BCL .Max() method which allows to pass a value to /// be used in case /// <paramref name="enumerable"/> is empty. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="valueToReturnIfEmpty"></param> /// <returns></returns> public static T Max<T>([NotNull] this IEnumerable<T> enumerable, T valueToReturnIfEmpty) where T : IComparable<T> { var frozen = enumerable as T[] ?? enumerable.ToArray(); return frozen.Any() ? frozen.Max() : valueToReturnIfEmpty; } /// <summary> /// Splits the enumerable into multiple enumerables of size /// <paramref name="chunkSize"/>. Note that the last chunk may contain fewer /// items. /// <example> /// new []{1,2,3,4,5,6,7,8,9, 0}.Chunk(3) will result in 3 chunks with /// 3 elements and a fourth chunk with only one element /// </example> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <param name="chunkSize"></param> /// <returns></returns> public static IEnumerable<IEnumerable<T>> Split<T>( this IEnumerable<T> enumerable, int chunkSize) { for (var rest = enumerable.ToArray(); !rest.IsEmpty(); rest = rest.Skip(chunkSize).ToArray()) yield return rest.Take(chunkSize); } /// <summary>Returns an enumeration of all elements .ToString().</summary> /// <typeparam name="T"></typeparam> /// <param name="enumerable"></param> /// <returns></returns> public static IEnumerable<string> ToStrings<T>( this IEnumerable<T> enumerable) { return enumerable.Select(e => e.ToString()); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; protected bool indentCaretOnCommit; protected int indentDepth; protected bool earlyEndExpansionHappened; internal IVsExpansionSession ExpansionSession; public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc); protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken); public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } SnapshotSpan snippetSpan; if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. AddReferencesAndImports(ExpansionSession, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan endTrackingSpan) { if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { SnapshotSpan endSpanInSurfaceBuffer; if (!TryGetSpanOnHigherBuffer( endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), TextView.TextBuffer, out endSpanInSurfaceBuffer)) { return; } int endLine, endColumn; TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endColumn, iEndLine = endLine, iEndIndex = endColumn }); } } private void CleanUpEndLocation(ITrackingSpan endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { indentCaretOnCommit = true; var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var tabSize = document.Options.GetOption(FormattingOptions.TabSize); indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize); } else { // If we don't have a document, then just guess the typical default TabSize value. indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4); } SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode) { IXMLDOMNode xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; IntPtr pNode; if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string endLineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out endLineText); int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); PositionCaretForEditingInternal(endLineText, endLinePosition); return VSConstants.S_OK; } /// <summary> /// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/> /// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>. /// Tests can call this method directly to avoid producing an IVsTextLines. /// </summary> /// <param name="endLineText"></param> /// <param name="endLinePosition"></param> internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition) { if (indentCaretOnCommit && endLineText == string.Empty) { TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth)); } } public virtual bool TryHandleTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; return true; } return false; } public virtual bool TryHandleReturn() { if (ExpansionSession != null) { // Only move the caret if the enter was hit within the snippet fields. var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0); ExpansionSession.EndCurrentExpansion(fLeaveCaret: hitWithinField ? 0 : 1); ExpansionSession = null; return hitWithinField; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return false; } int startLine = 0; int startIndex = 0; int endLine = 0; int endIndex = 0; // The expansion itself needs to be created in the data buffer, so map everything up var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer); var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer); SnapshotSpan dataBufferSpan; if (!TryGetSpanOnHigherBuffer( SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer), textViewModel.DataBuffer, out dataBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer); var expansion = buffer as IVsExpansion; if (buffer == null || expansion == null) { return false; } buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out startLine, out startIndex); buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out endLine, out endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK; } public int EndExpansion() { if (ExpansionSession == null) { earlyEndExpansionHappened = true; } ExpansionSession = null; indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); this.ExpansionSession = pSession; return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var textViewModel = TextView.TextViewModel; if (textViewModel == null) { Debug.Assert(TextView.IsClosed); return VSConstants.E_FAIL; } var hr = VSConstants.S_OK; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer) as IVsExpansion; earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession); if (earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. ExpansionSession = null; earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); IVsTextLines textLines; vsTextView.GetBuffer(out textLines); // Handle virtual space (e.g, see Dev10 778675) int lineLength; textLines.GetLengthOfLine(caretLine, out lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var placeSystemNamespaceFirst = documentWithImports.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst); documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (string.IsNullOrEmpty(assemblyName)) { continue; } if (visualStudioWorkspace == null || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine) + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, failedReferenceAdditions), severity: NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (vsWorkspace == null) { return false; } var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument; if (containedDocument == null) { return false; } var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal; if (containedLanguageHost != null) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default(SnapshotSpan); return false; } internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span) { var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer); // Bail if a snippet span does not map up to exactly one span. if (spanCollection.Count == 1) { span = spanCollection.Single(); return true; } span = default(SnapshotSpan); return false; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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.Internal.NetworkSenders { using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using NLog.Common; /// <summary> /// A base class for all network senders. Supports one-way sending of messages /// over various protocols. /// </summary> internal abstract class NetworkSender : IDisposable { private static int currentSendTime; /// <summary> /// Initializes a new instance of the <see cref="NetworkSender" /> class. /// </summary> /// <param name="url">The network URL.</param> protected NetworkSender(string url) { Address = url; LastSendTime = Interlocked.Increment(ref currentSendTime); } /// <summary> /// Gets the address of the network endpoint. /// </summary> public string Address { get; private set; } /// <summary> /// Gets the last send time. /// </summary> public int LastSendTime { get; private set; } /// <summary> /// Initializes this network sender. /// </summary> public void Initialize() { DoInitialize(); } /// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> /// <param name="continuation">The continuation.</param> public void Close(AsyncContinuation continuation) { DoClose(continuation); } /// <summary> /// Flushes any pending messages and invokes a continuation. /// </summary> /// <param name="continuation">The continuation.</param> public void FlushAsync(AsyncContinuation continuation) { DoFlush(continuation); } /// <summary> /// Send the given text over the specified protocol. /// </summary> /// <param name="bytes">Bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Send(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation) { try { LastSendTime = Interlocked.Increment(ref currentSendTime); DoSend(bytes, offset, length, asyncContinuation); } catch (Exception ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending network request"); asyncContinuation(ex); } } /// <summary> /// Closes the sender and releases any unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Performs sender-specific initialization. /// </summary> protected virtual void DoInitialize() { } /// <summary> /// Performs sender-specific close operation. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoClose(AsyncContinuation continuation) { continuation(null); } /// <summary> /// Performs sender-specific flush. /// </summary> /// <param name="continuation">The continuation.</param> protected virtual void DoFlush(AsyncContinuation continuation) { continuation(null); } /// <summary> /// Actually sends the given text over the specified protocol. /// </summary> /// <param name="bytes">The bytes to be sent.</param> /// <param name="offset">Offset in buffer.</param> /// <param name="length">Number of bytes to send.</param> /// <param name="asyncContinuation">The async continuation to be invoked after the buffer has been sent.</param> /// <remarks>To be overridden in inheriting classes.</remarks> protected abstract void DoSend(byte[] bytes, int offset, int length, AsyncContinuation asyncContinuation); /// <summary> /// Parses the URI into an endpoint address. /// </summary> /// <param name="uri">The URI to parse.</param> /// <param name="addressFamily">The address family.</param> /// <returns>Parsed endpoint.</returns> protected virtual EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily) { #if SILVERLIGHT return new DnsEndPoint(uri.Host, uri.Port, addressFamily); #else switch (uri.HostNameType) { case UriHostNameType.IPv4: case UriHostNameType.IPv6: return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port); default: { #if NETSTANDARD1_0 var addresses = Dns.GetHostAddressesAsync(uri.Host).Result; #else var addresses = Dns.GetHostEntry(uri.Host).AddressList; #endif foreach (var addr in addresses) { if (addr.AddressFamily == addressFamily || addressFamily == AddressFamily.Unspecified) { return new IPEndPoint(addr, uri.Port); } } throw new IOException($"Cannot resolve '{uri.Host}' to an address in '{addressFamily}'"); } } #endif } public virtual void CheckSocket() { } private void Dispose(bool disposing) { if (disposing) { Close(ex => { }); } } } }
#pragma warning disable GU0009 // Name the boolean parameter. namespace Gu.Persist.Core.Tests.Repositories { using System; using System.Collections.Generic; using NUnit.Framework; public abstract partial class RepositoryTests { [TestCaseSource(nameof(TestCases))] public void Save(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); var backupFile = testCase.BackupFile<DummySerializable>(repository); AssertFile.Exists(false, file); testCase.Save(repository, file, dummy); AssertFile.Exists(true, file); AssertFile.Exists(false, file.SoftDeleteFile()); AssertFile.Exists(false, file.TempFile(repository.Settings)); if (repository.Settings.BackupSettings != null) { AssertFile.Exists(false, backupFile!); } var read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); } [TestCaseSource(nameof(TestCases))] public void SaveTwice(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); var backupFile = testCase.BackupFile<DummySerializable>(repository); AssertFile.Exists(false, file); testCase.Save(repository, file, dummy); AssertFile.Exists(true, file); AssertFile.Exists(false, file.SoftDeleteFile()); AssertFile.Exists(false, file.TempFile(repository.Settings)); if (repository.Settings.BackupSettings != null) { AssertFile.Exists(false, backupFile!); } var read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); testCase.Save(repository, file, dummy); AssertFile.Exists(true, file); AssertFile.Exists(false, file.SoftDeleteFile()); AssertFile.Exists(false, file.TempFile(repository.Settings)); if (repository.Settings.BackupSettings != null) { AssertFile.Exists(true, backupFile!); } read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); } [TestCaseSource(nameof(TestCases))] public void SaveThrice(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); var backupFile = testCase.BackupFile<DummySerializable>(repository); AssertFile.Exists(false, file); testCase.Save(repository, file, dummy); AssertFile.Exists(true, file); AssertFile.Exists(false, file.SoftDeleteFile()); AssertFile.Exists(false, file.TempFile(repository.Settings)); if (repository.Settings.BackupSettings != null) { AssertFile.Exists(false, backupFile!); } var read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); testCase.Save(repository, file, dummy); AssertFile.Exists(true, file); AssertFile.Exists(false, file.SoftDeleteFile()); AssertFile.Exists(false, file.TempFile(repository.Settings)); if (repository.Settings.BackupSettings != null) { AssertFile.Exists(true, backupFile!); } read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); testCase.Save(repository, file, dummy); AssertFile.Exists(true, file); AssertFile.Exists(false, file.SoftDeleteFile()); AssertFile.Exists(false, file.TempFile(repository.Settings)); if (repository.Settings.BackupSettings != null) { AssertFile.Exists(true, backupFile!); } read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); } [TestCaseSource(nameof(TestCases))] public void SaveThenRead(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); testCase.Save(repository, file, dummy); var read = testCase.Read<DummySerializable>(repository, file); if (repository is ISingletonRepository) { Assert.AreSame(dummy, read); } else { Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); } } [TestCaseSource(nameof(TestCases))] public void SaveThenSaveNull(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); testCase.Save(repository, file, dummy); if (repository.Settings is IDataRepositorySettings { SaveNullDeletesFile: true }) { testCase.Save<DummySerializable?>(repository, file, null); AssertFile.Exists(false, file); if (repository.Settings.BackupSettings != null) { var backupFile = testCase.BackupFile<DummySerializable>(repository); AssertFile.Exists(true, backupFile!); } } else { _ = Assert.Throws<ArgumentNullException>(() => testCase.Save<DummySerializable?>(repository, file, null)); } } [TestCaseSource(nameof(TestCases))] public void SaveWhenTempFileExists(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); file.TempFile(repository.Settings).CreateFileOnDisk(); testCase.Save(repository, file, dummy); if (repository.Settings.BackupSettings != null) { var backupFile = testCase.BackupFile<DummySerializable>(repository); AssertFile.Exists(false, backupFile!); } var read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); } [TestCaseSource(nameof(TestCases))] public void SaveWhenFileAndSoftDeleteExists(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); file.CreateFileOnDisk(); file.TempFile(repository.Settings).CreateFileOnDisk(); file.SoftDeleteFile().CreateFileOnDisk(); testCase.Save(repository, file, dummy); if (repository.Settings.BackupSettings != null) { var backupFile = testCase.BackupFile<DummySerializable>(repository); AssertFile.Exists(true, backupFile!); } var read = this.Read<DummySerializable>(file); Assert.AreEqual(dummy.Value, read.Value); } [TestCaseSource(nameof(TestCases))] public void SaveLongListThenShortList(TestCase testCase) { var list = new List<DummySerializable> { new DummySerializable(1), new DummySerializable(2), }; var repository = this.CreateRepository(); var file = testCase.File<List<DummySerializable>>(repository); testCase.Save(repository, file, list); var read = this.Read<List<DummySerializable>>(file); CollectionAssert.AreEqual(list, read); list.RemoveAt(0); testCase.Save(repository, file, list); read = this.Read<List<DummySerializable>>(file); CollectionAssert.AreEqual(list, read); } [TestCaseSource(nameof(TestCases))] public void SaveManagesSingleton(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); testCase.Save(repository, file, dummy); var read = testCase.Read<DummySerializable>(repository, file); if (repository is ISingletonRepository) { Assert.AreSame(dummy, read); } else { Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); } dummy.Value++; testCase.Save(repository, file, dummy); read = testCase.Read<DummySerializable>(repository, file); if (repository is ISingletonRepository) { Assert.AreSame(dummy, read); } else { Assert.AreEqual(dummy.Value, read.Value); Assert.AreNotSame(dummy, read); } } [TestCaseSource(nameof(TestCases))] public void IsDirtyBeforeFirstSave(TestCase testCase) { var dummy = new DummySerializable(1); var repository = this.CreateRepository(); var file = testCase.File<DummySerializable>(repository); if (repository.Settings.IsTrackingDirty) { Assert.AreEqual(true, testCase.IsDirty(repository, file, dummy)); testCase.Save(repository, file, dummy); Assert.AreEqual(false, testCase.IsDirty(repository, file, dummy)); dummy.Value++; Assert.AreEqual(true, testCase.IsDirty(repository, file, dummy)); testCase.Save(repository, file, dummy); Assert.AreEqual(false, testCase.IsDirty(repository, file, dummy)); } else { var exception = Assert.Throws<InvalidOperationException>(() => repository.IsDirty(dummy)); Assert.AreEqual("This repository is not tracking dirty.", exception.Message); } } } }
// 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; internal class OVFTest { static public volatile bool rtv; static OVFTest() { rtv = Environment.TickCount != 0; } private static sbyte Test_sbyte(sbyte a) { if (!rtv) return 0; checked { #if OP_DIV return (sbyte)(a / 0.5); #elif OP_ADD return (sbyte)(a + a); #elif OP_SUB return (sbyte)(-1 - a - a); #else return (sbyte)(a * 2); #endif } } private static byte Test_byte(byte a) { if (!rtv) return 0; checked { #if OP_DIV return (byte)(a / 0.5); #elif OP_ADD return (byte)(a + a); #elif OP_SUB return (byte)(0 - a - a); #else return (byte)(a * 2); #endif } } private static short Test_short(short a) { if (!rtv) return 0; checked { #if OP_DIV return (short)(a / 0.5); #elif OP_ADD return (short)(a + a); #elif OP_SUB return (short)(-1 - a - a); #else return (short)(a * 2); #endif } } private static ushort Test_ushort(ushort a) { if (!rtv) return 0; checked { #if OP_DIV return (ushort)(a / 0.5); #elif OP_ADD return (ushort)(a + a); #elif OP_SUB return (ushort)(0 - a - a); #else return (ushort)(a * 2); #endif } } private static int Test_int(int a) { if (!rtv) return 0; checked { #if OP_DIV return (int)(a / 0.5); #elif OP_ADD return a + a; #elif OP_SUB return -1 - a - a; #else return a * 2; #endif } } private static uint Test_uint(uint a) { if (!rtv) return 0; checked { #if OP_DIV return (uint)(a / 0.5); #elif OP_ADD return a + a; #elif OP_SUB return 0U - a - a; #else return a * 2; #endif } } private static long Test_long(long a) { if (!rtv) return 0; checked { #if OP_DIV return (long)(a / 0.5); #elif OP_ADD return a + a; #elif OP_SUB return -1L - a - a; #else return a * 2; #endif } } private static ulong Test_ulong(ulong a) { if (!rtv) return 0; checked { #if OP_DIV return (ulong)(a / 0.5); #elif OP_ADD return a + a; #elif OP_SUB return 0UL - a - a; #else return a * 2; #endif } } private static int Main(string[] args) { #if OP_DIV const string op = "div.ovf"; #elif OP_ADD const string op = "add.ovf"; #elif OP_SUB const string op = "sub.ovf"; #else const string op = "mul.ovf"; #endif Console.WriteLine("Runtime Checks [OP: {0}]", op); int check = 8; try { Console.Write("Type 'byte' . . : "); byte a = Test_byte((byte)(OVFTest.rtv ? 1 + byte.MaxValue / 2 : 0)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'sbyte'. . : "); sbyte a = Test_sbyte((sbyte)(OVFTest.rtv ? 1 + sbyte.MaxValue / 2 : 0)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'short'. . : "); short a = Test_short((short)(OVFTest.rtv ? 1 + short.MaxValue / 2 : 0)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'ushort' . : "); ushort a = Test_ushort((ushort)(OVFTest.rtv ? 1 + ushort.MaxValue / 2 : 0)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'int'. . . : "); int a = Test_int((int)(OVFTest.rtv ? 1 + int.MaxValue / 2 : 0)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'uint' . . : "); uint a = Test_uint((uint)(OVFTest.rtv ? 1U + uint.MaxValue / 2U : 0U)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'long' . . : "); long a = Test_long((long)(OVFTest.rtv ? 1L + long.MaxValue / 2L : 0L)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } try { Console.Write("Type 'ulong'. . : "); ulong a = Test_ulong((ulong)(OVFTest.rtv ? 1UL + ulong.MaxValue / 2UL : 0UL)); Console.WriteLine("failed! - a = " + a); } catch (System.OverflowException) { Console.WriteLine("passed"); check--; } return check == 0 ? 100 : 1; } }
using System; using System.Collections; using System.Xml; namespace AutoAssess.Data.Nessus { public class NessusManager : IDisposable { NessusManagerSession _session; int RandomNumber { get { return new Random().Next(9999); } } /// <summary> /// Initializes a new instance of the <see cref="AutoAssess.Data.Nessus.NessusManager"/> class. /// </summary> /// <param name='sess'> /// NessesManagerSession configured to connect to the nessus host. /// </param> public NessusManager (NessusManagerSession sess) { _session = sess; } /// <summary> /// Login the specified username, password and loggedIn. /// </summary> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='loggedIn'> /// Logged in. /// </param> public XmlDocument Login(string username, string password, out bool loggedIn) { return this.Login(username, password, this.RandomNumber, out loggedIn); } /// <summary> /// Login the specified username, password, seq and loggedIn. /// </summary> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <param name='loggedIn'> /// Logged in. /// </param> public XmlDocument Login(string username, string password, int seq, out bool loggedIn) { return _session.Authenticate(username, password, seq, out loggedIn); } /// <summary> /// Logout this instance. /// </summary> public XmlDocument Logout () { return this.Logout(this.RandomNumber); } /// <summary> /// Logout the specified seq. /// </summary> /// <param name='seq'> /// Seq. /// </param> public XmlDocument Logout(int seq) { Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/logout", options); return response; } /// <summary> /// Adds the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> public XmlDocument AddUser(string username, string password, bool isAdmin) { return this.AddUser(username, password, isAdmin, this.RandomNumber); } /// <summary> /// Adds the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument AddUser(string username, string password, bool isAdmin, int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authenticated or not administrator"); Hashtable options = new Hashtable(); options.Add("seq", seq); options.Add("password", password); options.Add("admin", isAdmin ? "1" : "0"); options.Add("login", username); XmlDocument response = _session.ExecuteCommand("/users/add", options); return response; } /// <summary> /// Deletes the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> public XmlDocument DeleteUser(string username) { return this.DeleteUser(username, this.RandomNumber); } /// <summary> /// Deletes the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeleteUser(string username, int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authed or not admin"); Hashtable options = new Hashtable(); options.Add("login", username); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/delete", options); return response; } /// <summary> /// Edits the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> public XmlDocument EditUser(string username, string password, bool isAdmin) { return this.EditUser(username, password, isAdmin, this.RandomNumber); } /// <summary> /// Edits the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument EditUser(string username, string password, bool isAdmin, int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authed or not admin."); Hashtable options = new Hashtable(); options.Add("login", username); options.Add("password", password); options.Add("admin", isAdmin ? "1" : "0"); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/edit", options); return response; } /// <summary> /// Changes the user password. /// </summary> /// <returns> /// The user password. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> public XmlDocument ChangeUserPassword(string username, string password) { return this.ChangeUserPassword(username, password, this.RandomNumber); } /// <summary> /// Changes the user password. /// </summary> /// <returns> /// The user password. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ChangeUserPassword(string username, string password, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("login", username); options.Add("password", password); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/chpasswd", options); return response; } /// <summary> /// Lists the users. /// </summary> /// <returns> /// The users. /// </returns> public XmlDocument ListUsers() { return this.ListUsers(this.RandomNumber); } /// <summary> /// Lists the users. /// </summary> /// <returns> /// The users. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListUsers(int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authed or not admin."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/list", options); return response; } /// <summary> /// Lists the plugin families. /// </summary> /// <returns> /// The plugin families. /// </returns> public XmlDocument ListPluginFamilies() { return this.ListPluginFamilies(this.RandomNumber); } /// <summary> /// Lists the plugin families. /// </summary> /// <returns> /// The plugin families. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListPluginFamilies(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/plugins/list", options); return response; } /// <summary> /// Lists the plugins by family. /// </summary> /// <returns> /// The plugins by family. /// </returns> /// <param name='family'> /// Family. /// </param> public XmlDocument ListPluginsByFamily(string family) { return this.ListPluginsByFamily(family, this.RandomNumber); } /// <summary> /// Lists the plugins by family. /// </summary> /// <returns> /// The plugins by family. /// </returns> /// <param name='family'> /// Family. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListPluginsByFamily(string family, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("family", family); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/plugins/list/family", options); return response; } /// <summary> /// Gets the plugin descroption by filename. /// </summary> /// <returns> /// The plugin descroption by filename. /// </returns> /// <param name='filename'> /// Filename. /// </param> public XmlDocument GetPluginDescriptionByFilename(string filename) { return this.GetPluginDescriptionByFilename(filename, this.RandomNumber); } /// <summary> /// Gets the plugin description by filename. /// </summary> /// <returns> /// The plugin description by filename. /// </returns> /// <param name='filename'> /// Filename. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetPluginDescriptionByFilename(string filename, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("fname", filename); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/plugins/description", options); return response; } /// <summary> /// Lists the policies. /// </summary> /// <returns> /// The policies. /// </returns> public XmlDocument ListPolicies() { return this.ListPolicies(this.RandomNumber); } /// <summary> /// Lists the policies. /// </summary> /// <returns> /// The policies. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListPolicies(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/policy/list", options); return response; } /// <summary> /// Deletes the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy I. /// </param> public XmlDocument DeletePolicy(int policyID) { return this.DeletePolicy(policyID, this.RandomNumber); } /// <summary> /// Deletes the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeletePolicy(int policyID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("policy_id", policyID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/policy/delete", options); return response; } /// <summary> /// Copies the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy ID. /// </param> public XmlDocument CopyPolicy(int policyID) { return this.CopyPolicy(policyID, this.RandomNumber); } /// <summary> /// Copies the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument CopyPolicy(int policyID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("policy_id", policyID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/policy/copy", options); return response; } /// <summary> /// Gets the feed information. /// </summary> /// <returns> /// The feed information. /// </returns> public XmlDocument GetFeedInformation() { return this.GetFeedInformation(this.RandomNumber); } /// <summary> /// Gets the feed information. /// </summary> /// <returns> /// The feed information. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetFeedInformation(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed"); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/feed/", options); return response; } /// <summary> /// Creates the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='target'> /// Target. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='name'> /// Name. /// </param> public XmlDocument CreateScan(string target, int policyID, string name) { return this.CreateScan(target, policyID, name, this.RandomNumber); } /// <summary> /// Creates the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='target'> /// Target. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='name'> /// Name. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument CreateScan(string target, int policyID, string name, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("target", target); options.Add("policy_id", policyID); options.Add("scan_name", name); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/new", options); return response; } /// <summary> /// Stops the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> public XmlDocument StopScan(Guid scanID) { return this.StopScan(scanID, this.RandomNumber); } /// <summary> /// Stops the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument StopScan(Guid scanID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("scan_uuid", scanID.ToString()); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/stop", options); return response; } /// <summary> /// Pauses the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> public XmlDocument PauseScan(Guid scanID) { return this.PauseScan(scanID, this.RandomNumber); } /// <summary> /// Pauses the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument PauseScan(Guid scanID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("scan_uuid", scanID.ToString()); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/pause", options); return response; } /// <summary> /// Resumes the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> public XmlDocument ResumeScan(Guid scanID) { return this.ResumeScan(scanID, this.RandomNumber); } /// <summary> /// Resumes the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ResumeScan(Guid scanID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("scan_uuid", scanID.ToString()); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/resume", options); return response; } /// <summary> /// Lists the scans. /// </summary> /// <returns> /// The scans. /// </returns> public XmlDocument ListScans() { return this.ListScans(this.RandomNumber); } /// <summary> /// Lists the scans. /// </summary> /// <returns> /// The scans. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListScans(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/list", options); return response; } /// <summary> /// Creates the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> public XmlDocument CreateScanTemplate(string name, int policyID, string target) { return this.CreateScanTemplate(name, policyID, target, this.RandomNumber); } /// <summary> /// Creates the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument CreateScanTemplate(string name, int policyID, string target, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template_name", name); options.Add("policy_id", policyID); options.Add("target", target); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/new", options); return response; } /// <summary> /// Edits the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='readableName'> /// Readable name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> public XmlDocument EditScanTemplate(string name, string readableName, int policyID, string target) { return this.EditScanTemplate(name, readableName, policyID, target, this.RandomNumber); } /// <summary> /// Edits the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='readableName'> /// Readable name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument EditScanTemplate(string name, string readableName, int policyID, string target, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template", name); options.Add("template_name", readableName); options.Add("policy_id", policyID); options.Add("target", target); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/edit", options); return response; } /// <summary> /// Deletes the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> public XmlDocument DeleteScanTemplate(string name) { return this.DeleteScanTemplate(name, this.RandomNumber); } /// <summary> /// Deletes the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeleteScanTemplate(string name, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template", name); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/delete", options); return response; } /// <summary> /// Launchs the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> public XmlDocument LaunchScanTemplate(string name) { return this.LaunchScanTemplate(name, this.RandomNumber); } /// <summary> /// Launchs the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument LaunchScanTemplate(string name, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template", name); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/launch", options); return response; } /// <summary> /// Lists the reports. /// </summary> /// <returns> /// The reports. /// </returns> public XmlDocument ListReports() { return this.ListReports(this.RandomNumber); } /// <summary> /// Lists the reports. /// </summary> /// <returns> /// The reports. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListReports(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/list", options); return response; } /// <summary> /// Deletes the report. /// </summary> /// <returns> /// The report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> public XmlDocument DeleteReport(string reportID) { return this.DeleteReport(reportID, this.RandomNumber); } /// <summary> /// Deletes the report. /// </summary> /// <returns> /// The report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeleteReport(string reportID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/delete", options); return response; } /// <summary> /// Gets the report hosts. /// </summary> /// <returns> /// The report hosts. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> public XmlDocument GetReportHosts(string reportID) { return this.GetReportHosts(reportID, this.RandomNumber); } /// <summary> /// Gets the report hosts. /// </summary> /// <returns> /// The report hosts. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetReportHosts(string reportID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/hosts", options); return response; } /// <summary> /// Gets the ports for host from report. /// </summary> /// <returns> /// The ports for host from report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> public XmlDocument GetPortsForHostFromReport(string reportID, string host) { return this.GetPortsForHostFromReport(reportID, host, this.RandomNumber); } /// <summary> /// Gets the ports for host from report. /// </summary> /// <returns> /// The ports for host from report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetPortsForHostFromReport(string reportID, string host, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("hostname", host); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/ports", options); return response; } /// <summary> /// Gets the report details by port and host. /// </summary> /// <returns> /// The report details by port and host. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='port'> /// Port. /// </param> /// <param name='protocol'> /// Protocol. /// </param> public XmlDocument GetReportDetailsByPortAndHost(string reportID, string host, int port, string protocol) { return this.GetReportDetailsByPortAndHost(reportID, host, port, protocol, this.RandomNumber); } /// <summary> /// Gets the report details by port and host. /// </summary> /// <returns> /// The report details by port and host. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='port'> /// Port. /// </param> /// <param name='protocol'> /// Protocol. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetReportDetailsByPortAndHost(string reportID, string host, int port, string protocol, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("hostname", host); options.Add("port", port); options.Add("protocol", protocol); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/details", options); return response; } /// <summary> /// Gets the report tags. /// </summary> /// <returns> /// The report tags. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> public XmlDocument GetReportTags(Guid reportID, string host) { return this.GetReportTags(reportID, host, this.RandomNumber); } /// <summary> /// Gets the report tags. /// </summary> /// <returns> /// The report tags. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetReportTags(Guid reportID, string host, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID.ToString()); options.Add("hostname", host); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/tags", options); return response; } public XmlDocument GetNessusV2Report(string reportID) { return this.GetNessusV2Report(reportID, this.RandomNumber); } public XmlDocument GetNessusV2Report(string reportID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/file/report/download", options); return response; } public void Dispose() {} } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace DrillTime.WebApiNoOwEf.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* Copyright 2019 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. */ namespace DemoITableBinding { partial class MainWnd { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWnd)); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components); this.bindingNavigator1 = new System.Windows.Forms.BindingNavigator(this.components); this.bindingNavigatorAddNewItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorCountItem = new System.Windows.Forms.ToolStripLabel(); this.bindingNavigatorDeleteItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveFirstItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMovePreviousItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorPositionItem = new System.Windows.Forms.ToolStripTextBox(); this.bindingNavigatorSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.bindingNavigatorMoveNextItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorMoveLastItem = new System.Windows.Forms.ToolStripButton(); this.bindingNavigatorSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.textBox1 = new System.Windows.Forms.TextBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.chkUseCVD = new System.Windows.Forms.CheckBox(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator1)).BeginInit(); this.bindingNavigator1.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // dataGridView1 // dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.tableLayoutPanel1.SetColumnSpan(this.dataGridView1, 2); dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle2; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(3, 3); this.dataGridView1.Name = "dataGridView1"; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle3; this.dataGridView1.Size = new System.Drawing.Size(700, 454); this.dataGridView1.TabIndex = 0; // // bindingNavigator1 // this.bindingNavigator1.AddNewItem = this.bindingNavigatorAddNewItem; this.bindingNavigator1.BindingSource = this.bindingSource1; this.tableLayoutPanel1.SetColumnSpan(this.bindingNavigator1, 2); this.bindingNavigator1.CountItem = this.bindingNavigatorCountItem; this.bindingNavigator1.DeleteItem = this.bindingNavigatorDeleteItem; this.bindingNavigator1.Dock = System.Windows.Forms.DockStyle.Fill; this.bindingNavigator1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.bindingNavigatorMoveFirstItem, this.bindingNavigatorMovePreviousItem, this.bindingNavigatorSeparator, this.bindingNavigatorPositionItem, this.bindingNavigatorCountItem, this.bindingNavigatorSeparator1, this.bindingNavigatorMoveNextItem, this.bindingNavigatorMoveLastItem, this.bindingNavigatorSeparator2, this.bindingNavigatorAddNewItem, this.bindingNavigatorDeleteItem}); this.bindingNavigator1.Location = new System.Drawing.Point(0, 485); this.bindingNavigator1.MoveFirstItem = this.bindingNavigatorMoveFirstItem; this.bindingNavigator1.MoveLastItem = this.bindingNavigatorMoveLastItem; this.bindingNavigator1.MoveNextItem = this.bindingNavigatorMoveNextItem; this.bindingNavigator1.MovePreviousItem = this.bindingNavigatorMovePreviousItem; this.bindingNavigator1.Name = "bindingNavigator1"; this.bindingNavigator1.PositionItem = this.bindingNavigatorPositionItem; this.bindingNavigator1.Size = new System.Drawing.Size(706, 25); this.bindingNavigator1.TabIndex = 2; this.bindingNavigator1.Text = "bindingNavigator1"; // // bindingNavigatorAddNewItem // this.bindingNavigatorAddNewItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorAddNewItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorAddNewItem.Image"))); this.bindingNavigatorAddNewItem.Name = "bindingNavigatorAddNewItem"; this.bindingNavigatorAddNewItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorAddNewItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorAddNewItem.Text = "Add new"; // // bindingNavigatorCountItem // this.bindingNavigatorCountItem.Name = "bindingNavigatorCountItem"; this.bindingNavigatorCountItem.Size = new System.Drawing.Size(35, 22); this.bindingNavigatorCountItem.Text = "of {0}"; this.bindingNavigatorCountItem.ToolTipText = "Total number of items"; // // bindingNavigatorDeleteItem // this.bindingNavigatorDeleteItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorDeleteItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorDeleteItem.Image"))); this.bindingNavigatorDeleteItem.Name = "bindingNavigatorDeleteItem"; this.bindingNavigatorDeleteItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorDeleteItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorDeleteItem.Text = "Delete"; // // bindingNavigatorMoveFirstItem // this.bindingNavigatorMoveFirstItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveFirstItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveFirstItem.Image"))); this.bindingNavigatorMoveFirstItem.Name = "bindingNavigatorMoveFirstItem"; this.bindingNavigatorMoveFirstItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveFirstItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveFirstItem.Text = "Move first"; // // bindingNavigatorMovePreviousItem // this.bindingNavigatorMovePreviousItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMovePreviousItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMovePreviousItem.Image"))); this.bindingNavigatorMovePreviousItem.Name = "bindingNavigatorMovePreviousItem"; this.bindingNavigatorMovePreviousItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMovePreviousItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMovePreviousItem.Text = "Move previous"; // // bindingNavigatorSeparator // this.bindingNavigatorSeparator.Name = "bindingNavigatorSeparator"; this.bindingNavigatorSeparator.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorPositionItem // this.bindingNavigatorPositionItem.AccessibleName = "Position"; this.bindingNavigatorPositionItem.AutoSize = false; this.bindingNavigatorPositionItem.Name = "bindingNavigatorPositionItem"; this.bindingNavigatorPositionItem.Size = new System.Drawing.Size(50, 21); this.bindingNavigatorPositionItem.Text = "0"; this.bindingNavigatorPositionItem.ToolTipText = "Current position"; // // bindingNavigatorSeparator1 // this.bindingNavigatorSeparator1.Name = "bindingNavigatorSeparator1"; this.bindingNavigatorSeparator1.Size = new System.Drawing.Size(6, 25); // // bindingNavigatorMoveNextItem // this.bindingNavigatorMoveNextItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveNextItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveNextItem.Image"))); this.bindingNavigatorMoveNextItem.Name = "bindingNavigatorMoveNextItem"; this.bindingNavigatorMoveNextItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveNextItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveNextItem.Text = "Move next"; // // bindingNavigatorMoveLastItem // this.bindingNavigatorMoveLastItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.bindingNavigatorMoveLastItem.Image = ((System.Drawing.Image)(resources.GetObject("bindingNavigatorMoveLastItem.Image"))); this.bindingNavigatorMoveLastItem.Name = "bindingNavigatorMoveLastItem"; this.bindingNavigatorMoveLastItem.RightToLeftAutoMirrorImage = true; this.bindingNavigatorMoveLastItem.Size = new System.Drawing.Size(23, 22); this.bindingNavigatorMoveLastItem.Text = "Move last"; // // bindingNavigatorSeparator2 // this.bindingNavigatorSeparator2.Name = "bindingNavigatorSeparator2"; this.bindingNavigatorSeparator2.Size = new System.Drawing.Size(6, 25); // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.textBox1.Location = new System.Drawing.Point(3, 463); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(130, 20); this.textBox1.TabIndex = 0; // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.textBox1, 0, 1); this.tableLayoutPanel1.Controls.Add(this.bindingNavigator1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.chkUseCVD, 1, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 3; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(706, 510); this.tableLayoutPanel1.TabIndex = 4; // // chkUseCVD // this.chkUseCVD.AutoSize = true; this.chkUseCVD.Location = new System.Drawing.Point(356, 463); this.chkUseCVD.Name = "chkUseCVD"; this.chkUseCVD.Size = new System.Drawing.Size(231, 17); this.chkUseCVD.TabIndex = 3; this.chkUseCVD.Text = "Use Coded Value Domain on \'Enabled\' field"; this.chkUseCVD.UseVisualStyleBackColor = true; this.chkUseCVD.CheckedChanged += new System.EventHandler(this.chkUseCVD_CheckedChanged); // // MainWnd // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(706, 510); this.Controls.Add(this.tableLayoutPanel1); this.Name = "MainWnd"; this.Text = "ITable Data Binding"; this.Load += new System.EventHandler(this.MainWnd_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bindingNavigator1)).EndInit(); this.bindingNavigator1.ResumeLayout(false); this.bindingNavigator1.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.BindingSource bindingSource1; private System.Windows.Forms.BindingNavigator bindingNavigator1; private System.Windows.Forms.ToolStripButton bindingNavigatorAddNewItem; private System.Windows.Forms.ToolStripLabel bindingNavigatorCountItem; private System.Windows.Forms.ToolStripButton bindingNavigatorDeleteItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveFirstItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMovePreviousItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator; private System.Windows.Forms.ToolStripTextBox bindingNavigatorPositionItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator1; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveNextItem; private System.Windows.Forms.ToolStripButton bindingNavigatorMoveLastItem; private System.Windows.Forms.ToolStripSeparator bindingNavigatorSeparator2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.CheckBox chkUseCVD; } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// STSUP Transfer /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STSUP_TR : EduHubEntity { #region Navigation Property Cache private SKGS Cache_ORIG_SCHOOL_SKGS; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Transaction ID /// </summary> public int TID { get; internal set; } /// <summary> /// Originating School /// [Uppercase Alphanumeric (8)] /// </summary> public string ORIG_SCHOOL { get; internal set; } /// <summary> /// Unique STSUP Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string STSUP_TRANS_ID { get; internal set; } /// <summary> /// Original student key /// [Uppercase Alphanumeric (10)] /// </summary> public string SKEY { get; internal set; } /// <summary> /// New student key /// [Uppercase Alphanumeric (10)] /// </summary> public string SKEY_NEW { get; internal set; } /// <summary> /// First name /// [Alphanumeric (30)] /// </summary> public string FIRST_NAME { get; internal set; } /// <summary> /// Surname /// [Alphanumeric (30)] /// </summary> public string SURNAME { get; internal set; } /// <summary> /// Role of support person /// [Uppercase Alphanumeric (10)] /// </summary> public string SUPPORT_ROLE { get; internal set; } /// <summary> /// New role of support person /// [Uppercase Alphanumeric (10)] /// </summary> public string SUPPORT_ROLE_NEW { get; internal set; } /// <summary> /// Two business address lines /// [Alphanumeric (30)] /// </summary> public string ADDRESS01 { get; internal set; } /// <summary> /// Two business address lines /// [Alphanumeric (30)] /// </summary> public string ADDRESS02 { get; internal set; } /// <summary> /// Suburb /// [Alphanumeric (30)] /// </summary> public string SUBURB { get; internal set; } /// <summary> /// State code /// [Uppercase Alphanumeric (3)] /// </summary> public string STATE { get; internal set; } /// <summary> /// Postcode /// [Alphanumeric (4)] /// </summary> public string POSTCODE { get; internal set; } /// <summary> /// Link to KAP to allow for access to postcodes when entering an address: NOTE this should NOT be a foreign key to KAP as the user is free to enter different data in ADDRESS03 and POSTCODE /// [Alphanumeric (34)] /// </summary> public string KAP_LINK { get; internal set; } /// <summary> /// Business telephone number /// [Uppercase Alphanumeric (20)] /// </summary> public string BUS_PHONE { get; internal set; } /// <summary> /// Business email address /// [Alphanumeric (60)] /// </summary> public string BUS_EMAIL { get; internal set; } /// <summary> /// User who added the record /// [Uppercase Alphanumeric (128)] /// </summary> public string ADDED_BY { get; internal set; } /// <summary> /// Student received Student Support Services (SSS) (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string SUPPORT_SERVICES { get; internal set; } /// <summary> /// Student received other school-based or departmental student support (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string STUDENT_SUPPORT { get; internal set; } /// <summary> /// Student received non-school-based/non-departmental support over the last two years (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string STUDENT_OTHER_SUPPORT { get; internal set; } /// <summary> /// Is the Department of Health and Human Services currently involved with the child and their family? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string CHILD_PROTECTION { get; internal set; } /// <summary> /// Unique ST Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string ST_TRANS_ID { get; internal set; } /// <summary> /// Unique KGO Transfer ID /// [Uppercase Alphanumeric (30)] /// </summary> public string KGO_TRANS_ID { get; internal set; } /// <summary> /// Current status of import /// [Uppercase Alphanumeric (15)] /// </summary> public string IMP_STATUS { get; internal set; } /// <summary> /// Actual date data transferred into live table /// </summary> public DateTime? IMP_DATE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write user /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// SKGS (Schools) related entity by [STSUP_TR.ORIG_SCHOOL]-&gt;[SKGS.SCHOOL] /// Originating School /// </summary> public SKGS ORIG_SCHOOL_SKGS { get { if (Cache_ORIG_SCHOOL_SKGS == null) { Cache_ORIG_SCHOOL_SKGS = Context.SKGS.FindBySCHOOL(ORIG_SCHOOL); } return Cache_ORIG_SCHOOL_SKGS; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using GraphQL.NewtonsoftJson; using Newtonsoft.Json; using Shouldly; using Xunit; namespace GraphQL.Tests.Serialization.NewtonsoftJson { public class InputsConverterTests { private static readonly JsonSerializer _jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.None, Formatting = Formatting.Indented, Converters = { new InputsConverter() }, }); private T Deserialize<T>(string json) { using var stringReader = new System.IO.StringReader(json); using var jsonReader = new JsonTextReader(stringReader); return _jsonSerializer.Deserialize<T>(jsonReader); } private string Serialize<T>(T data) { using var stringWriter = new System.IO.StringWriter(); using (var jsonWriter = new JsonTextWriter(stringWriter)) { _jsonSerializer.Serialize(jsonWriter, data); } return stringWriter.ToString(); } [Fact] public void Deserialize_And_Serialize_Introspection() { string json = "IntrospectionResult".ReadJsonResult(); var data = Deserialize<Inputs>(json); string roundtrip = Serialize(data); roundtrip.ShouldBeCrossPlatJson(json); } [Fact] public void Deserialize_SimpleValues() { string json = @" { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true } "; var actual = Deserialize<Inputs>(json); actual["int"].ShouldBe(123); actual["double"].ShouldBe(123.456); actual["string"].ShouldBe("string"); actual["bool"].ShouldBe(true); } [Fact] public void Deserialize_Simple_Null() { string json = @" { ""string"": null } "; var actual = Deserialize<Inputs>(json); actual["string"].ShouldBeNull(); } [Fact] public void Deserialize_Array() { string json = @" { ""values"": [1, 2, 3] } "; var actual = Deserialize<Inputs>(json); actual["values"].ShouldNotBeNull(); } [Fact] public void Deserialize_Array_in_Array() { string json = @" { ""values"": [[1,2,3]] } "; var actual = Deserialize<Inputs>(json); actual["values"].ShouldNotBeNull(); object values = actual["values"]; values.ShouldBeAssignableTo<IEnumerable<object>>(); } [Fact] public void Deserialize_ComplexValue() { string json = @" { ""complex"": { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true } } "; var actual = Deserialize<Inputs>(json); var complex = actual["complex"].ShouldBeAssignableTo<IDictionary<string, object>>(); complex["int"].ShouldBe(123); complex["double"].ShouldBe(123.456); complex["string"].ShouldBe("string"); complex["bool"].ShouldBe(true); } [Fact] public void Deserialize_MixedValue() { string json = @" { ""int"": 123, ""complex"": { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true }, ""bool"": true } "; var actual = Deserialize<Inputs>(json); actual["int"].ShouldBe(123); actual["bool"].ShouldBe(true); var complex = actual["complex"].ShouldBeAssignableTo<IDictionary<string, object>>(); complex["int"].ShouldBe(123); complex["double"].ShouldBe(123.456); complex["string"].ShouldBe("string"); complex["bool"].ShouldBe(true); } [Fact] public void Deserialize_Nested_SimpleValues() { string json = @" { ""value1"": ""string"", ""dictionary"": { ""int"": 123, ""double"": 123.456, ""string"": ""string"", ""bool"": true }, ""value2"": 123 } "; var actual = Deserialize<Nested>(json); actual.Value1.ShouldBe("string"); actual.Value2.ShouldBe(123); } [Fact] public void Serialize_SimpleValues() { var source = new Nested { Value2 = 123, Value1 = null }; string json = Serialize(source); json.ShouldBeCrossPlatJson( @"{ ""Value1"": null, ""Dictionary"": null, ""Value2"": 123 }".Trim()); } [Fact] public void Serialize_Nested_SimpleValues() { var source = new Nested { Dictionary = new Dictionary<string, object> { ["int"] = 123, ["string"] = "string" }.ToInputs(), Value2 = 123, Value1 = "string" }; string json = Serialize(source); json.ShouldBeCrossPlatJson( @"{ ""Value1"": ""string"", ""Dictionary"": { ""int"": 123, ""string"": ""string"" }, ""Value2"": 123 }".Trim()); } [Fact] public void Serialize_Nested_Simple_Null() { var source = new Nested { Dictionary = new Dictionary<string, object> { ["string"] = null }.ToInputs(), Value2 = 123, Value1 = "string" }; string json = Serialize(source); json.ShouldBeCrossPlatJson( @"{ ""Value1"": ""string"", ""Dictionary"": { ""string"": null }, ""Value2"": 123 }".Trim()); } [Fact] public void Serialize_Nested_ComplexValues() { var source = new Nested { Dictionary = new Dictionary<string, object> { ["int"] = 123, ["string"] = "string", ["complex"] = new Dictionary<string, object> { ["double"] = 1.123d } }.ToInputs(), Value2 = 123, Value1 = "string" }; string json = Serialize(source); json.ShouldBeCrossPlatJson( @"{ ""Value1"": ""string"", ""Dictionary"": { ""int"": 123, ""string"": ""string"", ""complex"": { ""double"": 1.123 } }, ""Value2"": 123 }".Trim()); } [Fact] public void Deserializes_Dates() { var d = new DateTimeOffset(2022, 1, 3, 15, 47, 22, System.TimeSpan.Zero); var json = $"{{ \"date\": \"{d:o}\"}}"; var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateParseHandling = DateParseHandling.DateTimeOffset, Converters = { new InputsConverter() }, }); var dic = jsonSerializer.Deserialize<Inputs>(new JsonTextReader(new StringReader(json))); dic.ShouldContainKeyAndValue("date", d); } private class Nested { public string Value1 { get; set; } public Inputs Dictionary { get; set; } public int Value2 { get; set; } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Media; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Microsoft.PythonTools.Intellisense { /// <summary> /// Represents a completion item that can be individually shown and hidden. /// A completion set using these as items needs to provide a filter that /// checks the Visible property. /// </summary> public class DynamicallyVisibleCompletion : Completion { private Func<string> _lazyDescriptionSource; private Func<ImageSource> _lazyIconSource; private bool _visible, _previouslyVisible; /// <summary> /// Creates a default completion item. /// </summary> public DynamicallyVisibleCompletion() : base() { } /// <summary> /// Creates a completion item with the specifed text, which will be /// used both for display and insertion. /// </summary> public DynamicallyVisibleCompletion(string displayText) : base(displayText) { } /// <summary> /// Initializes a new instance with the specified text and description. /// </summary> /// <param name="displayText">The text that is to be displayed by an /// IntelliSense presenter.</param> /// <param name="insertionText">The text that is to be inserted into /// the buffer if this completion is committed.</param> /// <param name="description">A description that can be displayed with /// the display text of the completion.</param> /// <param name="iconSource">The icon.</param> /// <param name="iconAutomationText">The text to be used as the /// automation name for the icon.</param> public DynamicallyVisibleCompletion(string displayText, string insertionText, string description, ImageSource iconSource, string iconAutomationText) : base(displayText, insertionText, description, iconSource, iconAutomationText) { } /// <summary> /// Initializes a new instance with the specified text, description and /// a lazily initialized icon. /// </summary> /// <param name="displayText">The text that is to be displayed by an /// IntelliSense presenter.</param> /// <param name="insertionText">The text that is to be inserted into /// the buffer if this completion is committed.</param> /// <param name="lazyDescriptionSource">A function returning the /// description.</param> /// <param name="lazyIconSource">A function returning the icon. It will /// be called once and the result is cached.</param> /// <param name="iconAutomationText">The text to be used as the /// automation name for the icon.</param> public DynamicallyVisibleCompletion(string displayText, string insertionText, Func<string> lazyDescriptionSource, Func<ImageSource> lazyIconSource, string iconAutomationText) : base(displayText, insertionText, null, null, iconAutomationText) { _lazyDescriptionSource = lazyDescriptionSource; _lazyIconSource = lazyIconSource; } /// <summary> /// Gets or sets whether the completion item should be shown to the /// user. /// </summary> internal bool Visible { get { return _visible; } set { _previouslyVisible = _visible; _visible = value; } } /// <summary> /// Resets <see cref="Visible"/> to its value before it was last set. /// </summary> internal void UndoVisible() { _visible = _previouslyVisible; } // Summary: // Gets a description that can be displayed together with the display text of // the completion. // // Returns: // The description. /// <summary> /// Gets a description that can be displayed together with the display /// text of the completion. /// </summary> /// <value>The description.</value> public override string Description { get { if (base.Description == null && _lazyDescriptionSource != null) { base.Description = _lazyDescriptionSource(); _lazyDescriptionSource = null; } return base.Description.LimitLines(); } set { base.Description = value; } } /// <summary> /// Gets or sets an icon that could be used to describe the completion. /// </summary> /// <value>The icon.</value> public override ImageSource IconSource { get { if (base.IconSource == null && _lazyIconSource != null) { base.IconSource = _lazyIconSource(); _lazyIconSource = null; } return base.IconSource; } set { base.IconSource = value; } } } /// <summary> /// Represents a set of completions filtered and selected using a /// <see cref="FuzzyStringMatcher"/>. /// </summary> public class FuzzyCompletionSet : CompletionSet { BulkObservableCollection<Completion> _completions; FilteredObservableCollection<Completion> _filteredCompletions; Completion _previousSelection; readonly FuzzyStringMatcher _comparer; readonly bool _shouldFilter; readonly bool _shouldHideAdvanced; readonly bool _matchInsertionText; public const bool DefaultCommitByDefault = true; private readonly static Regex _advancedItemPattern = new Regex( @"__\w+__($|\s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant ); private readonly static IList<Completion> _noCompletions = new[] { new Completion( Strings.NoCompletionsCompletion, string.Empty, Strings.WarningUnknownType, null, null ) }; /// <summary> /// Initializes a new instance with the specified properties. /// </summary> /// <param name="moniker">The unique, non-localized identifier for the /// completion set.</param> /// <param name="displayName">The localized name of the completion set. /// </param> /// <param name="applicableTo">The tracking span to which the /// completions apply.</param> /// <param name="completions">The list of completions.</param> /// <param name="options">The options to use for filtering and /// selecting items.</param> /// <param name="comparer">The comparer to use to order the provided /// completions.</param> /// <param name="matchInsertionText">If true, matches user input against /// the insertion text; otherwise, uses the display text.</param> public FuzzyCompletionSet( string moniker, string displayName, ITrackingSpan applicableTo, IEnumerable<DynamicallyVisibleCompletion> completions, CompletionOptions options, IComparer<Completion> comparer, bool matchInsertionText = false ) : base(moniker, displayName, applicableTo, null, null) { _matchInsertionText = matchInsertionText; _completions = new BulkObservableCollection<Completion>(); _completions.AddRange(completions .Where(c => c != null && !string.IsNullOrWhiteSpace(c.DisplayText)) .OrderBy(c => c, comparer) ); _comparer = new FuzzyStringMatcher(options.SearchMode); _shouldFilter = options.FilterCompletions; _shouldHideAdvanced = options.HideAdvancedMembers && !_completions.All(IsAdvanced); if (!_completions.Any()) { _completions = null; } if (_completions != null && _shouldFilter | _shouldHideAdvanced) { _filteredCompletions = new FilteredObservableCollection<Completion>(_completions); foreach (var c in _completions.Cast<DynamicallyVisibleCompletion>()) { c.Visible = !_shouldHideAdvanced || !IsAdvanced(c); } _filteredCompletions.Filter(IsVisible); } CommitByDefault = DefaultCommitByDefault; } private bool IsAdvanced(Completion comp) { return _advancedItemPattern.IsMatch(_matchInsertionText ? comp.InsertionText : comp.DisplayText); } /// <summary> /// If True, the best item is selected by default. Otherwise, the user /// will need to manually select it before committing. /// </summary> /// <remarks> /// By default, this is set to <see cref="DefaultCommitByDefault"/> /// </remarks> public bool CommitByDefault { get; set; } /// <summary> /// Gets or sets the list of completions that are part of this completion set. /// </summary> /// <value> /// A list of <see cref="Completion"/> objects. /// </value> public override IList<Completion> Completions { get { return (IList<Completion>)_filteredCompletions ?? _completions ?? _noCompletions; } } private static bool IsVisible(Completion completion) { return ((DynamicallyVisibleCompletion)completion).Visible; } /// <summary> /// Restricts the set of completions to those that match the applicability text /// of the completion set, and then determines the best match. /// </summary> public override void Filter() { if (_completions == null) { return; } if (_filteredCompletions == null) { foreach (var c in _completions.Cast<DynamicallyVisibleCompletion>()) { c.Visible = true; } return; } var text = ApplicableTo.GetText(ApplicableTo.TextBuffer.CurrentSnapshot); if (text.Length > 0) { bool hideAdvanced = _shouldHideAdvanced && !text.StartsWith("__"); bool anyVisible = false; foreach (var c in _completions.Cast<DynamicallyVisibleCompletion>()) { if (hideAdvanced && IsAdvanced(c)) { c.Visible = false; } else if (_shouldFilter) { c.Visible = _comparer.IsCandidateMatch(_matchInsertionText ? c.InsertionText : c.DisplayText, text); } else { c.Visible = true; } anyVisible |= c.Visible; } if (!anyVisible) { foreach (var c in _completions.Cast<DynamicallyVisibleCompletion>()) { // UndoVisible only works reliably because we always // set Visible in the previous loop. c.UndoVisible(); } } _filteredCompletions.Filter(IsVisible); } else if (_shouldHideAdvanced) { foreach (var c in _completions.Cast<DynamicallyVisibleCompletion>()) { c.Visible = !IsAdvanced(c); } _filteredCompletions.Filter(IsVisible); } else { foreach (var c in _completions.Cast<DynamicallyVisibleCompletion>()) { c.Visible = true; } _filteredCompletions.StopFiltering(); } } /// <summary> /// Determines the best match in the completion set. /// </summary> public override void SelectBestMatch() { if (_completions == null) { return; } var text = ApplicableTo.GetText(ApplicableTo.TextBuffer.CurrentSnapshot); Completion bestMatch = _previousSelection; int bestValue = 0; bool isUnique = true; bool allowSelect = true; // Using the Completions property to only search through visible // completions. foreach (var comp in Completions) { int value = _comparer.GetSortKey(_matchInsertionText ? comp.InsertionText : comp.DisplayText, text); if (bestMatch == null || value > bestValue) { bestMatch = comp; bestValue = value; isUnique = true; } else if (value == bestValue) { isUnique = false; } } if (!CommitByDefault) { allowSelect = false; isUnique = false; } if (((DynamicallyVisibleCompletion)bestMatch).Visible) { SelectionStatus = new CompletionSelectionStatus( bestMatch, isSelected: allowSelect && bestValue > 0, isUnique: isUnique ); } else { SelectionStatus = new CompletionSelectionStatus( null, isSelected: false, isUnique: false ); } _previousSelection = bestMatch; } /// <summary> /// Determines and selects the only match in the completion set. /// This ignores the user's filtering preferences. /// </summary> /// <returns> /// True if a match is found and selected; otherwise, false if there /// is no single match in the completion set. /// </returns> public bool SelectSingleBest() { if (_completions == null) { return false; } var text = ApplicableTo.GetText(ApplicableTo.TextBuffer.CurrentSnapshot); Completion bestMatch = null; // Using the _completions field to search through all completions // and ignore filtering settings. foreach (var comp in _completions) { if (_comparer.IsCandidateMatch(_matchInsertionText ? comp.InsertionText : comp.DisplayText, text)) { if (bestMatch == null) { bestMatch = comp; } else { return false; } } } if (bestMatch != null) { SelectionStatus = new CompletionSelectionStatus( bestMatch, isSelected: true, isUnique: true ); return true; } else { return false; } } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Text.RegularExpressions; public class GA_Menu : MonoBehaviour { [MenuItem ("Window/GameAnalytics/Select GA_Settings", false, 0)] static void SelectGASettings () { Selection.activeObject = GA.SettingsGA; } [MenuItem ("Window/GameAnalytics/GA Setup Wizard", false, 100)] static void SetupAndTour () { GA_SetupWizard wizard = ScriptableObject.CreateInstance<GA_SetupWizard> (); wizard.ShowUtility (); wizard.position = new Rect (150, 150, 420, 340); } [MenuItem ("Window/GameAnalytics/GA Example Tutorial", false, 101)] static void ExampleTutorial () { GA_ExampleTutorial tutorial = ScriptableObject.CreateInstance<GA_ExampleTutorial> (); tutorial.ShowUtility (); tutorial.position = new Rect (150, 150, 420, 340); } [MenuItem ("Window/GameAnalytics/Create GA_SystemTracker", false, 200)] static void AddGASystemTracker () { if (FindObjectOfType (typeof(GA_SystemTracker)) == null) { GameObject go = new GameObject("GA_SystemTracker"); go.AddComponent<GA_Gui>(); go.AddComponent<GA_SpecialEvents>(); go.AddComponent<GA_SystemTracker>(); Selection.activeObject = go; } else { GA.LogWarning ("A GA_SystemTracker already exists in this scene - you should never have more than one per scene!"); } } [MenuItem ("Window/GameAnalytics/Create GA_Heatmap", false, 201)] static void AddHeatMap () { GameObject go = new GameObject("GA_HeatMap"); go.AddComponent<GA_HeatMapRenderer>(); go.AddComponent<GA_HeatMapDataFilter>(); Selection.activeObject = go; } [MenuItem ("Window/GameAnalytics/Add GA_Tracker to Object", false, 202)] static void AddGATracker () { if (Selection.activeGameObject != null) { if (Selection.activeGameObject.GetComponent<GA_Tracker> () == null) { Selection.activeGameObject.AddComponent<GA_Tracker> (); } else { GA.LogWarning ("That object already contains a GA_Tracker component."); } } else { GA.LogWarning ("You must select the gameobject you want to add the GA_Tracker component to."); } } [MenuItem ("Window/GameAnalytics/Open GA_Status Window", false, 300)] static void OpenGAStatus () { GA_Status status = ScriptableObject.CreateInstance<GA_Status> (); status.Show (); } [MenuItem ("Window/GameAnalytics/PlayMaker/Toggle Scripts", false, 400)] static void TogglePlayMaker () { bool enabled = false; bool fail = false; string searchText = "#if false"; string replaceText = "#if true"; string filePath = Application.dataPath + "/GameAnalytics/Plugins/Playmaker/SendBusinessEvent.cs"; string filePathJS = Application.dataPath + "/Plugins/GameAnalytics/Playmaker/SendBusinessEvent.cs"; try { enabled = ReplaceInFile (filePath, searchText, replaceText); } catch { try { enabled = ReplaceInFile (filePathJS, searchText, replaceText); } catch { fail = true; } } filePath = Application.dataPath + "/GameAnalytics/Plugins/Playmaker/SendDesignEvent.cs"; filePathJS = Application.dataPath + "/Plugins/GameAnalytics/Playmaker/SendDesignEvent.cs"; try { enabled = ReplaceInFile (filePath, searchText, replaceText); } catch { try { enabled = ReplaceInFile (filePathJS, searchText, replaceText); } catch { fail = true; } } filePath = Application.dataPath + "/GameAnalytics/Plugins/Playmaker/SendQualityEvent.cs"; filePathJS = Application.dataPath + "/Plugins/GameAnalytics/Playmaker/SendQualityEvent.cs"; try { enabled = ReplaceInFile (filePath, searchText, replaceText); } catch { try { enabled = ReplaceInFile (filePathJS, searchText, replaceText); } catch { fail = true; } } filePath = Application.dataPath + "/GameAnalytics/Plugins/Playmaker/SendUserEvent.cs"; filePathJS = Application.dataPath + "/Plugins/GameAnalytics/Playmaker/SendUserEvent.cs"; try { enabled = ReplaceInFile (filePath, searchText, replaceText); } catch { try { enabled = ReplaceInFile (filePathJS, searchText, replaceText); } catch { fail = true; } } AssetDatabase.Refresh(); if (fail) Debug.Log("Failed to toggle PlayMaker Scripts."); else if (enabled) Debug.Log("Enabled PlayMaker Scripts."); else Debug.Log("Disabled PlayMaker Scripts."); } private static bool ReplaceInFile (string filePath, string searchText, string replaceText) { bool enabled = false; StreamReader reader = new StreamReader (filePath); string content = reader.ReadToEnd (); reader.Close (); if (content.Contains(searchText)) { enabled = true; content = Regex.Replace (content, searchText, replaceText); } else { enabled = false; content = Regex.Replace (content, replaceText, searchText); } StreamWriter writer = new StreamWriter (filePath); writer.Write (content); writer.Close (); return enabled; } [MenuItem ("Window/GameAnalytics/Facebook/Toggle Scripts", false, 401)] static void ToggleFacebook () { bool enabled = false; bool fail = false; string searchText = "#if false"; string replaceText = "#if true"; string filePath = Application.dataPath + "/GameAnalytics/Plugins/Framework/Scripts/GA_FacebookSDK.cs"; string filePathJS = Application.dataPath + "/Plugins/GameAnalytics/Framework/Scripts/GA_FacebookSDK.cs"; try { enabled = ReplaceInFile (filePath, searchText, replaceText); } catch { try { enabled = ReplaceInFile (filePathJS, searchText, replaceText); } catch { fail = true; } } AssetDatabase.Refresh(); if (fail) Debug.Log("Failed to toggle Facebook Scripts."); else if (enabled) Debug.Log("Enabled Facebook Scripts."); else Debug.Log("Disabled Facebook Scripts."); } [MenuItem ("Window/GameAnalytics/Folder Structure/Switch to JS", false, 600)] static void JsFolders () { if (!Directory.Exists(Application.dataPath + "/GameAnalytics/Plugins/")) { Debug.LogWarning("Folder structure incompatible, did you already switch to JS folder structure, or have you manually changed the folder structure?"); return; } if (!Directory.Exists(Application.dataPath + "/Plugins/")) AssetDatabase.CreateFolder("Assets", "Plugins"); if (!Directory.Exists(Application.dataPath + "/Plugins/GameAnalytics")) AssetDatabase.CreateFolder("Assets/Plugins", "GameAnalytics"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/Android", "Assets/Plugins/GameAnalytics/Android"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/Components", "Assets/Plugins/GameAnalytics/Components"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/Examples", "Assets/Plugins/GameAnalytics/Examples"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/Framework", "Assets/Plugins/GameAnalytics/Framework"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/iOS", "Assets/Plugins/GameAnalytics/iOS"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/Playmaker", "Assets/Plugins/GameAnalytics/Playmaker"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Plugins/WebPlayer", "Assets/Plugins/GameAnalytics/WebPlayer"); if (!Directory.Exists(Application.dataPath + "/Editor/")) AssetDatabase.CreateFolder("Assets", "Editor"); AssetDatabase.MoveAsset("Assets/GameAnalytics/Editor", "Assets/Editor/GameAnalytics"); AssetDatabase.DeleteAsset("Assets/GameAnalytics/Plugins"); AssetDatabase.DeleteAsset("Assets/GameAnalytics/Editor"); AssetDatabase.DeleteAsset("Assets/GameAnalytics"); AssetDatabase.Refresh(); } [MenuItem ("Window/GameAnalytics/Folder Structure/Revert to original", false, 601)] static void RevertFolders () { if (!Directory.Exists(Application.dataPath + "/Plugins/GameAnalytics/")) { Debug.LogWarning("Folder structure incompatible, are you already using original folder structure, or have you manually changed the folder structure?"); return; } if (!Directory.Exists(Application.dataPath + "/GameAnalytics/")) AssetDatabase.CreateFolder("Assets", "GameAnalytics"); if (!Directory.Exists(Application.dataPath + "/GameAnalytics/Plugins")) AssetDatabase.CreateFolder("Assets/GameAnalytics", "Plugins"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Android", "Assets/GameAnalytics/Plugins/Android"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Components", "Assets/GameAnalytics/Plugins/Components"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Examples", "Assets/GameAnalytics/Plugins/Examples"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Framework", "Assets/GameAnalytics/Plugins/Framework"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/iOS", "Assets/GameAnalytics/Plugins/iOS"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/Playmaker", "Assets/GameAnalytics/Plugins/Playmaker"); AssetDatabase.MoveAsset("Assets/Plugins/GameAnalytics/WebPlayer", "Assets/GameAnalytics/Plugins/WebPlayer"); AssetDatabase.MoveAsset("Assets/Editor/GameAnalytics", "Assets/GameAnalytics/Editor"); AssetDatabase.DeleteAsset("Assets/Plugins/GameAnalytics"); AssetDatabase.DeleteAsset("Assets/Editor/GameAnalytics"); Debug.Log("Project must be reloaded when reverting folder structure."); EditorApplication.OpenProject(Application.dataPath.Remove(Application.dataPath.Length - "Assets".Length, "Assets".Length)); } }
using Lucene.Net.Support.Text; using Lucene.Net.Util; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Text; namespace Lucene.Net.Support.IO { /* * 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. */ /// <summary> /// Represents the methods to support some operations over files. /// </summary> internal static class FileSupport { private static readonly char[] INVALID_FILENAME_CHARS = Path.GetInvalidFileNameChars(); // LUCNENENET NOTE: Lookup the HResult value we are interested in for the current OS // by provoking the exception during initialization and caching its HResult value for later. // We optimize for Windows because those HResult values are known and documented, but for // other platforms, this is the only way we can reliably determine the HResult values // we are interested in. // // Reference: https://stackoverflow.com/q/46380483 private const int WIN_HRESULT_FILE_ALREADY_EXISTS = unchecked((int)0x80070050); private static readonly int? HRESULT_FILE_ALREADY_EXISTS = LoadFileAlreadyExistsHResult(); private static int? LoadFileAlreadyExistsHResult() { if (Constants.WINDOWS) return WIN_HRESULT_FILE_ALREADY_EXISTS; return GetFileIOExceptionHResult(provokeException: (fileName) => { //Try to create the file again -this should throw an IOException with the correct HResult for the current platform using (var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read)) { } }); } internal static int? GetFileIOExceptionHResult(Action<string> provokeException) { string fileName; try { // This could throw, but we don't care about this HResult value. fileName = Path.GetTempFileName(); } catch { return null; // We couldn't create a temp file } try { provokeException(fileName); } catch (IOException ex) when (ex.HResult != 0) // Assume 0 means the platform is not completely implemented, thus unknown { return ex.HResult; } catch { return null; // Unknown exception } finally { try { File.Delete(fileName); } catch { } } return null; // Should never get here } /// <summary> /// Creates a new empty file in a random subdirectory of <see cref="Path.GetTempPath()"/>, using the given prefix and /// suffix strings to generate its name. /// </summary> /// <remarks> /// If this method returns successfully then it is guaranteed that: /// <list type="number"> /// <item><description>The file denoted by the returned abstract pathname did not exist before this method was invoked, and</description></item> /// <item><description>Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.</description></item> /// </list> /// This method provides only part of a temporary-file facility. However, the file will not be deleted automatically, /// it must be deleted by the caller. /// <para/> /// The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful /// string such as "hjb" or "mail". /// <para/> /// The suffix argument may be null, in which case a random suffix will be used. /// <para/> /// Both prefix and suffix must be provided with valid characters for the underlying system, as specified by /// <see cref="Path.GetInvalidFileNameChars()"/>. /// <para/> /// If the directory argument is null then the system-dependent default temporary-file directory will be used, /// with a random subdirectory name. The default temporary-file directory is specified by the /// <see cref="Path.GetTempPath()"/> method. On UNIX systems the default value of this property is typically /// "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "C:\\Users\\[UserName]\\AppData\Local\Temp". /// </remarks> /// <param name="prefix">The prefix string to be used in generating the file's name; must be at least three characters long</param> /// <param name="suffix">The suffix string to be used in generating the file's name; may be null, in which case a random suffix will be generated</param> /// <returns>A <see cref="FileInfo"/> instance representing the temp file that was created.</returns> public static FileInfo CreateTempFile(string prefix, string suffix) { return CreateTempFile(prefix, suffix, null); } /// <summary> /// Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. /// </summary> /// <remarks> /// If this method returns successfully then it is guaranteed that: /// <list type="number"> /// <item><description>The file denoted by the returned abstract pathname did not exist before this method was invoked, and</description></item> /// <item><description>Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.</description></item> /// </list> /// This method provides only part of a temporary-file facility. However, the file will not be deleted automatically, /// it must be deleted by the caller. /// <para/> /// The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful /// string such as "hjb" or "mail". /// <para/> /// The suffix argument may be null, in which case a random suffix will be used. /// <para/> /// Both prefix and suffix must be provided with valid characters for the underlying system, as specified by /// <see cref="Path.GetInvalidFileNameChars()"/>. /// <para/> /// If the directory argument is null then the system-dependent default temporary-file directory will be used, /// with a random subdirectory name. The default temporary-file directory is specified by the /// <see cref="Path.GetTempPath()"/> method. On UNIX systems the default value of this property is typically /// "/tmp" or "/var/tmp"; on Microsoft Windows systems it is typically "C:\\Users\\[UserName]\\AppData\Local\Temp". /// </remarks> /// <param name="prefix">The prefix string to be used in generating the file's name; must be at least three characters long</param> /// <param name="suffix">The suffix string to be used in generating the file's name; may be null, in which case a random suffix will be generated</param> /// <param name="directory">The directory in which the file is to be created, or null if the default temporary-file directory is to be used</param> /// <returns>A <see cref="FileInfo"/> instance representing the temp file that was created.</returns> public static FileInfo CreateTempFile(string prefix, string suffix, DirectoryInfo directory) { if (string.IsNullOrEmpty(prefix)) throw new ArgumentNullException(nameof(prefix)); if (prefix.Length < 3) throw new ArgumentException("Prefix string too short"); // Ensure the strings passed don't contain invalid characters if (prefix.ContainsAny(INVALID_FILENAME_CHARS)) throw new ArgumentException(string.Format("Prefix contains invalid characters. You may not use any of '{0}'", string.Join(", ", INVALID_FILENAME_CHARS))); if (suffix != null && suffix.ContainsAny(INVALID_FILENAME_CHARS)) throw new ArgumentException(string.Format("Suffix contains invalid characters. You may not use any of '{0}'", string.Join(", ", INVALID_FILENAME_CHARS))); // If no directory supplied, create one. if (directory == null) { directory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()))); } // Ensure the directory exists (this does nothing if it already exists, although may throw exceptions in cases where permissions are changed) directory.Create(); string fileName = string.Empty; while (true) { fileName = NewTempFileName(prefix, suffix, directory); if (File.Exists(fileName)) { continue; } try { // Create the file, and close it immediately using (var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read)) { break; } } catch (IOException e) when (IsFileAlreadyExistsException(e, fileName)) { // If the error was because the file exists, try again. continue; } } return new FileInfo(fileName); } /// <summary> /// Tests whether the passed in <see cref="Exception"/> is an <see cref="IOException"/> /// corresponding to the underlying operating system's "File Already Exists" violation. /// This works by forcing the exception to occur during initialization and caching the /// <see cref="Exception.HResult"/> value for the current OS. /// </summary> /// <param name="ex">An exception, for comparison.</param> /// <param name="filePath">The path of the file to check. This is used as a fallback in case the /// current OS doesn't have an HResult (an edge case).</param> /// <returns><c>true</c> if the exception passed is an <see cref="IOException"/> with an /// <see cref="Exception.HResult"/> corresponding to the operating system's "File Already Exists" violation, which /// occurs when an attempt is made to create a file that already exists.</returns> public static bool IsFileAlreadyExistsException(Exception ex, string filePath) { if (!typeof(IOException).Equals(ex)) return false; else if (HRESULT_FILE_ALREADY_EXISTS.HasValue) return ex.HResult == HRESULT_FILE_ALREADY_EXISTS; else return File.Exists(filePath); } /// <summary> /// Generates a new random file name with the provided <paramref name="directory"/>, /// <paramref name="prefix"/> and optional <paramref name="suffix"/>. /// </summary> /// <param name="prefix">The prefix string to be used in generating the file's name</param> /// <param name="suffix">The suffix string to be used in generating the file's name; may be null, in which case a random suffix will be generated</param> /// <param name="directory">A <see cref="DirectoryInfo"/> object containing the temp directory path. Must not be null.</param> /// <returns>A random file name</returns> internal static string NewTempFileName(string prefix, string suffix, DirectoryInfo directory) { string randomFileName = Path.GetRandomFileName(); if (suffix != null) { randomFileName = string.Concat( Path.GetFileNameWithoutExtension(randomFileName), suffix.StartsWith(".", StringComparison.Ordinal) ? suffix : '.' + suffix ); } return Path.Combine(directory.FullName, string.Concat(prefix, randomFileName)); } private static readonly ConcurrentDictionary<string, string> fileCanonPathCache = new ConcurrentDictionary<string, string>(); /// <summary> /// Returns the absolute path of this <see cref="FileSystemInfo"/> with all references resolved and /// any drive letters normalized to upper case on Windows. An /// <em>absolute</em> path is one that begins at the root of the file /// system. The canonical path is one in which all references have been /// resolved. For the cases of '..' and '.', where the file system supports /// parent and working directory respectively, these are removed and replaced /// with a direct directory reference. /// </summary> /// <param name="path">This <see cref="FileSystemInfo"/> instance.</param> /// <returns>The canonical path of this file.</returns> // LUCENENET NOTE: Implementation ported mostly from Apache Harmony public static string GetCanonicalPath(this FileSystemInfo path) { string absPath = path.FullName; // LUCENENET NOTE: This internally calls GetFullPath(), which resolves relative paths byte[] result = Encoding.UTF8.GetBytes(absPath); string canonPath; if (fileCanonPathCache.TryGetValue(absPath, out canonPath) && canonPath != null) { return canonPath; } // LUCENENET TODO: On Unix, this resolves symbolic links. Not sure // if it is safe to assume Path.GetFullPath() does that for us. //if (Path.DirectorySeparatorChar == '/') //{ // //// resolve the full path first // //result = resolveLink(result, result.Length, false); // //// resolve the parent directories // //result = resolve(result); //} int numSeparators = 1; for (int i = 0; i < result.Length; i++) { if (result[i] == Path.DirectorySeparatorChar) { numSeparators++; } } int[] sepLocations = new int[numSeparators]; int rootLoc = 0; if (Path.DirectorySeparatorChar == '\\') { if (result[0] == '\\') { rootLoc = (result.Length > 1 && result[1] == '\\') ? 1 : 0; } else { rootLoc = 2; // skip drive i.e. c: } } byte[] newResult = new byte[result.Length + 1]; int newLength = 0, lastSlash = 0, foundDots = 0; sepLocations[lastSlash] = rootLoc; for (int i = 0; i <= result.Length; i++) { if (i < rootLoc) { // Normalize case of Windows drive letter to upper newResult[newLength++] = (byte)char.ToUpperInvariant((char)result[i]); } else { if (i == result.Length || result[i] == Path.DirectorySeparatorChar) { if (i == result.Length && foundDots == 0) { break; } if (foundDots == 1) { /* Don't write anything, just reset and continue */ foundDots = 0; continue; } if (foundDots > 1) { /* Go back N levels */ lastSlash = lastSlash > (foundDots - 1) ? lastSlash - (foundDots - 1) : 0; newLength = sepLocations[lastSlash] + 1; foundDots = 0; continue; } sepLocations[++lastSlash] = newLength; newResult[newLength++] = (byte)Path.DirectorySeparatorChar; continue; } if (result[i] == '.') { foundDots++; continue; } /* Found some dots within text, write them out */ if (foundDots > 0) { for (int j = 0; j < foundDots; j++) { newResult[newLength++] = (byte)'.'; } } newResult[newLength++] = result[i]; foundDots = 0; } } // remove trailing slash if (newLength > (rootLoc + 1) && newResult[newLength - 1] == Path.DirectorySeparatorChar) { newLength--; } newResult[newLength] = 0; //newResult = getCanonImpl(newResult); newLength = newResult.Length; canonPath = fileCanonPathCache.GetOrAdd( absPath, k => Encoding.UTF8.GetString(newResult, 0, newLength).TrimEnd('\0')); // LUCENENET: Eliminate null terminator char return canonPath; } } }
using System; using System.Diagnostics; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { // ideas taken from: // . The ocean spray in your face [Jeff Lander] // http://www.double.co.nz/dust/col0798.pdf // . Building an Advanced Particle System [John van der Burg] // http://www.gamasutra.com/features/20000623/vanderburg_01.htm // . LOVE game engine // http://love2d.org/ // // // Radius mode support, from 71 squared // http://particledesigner.71squared.com/ // // IMPORTANT: Particle Designer is supported by cocos2d, but // 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, // cocos2d uses a another approach, but the results are almost identical. // public enum CCEmitterMode { Gravity, Radius, } public enum CCPositionType { Free, // Living particles are attached to the world and are unaffected by emitter repositioning. Relative, // Living particles are attached to the world but will follow the emitter repositioning. // Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite. Grouped, // Living particles are attached to the emitter and are translated along with it. } public class CCParticleSystem : CCNode, ICCTexture { public const int ParticleDurationInfinity = -1; public const int ParticleStartSizeEqualToEndSize = -1; public const int ParticleStartRadiusEqualToEndRadius = -1; // ivars int totalParticles; CCParticleBatchNode batchNode; CCTexture2D texture; CCBlendFunc blendFunc = CCBlendFunc.AlphaBlend; GravityMoveMode gravityMode; RadialMoveMode radialMode; #region Structures protected struct GravityMoveMode { internal CCPoint Gravity { get; set; } internal float RadialAccel { get; set; } internal float RadialAccelVar { get; set; } internal float Speed { get; set; } internal float SpeedVar { get; set; } internal float TangentialAccel { get; set; } internal float TangentialAccelVar { get; set; } internal bool RotationIsDir { get; set; } } protected struct RadialMoveMode { internal float EndRadius { get; set; } internal float EndRadiusVar { get; set; } internal float RotatePerSecond { get; set; } internal float RotatePerSecondVar { get; set; } internal float StartRadius { get; set; } internal float StartRadiusVar { get; set; } } // Particle structures protected struct CCParticleBase { internal float TimeToLive { get; set; } internal float Rotation { get; set; } internal float Size { get; set; } internal float DeltaRotation { get; set; } internal float DeltaSize { get; set; } internal CCPoint Position { get; set; } internal CCPoint StartPosition { get; set; } internal CCColor4F Color { get; set; } internal CCColor4F DeltaColor { get; set; } } protected struct CCParticleGravity { internal int AtlasIndex { get; set; } internal CCParticleBase ParticleBase; internal CCPoint Direction { get; set; } internal float RadialAccel { get; set; } internal float TangentialAccel { get; set; } } protected struct CCParticleRadial { internal int AtlasIndex { get; set; } internal CCParticleBase ParticleBase; internal float Angle { get; set; } internal float Radius { get; set; } internal float DegreesPerSecond { get; set; } internal float DeltaRadius { get; set; } } #endregion Structures #region Properties public bool IsActive { get; private set; } public bool AutoRemoveOnFinish { get; set; } public bool OpacityModifyRGB { get; set; } protected int AllocatedParticles { get; set; } public int ParticleCount { get; private set; } public int AtlasIndex { get; set; } protected float Elapsed { get; private set; } public float Duration { get; set; } public float Life { get; set; } public float LifeVar { get; set; } public float Angle { get; set; } public float AngleVar { get; set; } public float StartSize { get; set; } public float StartSizeVar { get; set; } public float EndSize { get; set; } public float EndSizeVar { get; set; } public float StartSpin { get; set; } public float StartSpinVar { get; set; } public float EndSpin { get; set; } public float EndSpinVar { get; set; } public float EmissionRate { get; set; } protected float EmitCounter { get; set; } public CCPoint SourcePosition { get; set; } public CCPoint PositionVar { get; set; } public CCPositionType PositionType { get; set; } public CCColor4F StartColor { get; set; } public CCColor4F StartColorVar { get; set; } public CCColor4F EndColor { get; set; } public CCColor4F EndColorVar { get; set; } // We only want this to be set when system initialised public CCEmitterMode EmitterMode { get; private set; } protected CCParticleGravity[] GravityParticles { get; set; } protected CCParticleRadial[] RadialParticles { get; set; } public bool IsFull { get { return (ParticleCount == totalParticles); } } public virtual int TotalParticles { get { return totalParticles; } set { Debug.Assert(value <= AllocatedParticles, "Particle: resizing particle array only supported for quads"); totalParticles = value; } } public CCBlendFunc BlendFunc { get { return blendFunc; } set { if (blendFunc.Source != value.Source || blendFunc.Destination != value.Destination) { blendFunc = value; UpdateBlendFunc(); } } } public bool BlendAdditive { get { return blendFunc == CCBlendFunc.Additive; } set { if (value) { blendFunc = CCBlendFunc.Additive; } else { if (Texture != null && !Texture.HasPremultipliedAlpha) { blendFunc = CCBlendFunc.NonPremultiplied; } else { blendFunc = CCBlendFunc.AlphaBlend; } } } } public virtual CCParticleBatchNode BatchNode { get { return batchNode; } set { if (batchNode != value) { batchNode = value; if (value != null) { if (EmitterMode == CCEmitterMode.Gravity) { // each particle needs a unique index for (int i = 0; i < totalParticles; i++) { GravityParticles[i].AtlasIndex = i; } } else { // each particle needs a unique index for (int i = 0; i < totalParticles; i++) { RadialParticles[i].AtlasIndex = i; } } if(Layer != null && BatchNode.Layer != Layer) BatchNode.Layer = Layer; } } } } public virtual CCTexture2D Texture { get { return texture; } set { if (Texture != value) { texture = value; UpdateBlendFunc(); } } } protected GravityMoveMode GravityMode { get { Debug.Assert(EmitterMode == CCEmitterMode.Gravity, "Particle Mode should be Gravity"); return gravityMode; } set { gravityMode = value; } } protected RadialMoveMode RadialMode { get { Debug.Assert(EmitterMode == CCEmitterMode.Radius, "Particle Mode should be Radius"); return radialMode; } set { radialMode = value; } } // Gravity mode public CCPoint Gravity { get { return GravityMode.Gravity; } set { gravityMode.Gravity = value; } } public float TangentialAccel { get { return GravityMode.TangentialAccel; } set { gravityMode.TangentialAccel = value; } } public float TangentialAccelVar { get { return GravityMode.TangentialAccelVar; } set { gravityMode.TangentialAccelVar = value; } } public float RadialAccel { get { return GravityMode.RadialAccel; } set { gravityMode.RadialAccel = value; } } public float RadialAccelVar { get { return GravityMode.RadialAccelVar; } set { gravityMode.RadialAccelVar = value; } } public bool RotationIsDir { get { return GravityMode.RotationIsDir; } set { gravityMode.RotationIsDir = value; } } public float Speed { get { return GravityMode.Speed; } set { gravityMode.Speed = value; } } public float SpeedVar { get { return GravityMode.SpeedVar; } set { gravityMode.SpeedVar = value; } } // Radius mode public float StartRadius { get { return RadialMode.StartRadius; } set { radialMode.StartRadius = value; } } public float StartRadiusVar { get { return RadialMode.StartRadiusVar; } set { radialMode.StartRadiusVar = value; } } public float EndRadius { get { return RadialMode.EndRadius; } set { radialMode.EndRadius = value; } } public float EndRadiusVar { get { return RadialMode.EndRadiusVar; } set { radialMode.EndRadiusVar = value; } } public float RotatePerSecond { get { return RadialMode.RotatePerSecond; } set { radialMode.RotatePerSecond = value; } } public float RotatePerSecondVar { get { return RadialMode.RotatePerSecondVar; } set { radialMode.RotatePerSecondVar = value; } } public override CCScene Scene { get { return base.Scene; } internal set { if(Scene != null && BatchNode != null && BatchNode.Scene != Scene) { BatchNode.Scene = Scene; } base.Scene = value; } } public override CCLayer Layer { get { return base.Layer; } internal set { if(Layer != null && BatchNode != null && BatchNode.Layer != Layer) { BatchNode.Layer = Layer; } base.Layer = value; } } #endregion Properties #region Constructors internal CCParticleSystem() { } public CCParticleSystem(string plistFile, string directoryName = null) : this(new CCParticleSystemConfig(plistFile, directoryName)) { } protected CCParticleSystem(int numberOfParticles, CCEmitterMode emitterMode = CCEmitterMode.Gravity) : this(numberOfParticles, true, emitterMode) { } CCParticleSystem(int numberOfParticles, bool shouldAllocParticles, CCEmitterMode emitterMode = CCEmitterMode.Gravity) { TotalParticles = numberOfParticles; AllocatedParticles = numberOfParticles; BlendFunc = CCBlendFunc.AlphaBlend; PositionType = CCPositionType.Free; EmitterMode = emitterMode; IsActive = true; AutoRemoveOnFinish = false; if(shouldAllocParticles) { if (emitterMode == CCEmitterMode.Gravity) { GravityParticles = new CCParticleGravity[TotalParticles]; } else { RadialParticles = new CCParticleRadial[TotalParticles]; } } } public CCParticleSystem(CCParticleSystemConfig particleConfig) : this(particleConfig.MaxParticles, false) { Duration = particleConfig.Duration;; Life = particleConfig.Life; LifeVar = particleConfig.LifeVar; EmissionRate = TotalParticles / Life; Angle = particleConfig.Angle; AngleVar = particleConfig.AngleVar; CCBlendFunc blendFunc = new CCBlendFunc(); blendFunc.Source = particleConfig.BlendFunc.Source; blendFunc.Destination = particleConfig.BlendFunc.Destination; BlendFunc = blendFunc; CCColor4F startColor = new CCColor4F(); startColor.R = particleConfig.StartColor.R; startColor.G = particleConfig.StartColor.G; startColor.B = particleConfig.StartColor.B; startColor.A = particleConfig.StartColor.A; StartColor = startColor; CCColor4F startColorVar = new CCColor4F(); startColorVar.R = particleConfig.StartColorVar.R; startColorVar.G = particleConfig.StartColorVar.G; startColorVar.B = particleConfig.StartColorVar.B; startColorVar.A = particleConfig.StartColorVar.A; StartColorVar = startColorVar; CCColor4F endColor = new CCColor4F(); endColor.R = particleConfig.EndColor.R; endColor.G = particleConfig.EndColor.G; endColor.B = particleConfig.EndColor.B; endColor.A = particleConfig.EndColor.A; EndColor = endColor; CCColor4F endColorVar = new CCColor4F(); endColorVar.R = particleConfig.EndColorVar.R; endColorVar.G = particleConfig.EndColorVar.G; endColorVar.B = particleConfig.EndColorVar.B; endColorVar.A = particleConfig.EndColorVar.A; EndColorVar = endColorVar; StartSize = particleConfig.StartSize; StartSizeVar = particleConfig.StartSizeVar; EndSize = particleConfig.EndSize; EndSizeVar = particleConfig.EndSizeVar; CCPoint position; position.X = particleConfig.Position.X; position.Y = particleConfig.Position.Y; Position = position; CCPoint positionVar; positionVar.X = particleConfig.PositionVar.X; positionVar.Y = particleConfig.PositionVar.X; PositionVar = positionVar; StartSpin = particleConfig.StartSpin; StartSpinVar = particleConfig.StartSpinVar; EndSpin = particleConfig.EndSpin; EndSpinVar = particleConfig.EndSpinVar; EmitterMode = particleConfig.EmitterMode; if (EmitterMode == CCEmitterMode.Gravity) { GravityParticles = new CCParticleGravity[TotalParticles]; GravityMoveMode newGravityMode = new GravityMoveMode(); CCPoint gravity; gravity.X = particleConfig.Gravity.X; gravity.Y = particleConfig.Gravity.Y; newGravityMode.Gravity = gravity; newGravityMode.Speed = particleConfig.GravitySpeed; newGravityMode.SpeedVar = particleConfig.GravitySpeedVar; newGravityMode.RadialAccel = particleConfig.GravityRadialAccel; newGravityMode.RadialAccelVar = particleConfig.GravityRadialAccelVar; newGravityMode.TangentialAccel = particleConfig.GravityTangentialAccel; newGravityMode.TangentialAccelVar = particleConfig.GravityTangentialAccelVar; newGravityMode.RotationIsDir = particleConfig.GravityRotationIsDir; GravityMode = newGravityMode; } else if (EmitterMode == CCEmitterMode.Radius) { RadialParticles = new CCParticleRadial[TotalParticles]; RadialMoveMode newRadialMode = new RadialMoveMode(); newRadialMode.StartRadius = particleConfig.RadialStartRadius; newRadialMode.StartRadiusVar = particleConfig.RadialStartRadiusVar; newRadialMode.EndRadius = particleConfig.RadialEndRadius; newRadialMode.EndRadiusVar = particleConfig.RadialEndRadiusVar; newRadialMode.RotatePerSecond = particleConfig.RadialRotatePerSecond; newRadialMode.RotatePerSecondVar = particleConfig.RadialRotatePerSecondVar; RadialMode = newRadialMode; } else { Debug.Assert(false, "Invalid emitterType in config file"); return; } // Don't get the internal texture if a batchNode is used if (BatchNode == null) Texture = particleConfig.Texture; } #endregion Constructors public override void OnEnter() { base.OnEnter(); Schedule(1); } public override void OnExit() { Unschedule(); base.OnExit(); } #region Particle management public void StopSystem() { IsActive = false; Elapsed = Duration; EmitCounter = 0; } public void ResetSystem() { IsActive = true; Elapsed = 0; if (EmitterMode == CCEmitterMode.Gravity) { for (int i = 0; i < ParticleCount; ++i) { GravityParticles[i].ParticleBase.TimeToLive = 0; } } else { for (int i = 0; i < ParticleCount; ++i) { RadialParticles[i].ParticleBase.TimeToLive = 0; } } } // Initialise particle void InitParticle(ref CCParticleGravity particleGrav, ref CCParticleBase particleBase) { InitParticleBase(ref particleBase); // direction float a = MathHelper.ToRadians(Angle + AngleVar * CCRandom.Float_Minus1_1()); if(EmitterMode == CCEmitterMode.Gravity) { CCPoint v = new CCPoint(CCMathHelper.Cos(a), CCMathHelper.Sin(a)); float s = GravityMode.Speed + GravityMode.SpeedVar * CCRandom.Float_Minus1_1(); particleGrav.Direction = v * s; particleGrav.RadialAccel = GravityMode.RadialAccel + GravityMode.RadialAccelVar * CCRandom.Float_Minus1_1(); particleGrav.TangentialAccel = GravityMode.TangentialAccel + GravityMode.TangentialAccelVar * CCRandom.Float_Minus1_1(); if (GravityMode.RotationIsDir) { particleBase.Rotation = -MathHelper.ToDegrees(CCPoint.ToAngle(particleGrav.Direction)); } } } void InitParticle(ref CCParticleRadial particleRadial, ref CCParticleBase particleBase) { InitParticleBase(ref particleBase); // direction float a = MathHelper.ToRadians(Angle + AngleVar * CCRandom.Float_Minus1_1()); // Set the default diameter of the particle from the source position float startRadius = RadialMode.StartRadius + RadialMode.StartRadiusVar * CCRandom.Float_Minus1_1(); float endRadius = RadialMode.EndRadius + RadialMode.EndRadiusVar * CCRandom.Float_Minus1_1(); particleRadial.Radius = startRadius; particleRadial.DeltaRadius = (RadialMode.EndRadius == ParticleStartRadiusEqualToEndRadius) ? 0 : (endRadius - startRadius) / particleBase.TimeToLive; particleRadial.Angle = a; particleRadial.DegreesPerSecond = MathHelper.ToRadians(RadialMode.RotatePerSecond + RadialMode.RotatePerSecondVar * CCRandom.Float_Minus1_1()); } void InitParticleBase(ref CCParticleBase particleBase) { float timeToLive = Math.Max(0, Life + LifeVar * CCRandom.Float_Minus1_1()); particleBase.TimeToLive = timeToLive; CCPoint particlePos; particlePos.X = SourcePosition.X + PositionVar.X * CCRandom.Float_Minus1_1(); particlePos.Y = SourcePosition.Y + PositionVar.Y * CCRandom.Float_Minus1_1(); particleBase.Position = particlePos; CCColor4F start = new CCColor4F(); start.R = MathHelper.Clamp(StartColor.R + StartColorVar.R * CCRandom.Float_Minus1_1(), 0, 1); start.G = MathHelper.Clamp(StartColor.G + StartColorVar.G * CCRandom.Float_Minus1_1(), 0, 1); start.B = MathHelper.Clamp(StartColor.B + StartColorVar.B * CCRandom.Float_Minus1_1(), 0, 1); start.A = MathHelper.Clamp(StartColor.A + StartColorVar.A * CCRandom.Float_Minus1_1(), 0, 1); particleBase.Color = start; CCColor4F end = new CCColor4F(); end.R = MathHelper.Clamp(EndColor.R + EndColorVar.R * CCRandom.Float_Minus1_1(), 0, 1); end.G = MathHelper.Clamp(EndColor.G + EndColorVar.G * CCRandom.Float_Minus1_1(), 0, 1); end.B = MathHelper.Clamp(EndColor.B + EndColorVar.B * CCRandom.Float_Minus1_1(), 0, 1); end.A = MathHelper.Clamp(EndColor.A + EndColorVar.A * CCRandom.Float_Minus1_1(), 0, 1); CCColor4F deltaColor = new CCColor4F(); deltaColor.R = (end.R - start.R) / timeToLive; deltaColor.G = (end.G - start.G) / timeToLive; deltaColor.B = (end.B - start.B) / timeToLive; deltaColor.A = (end.A - start.A) / timeToLive; particleBase.DeltaColor = deltaColor; float startSize = Math.Max(0, StartSize + StartSizeVar * CCRandom.Float_Minus1_1()); particleBase.Size = startSize; if (EndSize == ParticleStartSizeEqualToEndSize) { particleBase.DeltaSize = 0; } else { float endS = EndSize + EndSizeVar * CCRandom.Float_Minus1_1(); endS = Math.Max(0, endS); particleBase.DeltaSize = (endS - startSize) / timeToLive; } float startSpin = StartSpin + StartSpinVar * CCRandom.Float_Minus1_1(); float endSpin = EndSpin + EndSpinVar * CCRandom.Float_Minus1_1(); particleBase.Rotation = startSpin; particleBase.DeltaRotation = (endSpin - startSpin) / timeToLive; if (PositionType == CCPositionType.Free) { particleBase.StartPosition = Layer.VisibleBoundsWorldspace.Origin; } else if (PositionType == CCPositionType.Relative) { particleBase.StartPosition = Position; } } // Update particle bool UpdateParticleBase(ref CCParticleBase particleBase, float dt) { particleBase.TimeToLive -= dt; if(particleBase.TimeToLive > 0) { CCColor4F color = particleBase.Color; color.R += (particleBase.DeltaColor.R * dt); color.G += (particleBase.DeltaColor.G * dt); color.B += (particleBase.DeltaColor.B * dt); color.A += (particleBase.DeltaColor.A * dt); particleBase.Color = color; particleBase.Size += (particleBase.DeltaSize * dt); if(particleBase.Size < 0) { particleBase.Size = 0; } particleBase.Rotation += (particleBase.DeltaRotation * dt); return true; } return false; } bool UpdateParticle(ref CCParticleRadial particleRadial, float dt) { if(UpdateParticleBase(ref particleRadial.ParticleBase, dt)) { particleRadial.Angle += particleRadial.DegreesPerSecond * dt; particleRadial.Radius += particleRadial.DeltaRadius * dt; CCPoint position = particleRadial.ParticleBase.Position; position.X = -CCMathHelper.Cos(particleRadial.Angle) * particleRadial.Radius; position.Y = -CCMathHelper.Sin(particleRadial.Angle) * particleRadial.Radius; particleRadial.ParticleBase.Position = position; return true; } return false; } bool UpdateParticle(ref CCParticleGravity particleGrav, float dt) { if(UpdateParticleBase(ref particleGrav.ParticleBase, dt)) { float radial_x = 0; float radial_y = 0; float tmp_x, tmp_y; float tangential_x, tangential_y; CCPoint pos = particleGrav.ParticleBase.Position; float x = pos.X; float y = pos.Y; if (x != 0 || y != 0) { float l = 1.0f / (float) Math.Sqrt(x * x + y * y); radial_x = x * l; radial_y = y * l; } tangential_x = radial_x; tangential_y = radial_y; float radialAccel = particleGrav.RadialAccel; radial_x *= radialAccel; radial_y *= radialAccel; float tangentAccel = particleGrav.TangentialAccel; float newy = tangential_x; tangential_x = -tangential_y; tangential_y = newy; tangential_x *= tangentAccel; tangential_y *= tangentAccel; CCPoint gravity = GravityMode.Gravity; tmp_x = (radial_x + tangential_x + gravity.X) * dt; tmp_y = (radial_y + tangential_y + gravity.Y) * dt; CCPoint direction = particleGrav.Direction; direction.X += tmp_x; direction.Y += tmp_y; particleGrav.Direction = direction; CCPoint position = particleGrav.ParticleBase.Position; position.X += direction.X * dt; position.Y += direction.Y * dt; particleGrav.ParticleBase.Position = position; return true; } return false; } #endregion Particle management #region Updating system public void UpdateWithNoTime() { Update(0.0f); } public virtual void UpdateQuads() { // should be overriden } protected virtual void PostStep() { // should be overriden } public override void Update(float dt) { if (EmitterMode == CCEmitterMode.Gravity) { UpdateGravityParticles(dt); } else { UpdateRadialParticles(dt); } UpdateQuads(); if (BatchNode == null) { PostStep(); } } void UpdateGravityParticles(float dt) { if (IsActive && EmissionRate > 0) { float rate = 1.0f / EmissionRate; //issue #1201, prevent bursts of particles, due to too high emitCounter if (ParticleCount < TotalParticles) { EmitCounter += dt; } while (ParticleCount < TotalParticles && EmitCounter > rate) { InitParticle(ref GravityParticles[ParticleCount], ref GravityParticles[ParticleCount].ParticleBase); ++ParticleCount; EmitCounter -= rate; } Elapsed += dt; if (Duration != -1 && Duration < Elapsed) { StopSystem(); } } int index = 0; if (Visible) { while (index < ParticleCount) { if (UpdateParticle(ref GravityParticles[index], dt)) { // update particle counter ++index; } else { // life < 0 int currentIndex = GravityParticles[index].AtlasIndex; if (index != ParticleCount - 1) { GravityParticles[index] = GravityParticles[ParticleCount - 1]; } if (BatchNode != null) { //disable the switched particle BatchNode.DisableParticle(AtlasIndex + currentIndex); //switch indexes GravityParticles[ParticleCount - 1].AtlasIndex = currentIndex; } --ParticleCount; if (ParticleCount == 0 && AutoRemoveOnFinish) { Unschedule(); Parent.RemoveChild(this, true); return; } } } } } void UpdateRadialParticles(float dt) { if (IsActive && EmissionRate > 0) { float rate = 1.0f / EmissionRate; //issue #1201, prevent bursts of particles, due to too high emitCounter if (ParticleCount < TotalParticles) { EmitCounter += dt; } while (ParticleCount < TotalParticles && EmitCounter > rate) { InitParticle(ref RadialParticles[ParticleCount], ref RadialParticles[ParticleCount].ParticleBase); ++ParticleCount; EmitCounter -= rate; } Elapsed += dt; if (Duration != -1 && Duration < Elapsed) { StopSystem(); } } int index = 0; if (Visible) { while (index < ParticleCount) { if (UpdateParticle(ref RadialParticles[index], dt)) { // update particle counter ++index; } else { // life < 0 int currentIndex = RadialParticles[index].AtlasIndex; if (index != ParticleCount - 1) { RadialParticles[index] = RadialParticles[ParticleCount - 1]; } if (BatchNode != null) { //disable the switched particle BatchNode.DisableParticle(AtlasIndex + currentIndex); //switch indexes RadialParticles[ParticleCount - 1].AtlasIndex = currentIndex; } --ParticleCount; if (ParticleCount == 0 && AutoRemoveOnFinish) { Unschedule(); Parent.RemoveChild(this, true); return; } } } } } void UpdateBlendFunc() { Debug.Assert(BatchNode == null, "Can't change blending functions when the particle is being batched"); if (Texture != null) { bool premultiplied = Texture.HasPremultipliedAlpha; OpacityModifyRGB = false; if (blendFunc == CCBlendFunc.AlphaBlend) { if (premultiplied) { OpacityModifyRGB = true; } else { blendFunc = CCBlendFunc.NonPremultiplied; } } } } #endregion Updating system } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using System.Runtime.Serialization; using Orleans.Runtime; namespace Orleans.Providers { #pragma warning disable 1574 /// <summary> /// Base interface for all type-specific provider interfaces in Orleans /// </summary> /// <seealso cref="Orleans.Providers.IBootstrapProvider"/> /// <seealso cref="Orleans.Storage.IStorageProvider"/> /// <seealso cref="Orleans.LogConsistency.ILogConsistencyProvider"/> public interface IProvider { /// <summary>The name of this provider instance, as given to it in the config.</summary> string Name { get; } /// <summary> /// Initialization function called by Orleans Provider Manager when a new provider class instance is created /// </summary> /// <param name="name">Name assigned for this provider</param> /// <param name="providerRuntime">Callback for accessing system functions in the Provider Runtime</param> /// <param name="config">Configuration metadata to be used for this provider instance</param> /// <returns>Completion promise Task for the inttialization work for this provider</returns> Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config); /// <summary>Close function for this provider instance.</summary> /// <returns>Completion promise for the Close operation on this provider.</returns> Task Close(); } #pragma warning restore 1574 /// <summary> /// Internal provider management interface for instantiating dependent providers in a hierarchical tree of dependencies /// </summary> public interface IProviderManager { /// <summary> /// Call into Provider Manager for instantiating dependent providers in a hierarchical tree of dependencies /// </summary> /// <param name="name">Name of the provider to be found</param> /// <returns>Provider instance with the given name</returns> IProvider GetProvider(string name); } /// <summary> /// Configuration information that a provider receives /// </summary> public interface IProviderConfiguration { /// <summary> /// Full type name of this provider. /// </summary> string Type { get; } /// <summary> /// Name of this provider. /// </summary> string Name { get; } void AddChildConfiguration(IProviderConfiguration config); /// <summary> /// Configuration properties for this provider instance, as name-value pairs. /// </summary> ReadOnlyDictionary<string, string> Properties { get; } /// <summary> /// Nested providers in case of a hierarchical tree of dependencies /// </summary> IList<IProvider> Children { get; } /// <summary> /// Set a property in this provider configuration. /// If the property with this key already exists, it is been overwritten with the new value, otherwise it is just added. /// </summary> /// <param name="key">The key of the property</param> /// <param name="val">The value of the property</param> /// <returns>Provider instance with the given name</returns> void SetProperty(string key, string val); /// <summary> /// Removes a property in this provider configuration. /// </summary> /// <param name="key">The key of the property.</param> /// <returns>True if the property was found and removed, false otherwise.</returns> bool RemoveProperty(string key); } public static class ProviderConfigurationExtensions { public static int GetIntProperty(this IProviderConfiguration config, string key, int settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? int.Parse(s) : settingDefault; } public static bool TryGetDoubleProperty(this IProviderConfiguration config, string key, out double setting) { if (config == null) { throw new ArgumentNullException("config"); } string s; setting = 0; return config.Properties.TryGetValue(key, out s) ? double.TryParse(s, out setting) : false; } public static string GetProperty(this IProviderConfiguration config, string key, string settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? s : settingDefault; } public static Guid GetGuidProperty(this IProviderConfiguration config, string key, Guid settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? Guid.Parse(s) : settingDefault; } public static T GetEnumProperty<T>(this IProviderConfiguration config, string key, T settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? (T)Enum.Parse(typeof(T),s) : settingDefault; } public static Type GetTypeProperty(this IProviderConfiguration config, string key, Type settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? Type.GetType(s) : settingDefault; } public static bool GetBoolProperty(this IProviderConfiguration config, string key, bool settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? bool.Parse(s) : settingDefault; } public static TimeSpan GetTimeSpanProperty(this IProviderConfiguration config, string key, TimeSpan settingDefault) { if (config == null) { throw new ArgumentNullException("config"); } string s; return config.Properties.TryGetValue(key, out s) ? TimeSpan.Parse(s) : settingDefault; } public static bool TryGetTimeSpanProperty(this IProviderConfiguration config, string key, out TimeSpan setting) { if (config == null) { throw new ArgumentNullException("config"); } string s; setting = TimeSpan.Zero; return config.Properties.TryGetValue(key, out s) ? TimeSpan.TryParse(s, out setting) : false; } } /// <summary> /// Exception thrown whenever a provider has failed to be initialized. /// </summary> [Serializable] public class ProviderInitializationException : OrleansException { public ProviderInitializationException() { } public ProviderInitializationException(string msg) : base(msg) { } public ProviderInitializationException(string msg, Exception exc) : base(msg, exc) { } #if !NETSTANDARD protected ProviderInitializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using SFML.Graphics; using SFML.Window; namespace NetGore.Graphics.GUI { /// <summary> /// A box of text. /// </summary> public class TextBox : TextControl, IEditableText { /// <summary> /// The name of this <see cref="Control"/> for when looking up the skin information. /// </summary> const string _controlSkinName = "TextBox"; readonly EditableTextHandler _editableTextHandler; readonly TextBoxLines _lines = new TextBoxLines(); readonly NumCharsToDrawCache _numCharsToDraw = new NumCharsToDrawCache(); int _bufferTruncateSize = 100; TickCount _currentTime; /// <summary> /// Keeps track of the time at which the cursor started as visible. /// </summary> TickCount _cursorBlinkTimer; int _cursorLinePosition = 0; bool _hasTextChanged = false; bool _isMultiLine = true; /// <summary> /// The index of the first line to draw. /// </summary> int _lineBufferOffset = 0; int _lineCharBufferOffset = 0; int _maxBufferSize = 200; /// <summary> /// The maximum number of visible lines to draw (how many lines fit into the visible area). /// </summary> int _maxVisibleLines = 1; /// <summary> /// Initializes a new instance of the <see cref="TextControl"/> class. /// </summary> /// <param name="parent">Parent <see cref="Control"/> of this <see cref="Control"/>.</param> /// <param name="position">Position of the Control reletive to its parent.</param> /// <param name="clientSize">The size of the <see cref="Control"/>'s client area.</param> /// <exception cref="NullReferenceException"><paramref name="parent"/> is null.</exception> public TextBox(Control parent, Vector2 position, Vector2 clientSize) : base(parent, position, clientSize) { _numCharsToDraw.TextBox = this; _editableTextHandler = new EditableTextHandler(this); // Set the initial line length and number of visible lines UpdateMaxLineLength(); UpdateMaxVisibleLines(); } /// <summary> /// Initializes a new instance of the <see cref="TextControl"/> class. /// </summary> /// <param name="guiManager">The GUI manager this <see cref="Control"/> will be managed by.</param> /// <param name="position">Position of the Control reletive to its parent.</param> /// <param name="clientSize">The size of the <see cref="Control"/>'s client area.</param> /// <exception cref="ArgumentNullException"><paramref name="guiManager"/> is null.</exception> public TextBox(IGUIManager guiManager, Vector2 position, Vector2 clientSize) : base(guiManager, position, clientSize) { _numCharsToDraw.TextBox = this; _editableTextHandler = new EditableTextHandler(this); // Set the initial line length and number of visible lines UpdateMaxLineLength(); UpdateMaxVisibleLines(); } /// <summary> /// Gets or sets a <see cref="Func{T,U}"/> used to determine if only certain keys should be accepted when entering /// text into this <see cref="TextBox"/>. If null, all of the default keys will be accepted. Default is null. /// </summary> public Func<TextEventArgs, bool> AllowKeysHandler { get; set; } /// <summary> /// Gets or sets the number of lines to trim the buffer down to when the number of lines in this /// <see cref="TextBox"/> has exceeded the <see cref="TextBox.MaxBufferSize"/>. For best performance, this /// value should be at least 20% less than the <see cref="TextBox.MaxBufferSize"/> since truncating has nearly /// the same overhead no matter how many lines are truncated. This value should always be less than the /// <see cref="TextBox.MaxBufferSize"/>. /// By default, this value is equal to 100. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than zero.</exception> [SyncValue] [DefaultValue(100)] public int BufferTruncateSize { get { return _bufferTruncateSize; } set { if (value < 0) throw new ArgumentOutOfRangeException("value"); _bufferTruncateSize = value; } } /// <summary> /// Gets or set the position of the cursor on the current line. This is equal to the index of the character /// the cursor is immediately before. For example, 2 would mean the cursor is immediately before the character /// on the line at index 2 (or between the second and 3rd character). /// </summary> public int CursorLinePosition { get { return _cursorLinePosition; } set { _cursorLinePosition = value; EnsureCursorPositionValid(); EnsureHorizontalOffsetValid(); } } /// <summary> /// Gets or sets the <see cref="Font"/> used by the <see cref="TextControl"/>. /// </summary> public override Font Font { get { return base.Font; } set { if (base.Font == value) return; base.Font = value; UpdateMaxVisibleLines(); UpdateMaxLineLength(); } } /// <summary> /// Gets or sets a <see cref="Func{T,U}"/> used to determine if certain keys should be ignored when entering text into /// this <see cref="TextBox"/>. If null, the default keys will be ignored. Default is null. /// </summary> public Func<TextEventArgs, bool> IgnoreKeysHandler { get; set; } /// <summary> /// Gets or sets if this <see cref="TextBox"/> supports multiple lines. When changing from multiple lines to /// a single line, all line breaks will be forever lost and replaced with a space instead. /// </summary> [SyncValue] public virtual bool IsMultiLine { get { return _isMultiLine; } set { if (_isMultiLine == value) return; _isMultiLine = value; UpdateMaxLineLength(); UpdateMaxVisibleLines(); // Re-add all the content var contents = _lines.GetText(); Clear(); foreach (var line in contents) { if (line.Count > 0) AppendLine(line); } } } /// <summary> /// Gets or sets the index of the first line to draw. Value must be greater than or equal to zero and less than /// or equal <see cref="LineCount"/>. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than zero or greater /// than <see cref="LineCount"/>.</exception> public int LineBufferOffset { get { return _lineBufferOffset; } set { if (_lineBufferOffset == value) return; if (value < 0 || value > LineCount) throw new ArgumentOutOfRangeException("value"); _lineBufferOffset = value; } } /// <summary> /// Gets or sets the index of the first character in the line to draw. /// </summary> protected int LineCharBufferOffset { get { return _lineCharBufferOffset; } set { _lineCharBufferOffset = value; _numCharsToDraw.Invalidate(); EnsureHorizontalOffsetValid(); } } /// <summary> /// Gets the number of lines in the <see cref="TextBox"/>. /// </summary> public int LineCount { get { return _lines.Count; } } /// <summary> /// Gets the lines in the <see cref="TextBox"/>. /// </summary> protected TextBoxLines Lines { get { return _lines; } } /// <summary> /// Gets or sets the maximum line buffer of a multi-line <see cref="TextBox"/>. Once this value has been reached, /// the number of lines in the <see cref="TextBox"/> will be reduced to <see cref="TextBox.BufferTruncateSize"/>. /// If less than or equal to zero, truncating will not be performed. /// By default, this value is equal to 200. /// </summary> /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is less than or equal to zero.</exception> [SyncValue] [DefaultValue(200)] public int MaxBufferSize { get { return _maxBufferSize; } set { if (value <= 0) throw new ArgumentOutOfRangeException("value"); _maxBufferSize = value; } } /// <summary> /// Gets or sets the maximum length of the Text in characters. If this value is less than or equal to 0, then /// no limit will be assumed. The limitation only applies to input characters through key events. This limit /// can still be surpassed by manually setting the text. /// </summary> [SyncValue] public int MaxInputTextLength { get; set; } /// <summary> /// Gets the maximum number of possible visible lines. Only valid is <see cref="IsMultiLine"/> is true. /// </summary> public int MaxVisibleLines { get { return _maxVisibleLines; } } /// <summary> /// Gets the number of characters to draw in a row. Only used if <see cref="IsMultiLine"/> is false, since otherwise /// we just use word wrapping. /// </summary> protected int NumCharsToDraw { get { return _numCharsToDraw; } } /// <summary> /// Gets or sets the text in this <see cref="TextBox"/>. Please beware that setting the text through this /// method will result in all font styling to be lost. /// </summary> public override string Text { get { return _lines.GetRawText(); } set { if (value == null) value = string.Empty; if (StringComparer.Ordinal.Equals(_lines.GetRawText(), value)) return; CursorLinePosition = 0; Clear(); Append(value); } } /// <summary> /// Appends the <paramref name="text"/> to the <see cref="TextBox"/> at the end. /// </summary> /// <param name="text">The text to append.</param> public void Append(string text) { if (string.IsNullOrEmpty(text)) return; Append(new StyledText(text)); } /// <summary> /// Appends the <paramref name="text"/> to the <see cref="TextBox"/> at the end. /// </summary> /// <param name="text">The text to append.</param> public void Append(IEnumerable<StyledText> text) { foreach (var t in text) { Append(t); } } /// <summary> /// Appends the <paramref name="text"/> to the <see cref="TextBox"/> at the end. /// </summary> /// <param name="text">The text to append.</param> public void Append(StyledText text) { if (text.Text.Length == 0) return; if (!IsMultiLine) _lines.LastLine.Append(text.ToSingleline()); else { var textLines = StyledText.ToMultiline(text); _lines.LastLine.Append(textLines[0]); for (var i = 1; i < textLines.Count; i++) { var newLine = new TextBoxLine(_lines); _lines.Insert(_lines.Count, newLine); newLine.Append(textLines[i]); } TruncateIfNeeded(); } _numCharsToDraw.Invalidate(); _hasTextChanged = true; } /// <summary> /// Appends the <paramref name="text"/> to the <see cref="TextBox"/> at the end, then inserts a line break. /// </summary> /// <param name="text">The text to append.</param> public void AppendLine(string text) { if (string.IsNullOrEmpty(text)) return; AppendLine(new StyledText(text)); } /// <summary> /// Appends the <paramref name="text"/> to the <see cref="TextBox"/> at the end, then inserts a line break. /// </summary> /// <param name="text">The text to append.</param> public void AppendLine(StyledText text) { Append(text); if (IsMultiLine) { _lines.Insert(_lines.Count, new TextBoxLine(_lines)); TruncateIfNeeded(); } } /// <summary> /// Appends the <paramref name="text"/> to the <see cref="TextBox"/> at the end, then inserts a line break. /// </summary> /// <param name="text">The text to append.</param> public void AppendLine(IEnumerable<StyledText> text) { foreach (var t in text) { Append(t); } if (IsMultiLine) { _lines.Insert(_lines.Count, new TextBoxLine(_lines)); TruncateIfNeeded(); } else Append(" "); } /// <summary> /// Clears all the text in this <see cref="TextBox"/>. /// </summary> public void Clear() { _cursorLinePosition = 0; _lineBufferOffset = 0; _lineCharBufferOffset = 0; _lines.Clear(); _hasTextChanged = true; Debug.Assert(_lines.Count == 1); Debug.Assert(_lines.CurrentLineIndex == 0); Debug.Assert(_cursorLinePosition == 0); } /// <summary> /// Draws the Control. /// </summary> /// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param> protected override void DrawControl(ISpriteBatch spriteBatch) { base.DrawControl(spriteBatch); // Get the text offset var textDrawOffset = ScreenPosition + new Vector2(Border.LeftWidth, Border.TopHeight); // Draw the text DrawControlText(spriteBatch, textDrawOffset); // Draw the text cursor DrawCursor(spriteBatch, textDrawOffset); } /// <summary> /// Draws the text to display for the <see cref="TextBox"/>. /// </summary> /// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param> /// <param name="offset">The offset to draw the text at.</param> protected virtual void DrawControlText(ISpriteBatch spriteBatch, Vector2 offset) { if (IsMultiLine) _lines.Draw(spriteBatch, Font, LineBufferOffset, MaxVisibleLines, offset, ForeColor); else _lines.FirstLine.Draw(spriteBatch, Font, offset, ForeColor, LineCharBufferOffset, _numCharsToDraw); } /// <summary> /// Draws the text insertion cursor. /// </summary> /// <param name="sb">The <see cref="SpriteBatch"/> to draw to.</param> /// <param name="textPos">The screen position to start drawing the text at.</param> void DrawCursor(ISpriteBatch sb, Vector2 textPos) { if (!HasFocus || !IsEnabled) return; if (_cursorBlinkTimer + EditableTextHandler.CursorBlinkRate < _currentTime) return; var offset = 0; if (CursorLinePosition > 0) { var len = Math.Min(CursorLinePosition, _lines.CurrentLine.LineText.Length); offset = GetTextCursorOffset(_lines.CurrentLine.LineText.Substring(LineCharBufferOffset, len - LineCharBufferOffset)); } var visibleLineOffset = (_lines.CurrentLineIndex - LineBufferOffset) * Font.GetLineSpacing(); var p1 = textPos + new Vector2(offset, visibleLineOffset); var p2 = p1 + new Vector2(0, Font.GetLineSpacing()); RenderLine.Draw(sb, p1, p2, Color.Black); } void EnsureCursorPositionValid() { // Make sure the is on a character that exists in the line if (CursorLinePosition < 0) _cursorLinePosition = 0; else if (CursorLinePosition > _lines.CurrentLine.LineText.Length) _cursorLinePosition = _lines.CurrentLine.LineText.Length; if (IsMultiLine) { // Change the buffer so that the line the cursor is on is visible if (LineBufferOffset < _lines.CurrentLineIndex - MaxVisibleLines + 1) LineBufferOffset = _lines.CurrentLineIndex - MaxVisibleLines + 1; else if (LineBufferOffset > _lines.CurrentLineIndex) LineBufferOffset = _lines.CurrentLineIndex; } else EnsureHorizontalOffsetValid(); } void EnsureHorizontalOffsetValid() { if (IsMultiLine) return; // Make sure the cursor is in view if (LineCharBufferOffset < _cursorLinePosition - _numCharsToDraw) _lineCharBufferOffset = _cursorLinePosition - _numCharsToDraw; else if (LineCharBufferOffset > _cursorLinePosition) _lineCharBufferOffset = _cursorLinePosition; // Make sure we don't move the buffer more than we need to (show as many characters as possible on the right side) var firstFitting = _lines.CurrentLine.CountFittingCharactersRight(Font, (int)ClientSize.X); if (_lineCharBufferOffset > firstFitting) _lineCharBufferOffset = firstFitting; // Double-check we are in a legal range if (_lineCharBufferOffset < 0) _lineCharBufferOffset = 0; else if (_lineCharBufferOffset > _lines.CurrentLine.LineText.Length) _lineCharBufferOffset = _lines.CurrentLine.LineText.Length; } void GetCharacterAtPoint(Vector2 point, out int lineIndex, out int lineCharIndex) { // Get the line if (IsMultiLine) { lineIndex = LineBufferOffset + (int)Math.Floor(point.Y / Font.GetLineSpacing()); if (lineIndex >= _lines.Count) lineIndex = _lines.Count - 1; } else lineIndex = 0; // Get the character if (IsMultiLine) lineCharIndex = StyledText.FindLastFittingChar(_lines[lineIndex].LineText, Font, (int)point.X); else { var substr = _lines[lineIndex].LineText.Substring(LineCharBufferOffset); lineCharIndex = StyledText.FindLastFittingChar(substr, Font, (int)point.X); lineCharIndex += LineCharBufferOffset; } if (lineCharIndex > _lines[lineIndex].LineText.Length) lineCharIndex = _lines[lineIndex].LineText.Length; } /// <summary> /// Gets the offset for the text cursor for the given text. This is usually just the length of the text. /// </summary> /// <param name="text">The text to get the offset for.</param> /// <returns>The X offset for the cursor.</returns> protected virtual int GetTextCursorOffset(string text) { if (string.IsNullOrEmpty(text)) return 0; return (int)Font.MeasureString(text).X; } /// <summary> /// Inserts the <paramref name="text"/> into the <see cref="TextBox"/> at the current cursor position. /// </summary> /// <param name="text">The text to insert.</param> public void Insert(StyledText text) { _lines.CurrentLine.Insert(text, CursorLinePosition); ((IEditableText)this).MoveCursor(MoveCursorDirection.Right); _numCharsToDraw.Invalidate(); TruncateIfNeeded(); } /// <summary> /// When overridden in the derived class, loads the skinning information for the <see cref="Control"/> /// from the given <paramref name="skinManager"/>. /// </summary> /// <param name="skinManager">The <see cref="ISkinManager"/> to load the skinning information from.</param> public override void LoadSkin(ISkinManager skinManager) { Border = skinManager.GetBorder(_controlSkinName); } /// <summary> /// Handles when this <see cref="Control"/> was clicked. /// This is called immediately before <see cref="Control.OnClick"/>. /// Override this method instead of using an event hook on <see cref="Control.OnClick"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnClick(MouseButtonEventArgs e) { base.OnClick(e); if (!IsEnabled || !IsVisible) return; int lineIndex; int lineCharIndex; GetCharacterAtPoint(e.Location(), out lineIndex, out lineCharIndex); _lines.MoveTo(lineIndex); CursorLinePosition = lineCharIndex; } /// <summary> /// Handles when a key is being pressed while the <see cref="Control"/> has focus. /// This is called immediately before <see cref="Control.KeyPressed"/>. /// Override this method instead of using an event hook on <see cref="Control.KeyPressed"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnKeyPressed(KeyEventArgs e) { if (_editableTextHandler == null) return; _editableTextHandler.HandleKey(e); base.OnKeyPressed(e); } /// <summary> /// Handles when the <see cref="Control.Size"/> of this <see cref="Control"/> has changed. /// This is called immediately before <see cref="Control.Resized"/>. /// Override this method instead of using an event hook on <see cref="Control.Resized"/> when possible. /// </summary> protected override void OnResized() { base.OnResized(); if (IsMultiLine) { UpdateMaxLineLength(); UpdateMaxVisibleLines(); } else _numCharsToDraw.Invalidate(); } /// <summary> /// Handles when text has been entered into this <see cref="Control"/>. /// This is called immediately before <see cref="Control.TextEntered"/>. /// Override this method instead of using an event hook on <see cref="Control.TextEntered"/> when possible. /// </summary> /// <param name="e">The event args.</param> protected override void OnTextEntered(TextEventArgs e) { if (_editableTextHandler == null) return; if (!IsEnabled) return; if (IgnoreKeysHandler != null && IgnoreKeysHandler(e)) return; if (AllowKeysHandler != null && !AllowKeysHandler(e)) return; _editableTextHandler.HandleText(e); base.OnTextEntered(e); _hasTextChanged = true; } void ResetCursorBlink() { _cursorBlinkTimer = _currentTime; } /// <summary> /// Resizes the <see cref="TextBox"/> to the minimum size needed to fit all of the text. /// </summary> /// <param name="maxWidth">If greater than 0, the width of the <see cref="TextBox"/> will not exceed this value.</param> /// <param name="maxHeight">If greater than 0, the height of the <see cref="TextBox"/> will not exceed this value.</param> public void ResizeToFitText(int maxWidth = 0, int maxHeight = 0) { var reqWidth = 2; var reqHeight = 2; // Reset the view to the first line CursorLinePosition = 0; LineBufferOffset = 0; LineCharBufferOffset = 0; // Get the required width for (var i = 0; i < LineCount; i++) { var line = _lines[i]; var width = line.GetWidth(Font); if (width > reqWidth) reqWidth = width; } if (LineCount > 0) { // Find the required height by using the number of lines and the spacing between lines reqHeight = LineCount * Font.GetLineSpacing(); } // Keep in bounds of the max sizes if (maxWidth > 0 && reqWidth > maxWidth) reqWidth = maxWidth; if (maxHeight > 0 && reqHeight > maxHeight) reqHeight = maxHeight; // Resize ClientSize = new Vector2(reqWidth, reqHeight); } /// <summary> /// Checks if the <see cref="TextBox"/>'s lines need to be truncated, and if they do, truncates. /// </summary> void TruncateIfNeeded() { // Can't truncate if not multiline or no max buffer size has been set if (!IsMultiLine || MaxBufferSize <= 0) return; // Check if we have exceeded the maximum buffer size if (_lines.Count <= MaxBufferSize) return; // Truncate down to the BufferTruncateSize _lines.Truncate(_lines.Count - BufferTruncateSize); // Update some values to ensure they are valid for our new size if (LineBufferOffset >= _lines.Count) LineBufferOffset = _lines.Count - 1; EnsureHorizontalOffsetValid(); EnsureCursorPositionValid(); _numCharsToDraw.Invalidate(); } /// <summary> /// Updates the <see cref="Control"/>. This is called for every <see cref="Control"/>, even if it is disabled or /// not visible. /// </summary> /// <param name="currentTime">The current time in milliseconds.</param> protected override void UpdateControl(TickCount currentTime) { _currentTime = currentTime; if (_cursorBlinkTimer + (EditableTextHandler.CursorBlinkRate * 2) < currentTime) ResetCursorBlink(); base.UpdateControl(currentTime); if (_hasTextChanged) { _hasTextChanged = false; InvokeTextChanged(); } } /// <summary> /// Updates the maximum line length set in the <see cref="TextBoxLines"/> (<see cref="_lines"/>). /// </summary> void UpdateMaxLineLength() { if (IsMultiLine) _lines.SetMaxLineLength((int)ClientSize.X, Font); else _lines.RemoveMaxLineLength(); } /// <summary> /// Updates the count of the maximum number of visible lines (for multi-line <see cref="TextBox"/>es). /// </summary> void UpdateMaxVisibleLines() { if (Font == null) return; if (IsMultiLine) _maxVisibleLines = (int)Math.Floor(ClientSize.Y / Font.GetLineSpacing()); } #region IEditableText Members /// <summary> /// Breaks the line at the current position of the text cursor. /// </summary> public void BreakLine() { if (!IsMultiLine) return; _lines.BreakLine(CursorLinePosition); // Move the cursor to the first character of the next line if (_lines.MoveNext(false)) CursorLinePosition = 0; ResetCursorBlink(); InvokeTextChanged(); } /// <summary> /// Deletes the character from the <see cref="Control"/>'s text immediately before the current position /// of the text cursor. When applicable, if the cursor is at the start of the line, the cursor be moved /// to the previous line and the remainder of the line will be appended to the end of the previous line. /// </summary> void IEditableText.DeleteCharLeft() { var charToDelete = CursorLinePosition - 1; if (charToDelete < 0) { if (IsMultiLine && _lines.CurrentLineIndex > 0) { var oldLineLength = _lines[_lines.CurrentLineIndex - 1].LineText.Length; // Join the current line to the previous line _lines.JoinLineWithPrevious(_lines.CurrentLineIndex); // Move the cursor to the previous line at where the line used to end _lines.MovePrevious(); CursorLinePosition = oldLineLength; } } else { // Delete the character behind the cursor _lines.CurrentLine.Remove(charToDelete); CursorLinePosition--; } _numCharsToDraw.Invalidate(); ResetCursorBlink(); InvokeTextChanged(); } /// <summary> /// Deletes the character from the <see cref="Control"/>'s text immediately after the current position /// of the text cursor. When applicable, if the cursor is at the end of the line, the cursor be moved /// to the next line and the remainder of the line will be appended to the start of the previous line. /// </summary> void IEditableText.DeleteCharRight() { var charToDelete = CursorLinePosition; if (_lines.CurrentLine.LineText.Length == charToDelete) { if (IsMultiLine && _lines.Count > 1) { _lines.JoinLineWithPrevious(_lines.CurrentLineIndex + 1); } } else { // Delete the character in front of the cursor if (charToDelete < _lines.CurrentLine.LineText.Length) _lines.CurrentLine.Remove(charToDelete); } _numCharsToDraw.Invalidate(); ResetCursorBlink(); InvokeTextChanged(); } /// <summary> /// Inserts the specified character to the <see cref="Control"/>'s text at the current position /// of the text cursor. /// </summary> /// <param name="c">The character to insert.</param> void IEditableText.InsertChar(string c) { // HACK: This stuff with lineOldLen and oldLine is a cheap way to make the cursor move to the end of the text // removed from one line and appended to the next when the line breaks var lineOldLen = _lines.CurrentLine.LineText.Length; var oldLine = _lines.CurrentLineIndex; if (MaxInputTextLength > 0 && _lines.GetTextLength() >= MaxInputTextLength) return; _lines.CurrentLine.Insert(c, CursorLinePosition); ((IEditableText)this).MoveCursor(MoveCursorDirection.Right); if (IsMultiLine && oldLine < _lines.CurrentLineIndex && oldLine < _lines.Count) { for (var i = 0; i < lineOldLen - _lines[oldLine].LineText.Length + 1; i++) { ((IEditableText)this).MoveCursor(MoveCursorDirection.Right); } } _numCharsToDraw.Invalidate(); ResetCursorBlink(); InvokeTextChanged(); } /// <summary> /// Moves the cursor in the specified <paramref name="direction"/> by one character. /// </summary> /// <param name="direction">The direction to move the cursor.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="direction"/> is not a defined value of the /// <see cref="MoveCursorDirection"/> enum.</exception> void IEditableText.MoveCursor(MoveCursorDirection direction) { switch (direction) { case MoveCursorDirection.Left: if (CursorLinePosition > 0) CursorLinePosition--; else { if (IsMultiLine && _lines.MovePrevious()) CursorLinePosition = _lines.CurrentLine.LineText.Length; else CursorLinePosition = 0; } ResetCursorBlink(); break; case MoveCursorDirection.Right: if (CursorLinePosition < _lines.CurrentLine.LineText.Length) CursorLinePosition++; else { if (IsMultiLine && _lines.MoveNext(false)) CursorLinePosition = 0; else CursorLinePosition = _lines.CurrentLine.LineText.Length; } ResetCursorBlink(); break; case MoveCursorDirection.Up: if (!IsMultiLine) break; if (_lines.MovePrevious()) { // Line changed, so update the cursor position EnsureCursorPositionValid(); } ResetCursorBlink(); break; case MoveCursorDirection.Down: if (!IsMultiLine) break; if (_lines.MoveNext(false)) { // Line changed, so update the cursor position EnsureCursorPositionValid(); } ResetCursorBlink(); break; default: throw new ArgumentOutOfRangeException("direction"); } } #endregion /// <summary> /// Contains and manages the number of characters to draw. This allows for an easy means of calculating /// the value only when it is needed, allowing the value to be invalidated multiple times without updating /// each time it is invalidated. /// </summary> class NumCharsToDrawCache { const short _invalidateValue = -1; short _value = _invalidateValue; public TextBox TextBox { get; set; } /// <summary> /// Gets the number of characters to draw. /// </summary> int Value { get { if (_value == _invalidateValue) Update(); return _value; } } /// <summary> /// Invalidates the cached value. Use whenever the line changes. /// </summary> public void Invalidate() { _value = _invalidateValue; } /// <summary> /// Updates the cached value. /// </summary> void Update() { if (TextBox == null) return; var currLine = TextBox._lines.CurrentLine; _value = (short) currLine.CountFittingCharactersLeft(TextBox.Font, TextBox.LineCharBufferOffset, (int)TextBox.ClientSize.X); } /// <summary> /// Performs an implicit conversion from <see cref="NetGore.Graphics.GUI.TextBox.NumCharsToDrawCache"/> to /// <see cref="System.Int32"/>. /// </summary> /// <param name="c">The <see cref="NumCharsToDrawCache"/>.</param> /// <returns>The result of the conversion.</returns> public static implicit operator int(NumCharsToDrawCache c) { return c.Value; } } } }
// // Mono.CSharp.Debugger/MonoSymbolFile.cs // // Author: // Martin Baulig ([email protected]) // // (C) 2003 Ximian, Inc. http://www.ximian.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.Reflection; using SRE = System.Reflection.Emit; using System.Collections.Generic; using System.Text; using System.Threading; using System.IO; namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException () : base () { } public MonoSymbolFileException (string message, params object[] args) : base (String.Format (message, args)) { } } internal class MyBinaryWriter : BinaryWriter { public MyBinaryWriter (Stream stream) : base (stream) { } public void WriteLeb128 (int value) { base.Write7BitEncodedInt (value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader (Stream stream) : base (stream) { } public int ReadLeb128 () { return base.Read7BitEncodedInt (); } public string ReadString (int offset) { long old_pos = BaseStream.Position; BaseStream.Position = offset; string text = ReadString (); BaseStream.Position = old_pos; return text; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } #if !CECIL // TODO: Obsolete under .net 4 internal class MonoDebuggerSupport { static GetMethodTokenFunc get_method_token; static GetGuidFunc get_guid; delegate int GetMethodTokenFunc (MethodBase method); delegate Guid GetGuidFunc (Module module); static Delegate create_delegate (Type type, Type delegate_type, string name) { MethodInfo mi = type.GetMethod (name, BindingFlags.Static | BindingFlags.NonPublic); if (mi == null) throw new Exception ("Can't find " + name); return Delegate.CreateDelegate (delegate_type, mi); } static MonoDebuggerSupport () { get_method_token = (GetMethodTokenFunc) create_delegate ( typeof (Assembly), typeof (GetMethodTokenFunc), "MonoDebugger_GetMethodToken"); get_guid = (GetGuidFunc) create_delegate ( typeof (Module), typeof (GetGuidFunc), "Mono_GetGuid"); } public static int GetMethodToken (MethodBase method) { return get_method_token (method); } public static Guid GetGuid (Module module) { return get_guid (module); } } #endif public class MonoSymbolFile : IDisposable { List<MethodEntry> methods = new List<MethodEntry> (); List<SourceFileEntry> sources = new List<SourceFileEntry> (); List<CompileUnitEntry> comp_units = new List<CompileUnitEntry> (); Dictionary<Type, int> type_hash = new Dictionary<Type, int> (); Dictionary<int, AnonymousScopeEntry> anonymous_scopes; OffsetTable ot; int last_type_index; int last_method_index; int last_namespace_index; public readonly string FileName = "<dynamic>"; public readonly int MajorVersion = OffsetTable.MajorVersion; public readonly int MinorVersion = OffsetTable.MinorVersion; public int NumLineNumbers; internal MonoSymbolFile () { ot = new OffsetTable (); } internal int AddSource (SourceFileEntry source) { sources.Add (source); return sources.Count; } internal int AddCompileUnit (CompileUnitEntry entry) { comp_units.Add (entry); return comp_units.Count; } internal int DefineType (Type type) { int index; if (type_hash.TryGetValue (type, out index)) return index; index = ++last_type_index; type_hash.Add (type, index); return index; } internal void AddMethod (MethodEntry entry) { methods.Add (entry); } public MethodEntry DefineMethod (CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) throw new InvalidOperationException (); MethodEntry method = new MethodEntry ( this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod (method); return method; } internal void DefineAnonymousScope (int id) { if (reader != null) throw new InvalidOperationException (); if (anonymous_scopes == null) anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> (); anonymous_scopes.Add (id, new AnonymousScopeEntry (id)); } internal void DefineCapturedVariable (int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) throw new InvalidOperationException (); AnonymousScopeEntry scope = anonymous_scopes [scope_id]; scope.AddCapturedVariable (name, captured_name, kind); } internal void DefineCapturedScope (int scope_id, int id, string captured_name) { if (reader != null) throw new InvalidOperationException (); AnonymousScopeEntry scope = anonymous_scopes [scope_id]; scope.AddCapturedScope (id, captured_name); } internal int GetNextTypeIndex () { return ++last_type_index; } internal int GetNextMethodIndex () { return ++last_method_index; } internal int GetNextNamespaceIndex () { return ++last_namespace_index; } void Write (MyBinaryWriter bw, Guid guid) { // Magic number and file version. bw.Write (OffsetTable.Magic); bw.Write (MajorVersion); bw.Write (MinorVersion); bw.Write (guid.ToByteArray ()); // // Offsets of file sections; we must write this after we're done // writing the whole file, so we just reserve the space for it here. // long offset_table_offset = bw.BaseStream.Position; ot.Write (bw, MajorVersion, MinorVersion); // // Sort the methods according to their tokens and update their index. // methods.Sort (); for (int i = 0; i < methods.Count; i++) ((MethodEntry) methods [i]).Index = i + 1; // // Write data sections. // ot.DataSectionOffset = (int) bw.BaseStream.Position; foreach (SourceFileEntry source in sources) source.WriteData (bw); foreach (CompileUnitEntry comp_unit in comp_units) comp_unit.WriteData (bw); foreach (MethodEntry method in methods) method.WriteData (this, bw); ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset; // // Write the method index table. // ot.MethodTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < methods.Count; i++) { MethodEntry entry = (MethodEntry) methods [i]; entry.Write (bw); } ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset; // // Write source table. // ot.SourceTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < sources.Count; i++) { SourceFileEntry source = (SourceFileEntry) sources [i]; source.Write (bw); } ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset; // // Write compilation unit table. // ot.CompileUnitTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < comp_units.Count; i++) { CompileUnitEntry unit = (CompileUnitEntry) comp_units [i]; unit.Write (bw); } ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset; // // Write anonymous scope table. // ot.AnonymousScopeCount = anonymous_scopes != null ? anonymous_scopes.Count : 0; ot.AnonymousScopeTableOffset = (int) bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry scope in anonymous_scopes.Values) scope.Write (bw); } ot.AnonymousScopeTableSize = (int) bw.BaseStream.Position - ot.AnonymousScopeTableOffset; // // Fixup offset table. // ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; // // Write offset table. // ot.TotalFileSize = (int) bw.BaseStream.Position; bw.Seek ((int) offset_table_offset, SeekOrigin.Begin); ot.Write (bw, MajorVersion, MinorVersion); bw.Seek (0, SeekOrigin.End); #if false Console.WriteLine ("TOTAL: {0} line numbes, {1} bytes, extended {2} bytes, " + "{3} methods.", NumLineNumbers, LineNumberSize, ExtendedLineNumberSize, methods.Count); #endif } public void CreateSymbolFile (Guid guid, FileStream fs) { if (reader != null) throw new InvalidOperationException (); Write (new MyBinaryWriter (fs), guid); } MyBinaryReader reader; Dictionary<int, SourceFileEntry> source_file_hash; Dictionary<int, CompileUnitEntry> compile_unit_hash; List<MethodEntry> method_list; Dictionary<int, MethodEntry> method_token_hash; Dictionary<string, int> source_name_hash; Guid guid; MonoSymbolFile (string filename) { this.FileName = filename; FileStream stream = new FileStream (filename, FileMode.Open, FileAccess.Read); reader = new MyBinaryReader (stream); try { long magic = reader.ReadInt64 (); int major_version = reader.ReadInt32 (); int minor_version = reader.ReadInt32 (); if (magic != OffsetTable.Magic) throw new MonoSymbolFileException ( "Symbol file `{0}' is not a valid " + "Mono symbol file", filename); if (major_version != OffsetTable.MajorVersion) throw new MonoSymbolFileException ( "Symbol file `{0}' has version {1}, " + "but expected {2}", filename, major_version, OffsetTable.MajorVersion); if (minor_version != OffsetTable.MinorVersion) throw new MonoSymbolFileException ( "Symbol file `{0}' has version {1}.{2}, " + "but expected {3}.{4}", filename, major_version, minor_version, OffsetTable.MajorVersion, OffsetTable.MinorVersion); MajorVersion = major_version; MinorVersion = minor_version; guid = new Guid (reader.ReadBytes (16)); ot = new OffsetTable (reader, major_version, minor_version); } catch { throw new MonoSymbolFileException ( "Cannot read symbol file `{0}'", filename); } source_file_hash = new Dictionary<int, SourceFileEntry> (); compile_unit_hash = new Dictionary<int, CompileUnitEntry> (); } void CheckGuidMatch (Guid other, string filename, string assembly) { if (other == guid) return; throw new MonoSymbolFileException ( "Symbol file `{0}' does not match assembly `{1}'", filename, assembly); } #if CECIL protected MonoSymbolFile (string filename, Mono.Cecil.ModuleDefinition module) : this (filename) { CheckGuidMatch (module.Mvid, filename, module.FullyQualifiedName); } public static MonoSymbolFile ReadSymbolFile (Mono.Cecil.ModuleDefinition module) { return ReadSymbolFile (module, module.FullyQualifiedName); } public static MonoSymbolFile ReadSymbolFile (Mono.Cecil.ModuleDefinition module, string filename) { string name = filename + ".mdb"; return new MonoSymbolFile (name, module); } #else protected MonoSymbolFile (string filename, Assembly assembly) : this (filename) { // Check that the MDB file matches the assembly, if we have been // passed an assembly. if (assembly == null) return; Module[] modules = assembly.GetModules (); Guid assembly_guid = MonoDebuggerSupport.GetGuid (modules [0]); CheckGuidMatch (assembly_guid, filename, assembly.Location); } public static MonoSymbolFile ReadSymbolFile (Assembly assembly) { string filename = assembly.Location; string name = filename + ".mdb"; return new MonoSymbolFile (name, assembly); } #endif public static MonoSymbolFile ReadSymbolFile (string mdbFilename) { return new MonoSymbolFile (mdbFilename, null); } public int CompileUnitCount { get { return ot.CompileUnitCount; } } public int SourceCount { get { return ot.SourceCount; } } public int MethodCount { get { return ot.MethodCount; } } public int TypeCount { get { return ot.TypeCount; } } public int AnonymousScopeCount { get { return ot.AnonymousScopeCount; } } public int NamespaceCount { get { return last_namespace_index; } } public Guid Guid { get { return guid; } } public OffsetTable OffsetTable { get { return ot; } } internal int LineNumberCount = 0; internal int LocalCount = 0; internal int StringSize = 0; internal int LineNumberSize = 0; internal int ExtendedLineNumberSize = 0; public SourceFileEntry GetSourceFile (int index) { if ((index < 1) || (index > ot.SourceCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { SourceFileEntry source; if (source_file_hash.TryGetValue (index, out source)) return source; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); source = new SourceFileEntry (this, reader); source_file_hash.Add (index, source); reader.BaseStream.Position = old_pos; return source; } } public SourceFileEntry[] Sources { get { if (reader == null) throw new InvalidOperationException (); SourceFileEntry[] retval = new SourceFileEntry [SourceCount]; for (int i = 0; i < SourceCount; i++) retval [i] = GetSourceFile (i + 1); return retval; } } public CompileUnitEntry GetCompileUnit (int index) { if ((index < 1) || (index > ot.CompileUnitCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { CompileUnitEntry unit; if (compile_unit_hash.TryGetValue (index, out unit)) return unit; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); unit = new CompileUnitEntry (this, reader); compile_unit_hash.Add (index, unit); reader.BaseStream.Position = old_pos; return unit; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) throw new InvalidOperationException (); CompileUnitEntry[] retval = new CompileUnitEntry [CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) retval [i] = GetCompileUnit (i + 1); return retval; } } void read_methods () { lock (this) { if (method_token_hash != null) return; method_token_hash = new Dictionary<int, MethodEntry> (); method_list = new List<MethodEntry> (); long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry entry = new MethodEntry (this, reader, i + 1); method_token_hash.Add (entry.Token, entry); method_list.Add (entry); } reader.BaseStream.Position = old_pos; } } public MethodEntry GetMethodByToken (int token) { if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); MethodEntry me; method_token_hash.TryGetValue (token, out me); return me; } } public MethodEntry GetMethod (int index) { if ((index < 1) || (index > ot.MethodCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); return (MethodEntry) method_list [index - 1]; } } public MethodEntry[] Methods { get { if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); MethodEntry[] retval = new MethodEntry [MethodCount]; method_list.CopyTo (retval, 0); return retval; } } } public int FindSource (string file_name) { if (reader == null) throw new InvalidOperationException (); lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int> (); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry source = GetSourceFile (i + 1); source_name_hash.Add (source.FileName, i); } } int value; if (!source_name_hash.TryGetValue (file_name, out value)) return -1; return value; } } public AnonymousScopeEntry GetAnonymousScope (int id) { if (reader == null) throw new InvalidOperationException (); AnonymousScopeEntry scope; lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue (id, out scope); return scope; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> (); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { scope = new AnonymousScopeEntry (reader); anonymous_scopes.Add (scope.ID, scope); } return anonymous_scopes [id]; } } internal MyBinaryReader BinaryReader { get { if (reader == null) throw new InvalidOperationException (); return reader; } } public void Dispose () { Dispose (true); } protected virtual void Dispose (bool disposing) { if (disposing) { if (reader != null) { reader.Close (); reader = null; } } } } }
using Certify.Locales; using Certify.Models; using Microsoft.ApplicationInsights; using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; namespace Certify.Management { public class Util { public const string APPDATASUBFOLDER = "Certify"; public static void SetSupportedTLSVersions() { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } public static string GetAppDataFolder(string subFolder = null) { var parts = new List<string>() { Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), APPDATASUBFOLDER }; if (subFolder != null) parts.Add(subFolder); var path = Path.Combine(parts.ToArray()); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } public TelemetryClient InitTelemetry() { var tc = new TelemetryClient(); tc.Context.InstrumentationKey = ConfigResources.AIInstrumentationKey; tc.InstrumentationKey = ConfigResources.AIInstrumentationKey; // Set session data: tc.Context.Session.Id = Guid.NewGuid().ToString(); tc.Context.Component.Version = GetAppVersion().ToString(); tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); return tc; } public Version GetAppVersion() { // returns the version of Certify.Shared System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); var v = assembly.GetName().Version; return v; } public async Task<UpdateCheck> CheckForUpdates() { var v = GetAppVersion(); return await this.CheckForUpdates(v); } public async Task<UpdateCheck> CheckForUpdates(Version appVersion) { return await this.CheckForUpdates(appVersion.ToString()); } public async Task<UpdateCheck> CheckForUpdates(string appVersion) { //get app version try { HttpClient client = new HttpClient(); var response = await client.GetAsync(ConfigResources.APIBaseURI + "update?version=" + appVersion); if (response.IsSuccessStatusCode) { string json = await response.Content.ReadAsStringAsync(); /*json = @"{ 'version': { 'major': 2, 'minor': 0, 'patch': 3 }, 'message': { 'body': 'There is an awesome update available.', 'downloadPageURL': 'https://certify.webprofusion.com', 'releaseNotesURL': 'https://certify.webprofusion.com/home/changelog', 'isMandatory': true } }";*/ UpdateCheck checkResult = Newtonsoft.Json.JsonConvert.DeserializeObject<UpdateCheck>(json); return CompareVersions(appVersion, checkResult); } return new UpdateCheck { IsNewerVersion = false }; } catch (Exception) { return null; } } public static UpdateCheck CompareVersions(string appVersion, UpdateCheck checkResult) { checkResult.IsNewerVersion = AppVersion.IsOtherVersionNewer(AppVersion.FromString(appVersion), checkResult.Version); // check for mandatory updates if (checkResult.Message != null && checkResult.Message.MandatoryBelowVersion != null) { checkResult.MustUpdate = AppVersion.IsOtherVersionNewer(AppVersion.FromString(appVersion), checkResult.Message.MandatoryBelowVersion); } return checkResult; } public string GetFileSHA256(Stream stream) { using (var bufferedStream = new BufferedStream(stream, 1024 * 32)) { SHA256 sha = null; try { sha = (SHA256)new System.Security.Cryptography.SHA256Managed(); } catch (System.InvalidOperationException) { // if creating managed SHA256 fails may be FIPS validation, try SHA256Cng sha = (SHA256)new System.Security.Cryptography.SHA256Cng(); } byte[] checksum = sha.ComputeHash(bufferedStream); return BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower(); } } /// <summary> /// Gets the certificate the file is signed with. /// </summary> /// <param name="filename"> /// The path of the signed file from which to create the X.509 certificate. /// </param> /// <returns> The certificate the file is signed with </returns> public X509Certificate2 GetFileCertificate(string filename) { // https://blogs.msdn.microsoft.com/windowsmobile/2006/05/17/programmatically-checking-the-authenticode-signature-on-a-file/ X509Certificate2 cert = null; try { cert = new X509Certificate2(X509Certificate.CreateFromSignedFile(filename)); X509Chain chain = new X509Chain(); X509ChainPolicy chainPolicy = new X509ChainPolicy() { RevocationMode = X509RevocationMode.Online, RevocationFlag = X509RevocationFlag.EntireChain }; chain.ChainPolicy = chainPolicy; if (chain.Build(cert)) { foreach (X509ChainElement chainElement in chain.ChainElements) { foreach (X509ChainStatus chainStatus in chainElement.ChainElementStatus) { System.Diagnostics.Debug.WriteLine(chainStatus.StatusInformation); } } } else { throw new Exception("Could not build cert chain"); } } catch (CryptographicException e) { Console.WriteLine("Error {0} : {1}", e.GetType(), e.Message); Console.WriteLine("Couldn't parse the certificate." + "Be sure it is a X.509 certificate"); return null; } return cert; } public bool VerifyUpdateFile(string tempFile, string expectedHash, bool throwOnDeviation = true) { bool signatureVerified = false; bool hashVerified = false; //get verified signed file cert var cert = GetFileCertificate(tempFile); //ensure cert subject if (!(cert != null && cert.SubjectName.Name.StartsWith("CN=Webprofusion Pty Ltd, O=Webprofusion Pty Ltd"))) { if (throwOnDeviation) { throw new Exception("Downloaded file failed digital signature check."); } else { return false; } } else { signatureVerified = true; } //verify file SHA256 string computedSHA256 = null; using (Stream stream = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read, 8192, true)) { computedSHA256 = GetFileSHA256(stream); } if (expectedHash.ToLower() == computedSHA256) { hashVerified = true; } else { if (throwOnDeviation) { throw new Exception("Downloaded file failed SHA256 hash check"); } else { return false; } } if (hashVerified && signatureVerified) { return true; } else { return false; } } public async Task<UpdateCheck> DownloadUpdate() { string pathname = Path.GetTempPath(); var result = await CheckForUpdates(); if (result.IsNewerVersion) { HttpClient client = new HttpClient(); //https://github.com/dotnet/corefx/issues/6849 var tempFile = Path.Combine(new string[] { pathname, "CertifySSL_" + result.Version.ToString() + "_Setup.tmp" }); var setupFile = tempFile.Replace(".tmp", ".exe"); bool downloadVerified = false; if (File.Exists(setupFile)) { // file already downloaded, see if it's already valid if (VerifyUpdateFile(setupFile, result.Message.SHA256, throwOnDeviation: false)) { downloadVerified = true; } } if (!downloadVerified) { // download and verify new setup try { using (HttpResponseMessage response = client.GetAsync(result.Message.DownloadFileURL, HttpCompletionOption.ResponseHeadersRead).Result) { response.EnsureSuccessStatusCode(); using (Stream contentStream = await response.Content.ReadAsStreamAsync(), fileStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true)) { var totalRead = 0L; var totalReads = 0L; var buffer = new byte[8192]; var isMoreToRead = true; do { var read = await contentStream.ReadAsync(buffer, 0, buffer.Length); if (read == 0) { isMoreToRead = false; } else { await fileStream.WriteAsync(buffer, 0, read); totalRead += read; totalReads += 1; if (totalReads % 512 == 0) { Console.WriteLine(string.Format("total bytes downloaded so far: {0:n0}", totalRead)); } } } while (isMoreToRead); fileStream.Close(); } } } catch (Exception exp) { System.Diagnostics.Debug.WriteLine("Failed to download update: " + exp.ToString()); downloadVerified = false; } // verify temp file if (!downloadVerified && VerifyUpdateFile(tempFile, result.Message.SHA256, throwOnDeviation: true)) { downloadVerified = true; if (File.Exists(setupFile)) File.Delete(setupFile); //delete existing file File.Move(tempFile, setupFile); // final setup file } } if (downloadVerified) { // setup is ready to run result.UpdateFilePath = setupFile; } } return result; } /// <summary> /// From https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#net_d /// </summary> /// <returns></returns> public static string GetDotNetVersion() { const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"; using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey)) { if (ndpKey != null && ndpKey.GetValue("Release") != null) { return GetDotNetVersion((int)ndpKey.GetValue("Release")); } else { return ".NET Version not detected."; } } } private static string GetDotNetVersion(int releaseKey) { if (releaseKey >= 460798) return "4.7 or later"; if (releaseKey >= 394802) return "4.6.2"; if (releaseKey >= 394254) return "4.6.1"; if (releaseKey >= 393295) return "4.6"; if (releaseKey >= 379893) return "4.5.2"; if (releaseKey >= 378675) return "4.5.1"; if (releaseKey >= 378389) return "4.5"; // This code should never execute. A non-null release key should mean that 4.5 or later // is installed. return "No 4.5 or later version detected"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Permissions; namespace System.DirectoryServices.AccountManagement { #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 [DirectoryRdnPrefix("CN")] public class GroupPrincipal : Principal { // // Public constructors // public GroupPrincipal(PrincipalContext context) { if (context == null) throw new ArgumentException(StringResources.NullArguments); this.ContextRaw = context; this.unpersisted = true; } public GroupPrincipal(PrincipalContext context, string samAccountName) : this(context) { if (samAccountName == null) throw new ArgumentException(StringResources.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) this.SamAccountName = samAccountName; this.Name = samAccountName; } // // Public properties // // IsSecurityGroup property private bool _isSecurityGroup = false; // the actual property value private LoadState _isSecurityGroupChanged = LoadState.NotSet; // change-tracking public Nullable<bool> IsSecurityGroup { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults as to the Enabled setting // (AD: creates disabled by default; SAM: creates enabled by default). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_isSecurityGroupChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Group", "Enabled: returning null, unpersisted={0}, enabledChanged={1}", this.unpersisted, _isSecurityGroupChanged); return null; } return HandleGet<bool>(ref _isSecurityGroup, PropertyNames.GroupIsSecurityGroup, ref _isSecurityGroupChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException("value"); HandleSet<bool>(ref _isSecurityGroup, value.Value, ref _isSecurityGroupChanged, PropertyNames.GroupIsSecurityGroup); } } // GroupScope property private GroupScope _groupScope = System.DirectoryServices.AccountManagement.GroupScope.Local; // the actual property value private LoadState _groupScopeChanged = LoadState.NotSet; // change-tracking public Nullable<GroupScope> GroupScope { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults for the GroupScope setting // (AD: Global; SAM: Local). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_groupScopeChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Group", "GroupScope: returning null, unpersisted={0}, groupScopeChanged={1}", this.unpersisted, _groupScopeChanged); return null; } return HandleGet<GroupScope>(ref _groupScope, PropertyNames.GroupGroupScope, ref _groupScopeChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException("value"); HandleSet<GroupScope>(ref _groupScope, value.Value, ref _groupScopeChanged, PropertyNames.GroupGroupScope); } } // Members property private PrincipalCollection _members = null; public PrincipalCollection Members { get { // We don't use HandleGet<T> here because we have to load in the PrincipalCollection // using a special procedure. It's not loaded as part of the regular LoadIfNeeded call. // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Check that we actually support this propery in our store //CheckSupportedProperty(PropertyNames.GroupMembers); if (_members == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: creating fresh PrincipalCollection"); if (!this.unpersisted) { // Retrieve the members from the store. // QueryCtx because when this group was retrieved, it was // assigned a _specific_ context for its store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: persisted, querying group membership"); BookmarkableResultSet refs = ContextRaw.QueryCtx.GetGroupMembership(this, false); _members = new PrincipalCollection(refs, this); } else { // unpersisted means there's no values to retrieve from the store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Members: unpersisted, creating empty PrincipalCollection"); _members = new PrincipalCollection(new EmptySet(), this); } } return _members; } } // // Public methods // public static new GroupPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (GroupPrincipal)FindByIdentityWithType(context, typeof(GroupPrincipal), identityValue); } public static new GroupPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (GroupPrincipal)FindByIdentityWithType(context, typeof(GroupPrincipal), identityType, identityValue); } public PrincipalSearchResult<Principal> GetMembers() { return GetMembers(false); } public PrincipalSearchResult<Principal> GetMembers(bool recursive) { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (!this.unpersisted) { // Retrieve the members from the store. // QueryCtx because when this group was retrieved, it was // assigned a _specific_ context for its store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetMembers: persisted, querying for members (recursive={0}", recursive); return new PrincipalSearchResult<Principal>(ContextRaw.QueryCtx.GetGroupMembership(this, recursive)); } else { // unpersisted means there's no values to retrieve from the store GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetMembers: unpersisted, creating empty PrincipalSearchResult"); return new PrincipalSearchResult<Principal>(null); } } private bool _disposed = false; public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "Dispose: disposing"); if (_members != null) _members.Dispose(); _disposed = true; GC.SuppressFinalize(this); } } finally { base.Dispose(); } } // // Internal "constructor": Used for constructing Groups returned by a query // static internal GroupPrincipal MakeGroup(PrincipalContext ctx) { GroupPrincipal g = new GroupPrincipal(ctx); g.unpersisted = false; return g; } // // Load/Store implementation // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "LoadValueIntoProperty: name=" + propertyName + " value=" + (value != null ? value.ToString() : "null")); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: _isSecurityGroup = (bool)value; _isSecurityGroupChanged = LoadState.Loaded; break; case PropertyNames.GroupGroupScope: _groupScope = (GroupScope)value; _groupScopeChanged = LoadState.Loaded; break; case PropertyNames.GroupMembers: Debug.Fail("Group.LoadValueIntoProperty: Trying to load Members, but Members is demand-loaded."); break; default: base.LoadValueIntoProperty(propertyName, value); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: return _isSecurityGroupChanged == LoadState.Changed; case PropertyNames.GroupGroupScope: return _groupScopeChanged == LoadState.Changed; case PropertyNames.GroupMembers: // If Members was never loaded, it couldn't possibly have changed if (_members != null) return _members.Changed; else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetChangeStatusForProperty: members was never loaded"); return false; } default: return base.GetChangeStatusForProperty(propertyName); } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.GroupIsSecurityGroup: return _isSecurityGroup; case PropertyNames.GroupGroupScope: return _groupScope; case PropertyNames.GroupMembers: return _members; default: return base.GetValueForProperty(propertyName); } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Group", "ResetAllChangeStatus"); _groupScopeChanged = (_groupScopeChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _isSecurityGroupChanged = (_isSecurityGroupChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; if (_members != null) _members.ResetTracking(); base.ResetAllChangeStatus(); } /// <summary> /// if isSmallGroup has a value, it means we already checked if the group is small /// </summary> private bool? _isSmallGroup; /// <summary> /// cache the search result for the member attribute /// it will only be set for small groups! /// </summary> internal SearchResult SmallGroupMemberSearchResult { get; private set; } /// <summary> /// Finds if the group is "small", meaning that it has less than MaxValRange values (usually 1500) /// The property list for the searcher of a group has "member" attribute. if there are more results than MaxValRange, there will also be a "member;range=..." attribute /// we can cache the result and don't fear from changes through Add/Remove/Save because the completed/pending lists are looked up before the actual values are /// </summary> internal bool IsSmallGroup() { if (_isSmallGroup.HasValue) { return _isSmallGroup.Value; } _isSmallGroup = false; DirectoryEntry de = (DirectoryEntry)this.UnderlyingObject; Debug.Assert(de != null); if (de != null) { using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base)) { SearchResult sr = ds.FindOne(); if (sr != null) { bool rangePropertyFound = false; foreach (string propName in sr.Properties.PropertyNames) { if (propName.StartsWith("member;range=", StringComparison.OrdinalIgnoreCase)) { rangePropertyFound = true; break; } } // we only consider the group "small" if there is a "member" property but no "member;range..." property if (!rangePropertyFound) { _isSmallGroup = true; SmallGroupMemberSearchResult = sr; } } } } return _isSmallGroup.Value; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.IO; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; namespace Org.BouncyCastle.Crypto.Tls { public class DefaultTlsCipherFactory : AbstractTlsCipherFactory { /// <exception cref="IOException"></exception> public override TlsCipher CreateCipher(TlsContext context, int encryptionAlgorithm, int macAlgorithm) { switch (encryptionAlgorithm) { case EncryptionAlgorithm.cls_3DES_EDE_CBC: return CreateDesEdeCipher(context, macAlgorithm); case EncryptionAlgorithm.AEAD_CHACHA20_POLY1305: // NOTE: Ignores macAlgorithm return CreateChaCha20Poly1305(context); case EncryptionAlgorithm.AES_128_CBC: return CreateAESCipher(context, 16, macAlgorithm); case EncryptionAlgorithm.AES_128_CCM: // NOTE: Ignores macAlgorithm return CreateCipher_Aes_Ccm(context, 16, 16); case EncryptionAlgorithm.AES_128_CCM_8: // NOTE: Ignores macAlgorithm return CreateCipher_Aes_Ccm(context, 16, 8); case EncryptionAlgorithm.AES_256_CCM: // NOTE: Ignores macAlgorithm return CreateCipher_Aes_Ccm(context, 32, 16); case EncryptionAlgorithm.AES_256_CCM_8: // NOTE: Ignores macAlgorithm return CreateCipher_Aes_Ccm(context, 32, 8); case EncryptionAlgorithm.AES_128_GCM: // NOTE: Ignores macAlgorithm return CreateCipher_Aes_Gcm(context, 16, 16); case EncryptionAlgorithm.AES_256_CBC: return CreateAESCipher(context, 32, macAlgorithm); case EncryptionAlgorithm.AES_256_GCM: // NOTE: Ignores macAlgorithm return CreateCipher_Aes_Gcm(context, 32, 16); case EncryptionAlgorithm.CAMELLIA_128_CBC: return CreateCamelliaCipher(context, 16, macAlgorithm); case EncryptionAlgorithm.CAMELLIA_128_GCM: // NOTE: Ignores macAlgorithm return CreateCipher_Camellia_Gcm(context, 16, 16); case EncryptionAlgorithm.CAMELLIA_256_CBC: return CreateCamelliaCipher(context, 32, macAlgorithm); case EncryptionAlgorithm.CAMELLIA_256_GCM: // NOTE: Ignores macAlgorithm return CreateCipher_Camellia_Gcm(context, 32, 16); case EncryptionAlgorithm.ESTREAM_SALSA20: return CreateSalsa20Cipher(context, 12, 32, macAlgorithm); case EncryptionAlgorithm.NULL: return CreateNullCipher(context, macAlgorithm); case EncryptionAlgorithm.RC4_128: return CreateRC4Cipher(context, 16, macAlgorithm); case EncryptionAlgorithm.SALSA20: return CreateSalsa20Cipher(context, 20, 32, macAlgorithm); case EncryptionAlgorithm.SEED_CBC: return CreateSeedCipher(context, macAlgorithm); default: throw new TlsFatalAlert(AlertDescription.internal_error); } } /// <exception cref="IOException"></exception> protected virtual TlsBlockCipher CreateAESCipher(TlsContext context, int cipherKeySize, int macAlgorithm) { return new TlsBlockCipher(context, CreateAesBlockCipher(), CreateAesBlockCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize); } /// <exception cref="IOException"></exception> protected virtual TlsBlockCipher CreateCamelliaCipher(TlsContext context, int cipherKeySize, int macAlgorithm) { return new TlsBlockCipher(context, CreateCamelliaBlockCipher(), CreateCamelliaBlockCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize); } /// <exception cref="IOException"></exception> protected virtual TlsCipher CreateChaCha20Poly1305(TlsContext context) { return new Chacha20Poly1305(context); } /// <exception cref="IOException"></exception> protected virtual TlsAeadCipher CreateCipher_Aes_Ccm(TlsContext context, int cipherKeySize, int macSize) { return new TlsAeadCipher(context, CreateAeadBlockCipher_Aes_Ccm(), CreateAeadBlockCipher_Aes_Ccm(), cipherKeySize, macSize); } /// <exception cref="IOException"></exception> protected virtual TlsAeadCipher CreateCipher_Aes_Gcm(TlsContext context, int cipherKeySize, int macSize) { return new TlsAeadCipher(context, CreateAeadBlockCipher_Aes_Gcm(), CreateAeadBlockCipher_Aes_Gcm(), cipherKeySize, macSize); } /// <exception cref="IOException"></exception> protected virtual TlsAeadCipher CreateCipher_Camellia_Gcm(TlsContext context, int cipherKeySize, int macSize) { return new TlsAeadCipher(context, CreateAeadBlockCipher_Camellia_Gcm(), CreateAeadBlockCipher_Camellia_Gcm(), cipherKeySize, macSize); } /// <exception cref="IOException"></exception> protected virtual TlsBlockCipher CreateDesEdeCipher(TlsContext context, int macAlgorithm) { return new TlsBlockCipher(context, CreateDesEdeBlockCipher(), CreateDesEdeBlockCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), 24); } /// <exception cref="IOException"></exception> protected virtual TlsNullCipher CreateNullCipher(TlsContext context, int macAlgorithm) { return new TlsNullCipher(context, CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm)); } /// <exception cref="IOException"></exception> protected virtual TlsStreamCipher CreateRC4Cipher(TlsContext context, int cipherKeySize, int macAlgorithm) { return new TlsStreamCipher(context, CreateRC4StreamCipher(), CreateRC4StreamCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize, false); } /// <exception cref="IOException"></exception> protected virtual TlsStreamCipher CreateSalsa20Cipher(TlsContext context, int rounds, int cipherKeySize, int macAlgorithm) { return new TlsStreamCipher(context, CreateSalsa20StreamCipher(rounds), CreateSalsa20StreamCipher(rounds), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), cipherKeySize, true); } /// <exception cref="IOException"></exception> protected virtual TlsBlockCipher CreateSeedCipher(TlsContext context, int macAlgorithm) { return new TlsBlockCipher(context, CreateSeedBlockCipher(), CreateSeedBlockCipher(), CreateHMacDigest(macAlgorithm), CreateHMacDigest(macAlgorithm), 16); } protected virtual IBlockCipher CreateAesEngine() { return new AesEngine(); } protected virtual IBlockCipher CreateCamelliaEngine() { return new CamelliaEngine(); } protected virtual IBlockCipher CreateAesBlockCipher() { return new CbcBlockCipher(CreateAesEngine()); } protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aes_Ccm() { return new CcmBlockCipher(CreateAesEngine()); } protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aes_Gcm() { // TODO Consider allowing custom configuration of multiplier return new GcmBlockCipher(CreateAesEngine()); } protected virtual IAeadBlockCipher CreateAeadBlockCipher_Camellia_Gcm() { // TODO Consider allowing custom configuration of multiplier return new GcmBlockCipher(CreateCamelliaEngine()); } protected virtual IBlockCipher CreateCamelliaBlockCipher() { return new CbcBlockCipher(CreateCamelliaEngine()); } protected virtual IBlockCipher CreateDesEdeBlockCipher() { return new CbcBlockCipher(new DesEdeEngine()); } protected virtual IStreamCipher CreateRC4StreamCipher() { return new RC4Engine(); } protected virtual IStreamCipher CreateSalsa20StreamCipher(int rounds) { return new Salsa20Engine(rounds); } protected virtual IBlockCipher CreateSeedBlockCipher() { return new CbcBlockCipher(new SeedEngine()); } /// <exception cref="IOException"></exception> protected virtual IDigest CreateHMacDigest(int macAlgorithm) { switch (macAlgorithm) { case MacAlgorithm.cls_null: return null; case MacAlgorithm.hmac_md5: return TlsUtilities.CreateHash(HashAlgorithm.md5); case MacAlgorithm.hmac_sha1: return TlsUtilities.CreateHash(HashAlgorithm.sha1); case MacAlgorithm.hmac_sha256: return TlsUtilities.CreateHash(HashAlgorithm.sha256); case MacAlgorithm.hmac_sha384: return TlsUtilities.CreateHash(HashAlgorithm.sha384); case MacAlgorithm.hmac_sha512: return TlsUtilities.CreateHash(HashAlgorithm.sha512); default: throw new TlsFatalAlert(AlertDescription.internal_error); } } } } #endif
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Management.Network { /// <summary> /// The Windows Azure Network management API provides a RESTful set of web /// services that interact with Windows Azure Networks service to manage /// your network resrources. The API has entities that capture the /// relationship between an end user and the Windows Azure Networks /// service. /// </summary> public static partial class RouteOperationsExtensions { /// <summary> /// The Put route operation creates/updates a route in the specified /// route table /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <param name='routeParameters'> /// Required. Parameters supplied to the create/update routeoperation /// </param> /// <returns> /// Response for PUT Routes Api servive call /// </returns> public static RoutePutResponse BeginCreateOrUpdating(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters) { return Task.Factory.StartNew((object s) => { return ((IRouteOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, routeTableName, routeName, routeParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put route operation creates/updates a route in the specified /// route table /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <param name='routeParameters'> /// Required. Parameters supplied to the create/update routeoperation /// </param> /// <returns> /// Response for PUT Routes Api servive call /// </returns> public static Task<RoutePutResponse> BeginCreateOrUpdatingAsync(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters) { return operations.BeginCreateOrUpdatingAsync(resourceGroupName, routeTableName, routeName, routeParameters, CancellationToken.None); } /// <summary> /// The delete route operation deletes the specified route from a route /// table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public static UpdateOperationResponse BeginDeleting(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName) { return Task.Factory.StartNew((object s) => { return ((IRouteOperations)s).BeginDeletingAsync(resourceGroupName, routeTableName, routeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete route operation deletes the specified route from a route /// table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <returns> /// If the resource provide needs to return an error to any operation, /// it should return the appropriate HTTP error code and a message /// body as can be seen below.The message should be localized per the /// Accept-Language header specified in the original request such /// thatit could be directly be exposed to users /// </returns> public static Task<UpdateOperationResponse> BeginDeletingAsync(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName) { return operations.BeginDeletingAsync(resourceGroupName, routeTableName, routeName, CancellationToken.None); } /// <summary> /// The Put route operation creates/updates a route in the specified /// route table /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <param name='routeParameters'> /// Required. Parameters supplied to the create/update route operation /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static AzureAsyncOperationResponse CreateOrUpdate(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters) { return Task.Factory.StartNew((object s) => { return ((IRouteOperations)s).CreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put route operation creates/updates a route in the specified /// route table /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <param name='routeParameters'> /// Required. Parameters supplied to the create/update route operation /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public static Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName, Route routeParameters) { return operations.CreateOrUpdateAsync(resourceGroupName, routeTableName, routeName, routeParameters, CancellationToken.None); } /// <summary> /// The delete route operation deletes the specified route from a route /// table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName) { return Task.Factory.StartNew((object s) => { return ((IRouteOperations)s).DeleteAsync(resourceGroupName, routeTableName, routeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete route operation deletes the specified route from a route /// table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName) { return operations.DeleteAsync(resourceGroupName, routeTableName, routeName, CancellationToken.None); } /// <summary> /// The Get route operation retreives information about the specified /// route from the route table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <returns> /// Response for GetRoute Api service call /// </returns> public static RouteGetResponse Get(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName) { return Task.Factory.StartNew((object s) => { return ((IRouteOperations)s).GetAsync(resourceGroupName, routeTableName, routeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get route operation retreives information about the specified /// route from the route table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <param name='routeName'> /// Required. The name of the route. /// </param> /// <returns> /// Response for GetRoute Api service call /// </returns> public static Task<RouteGetResponse> GetAsync(this IRouteOperations operations, string resourceGroupName, string routeTableName, string routeName) { return operations.GetAsync(resourceGroupName, routeTableName, routeName, CancellationToken.None); } /// <summary> /// The List network security rule opertion retrieves all the routes in /// a route table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <returns> /// Response for ListRoute Api servive call /// </returns> public static RouteListResponse List(this IRouteOperations operations, string resourceGroupName, string routeTableName) { return Task.Factory.StartNew((object s) => { return ((IRouteOperations)s).ListAsync(resourceGroupName, routeTableName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List network security rule opertion retrieves all the routes in /// a route table. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Network.IRouteOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='routeTableName'> /// Required. The name of the route table. /// </param> /// <returns> /// Response for ListRoute Api servive call /// </returns> public static Task<RouteListResponse> ListAsync(this IRouteOperations operations, string resourceGroupName, string routeTableName) { return operations.ListAsync(resourceGroupName, routeTableName, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using SortedDictionaryTests.SortedDictionary_SortedDictionary_OtherTests; using SortedDictionary_SortedDictionaryUtils; namespace SortedDictionaryTests { namespace SortedDictionary_SortedDictionary_OtherTests { public class SortedDictionary_CtorTests { [Fact] public static void SortedDictionary_ClearTest() { Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr[i] = new RefX1<int>(i); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); ValX1<string>[] stringArr = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr[i] = new ValX1<string>("SomeTestString" + i.ToString()); } IntDriver.Clear(intArr, stringArr, 1); IntDriver.Clear(intArr, stringArr, 10); IntDriver.Clear(new RefX1<int>[] { }, new ValX1<string>[] { }, 1); IntDriver.Clear(new RefX1<int>[] { }, new ValX1<string>[] { }, 10); StringDriver.Clear(stringArr, intArr, 1); StringDriver.Clear(stringArr, intArr, 10); StringDriver.Clear(new ValX1<string>[] { }, new RefX1<int>[] { }, 1); StringDriver.Clear(new ValX1<string>[] { }, new RefX1<int>[] { }, 10); IntDriver.NonGenericIDictionaryClear(intArr, stringArr, 1); IntDriver.NonGenericIDictionaryClear(intArr, stringArr, 10); IntDriver.NonGenericIDictionaryClear(new RefX1<int>[] { }, new ValX1<string>[] { }, 1); IntDriver.NonGenericIDictionaryClear(new RefX1<int>[] { }, new ValX1<string>[] { }, 10); StringDriver.NonGenericIDictionaryClear(stringArr, intArr, 1); StringDriver.NonGenericIDictionaryClear(stringArr, intArr, 10); StringDriver.NonGenericIDictionaryClear(new ValX1<string>[] { }, new RefX1<int>[] { }, 1); StringDriver.NonGenericIDictionaryClear(new ValX1<string>[] { }, new RefX1<int>[] { }, 10); } [Fact] public static void SortedDictionary_ConatinsValueTest() { Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } ValX1<string>[] stringArr2 = new ValX1<string>[10]; for (int i = 0; i < 10; i++) { stringArr2[i] = new ValX1<string>("SomeTestString" + (i + 100).ToString()); } //Ref<val>,Val<Ref> IntDriver.BasicContainsValue(intArr1, stringArr1); IntDriver.ContainsValueNegative(intArr1, stringArr1, stringArr2); IntDriver.ContainsValueNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, stringArr2); IntDriver.AddRemoveKeyContainsValue(intArr1, stringArr1, 0); IntDriver.AddRemoveKeyContainsValue(intArr1, stringArr1, 50); IntDriver.AddRemoveKeyContainsValue(intArr1, stringArr1, 99); IntDriver.AddRemoveAddKeyContainsValue(intArr1, stringArr1, 0, 1); IntDriver.AddRemoveAddKeyContainsValue(intArr1, stringArr1, 50, 2); IntDriver.AddRemoveAddKeyContainsValue(intArr1, stringArr1, 99, 3); //Val<Ref>,Ref<Val> StringDriver.BasicContainsValue(stringArr1, intArr1); StringDriver.BasicContainsValue(new ValX1<string>[] { new ValX1<string>("str") }, new RefX1<int>[] { null }); StringDriver.ContainsValueNegative(stringArr1, intArr1, intArr2); StringDriver.ContainsValueNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, intArr2); StringDriver.ContainsValueNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, new RefX1<int>[] { null }); StringDriver.AddRemoveKeyContainsValue(stringArr1, intArr1, 0); StringDriver.AddRemoveKeyContainsValue(stringArr1, intArr1, 50); StringDriver.AddRemoveKeyContainsValue(stringArr1, intArr1, 99); StringDriver.AddRemoveAddKeyContainsValue(stringArr1, intArr1, 0, 1); StringDriver.AddRemoveAddKeyContainsValue(stringArr1, intArr1, 50, 2); StringDriver.AddRemoveAddKeyContainsValue(stringArr1, intArr1, 99, 3); } [Fact] public static void SortedDictionary_GetEnumeratorTest() { Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr[i] = new RefX1<int>(i); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); ValX1<string>[] stringArr = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr[i] = new ValX1<string>("SomeTestString" + i.ToString()); } //Ref<Val>,Val<Ref> IntDriver.GetEnumeratorBasic(intArr, stringArr); IntDriver.GetEnumeratorBasic(new RefX1<int>[0], new ValX1<string>[0]); //Val<Ref>,Ref<Val> StringDriver.GetEnumeratorBasic(stringArr, intArr); StringDriver.GetEnumeratorBasic(new ValX1<string>[0], new RefX1<int>[0]); } [Fact] public static void SortedDictionary_GetEnumeratorTest_Negative() { Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr[i] = new RefX1<int>(i); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); ValX1<string>[] stringArr = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr[i] = new ValX1<string>("SomeTestString" + i.ToString()); } //Ref<Val>,Val<Ref> IntDriver.GetEnumeratorValidations(intArr, stringArr, new RefX1<int>(1000), new ValX1<string>("1000")); IntDriver.GetEnumeratorValidations(new RefX1<int>[0], new ValX1<string>[0], new RefX1<int>(1000), new ValX1<string>("1000")); //Val<Ref>,Ref<Val> StringDriver.GetEnumeratorValidations(new ValX1<string>[0], new RefX1<int>[0], new ValX1<string>("1000"), new RefX1<int>(1000)); } } // helper class public class Driver<K, V> where K : IComparableValue { // Clear helpers public void Clear(K[] keys, V[] values, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); tbl.Clear(); Assert.Equal(tbl.Count, 0); //"Err_1! Count was expected to be zero" for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } for (int i = 0; i < repeat; i++) { tbl.Clear(); Assert.Equal(tbl.Count, 0); //"Err_2! Count was expected to be zero" } } public void NonGenericIDictionaryClear(K[] keys, V[] values, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; _idic.Clear(); Assert.Equal(tbl.Count, 0); //"Err_3! Count was expected to be zero" for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } for (int i = 0; i < repeat; i++) { _idic.Clear(); Assert.Equal(tbl.Count, 0); //"Err_4! Count was expected to be zero" } } // ContainsValue helpers public void BasicContainsValue(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_5! Expected count to be equal to keys.Length" for (int i = 0; i < keys.Length; i++) { Assert.True(tbl.ContainsValue(values[i])); //"Err_6! Expected to get true" } } public void ContainsValueNegative(K[] keys, V[] values, V[] missingvalues) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_7! Expected count to be equal to keys.Length" for (int i = 0; i < missingvalues.Length; i++) { Assert.False(tbl.ContainsValue(missingvalues[i])); //"Err_8! Expected to get false" } } public void AddRemoveKeyContainsValue(K[] keys, V[] values, int index) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } tbl.Remove(keys[index]); Assert.False(tbl.ContainsValue(values[index])); //"Err_9! Expected to get false" } public void AddRemoveAddKeyContainsValue(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } for (int i = 0; i < repeat; i++) { tbl.Remove(keys[index]); tbl.Add(keys[index], values[index]); Assert.True(tbl.ContainsValue(values[index])); //"Err_10! Expected to get true" } } // GetEnumerators helpers public void GetEnumeratorBasic(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new TestSortedDictionary<K, V>(keys, values), new ValueKeyComparer<K>()); IEnumerator<KeyValuePair<K, V>> Enum = ((IDictionary<K, V>)tbl).GetEnumerator(); //There are no guarantees on the order of elements in the HT List<K> kls = new List<K>(); for (int i = 0; i < keys.Length; i++) kls.Add(keys[i]); List<V> vls = new List<V>(); for (int i = 0; i < keys.Length; i++) vls.Add(values[i]); for (int i = 0; i < keys.Length; i++) { Assert.True(Enum.MoveNext()); //"Err_11! Enumerator unexpectedly did not move" KeyValuePair<K, V> entry = Enum.Current; Assert.True(kls.Contains(entry.Key)); //"Err_12! Current enum key " + entry.Key + " not found in dictionary" kls.Remove(entry.Key); Assert.True(vls.Contains(entry.Value)); //"Err_13! Current enum value " + entry.Value + " not found in dictionary" vls.Remove(entry.Value); } for (int i = 0; i < keys.Length; i++) kls.Add(keys[i]); for (int i = 0; i < keys.Length; i++) vls.Add(values[i]); foreach (KeyValuePair<K, V> entry in tbl) { Assert.True(kls.Contains(entry.Key)); //"Err_14! Current enum key " + entry.Key + " not found in dictionary" kls.Remove(entry.Key); Assert.True(vls.Contains(entry.Value)); //"Err_15! Current enum value " + entry.Value + " not found in dictionary" vls.Remove(entry.Value); } kls = new List<K>(); for (int i = 0; i < keys.Length; i++) kls.Add(keys[i]); vls = new List<V>(); for (int i = 0; i < keys.Length; i++) vls.Add(values[i]); Assert.True(Enum.MoveNext() == false); //"Err_16! Enumerator unexpectedly moved" } public void GetEnumeratorValidations(K[] keys, V[] values, K nkey, V nvalue) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new TestSortedDictionary<K, V>(keys, values), new ValueKeyComparer<K>()); IEnumerator<KeyValuePair<K, V>> Enum = tbl.GetEnumerator(); KeyValuePair<K, V> entry; K currKey; V currValue; try { //The behavior here is undefined entry = Enum.Current; } catch (Exception) { } Assert.Throws<InvalidOperationException>((() => entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current)); //"5- Enum.Current did not throw invalid operation exception when positioned before collection" for (int i = 0; i < keys.Length; i++) { Assert.True(Enum.MoveNext()); //"Err_17! Expected MoveNext() to return true" } Assert.False(Enum.MoveNext()); //"Err_18! Enumerator unexpectedly moved" try { //The behavior here is undefined entry = Enum.Current; } catch (Exception) { } try { //The behavior here is undefined currKey = Enum.Current.Key; } catch (Exception) { } try { //The behavior here is undefined currValue = Enum.Current.Value; } catch (Exception) { } Assert.Throws<InvalidOperationException>((() => entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current)); //"Err_19! Enum.Current did not throw invalid operation exception when positioned after collection" Enum = ((IDictionary<K, V>)tbl).GetEnumerator(); Enum.MoveNext(); tbl.Add(nkey, nvalue); Assert.Throws<InvalidOperationException>((() => Enum.MoveNext())); //"Err_20! Enum.MoveNext did not throw expected invalid operation exception after collection was modified" tbl.Remove(nkey); // Test Reset Enum = tbl.GetEnumerator(); Enum.Reset(); Enum.Reset(); Enum.Reset(); for (int i = 0; i < keys.Length; i++) { Enum.MoveNext(); entry = Enum.Current; } Enum = tbl.GetEnumerator(); Enum.Reset(); for (int i = 0; i < keys.Length; i++) { Assert.True(Enum.MoveNext()); //"Err_21! Enumerator unexpectedly did not move" entry = Enum.Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_22! Actual: " + entry.Key.ToString() + ", " + entry.Value.ToString() + " Expected: " + keys[i].ToString() + ", " + values[i].ToString()); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_23! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_24! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); } // Iterate through half the collection, reset and then enumerate through it all Enum.Reset(); for (int i = 0; i < keys.Length / 2; i++) { Assert.True(Enum.MoveNext()); //"Err_25! Enumerator unexpectedly did not move" entry = Enum.Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_26! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_27! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_28! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); } Enum.Reset(); Enum.Reset(); for (int i = 0; i < keys.Length; i++) { Assert.True(Enum.MoveNext()); //"Err_29! Enumerator unexpectedly did not move" entry = Enum.Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_30! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_31! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(keys[i]) && (((null == (object)entry.Value) && (null == (object)values[i])) || entry.Value.Equals(values[i])), "Err_32! Enum.Current expected to be " + keys[i] + ", " + values[i] + ". Actually " + entry.Key + ", " + entry.Value); } tbl.Add(nkey, nvalue); Enum = tbl.GetEnumerator(); Enum.Reset(); Enum.MoveNext(); KeyValuePair<K, V> item = Enum.Current; tbl.Remove(nkey); tbl.Add(nkey, nvalue); entry = Enum.Current; Assert.True(entry.Key.Equals(item.Key) && (((null == (object)entry.Value) && (null == (object)item.Value)) || entry.Value.Equals(item.Value)), "Err_33! Enum.Current expected to be " + item.Key + ", " + item.Value + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(item.Key) && (((null == (object)entry.Value) && (null == (object)item.Value)) || entry.Value.Equals(item.Value)), "Err_34! Enum.Current expected to be " + item.Key + ", " + item.Value + ". Actually " + entry.Key + ", " + entry.Value); entry = (KeyValuePair<K, V>)((IEnumerator)Enum).Current; Assert.True(entry.Key.Equals(item.Key) && (((null == (object)entry.Value) && (null == (object)item.Value)) || entry.Value.Equals(item.Value)), "Err_35! Enum.Current expected to be " + item.Key + ", " + item.Value + ". Actually " + entry.Key + ", " + entry.Value); Assert.Throws<InvalidOperationException>((() => Enum.Reset())); //"Err_36! Enumerator.Reset did not throw expected invalid operation exception when called after the collection was modified" } } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; namespace Orleans.Runtime { /// <summary> /// The Utils class contains a variety of utility methods for use in application and grain code. /// </summary> public static class Utils { /// <summary> /// Returns a human-readable text string that describes an IEnumerable collection of objects. /// </summary> /// <typeparam name="T">The type of the list elements.</typeparam> /// <param name="collection">The IEnumerable to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use.</param> /// <param name="putInBrackets">Puts elements within brackets</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// elements with square brackets and separating them with commas.</returns> public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null, string separator = ", ", bool putInBrackets = true) { if (collection == null) { if (putInBrackets) return "[]"; else return "null"; } var sb = new StringBuilder(); if (putInBrackets) sb.Append("["); var enumerator = collection.GetEnumerator(); bool firstDone = false; while (enumerator.MoveNext()) { T value = enumerator.Current; string val; if (toString != null) val = toString(value); else val = value == null ? "null" : value.ToString(); if (firstDone) { sb.Append(separator); sb.Append(val); } else { sb.Append(val); firstDone = true; } } if (putInBrackets) sb.Append("]"); return sb.ToString(); } /// <summary> /// Returns a human-readable text string that describes a dictionary that maps objects to objects. /// </summary> /// <typeparam name="T1">The type of the dictionary keys.</typeparam> /// <typeparam name="T2">The type of the dictionary elements.</typeparam> /// <param name="dict">The dictionary to describe.</param> /// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param> /// <param name="separator">The separator to use. If none specified, the elements should appear separated by a new line.</param> /// <returns>A string assembled by wrapping the string descriptions of the individual /// pairs with square brackets and separating them with commas. /// Each key-value pair is represented as the string description of the key followed by /// the string description of the value, /// separated by " -> ", and enclosed in curly brackets.</returns> public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null) { if (dict == null || dict.Count == 0) { return "[]"; } if (separator == null) { separator = Environment.NewLine; } var sb = new StringBuilder("["); var enumerator = dict.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) { var pair = enumerator.Current; sb.Append("{"); sb.Append(pair.Key); sb.Append(" -> "); string val; if (toString != null) val = toString(pair.Value); else val = pair.Value == null ? "null" : pair.Value.ToString(); sb.Append(val); sb.Append("}"); if (index++ < dict.Count - 1) sb.Append(separator); } sb.Append("]"); return sb.ToString(); } public static string TimeSpanToString(TimeSpan timeSpan) { //00:03:32.8289777 return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds); } public static long TicksToMilliSeconds(long ticks) { return (long)TimeSpan.FromTicks(ticks).TotalMilliseconds; } public static float AverageTicksToMilliSeconds(float ticks) { return (float)TimeSpan.FromTicks((long)ticks).TotalMilliseconds; } /// <summary> /// Parse a Uri as an IPEndpoint. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port); } return null; } /// <summary> /// Parse a Uri as a Silo address, including the IPEndpoint and generation identifier. /// </summary> /// <param name="uri">The input Uri</param> /// <returns></returns> public static SiloAddress ToSiloAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), uri.Segments.Length > 1 ? int.Parse(uri.Segments[1]) : 0); } return null; } /// <summary> /// Parse a Uri as a Silo address, excluding the generation identifier. /// </summary> /// <param name="uri">The input Uri</param> public static SiloAddress ToGatewayAddress(this Uri uri) { switch (uri.Scheme) { case "gwy.tcp": return SiloAddress.New(uri.ToIPEndPoint(), 0); } return null; } /// <summary> /// Represent an IP end point in the gateway URI format.. /// </summary> /// <param name="ep">The input IP end point</param> /// <returns></returns> public static Uri ToGatewayUri(this System.Net.IPEndPoint ep) { var builder = new UriBuilder("gwy.tcp", ep.Address.ToString(), ep.Port, "0"); return builder.Uri; } /// <summary> /// Represent a silo address in the gateway URI format. /// </summary> /// <param name="address">The input silo address</param> /// <returns></returns> public static Uri ToGatewayUri(this SiloAddress address) { var builder = new UriBuilder("gwy.tcp", address.Endpoint.Address.ToString(), address.Endpoint.Port, address.Generation.ToString()); return builder.Uri; } /// <summary> /// Calculates an integer hash value based on the consistent identity hash of a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> public static int CalculateIdHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. int hash = 0; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i += 4) { int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]); hash = hash ^ tmp; } } finally { sha.Dispose(); } return hash; } /// <summary> /// Calculates a Guid hash value based on the consistent identity a string. /// </summary> /// <param name="text">The string to hash.</param> /// <returns>An integer hash for the string.</returns> internal static Guid CalculateGuidHash(string text) { SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1. byte[] hash = new byte[16]; try { byte[] data = Encoding.Unicode.GetBytes(text); byte[] result = sha.ComputeHash(data); for (int i = 0; i < result.Length; i ++) { byte tmp = (byte)(hash[i % 16] ^ result[i]); hash[i%16] = tmp; } } finally { sha.Dispose(); } return new Guid(hash); } public static bool TryFindException(Exception original, Type targetType, out Exception target) { if (original.GetType() == targetType) { target = original; return true; } else if (original is AggregateException) { var baseEx = original.GetBaseException(); if (baseEx.GetType() == targetType) { target = baseEx; return true; } else { var newEx = ((AggregateException)original).Flatten(); foreach (var exc in newEx.InnerExceptions) { if (exc.GetType() == targetType) { target = newEx; return true; } } } } target = null; return false; } public static void SafeExecute(Action action, ILogger logger = null, string caller = null) { SafeExecute(action, logger, caller==null ? (Func<string>)null : () => caller); } // a function to safely execute an action without any exception being thrown. // callerGetter function is called only in faulty case (now string is generated in the success case). [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public static void SafeExecute(Action action, ILogger logger, Func<string> callerGetter) { try { action(); } catch (Exception exc) { try { if (logger != null) { string caller = null; if (callerGetter != null) { try { caller = callerGetter(); }catch (Exception) { } } foreach (var e in exc.FlattenAggregate()) { logger.Warn(ErrorCode.Runtime_Error_100325, $"Ignoring {e.GetType().FullName} exception thrown from an action called by {caller ?? String.Empty}.", exc); } } } catch (Exception) { // now really, really ignore. } } } public static TimeSpan Since(DateTime start) { return DateTime.UtcNow.Subtract(start); } public static List<Exception> FlattenAggregate(this Exception exc) { var result = new List<Exception>(); if (exc is AggregateException) result.AddRange(exc.InnerException.FlattenAggregate()); else result.Add(exc); return result; } public static AggregateException Flatten(this ReflectionTypeLoadException rtle) { // if ReflectionTypeLoadException is thrown, we need to provide the // LoaderExceptions property in order to make it meaningful. var all = new List<Exception> { rtle }; all.AddRange(rtle.LoaderExceptions); throw new AggregateException("A ReflectionTypeLoadException has been thrown. The original exception and the contents of the LoaderExceptions property have been aggregated for your convenience.", all); } /// <summary> /// </summary> public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize) { var batch = new List<T>(batchSize); foreach (var item in sequence) { batch.Add(item); // when we've accumulated enough in the batch, send it out if (batch.Count >= batchSize) { yield return batch; // batch.ToArray(); batch = new List<T>(batchSize); } } if (batch.Count > 0) { yield return batch; //batch.ToArray(); } } [MethodImpl(MethodImplOptions.NoInlining)] public static string GetStackTrace(int skipFrames = 0) { skipFrames += 1; //skip this method from the stack trace #if NETSTANDARD skipFrames += 2; //skip the 2 Environment.StackTrace related methods. var stackTrace = Environment.StackTrace; for (int i = 0; i < skipFrames; i++) { stackTrace = stackTrace.Substring(stackTrace.IndexOf(Environment.NewLine) + Environment.NewLine.Length); } return stackTrace; #else return new System.Diagnostics.StackTrace(skipFrames).ToString(); #endif } public static GrainReference FromKeyString(string key, IGrainReferenceRuntime runtime) { return GrainReference.FromKeyString(key, runtime); } } }
// 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. //testing double narrowing using System; public struct VT { public double f1; public double delta1; public int a1; public double b1; public double temp; } public class CL { //used for add and sub public double f1 = 1.0; public double delta1 = 1.0E-18; //used for mul and div public int a1 = 3; public double b1 = (1.0 / 3.0); //used as temp variable public double temp; } public class ConvR8test { //static field of a1 class private static double s_f1 = 1.0; private static double s_delta1 = 1.0E-18; private static int s_a1 = 3; private static double s_b1 = (1.0 / 3.0); private static void disableInline(ref int x) { } //f1 and delta1 are static filed of a1 class private static double doubleadd() { int i = 0; disableInline(ref i); return s_f1 + s_delta1; } private static double doublesub() { int i = 0; disableInline(ref i); return s_f1 - s_delta1; } private static double doublemul() { int i = 0; disableInline(ref i); return s_a1 * s_b1; } private static double doublediv() { int i = 0; disableInline(ref i); return s_f1 / s_a1; } private static double doubleadd_inline() { return s_f1 + s_delta1; } private static double doublesub_inline() { return s_f1 - s_delta1; } private static double doublemul_inline() { return s_a1 * s_b1; } private static double doublediv_inline() { return s_f1 / s_a1; } public static int Main() { bool pass = true; double temp; double[] arr = new double[3]; VT vt1; CL cl1 = new CL(); //*** add *** Console.WriteLine(); Console.WriteLine("***add***"); //local, in-line if (((double)(s_f1 + s_delta1)) != s_f1) { Console.WriteLine("((double)(f1+delta1))!=f1"); pass = false; } //local temp = s_f1 + s_delta1; if (((double)temp) != s_f1) { Console.WriteLine("((double)temp)!=f1, temp=f1+delta1"); pass = false; } //method call if (((double)doubleadd()) != s_f1) { Console.WriteLine("((double)doubleadd())!=f1"); pass = false; } //inline method call if (((double)doubleadd_inline()) != s_f1) { Console.WriteLine("((double)doubleadd_inline())!=f1"); pass = false; } //array element arr[0] = s_f1; arr[1] = s_delta1; arr[2] = arr[0] + arr[1]; if (((double)arr[2]) != s_f1) { Console.WriteLine("((double)arr[2])!=f1"); pass = false; } //struct vt1.f1 = 1.0; vt1.delta1 = 1.0E-18; vt1.temp = vt1.f1 + vt1.delta1; if (((double)vt1.temp) != s_f1) { Console.WriteLine("((double)vt1.temp)!=f1"); pass = false; } //class cl1.temp = cl1.f1 + cl1.delta1; if (((double)cl1.temp) != s_f1) { Console.WriteLine("((double)cl1.temp)!=f1"); pass = false; } //*** minus *** Console.WriteLine(); Console.WriteLine("***sub***"); //local, in-line if (((double)(s_f1 - s_delta1)) != s_f1) { Console.WriteLine("((double)(f1-delta1))!=f1"); pass = false; } //local temp = s_f1 - s_delta1; if (((double)temp) != s_f1) { Console.WriteLine("((double)temp)!=f1, temp=f1-delta1"); pass = false; } //method call if (((double)doublesub()) != s_f1) { Console.WriteLine("((double)doublesub())!=f1"); pass = false; } //inline method call if (((double)doublesub_inline()) != s_f1) { Console.WriteLine("((double)doublesub_inline())!=f1"); pass = false; } //array element arr[0] = s_f1; arr[1] = s_delta1; arr[2] = arr[0] - arr[1]; if (((double)arr[2]) != s_f1) { Console.WriteLine("((double)arr[2])!=f1"); pass = false; } //struct vt1.f1 = 1.0; vt1.delta1 = 1.0E-18; vt1.temp = vt1.f1 - vt1.delta1; if (((double)vt1.temp) != s_f1) { Console.WriteLine("((double)vt1.temp)!=f1"); pass = false; } //class cl1.temp = cl1.f1 - cl1.delta1; if (((double)cl1.temp) != s_f1) { Console.WriteLine("((double)cl1.temp)!=f1"); pass = false; } //*** multiply *** Console.WriteLine(); Console.WriteLine("***mul***"); //local, in-line if (((double)(s_a1 * s_b1)) != s_f1) { Console.WriteLine("((double)(a1*b1))!=f1"); pass = false; } //local temp = s_a1 * s_b1; if (((double)temp) != s_f1) { Console.WriteLine("((double)temp)!=f1, temp=a1*b1"); pass = false; } //method call if (((double)doublemul()) != s_f1) { Console.WriteLine("((double)doublemul())!=f1"); pass = false; } //inline method call if (((double)doublemul_inline()) != s_f1) { Console.WriteLine("((double)doublemul_inline())!=f1"); pass = false; } //array element arr[0] = s_a1; arr[1] = s_b1; arr[2] = arr[0] * arr[1]; if (((double)arr[2]) != s_f1) { Console.WriteLine("((double)arr[2])!=f1"); pass = false; } //struct vt1.a1 = 3; vt1.b1 = 1.0 / 3.0; vt1.temp = vt1.a1 * vt1.b1; if (((double)vt1.temp) != s_f1) { Console.WriteLine("((double)vt1.temp)!=f1"); pass = false; } //class cl1.temp = cl1.a1 * cl1.b1; if (((double)cl1.temp) != s_f1) { Console.WriteLine("((double)cl1.temp)!=f1"); pass = false; } //*** divide *** Console.WriteLine(); Console.WriteLine("***div***"); //local, in-line if (((double)(s_f1 / s_a1)) != s_b1) { Console.WriteLine("((double)(f1/a1))!=b1"); pass = false; } //local temp = s_f1 / s_a1; if (((double)temp) != s_b1) { Console.WriteLine("((double)temp)!=f1, temp=f1/a1"); pass = false; } //method call if (((double)doublediv()) != s_b1) { Console.WriteLine("((double)doubledivl())!=b1"); pass = false; } //method call if (((double)doublediv_inline()) != s_b1) { Console.WriteLine("((double)doublediv_inline())!=b1"); pass = false; } //array element arr[0] = s_f1; arr[1] = s_a1; arr[2] = arr[0] / arr[1]; if (((double)arr[2]) != s_b1) { Console.WriteLine("((double)arr[2])!=b1"); pass = false; } //struct vt1.f1 = 1.0; vt1.a1 = 3; vt1.temp = vt1.f1 / vt1.a1; if (((double)vt1.temp) != s_b1) { Console.WriteLine("((double)vt1.temp)!=b1"); pass = false; } //class cl1.temp = cl1.f1 / cl1.a1; if (((double)cl1.temp) != s_b1) { Console.WriteLine("((double)cl1.temp)!=b1"); pass = false; } Console.WriteLine(); if (pass) { Console.WriteLine("SUCCESS"); return 100; } else { Console.WriteLine("FAILURE: double not truncated properly"); return 1; } } }
using System; using System.IO; using System.Collections; using System.Security; using System.Net.Sockets; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; /// ****************************************************************************************************************** /// * Copyright (c) 2011 Dialect Software LLC * /// * This software is distributed under the terms of the Apache License http://www.apache.org/licenses/LICENSE-2.0 * /// * * /// ****************************************************************************************************************** namespace DialectSoftware.Networking { namespace Controls { public enum TimeOut:int { Default = 30000 } public enum BuildAdpaterState:int { Idle = 0, Connecting = 1, Authenticating = 2, Negotiating = 3, Scheduling = 4, Processing = 5, Terminating = 6 } public class AsyncBuildAdapter:AsyncTcpClientAdapter { private Build _command = null; private IBuildFactory _factory = null; private BuildAdpaterState _buildState = BuildAdpaterState.Idle; private Security.Authentication.SSPI.SSPIAuthenticate _securityServer = null; public Build Command { get{return _command;} set{_command = value;} } public BuildAdpaterState BuildState { set{_buildState = value;} get{return _buildState;} } public Security.Authentication.SSPI.SSPIAuthenticate SecurityServer { get{return _securityServer;} } public IBuildFactory Factory { set{_factory = value;} get{return _factory;} } public AsyncBuildAdapter(Security.Authentication.SSPI.SSPIAuthenticate SecurityServer,TcpClient socket, AsyncNetworkErrorCallBack Error):base(socket,Error) { this._securityServer = SecurityServer; } } } public struct SpecialFolders { public static string BuildFolder = "{32fbb9e3-09e0-4c41-ac1d-b69bd248c7d0}"; } public interface IBuildFactory { void GetBuild(object Data,Build build); } public interface IBuildPattern { string Execute(); } [Serializable()] public abstract class BuildObject { protected object _id = null; public BuildObject() { } public object ID { set{this._id = value;} get{return this._id;} } ~BuildObject() { if(_id != null && _id.GetType().GetInterface(typeof(System.IDisposable).ToString())!=null) _id.GetType().GetInterface(typeof(System.IDisposable).ToString()).GetMethod("Dispose").Invoke(_id,null); } } [Serializable()] public class Project:BuildObject { private Project _parent = null; protected internal FileArrayList _files = null; protected internal ProjectArrayList _subprojects = null; //constructor logic here public Project():base() { _files = new FileArrayList(); _subprojects = new ProjectArrayList(); } public void Add(Project project) { project._parent = this; _subprojects.Add(project); } public void Add(System.Windows.Forms.ListViewItem Files) { _files.Add(Files); } public FileArrayList Files { get{return _files;} } public ProjectArrayList SubProjects { get{return _subprojects;} } ~Project() { _files.Clear(); } } [Serializable()] public class ProjectArrayList:System.Collections.ArrayList { //constructor logic here public ProjectArrayList():base() { } public int Add(Project project) { return base.Add(project); } public override object this[int index] { get{return base[index];} } ~ProjectArrayList() { this.Clear(); } } [Serializable()] public class FileArrayList:System.Collections.ArrayList { //constructor logic here public FileArrayList():base() { } public int Add(System.Windows.Forms.ListViewItem file) { return base.Add(file); } public override object this[int index] { get{return base[index];} } ~FileArrayList() { this.Clear(); } } [Serializable()] public abstract class Build:BuildObject,IBuildPattern { private ProjectArrayList _projects = null; //constructor logic here public Build():base() { _projects = new ProjectArrayList(); } public void Add(Project project) { _projects.Add(project); } public ProjectArrayList Projects { get{return _projects;} } public abstract string Execute(); ~Build() { } } public abstract class BuildFactory:IBuildFactory { public BuildFactory() { } public abstract void GetBuild(object Data,Build build); } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Xml.Linq; using NuGet.Resources; namespace NuGet { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public class ProjectManager : IProjectManager { public event EventHandler<PackageOperationEventArgs> PackageReferenceAdding; public event EventHandler<PackageOperationEventArgs> PackageReferenceAdded; public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoving; public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoved; private ILogger _logger; private IPackageConstraintProvider _constraintProvider; private readonly IPackageReferenceRepository _packageReferenceRepository; private readonly IDictionary<FileTransformExtensions, IPackageFileTransformer> _fileTransformers = new Dictionary<FileTransformExtensions, IPackageFileTransformer>() { { new FileTransformExtensions(".transform", ".transform"), new XmlTransformer(GetConfigMappings()) }, { new FileTransformExtensions(".pp", ".pp"), new Preprocessor() }, { new FileTransformExtensions(".install.xdt", ".uninstall.xdt"), new XdtTransformer() } }; public ProjectManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IProjectSystem project, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (project == null) { throw new ArgumentNullException("project"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; Project = project; PathResolver = pathResolver; LocalRepository = localRepository; _packageReferenceRepository = LocalRepository as IPackageReferenceRepository; DependencyVersion = DependencyVersion.Lowest; } public IPackagePathResolver PathResolver { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackageRepository SourceRepository { get; private set; } public IPackageConstraintProvider ConstraintProvider { get { return _constraintProvider ?? NullConstraintProvider.Instance; } set { _constraintProvider = value; } } public IProjectSystem Project { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public DependencyVersion DependencyVersion { get; set; } public bool WhatIf { get; set; } /// <summary> /// Seems to be used by unit tests only. Perhaps, consumers of NuGet.Core may be using this overload /// </summary> public virtual void AddPackageReference(string packageId) { AddPackageReference(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version) { AddPackageReference(packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, NullConstraintProvider.Instance, packageId, version, allowPrereleaseVersions); AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions); } public virtual void AddPackageReference(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { // In case of a scenario like UpdateAll, the graph has already been walked once for all the packages as a bulk operation // But, we walk here again, just for a single package, since, we need to use UpdateWalker for project installs // unlike simple package installs for which InstallWalker is used // Also, it is noteworthy that the DependentsWalker has the same TargetFramework as the package in PackageReferenceRepository // unlike the UpdateWalker whose TargetFramework is the same as that of the Project // This makes it harder to perform a bulk operation for AddPackageReference and we have to go package by package var dependentsWalker = new DependentsWalker(LocalRepository, GetPackageTargetFramework(package.Id)) { DependencyVersion = DependencyVersion }; Execute(package, new UpdateWalker(LocalRepository, SourceRepository, dependentsWalker, ConstraintProvider, Project.TargetFramework, NullLogger.Instance, !ignoreDependencies, allowPrereleaseVersions) { DisableWalkInfo = WhatIf, AcceptedTargets = PackageTargets.Project, DependencyVersion = DependencyVersion }); } private void Execute(IPackage package, IPackageOperationResolver resolver) { IEnumerable<PackageOperation> operations = resolver.ResolveOperations(package); if (operations.Any()) { foreach (PackageOperation operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, operation.Package.GetFullName()); } else { if (WhatIf) { Logger.Log( MessageLevel.Info, NuGetResources.Log_InstallPackageIntoProject, operation.Package, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(operation.Package); OnPackageReferenceAdding(args); } else { AddPackageReferenceToProject(operation.Package); } } } else { if (packageExists) { if (WhatIf) { Logger.Log( MessageLevel.Info, NuGetResources.Log_UninstallPackageFromProject, operation.Package, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(operation.Package); OnPackageReferenceRemoved(args); } else { RemovePackageReferenceFromProject(operation.Package); } } } } protected void AddPackageReferenceToProject(IPackage package) { string packageFullName = package.GetFullName(); Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginAddPackageReference, packageFullName, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceAdding(args); if (args.Cancel) { return; } ExtractPackageFilesToProject(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyAddedPackageReference, packageFullName, Project.ProjectName); OnPackageReferenceAdded(args); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] protected virtual void ExtractPackageFilesToProject(IPackage package) { // BUG 491: Installing a package with incompatible binaries still does a partial install. // Resolve assembly references and content files first so that if this fails we never do anything to the project List<IPackageAssemblyReference> assemblyReferences = Project.GetCompatibleItemsCore(package.AssemblyReferences).ToList(); List<FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies).ToList(); List<IPackageFile> contentFiles = Project.GetCompatibleItemsCore(package.GetContentFiles()).ToList(); List<IPackageFile> buildFiles = Project.GetCompatibleItemsCore(package.GetBuildFiles()).ToList(); // If the package doesn't have any compatible assembly references or content files, // throw, unless it's a meta package. if (assemblyReferences.Count == 0 && frameworkReferences.Count == 0 && contentFiles.Count == 0 && buildFiles.Count == 0 && (package.FrameworkAssemblies.Any() || package.AssemblyReferences.Any() || package.GetContentFiles().Any() || package.GetBuildFiles().Any())) { // for portable framework, we want to show the friendly short form (e.g. portable-win8+net45+wp8) instead of ".NETPortable, Profile=Profile104". FrameworkName targetFramework = Project.TargetFramework; string targetFrameworkString = targetFramework.IsPortableFramework() ? VersionUtility.GetShortFrameworkName(targetFramework) : targetFramework != null ? targetFramework.ToString() : null; throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToFindCompatibleItems, package.GetFullName(), targetFrameworkString)); } // IMPORTANT: this filtering has to be done AFTER the 'if' statement above, // so that we don't throw the exception in case the <References> filters out all assemblies. FilterAssemblyReferences(assemblyReferences, package.PackageAssemblyReferences); try { // Log target framework info for debugging LogTargetFrameworkInfo(package, assemblyReferences, contentFiles, buildFiles); // Add content files Project.AddFiles(contentFiles, _fileTransformers); // Add the references to the reference path foreach (IPackageAssemblyReference assemblyReference in assemblyReferences) { if (assemblyReference.IsEmptyFolder()) { continue; } // Get the physical path of the assembly reference string referencePath = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path); string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath); if (Project.ReferenceExists(assemblyReference.Name)) { Project.RemoveReference(assemblyReference.Name); } // The current implementation of all ProjectSystem does not use the Stream parameter at all. // We can't change the API now, so just pass in a null stream. Project.AddReference(relativeReferencePath, Stream.Null); } // Add GAC/Framework references foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences) { if (!Project.ReferenceExists(frameworkReference.AssemblyName)) { Project.AddFrameworkReference(frameworkReference.AssemblyName); } } foreach (var importFile in buildFiles) { string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path); Project.AddImport( fullImportFilePath, importFile.Path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ProjectImportLocation.Top : ProjectImportLocation.Bottom); } } finally { if (_packageReferenceRepository != null) { // save the used project's framework if the repository supports it. _packageReferenceRepository.AddPackage(package.Id, package.Version, package.DevelopmentDependency, Project.TargetFramework); } else { // Add package to local repository in the finally so that the user can uninstall it // if any exception occurs. This is easier than rolling back since the user can just // manually uninstall things that may have failed. // If this fails then the user is out of luck. LocalRepository.AddPackage(package); } } } private void LogTargetFrameworkInfo(IPackage package, List<IPackageAssemblyReference> assemblyReferences, List<IPackageFile> contentFiles, List<IPackageFile> buildFiles) { if (assemblyReferences.Count > 0 || contentFiles.Count > 0 || buildFiles.Count > 0) { // targetFramework can be null for unknown project types string shortFramework = Project.TargetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(Project.TargetFramework); Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfoPrefix, package.GetFullName(), Project.ProjectName, shortFramework); if (assemblyReferences.Count > 0) { Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_AssemblyReferences, Path.GetDirectoryName(assemblyReferences[0].Path), VersionUtility.GetTargetFrameworkLogString(assemblyReferences[0].TargetFramework)); } if (contentFiles.Count > 0) { Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_ContentFiles, Path.GetDirectoryName(contentFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(contentFiles[0].TargetFramework)); } if (buildFiles.Count > 0) { Logger.Log(MessageLevel.Debug, NuGetResources.Debug_TargetFrameworkInfo, NuGetResources.Debug_TargetFrameworkInfo_BuildFiles, Path.GetDirectoryName(buildFiles[0].Path), VersionUtility.GetTargetFrameworkLogString(buildFiles[0].TargetFramework)); } } } private void FilterAssemblyReferences(List<IPackageAssemblyReference> assemblyReferences, ICollection<PackageReferenceSet> packageAssemblyReferences) { if (packageAssemblyReferences != null && packageAssemblyReferences.Count > 0) { var packageReferences = Project.GetCompatibleItemsCore(packageAssemblyReferences).FirstOrDefault(); if (packageReferences != null) { // remove all assemblies of which names do not appear in the References list assemblyReferences.RemoveAll(assembly => !packageReferences.References.Contains(assembly.Name, StringComparer.OrdinalIgnoreCase)); } } } public bool IsInstalled(IPackage package) { return LocalRepository.Exists(package); } public void RemovePackageReference(string packageId) { RemovePackageReference(packageId, forceRemove: false, removeDependencies: false); } public void RemovePackageReference(string packageId, bool forceRemove) { RemovePackageReference(packageId, forceRemove: forceRemove, removeDependencies: false); } public virtual void RemovePackageReference(string packageId, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } RemovePackageReference(package, forceRemove, removeDependencies); } public virtual void RemovePackageReference(IPackage package, bool forceRemove, bool removeDependencies) { FrameworkName targetFramework = GetPackageTargetFramework(package.Id); Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository, targetFramework), targetFramework, NullLogger.Instance, removeDependencies, forceRemove)); } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void RemovePackageReferenceFromProject(IPackage package) { string packageFullName = package.GetFullName(); Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginRemovePackageReference, packageFullName, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceRemoving(args); if (args.Cancel) { return; } // Get other packages IEnumerable<IPackage> otherPackages = from p in LocalRepository.GetPackages() where p.Id != package.Id select p; // Get other references var otherAssemblyReferences = from p in otherPackages let assemblyReferences = GetFilteredAssembliesToDelete(p) from assemblyReference in assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>() // This can happen if package installed left the project in a bad state select assemblyReference; // Get content files from other packages // Exclude transform files since they are treated specially var otherContentFiles = from p in otherPackages from file in GetCompatibleInstalledItemsForPackage(p.Id, p.GetContentFiles()) where !IsTransformFile(file.Path) select file; // Get the files and references for this package, that aren't in use by any other packages so we don't have to do reference counting var assemblyReferencesToDelete = GetFilteredAssembliesToDelete(package) .Except(otherAssemblyReferences, PackageFileComparer.Default); var contentFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetContentFiles()) .Except(otherContentFiles, PackageFileComparer.Default); var buildFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetBuildFiles()); // Delete the content files Project.DeleteFiles(contentFilesToDelete, otherPackages, _fileTransformers); // Remove references foreach (IPackageAssemblyReference assemblyReference in assemblyReferencesToDelete) { Project.RemoveReference(assemblyReference.Name); } // remove the <Import> statement from projects for the .targets and .props files foreach (var importFile in buildFilesToDelete) { string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path); Project.RemoveImport(fullImportFilePath); } // Remove package to the repository LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyRemovedPackageReference, packageFullName, Project.ProjectName); OnPackageReferenceRemoved(args); } private bool IsTransformFile(string path) { return _fileTransformers.Keys.Any( file => path.EndsWith(file.InstallExtension, StringComparison.OrdinalIgnoreCase) || path.EndsWith(file.UninstallExtension, StringComparison.OrdinalIgnoreCase)); } private IList<IPackageAssemblyReference> GetFilteredAssembliesToDelete(IPackage package) { List<IPackageAssemblyReference> assemblyReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.AssemblyReferences).ToList(); if (assemblyReferences.Count == 0) { return assemblyReferences; } var packageReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.PackageAssemblyReferences).FirstOrDefault(); if (packageReferences != null) { assemblyReferences.RemoveAll(p => !packageReferences.References.Contains(p.Name, StringComparer.OrdinalIgnoreCase)); } return assemblyReferences; } /// <summary> /// Seems to be used by unit tests only. Perhaps, consumers of NuGet.Core may be using this overload /// </summary> internal void UpdatePackageReference(string packageId) { UpdatePackageReference(packageId, version: null, updateDependencies: true, allowPrereleaseVersions: false); } /// <summary> /// Seems to be used by unit tests only. Perhaps, consumers of NuGet.Core may be using this overload /// </summary> internal void UpdatePackageReference(string packageId, SemanticVersion version) { UpdatePackageReference(packageId, version: version, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference( packageId, () => SourceRepository.FindPackage(packageId, versionSpec, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: versionSpec != null); } /// <summary> /// If the remote package is already determined, consider using the overload which directly takes in the remote package /// Can avoid calls FindPackage calls to source repository. However, it should also be remembered that SourceRepository of ProjectManager /// is an aggregate of "SharedPackageRepository" and the selected repository. So, if the package is present on the repository path (by default, the packages folder) /// It would not result in a call to the server /// </summary> public virtual void UpdatePackageReference(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference(packageId, () => SourceRepository.FindPackage(packageId, version, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: version != null); } private void UpdatePackageReference(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, bool targetVersionSetExplicitly) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.ProjectDoesNotHaveReference, Project.ProjectName, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage package = resolvePackage(); // the condition (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version) // is to fix bug 1574. We want to do nothing if, let's say, you have package 2.0alpha installed, and you do: // update-package // without specifying a version explicitly, and the feed only has version 1.0 as the latest stable version. if (package != null && oldPackage.Version != package.Version && (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackages, package.Id, oldPackage.Version, package.Version, Project.ProjectName); UpdatePackageReferenceCore(package, updateDependencies, allowPrereleaseVersions); } else { IVersionSpec constraint = ConstraintProvider.GetConstraint(packageId); if (constraint != null) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ApplyingConstraints, packageId, VersionUtility.PrettyPrint(constraint), ConstraintProvider.Source); } Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailableForProject, packageId, Project.ProjectName); } } public virtual void UpdatePackageReference(IPackage remotePackage, bool updateDependencies, bool allowPrereleaseVersions) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackagesWithoutOldVersion, remotePackage.Id, remotePackage.Version, Project.ProjectName); UpdatePackageReferenceCore(remotePackage, updateDependencies, allowPrereleaseVersions); } protected void UpdatePackageReference(IPackage package) { UpdatePackageReferenceCore(package, updateDependencies: true, allowPrereleaseVersions: false); } private void UpdatePackageReferenceCore(IPackage package, bool updateDependencies, bool allowPrereleaseVersions) { AddPackageReference(package, !updateDependencies, allowPrereleaseVersions); } private void OnPackageReferenceAdding(PackageOperationEventArgs e) { if (PackageReferenceAdding != null) { PackageReferenceAdding(this, e); } } private void OnPackageReferenceAdded(PackageOperationEventArgs e) { if (PackageReferenceAdded != null) { PackageReferenceAdded(this, e); } } private void OnPackageReferenceRemoved(PackageOperationEventArgs e) { if (PackageReferenceRemoved != null) { PackageReferenceRemoved(this, e); } } private void OnPackageReferenceRemoving(PackageOperationEventArgs e) { if (PackageReferenceRemoving != null) { PackageReferenceRemoving(this, e); } } private FrameworkName GetPackageTargetFramework(string packageId) { if (_packageReferenceRepository != null) { return _packageReferenceRepository.GetPackageTargetFramework(packageId) ?? Project.TargetFramework; } return Project.TargetFramework; } /// <summary> /// This method uses the 'targetFramework' attribute in the packages.config to determine compatible items. /// Hence, it's only good for uninstall operations. /// </summary> private IEnumerable<T> GetCompatibleInstalledItemsForPackage<T>(string packageId, IEnumerable<T> items) where T : IFrameworkTargetable { FrameworkName packageFramework = GetPackageTargetFramework(packageId); if (packageFramework == null) { return items; } IEnumerable<T> compatibleItems; if (VersionUtility.TryGetCompatibleItems(packageFramework, items, out compatibleItems)) { return compatibleItems; } return Enumerable.Empty<T>(); } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, Project, PathResolver.GetInstallPath(package)); } private static IDictionary<XName, Action<XElement, XElement>> GetConfigMappings() { // REVIEW: This might be an edge case, but we're setting this rule for all xml files. // If someone happens to do a transform where the xml file has a configSections node // we will add it first. This is probably fine, but this is a config specific scenario return new Dictionary<XName, Action<XElement, XElement>>() { { "configSections" , (parent, element) => parent.AddFirst(element) } }; } private class PackageFileComparer : IEqualityComparer<IPackageFile> { internal readonly static PackageFileComparer Default = new PackageFileComparer(); private PackageFileComparer() { } public bool Equals(IPackageFile x, IPackageFile y) { // technically, this check will fail if, for example, 'x' is a content file and 'y' is a lib file. // However, because we only use this comparer to compare files within the same folder type, // this check is sufficient. return x.TargetFramework == y.TargetFramework && x.EffectivePath.Equals(y.EffectivePath, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(IPackageFile obj) { return obj.Path.GetHashCode(); } } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using SchoolBusAPI.Models; namespace SchoolBusAPI.Models { /// <summary> /// The collection of permissions included in a role. /// </summary> [MetaDataExtension (Description = "The collection of permissions included in a role.")] public partial class RolePermission : AuditableEntity, IEquatable<RolePermission> { /// <summary> /// Default constructor, required by entity framework /// </summary> public RolePermission() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="RolePermission" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a RolePermission (required).</param> /// <param name="Role">A foreign key reference to the system-generated unique identifier for a Role.</param> /// <param name="Permission">A foreign key reference to the system-generated unique identifier for a Permission.</param> public RolePermission(int Id, Role Role = null, Permission Permission = null) { this.Id = Id; this.Role = Role; this.Permission = Permission; } /// <summary> /// A system-generated unique identifier for a RolePermission /// </summary> /// <value>A system-generated unique identifier for a RolePermission</value> [MetaDataExtension (Description = "A system-generated unique identifier for a RolePermission")] public int Id { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Role /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Role</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Role")] public Role Role { get; set; } /// <summary> /// Foreign key for Role /// </summary> [ForeignKey("Role")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Role")] public int? RoleId { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Permission /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Permission</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Permission")] public Permission Permission { get; set; } /// <summary> /// Foreign key for Permission /// </summary> [ForeignKey("Permission")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Permission")] public int? PermissionId { get; set; } /// <summary> /// The date on which a permission previously assigned to a role was removed from that role. /// </summary> /// <value>The date on which a permission previously assigned to a role was removed from that role.</value> [MetaDataExtension(Description = "The date on which a permission previously assigned to a role was removed from that role.")] public DateTime? ExpiryDate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { return ToJson(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((RolePermission)obj); } /// <summary> /// Returns true if RolePermission instances are equal /// </summary> /// <param name="other">Instance of RolePermission to be compared</param> /// <returns>Boolean</returns> public bool Equals(RolePermission other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.Role == other.Role || this.Role != null && this.Role.Equals(other.Role) ) && ( this.Permission == other.Permission || this.Permission != null && this.Permission.Equals(other.Permission) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.Role != null) { hash = hash * 59 + this.Role.GetHashCode(); } if (this.Permission != null) { hash = hash * 59 + this.Permission.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(RolePermission left, RolePermission right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(RolePermission left, RolePermission right) { return !Equals(left, right); } #endregion Operators } }
/* Email.cs * SSIS Script Loader by Karan Misra (kid0m4n) */ using System; using System.Data; using Microsoft.SqlServer.Dts.Runtime; using System.Windows.Forms; using System.Net.Mail; using System.Net; using System.IO; using System.Text; using System.Linq; using System.Data.Linq; namespace ST_ea8b62ccdbd845e7a8a1104cf064c859.csproj { [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")] public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { #region VSTA generated code enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; #endregion private string _emailFrom; private string _emailTo; private string _smtpServer; private int _smtpPort; private string _userName; private string _password; private string _domain; private string _metaTableConn; private string _parentPackageName; private string _parentTaskName; private DateTime _parentStartTime; private DateTime _parentEndTime; private string _parentVersion; private int _parentStatusID; private T GetVariable<T>(string varName) { return (T)Dts.Variables[varName].Value; } private void InitializeVariables() { _emailFrom = (string)Dts.Variables["v_EmailFrom"].Value; _emailTo = (string)Dts.Variables["v_EmailTo"].Value; _smtpServer = (string)Dts.Variables["v_EmailSmtpServer"].Value; _smtpPort = GetVariable<int>("v_EmailSmtpPort"); _userName = (string)Dts.Variables["v_EmailUserName"].Value; _password = (string)Dts.Variables["v_EmailPassword"].Value; _domain = (string)Dts.Variables["v_EmailDomain"].Value; _metaTableConn = GetVariable<string>("v_MetaConn"); _parentPackageName = (string)Dts.Variables["v_ParentPackageName"].Value; _parentTaskName = GetVariable<string>("v_ParentTaskName").ToUpper(); _parentStartTime = (DateTime)Dts.Variables["v_ParentStartTime"].Value; _parentEndTime = DateTime.Now; _parentVersion = string.Format( "{0}.{1}.{2}", Dts.Variables["v_ParentVersionMajor"].Value, Dts.Variables["v_ParentVersionMinor"].Value, Dts.Variables["v_ParentVersionBuild"].Value); _parentStatusID = GetVariable<int>("v_ParentStatusID"); } private void SendEmail( string from, string to, string subject, string body, bool isBodyHtml, string smtpServer, int smtpPort, string userName, string password, string domain, string[] attachments) { var smtpClient = new SmtpClient(smtpServer, smtpPort); var message = new MailMessage(); message.From = new MailAddress(from); foreach (var toAddress in to.Split(';')) message.To.Add(toAddress); message.Subject = subject; message.Body = body; message.IsBodyHtml = isBodyHtml; if (string.IsNullOrEmpty(userName)) smtpClient.UseDefaultCredentials = true; else smtpClient.Credentials = new NetworkCredential(userName, password, domain); if (attachments != null) { int i = 0; foreach (var attachment in attachments) { if (attachment == null) continue; var stream = new MemoryStream(Encoding.ASCII.GetBytes(attachment)); message.Attachments.Add(new Attachment(stream, "ExecutionReport" + i++ + ".html")); } } smtpClient.Send(message); } public void Main() { InitializeVariables(); string subject = null, bodyText = null; using (LoggingDataContext dc = new LoggingDataContext(_metaTableConn)) { bool hasFailures, hasSuccesses; string failureAttachment = null, successAttachment = null; var errors = from e in dc.Failures where e.Package_Name == _parentPackageName && e.Error_Time >= _parentStartTime select e; if ((hasFailures = (errors.Count() > 0))) { var sb = new StringBuilder(); sb.AppendLine("<html>"); sb.AppendLine("<head></head>"); sb.AppendLine("<body>"); sb.AppendLine("<h4 style=\"color: red;\">Package Name: " + _parentPackageName + "</h4>"); sb.AppendLine("<h4 style=\"color: red;\">Package Version: " + _parentVersion + "</h4>"); sb.AppendLine("<h4 style=\"color: red;\">Package Start Time: " + _parentStartTime.ToString() + "</h4"); sb.AppendLine("<h4 style=\"color: red;\">Package End Time: " + _parentEndTime.ToString() + "</h4>"); sb.AppendLine("<table border=\"2\">"); sb.AppendLine("<tr><th>Task Name</th><th>Version</th><th>Error Num</th><th>Error Desc</th><th>Error Time</th></tr>"); foreach (var e in errors) { sb.AppendLine("<tr><td>" + e.Task_Name.ToNullString() + "</td><td>" + e.Version.ToNullString() + "</td><td>" + e.Error_Num.ToNullString() + "</td><td>" + e.Error_Desc.ToNullString() + "</td><td>" + e.Error_Time.ToNullString() + "</td></tr>"); } sb.AppendLine("</table>"); sb.AppendLine("</body>"); sb.AppendLine("</html>"); failureAttachment = sb.ToString(); } var successes = from s in dc.Successes where s.Package_Name == _parentPackageName && s.Starttime >= _parentStartTime select s; if (hasSuccesses = (successes.Count() > 0)) { var sb = new StringBuilder(); sb.AppendLine("<html>"); sb.AppendLine("<head></head>"); sb.AppendLine("<body>"); sb.AppendLine("<h4 style=\"color: blue;\">Package Name: " + _parentPackageName + "</h4>"); sb.AppendLine("<h4 style=\"color: blue;\">Package Version: " + _parentVersion + "</h4>"); sb.AppendLine("<h4 style=\"color: blue;\">Package Start Time: " + _parentStartTime.ToString() + "</h4"); sb.AppendLine("<h4 style=\"color: blue;\">Package End Time: " + _parentEndTime.ToString() + "</h4>"); sb.AppendLine("<table border=\"2\">"); sb.AppendLine("<tr><th>Task Name</th><th>Imported Row Count</th><th>Inserted Row Count</th><th>Deleted Row Count</th><th>Updated Row Count</th><th>Start Time</th><th>End Time</th><th>Elapsed Time</th></tr>"); foreach (var s in successes) { sb.AppendLine("<tr><td>" + s.Task_Name.ToNullString() + "</td><td>" + s.Imported_RowCount.ToNullString() + "</td><td>" + s.Inserted_RowCount.ToNullString() + "</td><td>" + s.Del_Trunc_RowCount.ToNullString() + "</td><td>" + s.Updated_RowCount.ToNullString() + "</td><td>" + s.Starttime.ToNullString() + "</td><td>" + s.Endtime.ToNullString() + "</td><td>" + s.ElapsedTime.ToNullString() + "</td></tr>"); } sb.AppendLine("</table>"); sb.AppendLine("</body>"); sb.AppendLine("</html>"); successAttachment = sb.ToString(); } if (hasFailures) { subject = _parentPackageName + " Executed with errors"; bodyText = _parentPackageName + " Executed with errors. Please see attachments for details."; } else if (hasSuccesses) { subject = _parentPackageName + " Executed Succesfully"; bodyText = _parentPackageName + " Executed Succesfully. Please see attachment for details."; } else { subject = _parentPackageName + " Executed with unknown status"; bodyText = _parentPackageName + " Executed with unknown status. Please investigate further."; } SendEmail(_emailFrom, _emailTo, subject, bodyText, false, _smtpServer, _smtpPort, _userName, _password, _domain, hasFailures && hasSuccesses ? new string[] { successAttachment, failureAttachment } : hasFailures ? new string[] { failureAttachment } : hasSuccesses ? new string[] { successAttachment } : null); if (_parentStatusID != -1) { var ps = dc.PackageStatus.Single(x => x.package_id == _parentStatusID); ps.run_flag = hasFailures ? 'N' : 'Y'; ps.run_date = _parentEndTime; dc.SubmitChanges(); } } Dts.TaskResult = (int)ScriptResults.Success; } } }
// // Curve.cs // // Author: // Stephane Delcroix <[email protected]> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Stephane Delcroix // // 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 Gtk; using Gdk; namespace FSpot.Widgets { public class Curve : DrawingArea { #region public API public Curve () { Events |= EventMask.ExposureMask | EventMask.PointerMotionMask | EventMask.PointerMotionHintMask | EventMask.EnterNotifyMask | EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.Button1MotionMask; ResetVector (); } public void Reset () { CurveType old_type = CurveType; CurveType = CurveType.Spline; ResetVector (); if (old_type != CurveType.Spline) CurveTypeChanged?.Invoke (this, EventArgs.Empty); } float min_x = 0f; public float MinX { get { return min_x; } set { SetRange (value, max_x, min_y, max_y); } } float max_x = 1.0f; public float MaxX { get { return max_x; } set { SetRange (min_x, value, min_y, max_y); } } float min_y = 0f; public float MinY { get { return min_y; } set { SetRange (min_x, max_x, value, max_y); } } float max_y = 1.0f; public float MaxY { get { return max_y; } set { SetRange (min_x, max_x, min_y, value); } } public void SetRange (float min_x, float max_x, float min_y, float max_y) { this.min_x = min_x; this.max_x = max_x; this.min_y = min_y; this.max_y = max_y; ResetVector (); QueueDraw (); } CurveType curve_type = CurveType.Spline; public CurveType CurveType { get { return curve_type; } set { curve_type = value; QueueDraw (); } } public float [] GetVector (int len) { if (len <= 0) return null; var vector = new float [len]; var xv = new float [points.Count]; var yv = new float [points.Count]; int i = 0; foreach (var keyval in points) { xv[i] = keyval.Key; yv[i] = keyval.Value; i++; } float rx = MinX; float dx = (MaxX - MinX) / (len - 1.0f); switch (CurveType) { case CurveType.Spline: var y2v = SplineSolve (xv, yv); for (int x = 0; x < len; x++, rx += dx) { float ry = SplineEval (xv, yv, y2v, rx); if (ry < MinY) ry = MinY; if (ry > MaxY) ry = MaxY; vector[x] = ry; } break;; case CurveType.Linear: for (int x = 0; x < len; x++, rx += dx) { float ry = LinearEval (xv, yv, rx); if (ry < MinY) ry = MinY; if (ry > MaxY) ry = MaxY; vector[x] = ry; } break; case CurveType.Free: throw new NotImplementedException (); } return vector; } public void SetVector (float[] vector) { throw new NotImplementedException ("FSpot.Gui.Widgets.Curve SetVector does nothing!!!"); } public void AddPoint (float x, float y) { points.Add (x, y); CurveChanged?.Invoke (this, EventArgs.Empty); } public event EventHandler CurveTypeChanged; public event EventHandler CurveChanged; #endregion #region vector handling SortedDictionary<float, float> points; void ResetVector () { points = new SortedDictionary<float, float> (); points.Add (min_x, min_y); points.Add (max_x, max_y); points.Add (.2f, .1f); points.Add (.5f, .5f); points.Add (.8f, .9f); } #endregion #region math helpers /* Solve the tridiagonal equation system that determines the second derivatives for the interpolation points. (Based on Numerical Recipies 2nd Edition) */ static float [] SplineSolve (float[] x, float[] y) { var y2 = new float [x.Length]; var u = new float [x.Length - 1]; y2[0] = u[0] = 0.0f; //Set lower boundary condition to "natural" for (int i = 1; i < x.Length - 1; ++i) { float sig = (x[i] - x[i - 1]) / (x[i + 1] - x[i - 1]); float p = sig * y2[i - 1] + 2.0f; y2[i] = (sig - 1.0f) / p; u[i] = ((y[i + 1] - y[i]) / (x[i + 1] - x[i]) - (y[i] - y[i - 1]) / (x[i] - x[i - 1])); u[i] = (6.0f * u[i] / (x[i + 1] - x[i - 1]) - sig * u[i - 1]) / p; } y2[x.Length - 1] = 0.0f; for (int k = x.Length - 2; k >= 0; --k) y2[k] = y2[k] * y2[k + 1] + u[k]; return y2; } /* Returns a y value for val, given x[], y[] and y2[] */ static float SplineEval (float[] x, float[] y, float[] y2, float val) { //binary search for the right interval int k_lo = 0; int k_hi = x.Length - 1; while (k_hi - k_lo > 1) { int k = (k_hi + k_lo) / 2; if (x[k] > val) k_hi = k; else k_lo = k; } float h = x[k_hi] - x[k_lo]; float a = (x[k_hi] - val) / h; float b = (val - x[k_lo]) / h; return a * y[k_lo] + b * y[k_hi] + ((a*a*a - a) * y2[k_lo] + (b*b*b - b) * y2[k_hi]) * (h*h)/6.0f; } static float LinearEval (float[] x, float[] y, float val) { //binary search for the right interval int k_lo = 0; int k_hi = x.Length - 1; while (k_hi - k_lo > 1) { int k = (k_hi + k_lo) / 2; if (x[k] > val) k_hi = k; else k_lo = k; } float dx = x[k_hi] - x[k_lo]; float dy = y[k_hi] - y[k_lo]; return val*dy/dx + y[k_lo] - dy/dx*x[k_lo]; } static int Project (float val, float min, float max, int norm) { return (int)((norm - 1) * ((val - min) / (max - min)) + .5f); } static float Unproject (int val, float min, float max, int norm) { return val / (float) (norm - 1) * (max - min) + min; } #endregion #region Gtk widgetry const int radius = 3; //radius of the control points const int min_distance = 8; //min distance between control points int x_offset = radius; int y_offset = radius; int width, height; //the real graph Pixmap pixmap = null; protected override bool OnConfigureEvent (EventConfigure evnt) { pixmap = null; return base.OnConfigureEvent (evnt); } protected override bool OnExposeEvent (EventExpose evnt) { pixmap = new Pixmap (GdkWindow, Allocation.Width, Allocation.Height); Draw (); return base.OnExposeEvent (evnt); } Gdk.Point [] Interpolate (int width, int height) { var vector = GetVector (width); var retval = new Gdk.Point [width]; for (int i = 0; i < width; i++) { retval[i].X = x_offset + i; retval[i].Y = y_offset + height - Project (vector[i], MinY, MaxY, height); } return retval; } void Draw () { if (pixmap == null) return; Style style = Style; StateType state = Sensitive ? StateType.Normal : StateType.Insensitive; if (width <= 0 || height <= 0) return; //clear the pixmap GtkBeans.Style.PaintFlatBox (style, pixmap, StateType.Normal, ShadowType.None, null, this, "curve_bg", 0, 0, Allocation.Width, Allocation.Height); //draw the grid lines for (int i = 0; i < 5; i++) { pixmap.DrawLine (style.DarkGC (state), x_offset, i * (int)(height / 4.0) + y_offset, width + x_offset, i * (int)(height / 4.0) + y_offset); pixmap.DrawLine (style.DarkGC (state), i * (int)(width / 4.0) + x_offset, y_offset, i * (int)(width / 4.0) + x_offset, height + y_offset); } //draw the curve pixmap.DrawPoints (style.ForegroundGC (state), Interpolate (width, height)); //draw the bullets if (CurveType != CurveType.Free) foreach (var keyval in points) { if (keyval.Key < MinX) continue; int x = Project (keyval.Key, MinX, MaxX, width); int y = height - Project (keyval.Value, MinY, MaxY, height); pixmap.DrawArc (style.ForegroundGC (state), true, x, y, radius * 2, radius * 2, 0, 360*64); } GdkWindow.DrawDrawable (style.ForegroundGC (state), pixmap, 0, 0, 0, 0, Allocation.Width, Allocation.Height); } protected override void OnSizeAllocated (Rectangle allocation) { width = allocation.Width - 2 * radius; height = allocation.Height - 2 * radius; base.OnSizeAllocated (allocation); } protected override void OnSizeRequested (ref Requisition requisition) { requisition.Width = 128 + 2 * x_offset; requisition.Height = 128 + 2 * y_offset; } float? grab_point = null; protected override bool OnButtonPressEvent (EventButton evnt) { int px = (int)evnt.X - x_offset; int py = (int)evnt.Y - y_offset; if (px < 0) px = 0; if (px > width - 1) px = width - 1; if (py < 0) py = 0; if (py > height - 1) py = height - 1; //find the closest point float closest_x = MinX - 1; var distance = Int32.MaxValue; foreach (var point in points) { int cx = Project (point.Key, MinX, MaxX, width); if (Math.Abs (px - cx) < distance) { distance = Math.Abs (px - cx); closest_x = point.Key; } } Grab.Add (this); CursorType = CursorType.Tcross; switch (CurveType) { case CurveType.Linear: case CurveType.Spline: if (distance > min_distance) { //insert a new control point AddPoint ((closest_x = Unproject (px, MinX, MaxX, width)), MaxY - Unproject (py, MinY, MaxY, height)); QueueDraw (); } grab_point = closest_x; break; case CurveType.Free: throw new NotImplementedException (); } return true; } protected override bool OnButtonReleaseEvent (EventButton evnt) { Grab.Remove (this); //FIXME: remove inactive points CursorType = CursorType.Fleur; grab_point = null; return true; } protected override bool OnMotionNotifyEvent (EventMotion evnt) { int px = (int)evnt.X - x_offset; int py = (int)evnt.Y - y_offset; if (px < 0) px = 0; if (px > width - 1) px = width - 1; if (py < 0) py = 0; if (py > height - 1) py = height - 1; //find the closest point float closest_x = MinX - 1; var distance = Int32.MaxValue; foreach (var point in points) { int cx = Project (point.Key, MinX, MaxX, width); if (Math.Abs (px - cx) < distance) { distance = Math.Abs (px - cx); closest_x = point.Key; } } switch (CurveType) { case CurveType.Spline: case CurveType.Linear: if (grab_point == null) { //No grabbed point if (distance <= min_distance) CursorType = CursorType.Fleur; else CursorType = CursorType.Tcross; return true; } CursorType = CursorType.Tcross; points.Remove (grab_point.Value); AddPoint ((closest_x = Unproject (px, MinX, MaxX, width)), MaxY - Unproject (py, MinY, MaxY, height)); QueueDraw (); grab_point = closest_x; break; case CurveType.Free: throw new NotImplementedException (); } return true; } Gdk.CursorType cursor_type = Gdk.CursorType.TopLeftArrow; CursorType CursorType { get { return cursor_type; } set { if (value == cursor_type) return; cursor_type = value; GdkWindow.Cursor = new Cursor (CursorType); } } #endregion } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // The controller is not available for versions of Unity without the // GVR native integration. using UnityEngine; using System.Collections; /// Provides visual feedback for the daydream controller. [RequireComponent(typeof(Renderer))] public class GvrControllerVisual : MonoBehaviour, IGvrArmModelReceiver { [System.Serializable] public struct ControllerDisplayState { public GvrControllerBatteryLevel batteryLevel; public bool batteryCharging; public bool clickButton; public bool appButton; public bool homeButton; public bool touching; public Vector2 touchPos; } /// An array of prefabs that will be instantiated and added as children /// of the controller visual when the controller is created. Used to /// attach tooltips or other additional visual elements to the control dynamically. [SerializeField] private GameObject[] attachmentPrefabs; [SerializeField] private Color touchPadColor = new Color(200f / 255f, 200f / 255f, 200f / 255f, 1); [SerializeField] private Color appButtonColor = new Color(200f / 255f, 200f / 255f, 200f / 255f, 1); [SerializeField] private Color systemButtonColor = new Color(20f / 255f, 20f / 255f, 20f / 255f, 1); /// Determines if the displayState is set from GvrControllerInput. [Tooltip("Determines if the displayState is set from GvrControllerInput.")] public bool readControllerState = true; /// Used to set the display state of the controller visual. /// This can be used for tutorials that visualize the controller or other use-cases that require /// displaying the controller visual without the state being determined by controller input. /// Additionally, it can be used to preview the controller visual in the editor. /// NOTE: readControllerState must be disabled to set the display state. public ControllerDisplayState displayState; /// This is the preferred, maximum alpha value the object should have /// when it is a comfortable distance from the head. [Range(0.0f, 1.0f)] public float maximumAlpha = 1.0f; public GvrBaseArmModel ArmModel { get; set; } public float PreferredAlpha{ get{ return ArmModel != null ? maximumAlpha * ArmModel.PreferredAlpha : maximumAlpha; } } public Color TouchPadColor { get { return touchPadColor; } set { touchPadColor = value; if(materialPropertyBlock != null) { materialPropertyBlock.SetColor(touchPadId, touchPadColor); } } } public Color AppButtonColor { get { return appButtonColor; } set { appButtonColor = value; if(materialPropertyBlock != null){ materialPropertyBlock.SetColor(appButtonId, appButtonColor); } } } public Color SystemButtonColor { get { return systemButtonColor; } set { systemButtonColor = value; if(materialPropertyBlock != null) { materialPropertyBlock.SetColor(systemButtonId, systemButtonColor); } } } private Renderer controllerRenderer; private MaterialPropertyBlock materialPropertyBlock; private int alphaId; private int touchId; private int touchPadId; private int appButtonId; private int systemButtonId; private int batteryColorId; private bool wasTouching; private float touchTime; // Data passed to shader, (xy) touch position, (z) touch duration, (w) battery state. private Vector4 controllerShaderData; // Data passed to shader, (x) overall alpha, (y) touchpad click duration, // (z) app button click duration, (w) system button click duration. private Vector4 controllerShaderData2; private Color currentBatteryColor; // These values control animation times for the controller buttons public const float APP_BUTTON_ACTIVE_DURATION_SECONDS = 0.111f; public const float APP_BUTTON_RELEASE_DURATION_SECONDS = 0.0909f; public const float SYSTEM_BUTTON_ACTIVE_DURATION_SECONDS = 0.111f; public const float SYSTEM_BUTTON_RELEASE_DURATION_SECONDS = 0.0909f; public const float TOUCHPAD_CLICK_DURATION_SECONDS = 0.111f; public const float TOUCHPAD_RELEASE_DURATION_SECONDS = 0.0909f; public const float TOUCHPAD_CLICK_SCALE_DURATION_SECONDS = 0.075f; public const float TOUCHPAD_POINT_SCALE_DURATION_SECONDS = 0.15f; // These values are used by the shader to control battery display // Only modify these values if you are also modifying the shader. private const float BATTERY_FULL = 0; private const float BATTERY_ALMOST_FULL = .125f; private const float BATTERY_MEDIUM = .225f; private const float BATTERY_LOW = .325f; private const float BATTERY_CRITICAL = .425f; private const float BATTERY_HIDDEN = .525f; private readonly Color GVR_BATTERY_CRITICAL_COLOR = new Color(1,0,0,1); private readonly Color GVR_BATTERY_LOW_COLOR = new Color(1,0.6823f,0,1); private readonly Color GVR_BATTERY_MED_COLOR = new Color(0,1,0.588f,1); private readonly Color GVR_BATTERY_FULL_COLOR = new Color(0,1,0.588f,1); // How much time to use as an 'immediate update'. // Any value large enough to instantly update all visual animations. private const float IMMEDIATE_UPDATE_TIME = 10f; void Awake() { Initialize(); CreateAttachments(); } void OnEnable() { GvrControllerInput.OnPostControllerInputUpdated += OnPostControllerInputUpdated; } void OnDisable() { GvrControllerInput.OnPostControllerInputUpdated -= OnPostControllerInputUpdated; } void OnValidate() { if (!Application.isPlaying) { Initialize(); OnVisualUpdate(true); } } private void OnPostControllerInputUpdated() { OnVisualUpdate(); } private void CreateAttachments() { if (attachmentPrefabs == null) { return; } for (int i = 0; i < attachmentPrefabs.Length; i++) { GameObject prefab = attachmentPrefabs[i]; GameObject attachment = Instantiate(prefab); attachment.transform.SetParent(transform, false); } } private void Initialize() { if(controllerRenderer == null) { controllerRenderer = GetComponent<Renderer>(); } if(materialPropertyBlock == null) { materialPropertyBlock = new MaterialPropertyBlock(); } alphaId = Shader.PropertyToID("_GvrControllerAlpha"); touchId = Shader.PropertyToID("_GvrTouchInfo"); touchPadId = Shader.PropertyToID("_GvrTouchPadColor"); appButtonId = Shader.PropertyToID("_GvrAppButtonColor"); systemButtonId = Shader.PropertyToID("_GvrSystemButtonColor"); batteryColorId = Shader.PropertyToID("_GvrBatteryColor"); materialPropertyBlock.SetColor(appButtonId, appButtonColor); materialPropertyBlock.SetColor(systemButtonId, systemButtonColor); materialPropertyBlock.SetColor(touchPadId, touchPadColor); controllerRenderer.SetPropertyBlock(materialPropertyBlock); } private void UpdateControllerState() { // Return early when the application isn't playing to ensure that the serialized displayState // is used to preview the controller visual instead of the default GvrControllerInput values. #if UNITY_EDITOR if (!Application.isPlaying) { return; } #endif displayState.batteryLevel = GvrControllerInput.BatteryLevel; displayState.batteryCharging = GvrControllerInput.IsCharging; displayState.clickButton = GvrControllerInput.ClickButton; displayState.appButton = GvrControllerInput.AppButton; displayState.homeButton = GvrControllerInput.HomeButtonState; displayState.touching = GvrControllerInput.IsTouching; displayState.touchPos = GvrControllerInput.TouchPosCentered; } private void OnVisualUpdate(bool updateImmediately = false) { // Update the visual display based on the controller state if(readControllerState) { UpdateControllerState(); } float deltaTime = Time.deltaTime; // If flagged to update immediately, set deltaTime to an arbitrarily large value // This is particularly useful in editor, but also for resetting state quickly if(updateImmediately) { deltaTime = IMMEDIATE_UPDATE_TIME; } if (displayState.clickButton) { controllerShaderData2.y = Mathf.Min(1, controllerShaderData2.y + deltaTime / TOUCHPAD_CLICK_DURATION_SECONDS); } else{ controllerShaderData2.y = Mathf.Max(0, controllerShaderData2.y - deltaTime / TOUCHPAD_RELEASE_DURATION_SECONDS); } if (displayState.appButton) { controllerShaderData2.z = Mathf.Min(1, controllerShaderData2.z + deltaTime / APP_BUTTON_ACTIVE_DURATION_SECONDS); } else{ controllerShaderData2.z = Mathf.Max(0, controllerShaderData2.z - deltaTime / APP_BUTTON_RELEASE_DURATION_SECONDS); } if (displayState.homeButton) { controllerShaderData2.w = Mathf.Min(1, controllerShaderData2.w + deltaTime / SYSTEM_BUTTON_ACTIVE_DURATION_SECONDS); } else { controllerShaderData2.w = Mathf.Max(0, controllerShaderData2.w - deltaTime / SYSTEM_BUTTON_RELEASE_DURATION_SECONDS); } // Set the material's alpha to the multiplied preferred alpha. controllerShaderData2.x = PreferredAlpha; materialPropertyBlock.SetVector(alphaId, controllerShaderData2); controllerShaderData.x = displayState.touchPos.x; controllerShaderData.y = displayState.touchPos.y; if (displayState.touching || displayState.clickButton) { if (!wasTouching) { wasTouching = true; } if(touchTime < 1) { touchTime = Mathf.Min(touchTime + deltaTime / TOUCHPAD_POINT_SCALE_DURATION_SECONDS, 1); } } else { wasTouching = false; if(touchTime > 0) { touchTime = Mathf.Max(touchTime - deltaTime / TOUCHPAD_POINT_SCALE_DURATION_SECONDS, 0); } } controllerShaderData.z = touchTime; UpdateBatteryIndicator(); materialPropertyBlock.SetVector(touchId, controllerShaderData); materialPropertyBlock.SetColor(batteryColorId, currentBatteryColor); // Update the renderer controllerRenderer.SetPropertyBlock(materialPropertyBlock); } private void UpdateBatteryIndicator() { GvrControllerBatteryLevel level = displayState.batteryLevel; bool charging = displayState.batteryCharging; switch (level) { case GvrControllerBatteryLevel.Full: controllerShaderData.w = BATTERY_FULL; currentBatteryColor = GVR_BATTERY_FULL_COLOR; break; case GvrControllerBatteryLevel.AlmostFull: controllerShaderData.w = BATTERY_ALMOST_FULL; currentBatteryColor = GVR_BATTERY_FULL_COLOR; break; case GvrControllerBatteryLevel.Medium: controllerShaderData.w = BATTERY_MEDIUM; currentBatteryColor = GVR_BATTERY_MED_COLOR; break; case GvrControllerBatteryLevel.Low: controllerShaderData.w = BATTERY_LOW; currentBatteryColor = GVR_BATTERY_LOW_COLOR; break; case GvrControllerBatteryLevel.CriticalLow: controllerShaderData.w = BATTERY_CRITICAL; currentBatteryColor = GVR_BATTERY_CRITICAL_COLOR; break; default: controllerShaderData.w = BATTERY_HIDDEN; currentBatteryColor.a = 0; break; } if (charging) { controllerShaderData.w = -controllerShaderData.w; currentBatteryColor = GVR_BATTERY_FULL_COLOR; } } }
// 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.Media.DoubleCollection.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.Media { sealed public partial class DoubleCollection : System.Windows.Freezable, IFormattable, System.Collections.IList, System.Collections.ICollection, IList<double>, ICollection<double>, IEnumerable<double>, System.Collections.IEnumerable { #region Methods and constructors public void Add(double value) { } public void Clear() { } public DoubleCollection Clone() { return default(DoubleCollection); } protected override void CloneCore(System.Windows.Freezable source) { } public DoubleCollection CloneCurrentValue() { return default(DoubleCollection); } protected override void CloneCurrentValueCore(System.Windows.Freezable source) { } public bool Contains(double value) { return default(bool); } public void CopyTo(double[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } public DoubleCollection(int capacity) { } public DoubleCollection(IEnumerable<double> collection) { } public DoubleCollection() { } protected override void GetAsFrozenCore(System.Windows.Freezable source) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source) { } public DoubleCollection.Enumerator GetEnumerator() { return default(DoubleCollection.Enumerator); } public int IndexOf(double value) { return default(int); } public void Insert(int index, double value) { } public static DoubleCollection Parse(string source) { return default(DoubleCollection); } public bool Remove(double value) { return default(bool); } public void RemoveAt(int index) { } IEnumerator<double> System.Collections.Generic.IEnumerable<System.Double>.GetEnumerator() { return default(IEnumerator<double>); } void System.Collections.ICollection.CopyTo(Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(Object value) { return default(int); } bool System.Collections.IList.Contains(Object value) { return default(bool); } int System.Collections.IList.IndexOf(Object value) { return default(int); } void System.Collections.IList.Insert(int index, Object value) { } void System.Collections.IList.Remove(Object value) { } string System.IFormattable.ToString(string format, IFormatProvider provider) { return default(string); } public string ToString(IFormatProvider provider) { return default(string); } #endregion #region Properties and indexers public int Count { get { return default(int); } } public double this [int index] { get { return default(double); } set { } } bool System.Collections.Generic.ICollection<System.Double>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
using Lucene.Net.Documents; namespace Lucene.Net.Search { using NUnit.Framework; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using Document = Documents.Document; using English = Lucene.Net.Util.English; using Field = Field; using Fields = Lucene.Net.Index.Fields; using FieldType = FieldType; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using OpenMode = Lucene.Net.Index.IndexWriterConfig.OpenMode_e; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TextField = TextField; public class TestTermVectors : LuceneTestCase { private static IndexReader Reader; private static Directory Directory; [TestFixtureSetUp] public static void BeforeClass() { Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true)).SetMergePolicy(NewLogMergePolicy())); //writer.setNoCFSRatio(1.0); //writer.infoStream = System.out; for (int i = 0; i < 1000; i++) { Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); int mod3 = i % 3; int mod2 = i % 2; if (mod2 == 0 && mod3 == 0) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; ft.StoreTermVectorPositions = true; } else if (mod2 == 0) { ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; } else if (mod3 == 0) { ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; } else { ft.StoreTermVectors = true; } doc.Add(new Field("field", English.IntToEnglish(i), ft)); //test no term vectors too doc.Add(new TextField("noTV", English.IntToEnglish(i), Field.Store.YES)); writer.AddDocument(doc); } Reader = writer.Reader; writer.Dispose(); } [TestFixtureTearDown] public static void AfterClass() { Reader.Dispose(); Directory.Dispose(); Reader = null; Directory = null; } // In a single doc, for the same field, mix the term // vectors up [Test] public virtual void TestMixedVectrosVectors() { RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.SIMPLE, true)).SetOpenMode(OpenMode.CREATE)); Document doc = new Document(); FieldType ft2 = new FieldType(TextField.TYPE_STORED); ft2.StoreTermVectors = true; FieldType ft3 = new FieldType(TextField.TYPE_STORED); ft3.StoreTermVectors = true; ft3.StoreTermVectorPositions = true; FieldType ft4 = new FieldType(TextField.TYPE_STORED); ft4.StoreTermVectors = true; ft4.StoreTermVectorOffsets = true; FieldType ft5 = new FieldType(TextField.TYPE_STORED); ft5.StoreTermVectors = true; ft5.StoreTermVectorOffsets = true; ft5.StoreTermVectorPositions = true; doc.Add(NewTextField("field", "one", Field.Store.YES)); doc.Add(NewField("field", "one", ft2)); doc.Add(NewField("field", "one", ft3)); doc.Add(NewField("field", "one", ft4)); doc.Add(NewField("field", "one", ft5)); writer.AddDocument(doc); IndexReader reader = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(reader); Query query = new TermQuery(new Term("field", "one")); ScoreDoc[] hits = searcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Fields vectors = searcher.IndexReader.GetTermVectors(hits[0].Doc); Assert.IsNotNull(vectors); Assert.AreEqual(1, vectors.Size); Terms vector = vectors.Terms("field"); Assert.IsNotNull(vector); Assert.AreEqual(1, vector.Size()); TermsEnum termsEnum = vector.Iterator(null); Assert.IsNotNull(termsEnum.Next()); Assert.AreEqual("one", termsEnum.Term().Utf8ToString()); Assert.AreEqual(5, termsEnum.TotalTermFreq()); DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null); Assert.IsNotNull(dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.AreEqual(5, dpEnum.Freq()); for (int i = 0; i < 5; i++) { Assert.AreEqual(i, dpEnum.NextPosition()); } dpEnum = termsEnum.DocsAndPositions(null, dpEnum); Assert.IsNotNull(dpEnum); Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.AreEqual(5, dpEnum.Freq()); for (int i = 0; i < 5; i++) { dpEnum.NextPosition(); Assert.AreEqual(4 * i, dpEnum.StartOffset()); Assert.AreEqual(4 * i + 3, dpEnum.EndOffset()); } reader.Dispose(); } private IndexWriter CreateWriter(Directory dir) { return new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2)); } private void CreateDir(Directory dir) { IndexWriter writer = CreateWriter(dir); writer.AddDocument(CreateDoc()); writer.Dispose(); } private Document CreateDoc() { Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_STORED); ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; ft.StoreTermVectorPositions = true; doc.Add(NewField("c", "aaa", ft)); return doc; } private void VerifyIndex(Directory dir) { IndexReader r = DirectoryReader.Open(dir); int numDocs = r.NumDocs; for (int i = 0; i < numDocs; i++) { Assert.IsNotNull(r.GetTermVectors(i).Terms("c"), "term vectors should not have been null for document " + i); } r.Dispose(); } [Test] public virtual void TestFullMergeAddDocs() { Directory target = NewDirectory(); IndexWriter writer = CreateWriter(target); // with maxBufferedDocs=2, this results in two segments, so that forceMerge // actually does something. for (int i = 0; i < 4; i++) { writer.AddDocument(CreateDoc()); } writer.ForceMerge(1); writer.Dispose(); VerifyIndex(target); target.Dispose(); } [Test] public virtual void TestFullMergeAddIndexesDir() { Directory[] input = new Directory[] { NewDirectory(), NewDirectory() }; Directory target = NewDirectory(); foreach (Directory dir in input) { CreateDir(dir); } IndexWriter writer = CreateWriter(target); writer.AddIndexes(input); writer.ForceMerge(1); writer.Dispose(); VerifyIndex(target); IOUtils.Close(target, input[0], input[1]); } [Test] public virtual void TestFullMergeAddIndexesReader() { Directory[] input = new Directory[] { NewDirectory(), NewDirectory() }; Directory target = NewDirectory(); foreach (Directory dir in input) { CreateDir(dir); } IndexWriter writer = CreateWriter(target); foreach (Directory dir in input) { IndexReader r = DirectoryReader.Open(dir); writer.AddIndexes(r); r.Dispose(); } writer.ForceMerge(1); writer.Dispose(); VerifyIndex(target); IOUtils.Close(target, input[0], input[1]); } } }
using System; using System.Collections.Generic; using ServiceStack.Logging; using ServiceStack.Net30.Collections.Concurrent; namespace ServiceStack.CacheAccess.Providers { public class MemoryCacheClient : ICacheClient { private static readonly ILog Log = LogManager.GetLogger(typeof (MemoryCacheClient)); private ConcurrentDictionary<string, CacheEntry> memory; private ConcurrentDictionary<string, int> counters; public bool FlushOnDispose { get; set; } private class CacheEntry { private object cacheValue; public CacheEntry(object value, DateTime expiresAt) { Value = value; ExpiresAt = expiresAt; LastModifiedTicks = DateTime.Now.Ticks; } internal DateTime ExpiresAt { get; set; } internal object Value { get { return cacheValue; } set { cacheValue = value; LastModifiedTicks = DateTime.Now.Ticks; } } internal long LastModifiedTicks { get; private set; } } public MemoryCacheClient() { this.memory = new ConcurrentDictionary<string, CacheEntry>(); this.counters = new ConcurrentDictionary<string, int>(); } private bool CacheAdd(string key, object value) { return CacheAdd(key, value, DateTime.MaxValue); } private bool TryGetValue(string key, out CacheEntry entry) { return this.memory.TryGetValue(key, out entry); } private void Set(string key, CacheEntry entry) { this.memory[key] = entry; } /// <summary> /// Stores The value with key only if such key doesn't exist at the server yet. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="expiresAt">The expires at.</param> /// <returns></returns> private bool CacheAdd(string key, object value, DateTime expiresAt) { CacheEntry entry; if (this.TryGetValue(key, out entry)) return false; entry = new CacheEntry(value, expiresAt); this.Set(key, entry); return true; } private bool CacheSet(string key, object value) { return CacheSet(key, value, DateTime.MaxValue); } private bool CacheSet(string key, object value, DateTime expiresAt) { return CacheSet(key, value, expiresAt, null); } /// <summary> /// Adds or replaces the value with key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="expiresAt">The expires at.</param> /// <param name="checkLastModified">The check last modified.</param> /// <returns>True; if it succeeded</returns> private bool CacheSet(string key, object value, DateTime expiresAt, long? checkLastModified) { CacheEntry entry; if (!this.TryGetValue(key, out entry)) { entry = new CacheEntry(value, expiresAt); this.Set(key, entry); return true; } if (checkLastModified.HasValue && entry.LastModifiedTicks != checkLastModified.Value) return false; entry.Value = value; entry.ExpiresAt = expiresAt; return true; } private bool CacheReplace(string key, object value) { return CacheReplace(key, value, DateTime.MaxValue); } private bool CacheReplace(string key, object value, DateTime expiresAt) { return !CacheSet(key, value, expiresAt); } public void Dispose() { if (!FlushOnDispose) return; this.memory = new ConcurrentDictionary<string, CacheEntry>(); this.counters = new ConcurrentDictionary<string, int>(); } public bool Remove(string key) { CacheEntry item; return this.memory.TryRemove(key, out item); } public void RemoveAll(IEnumerable<string> keys) { foreach (var key in keys) { try { this.Remove(key); } catch (Exception ex) { Log.Error(string.Format("Error trying to remove {0} from the cache", key), ex); } } } public object Get(string key) { long lastModifiedTicks; return Get(key, out lastModifiedTicks); } public object Get(string key, out long lastModifiedTicks) { lastModifiedTicks = 0; CacheEntry cacheEntry; if (this.memory.TryGetValue(key, out cacheEntry)) { if (cacheEntry.ExpiresAt < DateTime.Now) { this.memory.TryRemove(key, out cacheEntry); return null; } lastModifiedTicks = cacheEntry.LastModifiedTicks; return cacheEntry.Value; } return null; } public T Get<T>(string key) { var value = Get(key); if (value != null) return (T)value; return default(T); } private int UpdateCounter(string key, int value) { if (!this.counters.ContainsKey(key)) { this.counters[key] = 0; } this.counters[key] += value; return this.counters[key]; } public long Increment(string key, uint amount) { return UpdateCounter(key, 1); } public long Decrement(string key, uint amount) { return UpdateCounter(key, -1); } public bool Add<T>(string key, T value) { return CacheAdd(key, value); } public bool Set<T>(string key, T value) { return CacheSet(key, value); } public bool Replace<T>(string key, T value) { return CacheReplace(key, value); } public bool Add<T>(string key, T value, DateTime expiresAt) { return CacheAdd(key, value, expiresAt); } public bool Set<T>(string key, T value, DateTime expiresAt) { return CacheSet(key, value, expiresAt); } public bool Replace<T>(string key, T value, DateTime expiresAt) { return CacheReplace(key, value, expiresAt); } public bool Add<T>(string key, T value, TimeSpan expiresIn) { return CacheAdd(key, value, DateTime.Now.Add(expiresIn)); } public bool Set<T>(string key, T value, TimeSpan expiresIn) { return CacheSet(key, value, DateTime.Now.Add(expiresIn)); } public bool Replace<T>(string key, T value, TimeSpan expiresIn) { return CacheReplace(key, value, DateTime.Now.Add(expiresIn)); } public void FlushAll() { this.memory = new ConcurrentDictionary<string, CacheEntry>(); } public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys) { var valueMap = new Dictionary<string, T>(); foreach (var key in keys) { var value = Get<T>(key); valueMap[key] = value; } return valueMap; } public void SetAll<T>(IDictionary<string, T> values) { foreach (var entry in values) { Set(entry.Key, entry.Value); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Test { public class TakeTakeWhileTests { // // Take // public static IEnumerable<object[]> TakeUnorderedData(object[] counts) { Func<int, IEnumerable<int>> take = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct(); foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), take)) yield return results; } public static IEnumerable<object[]> TakeData(object[] counts) { Func<int, IEnumerable<int>> take = x => new[] { -x, -1, 0, 1, x / 2, x, x * 2 }.Distinct(); foreach (object[] results in Sources.Ranges(counts.Cast<int>(), take)) yield return results; } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Take_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take))); foreach (int i in query.Take(take)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void Take_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { Take_Unordered(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Take(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (int i in query.Take(take)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Min(count, Math.Max(0, take)), seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void Take_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { Take(labeled, count, take); } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Take_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take))); Assert.All(query.Take(take).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void Take_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { Take_Unordered_NotPipelined(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Take_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Take(take).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Min(count, Math.Max(0, take)), seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void Take_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { Take_NotPipelined(labeled, count, take); } [Fact] public static void Take_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Take(0)); } // // TakeWhile // public static IEnumerable<object[]> TakeWhileData(object[] counts) { foreach (object[] results in Sources.Ranges(counts.Cast<int>())) { yield return new[] { results[0], results[1], new[] { 0 } }; yield return new[] { results[0], results[1], Enumerable.Range((int)results[1] / 2, ((int)results[1] - 1) / 2 + 1) }; yield return new[] { results[0], results[1], new[] { (int)results[1] - 1 } }; } } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take))); foreach (int i in query.TakeWhile(x => x < take)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_Unordered(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (int i in query.TakeWhile(x => x < take)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Min(count, Math.Max(0, take)), seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile(labeled, count, take); } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take))); Assert.All(query.TakeWhile(x => x < take).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_Unordered_NotPipelined(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.TakeWhile(x => x < take).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Min(count, Math.Max(0, take)), seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_NotPipelined(labeled, count, take); } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take))); foreach (int i in query.TakeWhile((x, index) => index < take)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_Indexed_Unordered(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_Indexed(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (int i in query.TakeWhile((x, index) => index < take)) { Assert.Equal(seen++, i); } Assert.Equal(Math.Min(count, Math.Max(0, take)), seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_Indexed(labeled, count, take); } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; // For unordered collections, which elements (if any) are taken isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(count, Math.Max(0, take))); Assert.All(query.TakeWhile((x, index) => index < take).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_Indexed_Unordered_NotPipelined(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.TakeWhile((x, index) => index < take).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(Math.Min(count, Math.Max(0, take)), seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_Indexed_NotPipelined(labeled, count, take); } [Theory] [MemberData("TakeUnorderedData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_AllFalse(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; Assert.Empty(query.TakeWhile(x => false)); } [Theory] [OuterLoop] [MemberData("TakeUnorderedData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_AllFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_AllFalse(labeled, count, take); } [Theory] [MemberData("TakeData", (object)(new int[] { 0, 1, 2, 16 }))] public static void TakeWhile_AllTrue(Labeled<ParallelQuery<int>> labeled, int count, int take) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.TakeWhile(x => true), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData("TakeData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_AllTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int take) { TakeWhile_AllTrue(labeled, count, take); } [Theory] [MemberData("TakeWhileData", (object)(new int[] { 2, 16 }))] public static void TakeWhile_SomeTrue(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.TakeWhile(x => take.Contains(x)), x => Assert.Equal(seen++, x)); Assert.Equal(take.Min() > 0 ? 0 : take.Max() + 1, seen); } [Theory] [OuterLoop] [MemberData("TakeWhileData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_SomeTrue_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take) { TakeWhile_SomeTrue(labeled, count, take); } [Theory] [MemberData("TakeWhileData", (object)(new int[] { 2, 16 }))] public static void TakeWhile_SomeFalse(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.TakeWhile(x => !take.Contains(x)), x => Assert.Equal(seen++, x)); Assert.Equal(take.Min(), seen); } [Theory] [OuterLoop] [MemberData("TakeWhileData", (object)(new int[] { 1024 * 32 }))] public static void TakeWhile_SomeFalse_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, IEnumerable<int> take) { TakeWhile_SomeFalse(labeled, count, take); } [Fact] public static void TakeWhile_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).TakeWhile(x => true)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().TakeWhile((Func<bool, bool>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().TakeWhile((Func<bool, int, bool>)null)); } } }
using Bridge.Test.NUnit; using System; namespace Bridge.ClientTest.BasicCSharp { internal class ClassA { // TODO Add more types public static int StatitIntNotInitialized; public static string StatitStringNotInitialized; public static int StaticInt; public static string StaticString; public const char CONST_CHAR = 'Q'; // TODO Add more to check big/small numbers, precision etc public const decimal CONST_DECIMAL = 3.123456789324324324m; // TODO Add more types public int NumberA { get; set; } public string StringA { get; set; } public bool BoolA { get; set; } public double DoubleA { get; set; } public decimal DecimalA { get; set; } private Aux1 data; public Aux1 Data { get { return data; } set { data = value; } } static ClassA() { ClassA.StaticString = "Defined string"; ClassA.StaticInt = -340; } public ClassA() { this.NumberA = 10; this.StringA = "Str"; this.BoolA = true; this.DoubleA = Double.PositiveInfinity; this.DecimalA = Decimal.MinusOne; this.Data = new Aux1() { Number = 700 }; } public ClassA(Aux1 d) : this() { if (d == null) throw new Exception("Related should not be null"); this.Data = d; } // [#89] public ClassA(params object[] p) : this() { if (p == null || p.Length < 6) { throw new Exception("Should pass six parameters"); } if (p[0] is int) { this.NumberA = (int)p[0]; } if (p[1] is string) { this.StringA = (string)p[1]; } if (p[2] is bool) { this.BoolA = (bool)p[2]; } if (p[3] is double) { this.DoubleA = (double)p[3]; } if (p[4] is decimal) { this.DecimalA = (decimal)p[4]; } if (p[5] is Aux1) { this.Data = (Aux1)p[5]; } } public ClassA.Aux1 Method1() { var a1 = new Aux1() { Number = 1 }; return new Aux1() { Number = 2, Related = a1 }; } public void Method2(ClassA.Aux1 a) { a.Related = a; } public string Method3() { if (this.Data != null) { return this.Data.ToString(); } return "no data"; } public int Method4(int i, int add) { i = i + add; return i; } public int Method5(int i = -5) { return i; } public int Method5(int i = -50, int k = -60) { return i + k; } public static ClassA StaticMethod1(int i, string s, double d) { ClassA.StatitIntNotInitialized = i; ClassA.StatitStringNotInitialized = s; return new ClassA() { DoubleA = d }; } // [#89] public static ClassA StaticMethod2(params object[] p) { var i = (int)p[0] + 1000; var s = (string)p[1]; var d = (double)p[2]; return ClassA.StaticMethod1(i, s, d); } public static bool TryParse(object o, out int i) { i = 3; return true; } public static int GetDefaultInt() { return default(int); } // due to [#73] needs priority to be generated after the parent class // [Priority(-1)] public class Aux1 { public int Number { get; set; } public Aux1 Related { get; set; } public override string ToString() { return string.Format("{0} Has related {1}", this.Number, this.Related != null ? this.Related.Number.ToString() : "No"); } } } // [#68] Multiple field declaration renders incorrectly public class Class68 { public int x, y = 1; public void Test() { // Multiple local vars correctly int x = 1, y = 2; var z = x + y; } } // Tests: // Reference type constructors, params method parameters, method overloading, nested classes, [FileName] // Full properties, short get/set properties, exceptions [Category(Constants.MODULE_BASIC_CSHARP)] [TestFixture(TestNameFormat = "Reference types - {0}")] public class TestReferenceTypes { // Check instance methods and constructors [Test(ExpectedCount = 26)] public static void TestInstanceConstructorsAndMethods() { // Check parameterless constructor var a = new ClassA(); // TEST Assert.AreEqual(10, a.NumberA, "NumberA 10"); Assert.AreEqual("Str", a.StringA, "StringA Str"); Assert.AreEqual(true, a.BoolA, "BoolA true"); Assert.True(a.DoubleA == Double.PositiveInfinity, "DoubleA Double.PositiveInfinity"); Assert.AreDeepEqual(-1m, a.DecimalA, "DecimalA Decimal.MinusOne"); Assert.True(a.Data != null, "Data not null"); Assert.AreEqual(700, a.Data.Number, "Data.Number 700"); // TEST // Check constructor with parameter Assert.Throws<Exception>(TestSet1FailureHelper.TestConstructor1Failure, "Related should not be null"); // TEST // Check constructor with parameter Assert.Throws<Exception>(TestSet1FailureHelper.TestConstructor2Failure, "Should pass six parameters"); a = new ClassA(150, "151", true, 1.53d, 1.54m, new ClassA.Aux1() { Number = 155 }); Assert.AreEqual(150, a.NumberA, "NumberA 150"); Assert.AreEqual("151", a.StringA, "StringA 151"); Assert.AreEqual(true, a.BoolA, "BoolA true"); Assert.AreEqual(1.53, a.DoubleA, "DoubleA Double.PositiveInfinity"); Assert.AreDeepEqual(1.54m, a.DecimalA, "DecimalA 154"); Assert.True(a.Data != null, "Data not null"); Assert.AreEqual(155, a.Data.Number, "Data.Number 155"); // TEST // Check instance methods var b = a.Method1(); Assert.True(b != null, "b not null"); Assert.AreEqual(2, b.Number, "b Number 2"); Assert.True(b.Related != null, "b.Related not null"); Assert.AreEqual(1, b.Related.Number, "b.Related Number 1"); a.Data = b; Assert.AreEqual("2 Has related 1", a.Method3(), "Method3 2 Has related 1"); a.Data = null; Assert.AreEqual("no data", a.Method3(), "Method3 no data"); // TEST // Check [#68] var c68 = new Class68(); Assert.AreEqual(0, c68.x, "c68.x 0"); Assert.AreEqual(1, c68.y, "c68.y 1"); // TEST // Check local vars do not get overridden by fields c68.Test(); Assert.AreEqual(0, c68.x, "c68.x 0"); Assert.AreEqual(1, c68.y, "c68.y 1"); } // Check static methods and constructor [Test(ExpectedCount = 14)] public static void TestStaticConstructorsAndMethods() { // TEST // Check static fields initialization Assert.AreEqual(0, ClassA.StatitIntNotInitialized, "#74 StatitInt not initialized"); Assert.AreEqual(null, ClassA.StatitStringNotInitialized, "#74 StatitString not initialized"); Assert.AreEqual(81, ClassA.CONST_CHAR, "#74 CONST_CHAR Q"); Assert.AreEqual(true, ClassA.CONST_DECIMAL == 3.123456789324324324m, "#74 CONST_DECIMAL 3.123456789324324324m"); // TEST // Check static constructor Assert.AreEqual(-340, ClassA.StaticInt, "StatitInt initialized"); Assert.AreEqual("Defined string", ClassA.StaticString, "StatitString initialized"); // TEST // Check static methods var a = ClassA.StaticMethod1(678, "ASD", double.NaN); Assert.AreEqual(678, ClassA.StatitIntNotInitialized, "StatitIntNotInitialized 678"); Assert.AreEqual("ASD", ClassA.StatitStringNotInitialized, "ClassA.StatitStringNotInitialized ASD"); Assert.AreDeepEqual(double.NaN, a.DoubleA, "DoubleA double.NaN"); // Adapts test for original call according to the native C# result: (#3613) Assert.Throws<System.InvalidCastException>(() => { a = ClassA.StaticMethod2((object)678, "QWE", 234); }, "Casting int to Double throws InvalidCast Exception."); // Introduces different test by issue #3613 a = ClassA.StaticMethod2((object)678, "QWE", 234.0); Assert.AreEqual(1678, ClassA.StatitIntNotInitialized, "StatitIntNotInitialized 1678"); Assert.AreEqual("QWE", ClassA.StatitStringNotInitialized, "ClassA.StatitStringNotInitialized QWE"); Assert.AreEqual(234, a.DoubleA, "DoubleA 234"); Assert.Throws<InvalidCastException>(TestSet1FailureHelper.StaticMethod2Failure, "Cast exception should occur"); } // Check default parameters, method parameters, default values [Test(ExpectedCount = 16)] public static void TestMethodParameters() { // Check default parameters var ra = new ClassA(); int r = ra.Method5(5); Assert.AreEqual(5, r, "r 5"); r = ra.Method5(i: 15); Assert.AreEqual(15, r, "r 15"); r = ra.Method5(5, 6); Assert.AreEqual(11, r, "r 11"); r = ra.Method5(k: 6); Assert.AreEqual(-44, r, "r -44"); // Check referencing did not change data var a = new ClassA(); var b = a.Method1(); var c = b.Related; a.Method2(b); Assert.True(b != null, "b not null"); Assert.AreEqual(2, b.Number, "b Number 2"); Assert.True(b.Related != null, "b.Related not null"); Assert.AreEqual(2, b.Related.Number, "b.Related Number 2"); Assert.True(c != null, "c not null"); Assert.AreEqual(1, c.Number, "c Number 1"); Assert.True(c.Related == null, "c.Related null"); // Check value local parameter var input = 1; var result = a.Method4(input, 4); Assert.AreEqual(1, input, "input 1"); Assert.AreEqual(5, result, "result 5"); // TEST // [#86] var di = ClassA.GetDefaultInt(); Assert.AreEqual(0, di, "di 0"); // TEST // Check "out parameter" // [#85] int i; var tryResult = ClassA.TryParse("", out i); Assert.True(tryResult, "tryResult"); Assert.AreEqual(3, i, "i 3"); } } public class TestSet1FailureHelper { // For testing exception throwing in constructors we need a separate method as constructors cannot be delegates public static void TestConstructor1Failure() { new ClassA((ClassA.Aux1)null); } public static void TestConstructor2Failure() { var t = new ClassA(new object[2]); } public static void StaticMethod2Failure() { ClassA.StaticMethod2("1", "some string", "345.345435"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Hangfire.Console; using Hangfire.Server; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Relisten.Api.Models; using Relisten.Data; namespace Relisten.Import { public class PhishNetImporter : ImporterBase { public const string DataSourceName = "phish.net"; private static readonly Regex PhishNetRatingScraper = new(@"Overall: (?<AverageRating>[\d.]+)\/5 \((?<VotesCast>\d+) ratings\)"); private static readonly Regex PhishNetReviewCountScraper = new(@"class='tpc-comment review'"); private readonly LinkService linkService; public PhishNetImporter( DbService db, SourceService sourceService, SourceReviewService sourceReviewService, LinkService linkService, ILogger<PhishNetImporter> log, RedisService redisService ) : base(db, redisService) { this.linkService = linkService; _sourceService = sourceService; _log = log; _sourceReviewService = sourceReviewService; } protected SourceService _sourceService { get; set; } protected SourceReviewService _sourceReviewService { get; set; } protected ILogger<PhishNetImporter> _log { get; set; } public override string ImporterName => "phish.net"; public override ImportableData ImportableDataForArtist(Artist artist) { return ImportableData.SourceRatings | ImportableData.SourceReviews | ImportableData.Sources; } public override async Task<ImportStats> ImportDataForArtist(Artist artist, ArtistUpstreamSource src, PerformContext ctx) { var stats = new ImportStats(); var shows = (await _sourceService.AllForArtist(artist)).OrderBy(s => s.display_date).ToList(); var prog = ctx?.WriteProgressBar(); ctx?.WriteLine($"Processing {shows.Count} shows"); await shows.ForEachAsync(async dbSource => { stats += await ProcessSource(artist, src, dbSource, ctx); }, prog, 1); ctx?.WriteLine("Rebuilding..."); await RebuildShows(artist); await RebuildYears(artist); return stats; } public override Task<ImportStats> ImportSpecificShowDataForArtist(Artist artist, ArtistUpstreamSource src, string showIdentifier, PerformContext ctx) { return Task.FromResult(new ImportStats()); } private string PhishNetUrlForSource(Source dbSource) { return "http://phish.net/setlists/?d=" + dbSource.display_date; } private string PhishNetApiReviewsUrlForSource(Source dbSource) { return "https://api.phish.net/api.js?api=2.0&method=pnet.reviews.query&format=json&apikey=B6570BEDA805B616AB6C&showdate=" + dbSource.display_date; } private string PhishNetApiSetlistUrlForSource(Source dbSource) { return "https://api.phish.net/api.js?api=2.0&method=pnet.shows.setlists.get&format=json&apikey=C60F490D1358FBBE31DA&showdate=" + dbSource.display_date; } private int TryParseInt(string str) { var i = 0; int.TryParse(str, out i); return i; } private double TryParseDouble(string str) { double i = 0; double.TryParse(str, out i); return i; } private async Task<PhishNetScrapeResults> ScrapePhishNetForSource(Source dbSource, PerformContext ctx) { var url = PhishNetUrlForSource(dbSource); ctx?.WriteLine($"Requesting {url}"); var resp = await http.GetAsync(url); var page = await resp.Content.ReadAsStringAsync(); var ratingMatches = PhishNetRatingScraper.Match(page); return new PhishNetScrapeResults { RatingAverage = TryParseDouble(ratingMatches.Groups["AverageRating"].Value), RatingVotesCast = TryParseInt(ratingMatches.Groups["VotesCast"].Value), NumberOfReviewsWritten = PhishNetReviewCountScraper.Matches(page).Count }; } private async Task<PhishNetApiSetlist> GetPhishNetApiSetlist(Source dbSource, PerformContext ctx) { var url = PhishNetApiSetlistUrlForSource(dbSource); ctx?.WriteLine($"Requesting {url}"); var resp = await http.GetAsync(url); var page = await resp.Content.ReadAsStringAsync(); if (page.Length == 0) { return null; } var setlists = JsonConvert.DeserializeObject<IEnumerable<PhishNetApiSetlist>>(page); return setlists.Where(setlist => setlist.artist_name == "Phish").FirstOrDefault(); } private async Task<IEnumerable<PhishNetApiReview>> GetPhishNetApiReviews(Source dbSource, PerformContext ctx) { var url = PhishNetApiReviewsUrlForSource(dbSource); ctx?.WriteLine($"Requesting {url}"); var resp = await http.GetAsync(url); var page = await resp.Content.ReadAsStringAsync(); // some shows have no reviews if (page.Length == 0 || page[0] == '{') { return new List<PhishNetApiReview>(); } return JsonConvert.DeserializeObject<IEnumerable<PhishNetApiReview>>(page); } private async Task<ImportStats> ProcessSource(Artist artist, ArtistUpstreamSource src, Source dbSource, PerformContext ctx) { var stats = new ImportStats(); var ratings = await ScrapePhishNetForSource(dbSource, ctx); var dirty = false; if (dbSource.num_ratings != ratings.RatingVotesCast) { dbSource.num_ratings = ratings.RatingVotesCast; dbSource.avg_rating = ratings.RatingAverage * 2.0; dirty = true; } if (dbSource.num_reviews != ratings.NumberOfReviewsWritten) { var reviewsTask = GetPhishNetApiReviews(dbSource, ctx); var setlistTask = GetPhishNetApiSetlist(dbSource, ctx); await Task.WhenAll(reviewsTask, setlistTask); var dbReviews = reviewsTask.Result.Select(rev => { return new SourceReview { rating = null, title = null, review = rev.review, author = rev.author, updated_at = DateTimeOffset.FromUnixTimeSeconds(rev.tstamp).UtcDateTime }; }).ToList(); dbSource.num_reviews = dbReviews.Count(); dbSource.description = setlistTask.Result.setlistnotes + "\n\n\n" + setlistTask.Result.setlistdata; dirty = true; await ReplaceSourceReviews(stats, dbSource, dbReviews); } if (dirty) { await _sourceService.Save(dbSource); stats.Updated++; } stats.Created += (await linkService.AddLinksForSource(dbSource, new[] { new Link { source_id = dbSource.id, for_ratings = true, for_source = false, for_reviews = true, upstream_source_id = src.upstream_source_id, url = PhishNetUrlForSource(dbSource), label = "View on phish.net" } })).Count(); return stats; } private async Task<IEnumerable<SourceReview>> ReplaceSourceReviews(ImportStats stats, Source source, IEnumerable<SourceReview> reviews) { foreach (var review in reviews) { review.source_id = source.id; } var res = await _sourceReviewService.UpdateAll(source, reviews); stats.Created += res.Count(); return res; } private class PhishNetScrapeResults { public double RatingAverage { get; set; } public int RatingVotesCast { get; set; } public int NumberOfReviewsWritten { get; set; } } public class PhishNetApiReview { public string commentid { get; set; } public string showdate { get; set; } public string showyear { get; set; } public string review { get; set; } public string venue { get; set; } public string city { get; set; } public string state { get; set; } public string country { get; set; } public int tstamp { get; set; } public string author { get; set; } } public class PhishNetApiSetlist { public string artist { get; set; } public string showid { get; set; } public string showdate { get; set; } public string showyear { get; set; } public string meta { get; set; } public string city { get; set; } public string state { get; set; } public string country { get; set; } public string venue { get; set; } public string setlistnotes { get; set; } public string venuenotes { get; set; } public string venueid { get; set; } public string url { get; set; } [JsonProperty("artist-name")] public string artist_name { get; set; } public string mmddyy { get; set; } public string nicedate { get; set; } public string relativetime { get; set; } public string setlistdata { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Claudy.Input; namespace Cliffhanger { public class LevelOne : Microsoft.Xna.Framework.GameComponent { //Viewport stuff RenderTarget2D topScreen; RenderTarget2D bottomScreen; int bottomOffset; //Cliff Texture2D cliffTex; Rectangle cliffRect; Vector2 offsetTop; Vector2 offsetBottom; //Screen Player stuff Vector2 p1ScreenPos, p2ScreenPos; Vector2 p1ScreenVel, p2ScreenVel; Texture2D test; Boolean screenSplit; Color p1, p2; Rectangle playerBounds; //Player Stuff Player player1; Player player2; //Platform List<Platform> platforms; Platform ground; //Rock List<Rock> rocks; //Vine List<Vine> vines; //Rock Machine RockMachine guitar; const int FINISH = -3180; public bool isCompleted; public int victorPlayerNum; //Audio Effects SoundEffect victorySound; SoundEffect jumpSound; GraphicsDevice GraphicsDevice; SpriteFont font; public LevelOne(Game game) : base(game) { } public void Initialize(GraphicsDevice gd) { jumpSound = Game.Content.Load<SoundEffect>("Jump"); GraphicsDevice = gd; topScreen = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height / 2); bottomScreen = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height / 2); offsetTop = Vector2.Zero; offsetBottom = new Vector2(0, -topScreen.Height); //Player player1 = new Player(Game, 1, jumpSound); player1.Initialize(); player1.position = new Vector2(100, 0); player2 = new Player(Game, 2, jumpSound); player2.Initialize(); player2.position = new Vector2(400, 0); //Platform platforms = new List<Platform>(); ground = new Platform(Game, -20, 400, 2000, 1000); ground.Initialize(); platforms.Add(ground); //Screen Representation of players p1ScreenPos = new Vector2(100, 20); p2ScreenPos = new Vector2(GraphicsDevice.Viewport.Width - 100, 20); p1ScreenVel = new Vector2(0, 0); p2ScreenVel = new Vector2(0, 0); //changes the screen bounds of where the player is. playerBounds = new Rectangle(0, 0, 10, 60); screenSplit = false; p1 = Color.Red; p2 = Color.Blue; //Rock rocks = new List<Rock>(); //Guitar (Rock Machine) guitar = new RockMachine(Game, 700, 200); //Vine vines = new List<Vine>(); //vines.Add(new Vine(Game, -128, 11, 0)); // (Game, Position Y, Height/32, Lane) vines.Add(new Vine(Game, 64, 10, 1)); // Ground is some where about 224 . vines.Add(new Vine(Game, 0, 8, 2)); vines.Add(new Vine(Game, -224, 22, 4)); vines.Add(new Vine(Game, -352, 10, 1)); vines.Add(new Vine(Game, -352, 5, 2)); vines.Add(new Vine(Game, -554, 3, 2)); vines.Add(new Vine(Game, -554, 4, 3)); vines.Add(new Vine(Game, -554, 7, 4)); vines.Add(new Vine(Game, -554, 14, 5)); vines.Add(new Vine(Game, -554, 4, 6)); vines.Add(new Vine(Game, -554, 2, 7)); //vines.Add(new Vine(Game, -554, 4, 8)); //vines.Add(new Vine(Game, -736, 7, 0)); vines.Add(new Vine(Game, -736, 5, 1)); vines.Add(new Vine(Game, -960, 2, 0)); vines.Add(new Vine(Game, -864, 7, 3)); vines.Add(new Vine(Game, -928, 4, 2)); vines.Add(new Vine(Game, -1056, 4, 4)); vines.Add(new Vine(Game, -992, 7, 5)); vines.Add(new Vine(Game, -1056, 4, 7)); //vines.Add(new Vine(Game, -1056, 15, 8)); //vines.Add(new Vine(Game, -1216, 3, 8)); vines.Add(new Vine(Game, -1248, 3, 7)); vines.Add(new Vine(Game, -1280, 3, 6)); vines.Add(new Vine(Game, -1344, 3, 5)); vines.Add(new Vine(Game, -1312, 3, 4)); vines.Add(new Vine(Game, -1280, 5, 3)); vines.Add(new Vine(Game, -1344, 4, 2)); vines.Add(new Vine(Game, -1280, 4, 1)); //vines.Add(new Vine(Game, -1248, 7, 0)); //After 1400 vines.Add(new Vine(Game, -1440, 2, 6)); vines.Add(new Vine(Game, -1504, 1, 2)); vines.Add(new Vine(Game, -1536, 2, 5)); vines.Add(new Vine(Game, -1568, 1, 4)); vines.Add(new Vine(Game, -1600, 1, 3)); vines.Add(new Vine(Game, -1664, 1, 4)); vines.Add(new Vine(Game, -1696, 1, 3)); vines.Add(new Vine(Game, -1824, 1, 3)); vines.Add(new Vine(Game, -1792, 1, 4)); vines.Add(new Vine(Game, -1760, 1, 4)); vines.Add(new Vine(Game, -1792, 1, 3)); vines.Add(new Vine(Game, -1760, 12, 1)); vines.Add(new Vine(Game, -1728, 9, 7)); vines.Add(new Vine(Game, -1984, 10, 6)); vines.Add(new Vine(Game, -1952, 5, 1)); //After 2000 vines.Add(new Vine(Game, -2016, 4, 4)); vines.Add(new Vine(Game, -2112, 4, 2)); vines.Add(new Vine(Game, -2176, 3, 3)); vines.Add(new Vine(Game, -2176, 3, 7)); vines.Add(new Vine(Game, -2336, 12, 6)); vines.Add(new Vine(Game, -2464, 4, 7)); vines.Add(new Vine(Game, -2464, 7, 1)); vines.Add(new Vine(Game, -2560, 11, 2)); vines.Add(new Vine(Game, -2560, 3, 6)); vines.Add(new Vine(Game, -2688, 5, 3)); vines.Add(new Vine(Game, -2720, 6, 4)); vines.Add(new Vine(Game, -2784, 4, 5)); vines.Add(new Vine(Game, -2784, 4, 7)); vines.Add(new Vine(Game, -2848, 1, 6)); vines.Add(new Vine(Game, -2944, 5, 1)); vines.Add(new Vine(Game, -2848, 3, 7)); vines.Add(new Vine(Game, -3008, 4, 2)); vines.Add(new Vine(Game, -3136, 7, 3)); vines.Add(new Vine(Game, -3136, 7, 5)); foreach (Vine vine in vines) { vine.Initialize(); } isCompleted = false; victorPlayerNum = 0; base.Initialize(); } public void LoadContent() { cliffTex = Game.Content.Load<Texture2D>("cliff"); cliffRect = new Rectangle(0, GraphicsDevice.Viewport.Height - cliffTex.Height * 2, GraphicsDevice.Viewport.Width * 2, cliffTex.Height * 2); font = Game.Content.Load<SpriteFont>("Consolas"); test = Game.Content.Load<Texture2D>("blankTex"); victorySound = Game.Content.Load<SoundEffect>("Flashpoint001"); } public void reset() { offsetTop = Vector2.Zero; offsetBottom = new Vector2(0, -topScreen.Height); //Player player1 = new Player(Game, 1, jumpSound); player1.Initialize(); player1.position = new Vector2(100, 0); player2 = new Player(Game, 2, jumpSound); player2.Initialize(); player2.position = new Vector2(400, 0); //Screen Representation of players p1ScreenPos = new Vector2(100, 20); p2ScreenPos = new Vector2(GraphicsDevice.Viewport.Width - 100, 20); p1ScreenVel = new Vector2(0, 0); p2ScreenVel = new Vector2(0, 0); screenSplit = false; isCompleted = false; } public void Update(GameTime gameTime, ClaudyInput input, Rectangle titleSafeRect) { ground.Update(gameTime); #region Platform Collision foreach (Platform platform in platforms) { if (player1.vel.Y >= 0) { if (Collision.PlayerPlatformCollision(player1, platform)) { //state = PlayerState.standing; player1.canjump = true; if(!screenSplit) p1ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetTop.Y; else p1ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetBottom.Y + GraphicsDevice.Viewport.Height / 2; break; } else { //state = PlayerState.falling; player1.canjump = false; } } } foreach (Platform platform in platforms) { if (player2.vel.Y >= 0) { if (Collision.PlayerPlatformCollision(player2, platform)) { //state = PlayerState.standing; player2.canjump = true; if(!screenSplit) p2ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetTop.Y; else p2ScreenPos.Y = platform.position.Y - playerBounds.Height + offsetBottom.Y + GraphicsDevice.Viewport.Height/2; break; } else { //state = PlayerState.falling; player2.canjump = false; } } } #endregion //Platform Collision foreach (Rock r in rocks) { r.Update(gameTime, ground); } for (int i = 0; i < rocks.Count; i++) { if (!rocks[i].Enabled) // Remove any rocks deemed to be disposed of. { rocks.RemoveAt(i); } } #region Rock Machine Collision if (guitar.IsActive && (player1.hitbox.Intersects(guitar.rect) || player2.hitbox.Intersects(guitar.rect))) { Random rng = new Random(); for(int i = 0; i < 10; i++) { Rock r = new Rock(Game, (float)rng.Next(1000), -(float)rng.Next(2500), Rock.SUGGESTED_UP_R_VELOCITY, 3); rocks.Add(r); } for (int i = 0; i < 10; i++) { Rock r = new Rock(Game, (float)rng.Next(1000), -(float)rng.Next(2500), Rock.SUGGESTED_UP_L_VELOCITY, 3); rocks.Add(r); } guitar.Fired(gameTime); } guitar.Update(gameTime); #endregion #region Vine Collision foreach (Vine vine in vines) { if (Collision.PlayerVineCollision(player1, vine, gameTime) && input.GetAs8DirectionLeftThumbStick(player1.Num).Y > 0) { player1.vel.Y = -2f; player1.vel.X *= .5f; if (player1.position.Y + player1.hitbox.Height> vine.position.Y && player1.position.Y + player1.hitbox.Height < vine.position.Y + 4) { player1.vel.Y = 0; } } if (player1.vel.Y >= 0) { if (Collision.PlayerVineCollision(player1, vine, gameTime)) { //state = PlayerState.standing; player1.canjump = true; player1.vel.X *= .5f; player1.vel.Y = 0; break; } else { //state = PlayerState.falling; //player1.canjump = false; } } } foreach (Vine vine in vines) { if (Collision.PlayerVineCollision(player2, vine, gameTime) && input.GetAs8DirectionLeftThumbStick(player2.Num).Y > 0) { player2.vel.Y = -2; player2.vel.X *= .5f; if (player2.position.Y + player2.hitbox.Height > vine.position.Y && player2.position.Y + player2.hitbox.Height < vine.position.Y + 4) { player2.vel.Y = 0; } } if (player2.vel.Y >= 0) { if (Collision.PlayerVineCollision(player2, vine, gameTime)) { //state = PlayerState.standing; player2.canjump = true; player2.vel.X *= .5f; player2.vel.Y = 0; break; } else { //state = PlayerState.falling; //player1.canjump = false; } } } #endregion //Vine Collision //Player updates player1.Update(gameTime, titleSafeRect); player2.Update(gameTime, titleSafeRect); #region Throw Rocks (requires knowledge of player & of the rock list) //PLAYER 1 if (input.GamepadByID[player1.Num].Triggers.Left > 0.5f && input.PreviousGamepadByID[player1.Num].Triggers.Left <= 0.5f) { Rock r = new Rock(Game, player1.hitbox.X, player1.hitbox.Y, Rock.SUGGESTED_SIDE_L_VELOCITY, player1.Num); r.Initialize(); rocks.Add(r); } if (input.GamepadByID[player1.Num].Triggers.Right > 0.5f && input.PreviousGamepadByID[player1.Num].Triggers.Right <= 0.5f) { Rock r = new Rock(Game, player1.hitbox.X + player1.hitbox.Width, player1.hitbox.Y, Rock.SUGGESTED_SIDE_R_VELOCITY, player1.Num); r.Initialize(); rocks.Add(r); } if (input.isFirstPress(Buttons.RightShoulder, player1.Num)) { Rock r = new Rock(Game, player1.hitbox.X, player1.hitbox.Y, Rock.SUGGESTED_UP_R_VELOCITY, player1.Num); r.Initialize(); rocks.Add(r); } if (input.isFirstPress(Buttons.LeftShoulder, player1.Num)) { Rock r = new Rock(Game, player1.hitbox.X + player1.hitbox.Width, player1.hitbox.Y, Rock.SUGGESTED_UP_L_VELOCITY, player1.Num); r.Initialize(); rocks.Add(r); } //PLAYER 2 if (input.GamepadByID[player2.Num].Triggers.Left > 0.5f && input.PreviousGamepadByID[player2.Num].Triggers.Left <= 0.5f) { Rock r = new Rock(Game, player2.hitbox.X, player2.hitbox.Y, Rock.SUGGESTED_SIDE_L_VELOCITY, player2.Num); r.Initialize(); rocks.Add(r); } if (input.GamepadByID[player2.Num].Triggers.Right > 0.5f && input.PreviousGamepadByID[player2.Num].Triggers.Right <= 0.5f) { Rock r = new Rock(Game, player2.hitbox.X + player2.hitbox.Width, player2.hitbox.Y, Rock.SUGGESTED_SIDE_R_VELOCITY, player2.Num); r.Initialize(); rocks.Add(r); } if (input.isFirstPress(Buttons.RightShoulder, player2.Num)) { Rock r = new Rock(Game, player2.hitbox.X, player2.hitbox.Y, Rock.SUGGESTED_UP_R_VELOCITY, player2.Num); r.Initialize(); rocks.Add(r); } if (input.isFirstPress(Buttons.LeftShoulder, player2.Num)) { Rock r = new Rock(Game, player2.hitbox.X + player2.hitbox.Width, player2.hitbox.Y, Rock.SUGGESTED_UP_L_VELOCITY, player2.Num); r.Initialize(); rocks.Add(r); } #endregion p1ScreenVel.Y = -player1.vel.Y; p2ScreenVel.Y = -player2.vel.Y; p1ScreenPos.Y -= p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; p2ScreenPos.Y -= p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; #region splitScreen Movement if (p1ScreenPos.Y < titleSafeRect.Y + 20) { p1ScreenPos.Y = titleSafeRect.Y + 20; offsetTop.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; if (p2ScreenPos.Y > titleSafeRect.Height - playerBounds.Height - 5) { screenSplit = true; } if (!screenSplit) { p2ScreenPos.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; offsetBottom.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; } } if (p2ScreenPos.Y < titleSafeRect.Y + 20) { p2ScreenPos.Y = titleSafeRect.Y + 20; offsetTop.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; if (p1ScreenPos.Y > titleSafeRect.Height - playerBounds.Height - 5 && !screenSplit) { screenSplit = true; } if (!screenSplit) { p1ScreenPos.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; offsetBottom.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; } } else if (p2ScreenPos.Y > titleSafeRect.Height - playerBounds.Height) { offsetBottom.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; p2ScreenPos.Y = titleSafeRect.Height - playerBounds.Height; if (p1ScreenPos.Y < titleSafeRect.Y && !screenSplit) { screenSplit = true; } if (!screenSplit) { p1ScreenPos.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; offsetTop.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; } } if (p1ScreenPos.Y > titleSafeRect.Height - playerBounds.Height) { offsetBottom.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; p1ScreenPos.Y = titleSafeRect.Height - playerBounds.Height; if (p2ScreenPos.Y < titleSafeRect.Y && !screenSplit) { screenSplit = true; } if (!screenSplit) { p2ScreenPos.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; offsetTop.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; } } if (screenSplit) { if (p1ScreenPos.Y > GraphicsDevice.Viewport.Height / 2 - playerBounds.Height && p1ScreenPos.Y < GraphicsDevice.Viewport.Height / 2) { p1ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 - playerBounds.Height; offsetTop.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2) screenSplit = false; } if (p2ScreenPos.Y > GraphicsDevice.Viewport.Height / 2 - playerBounds.Height && p2ScreenPos.Y < GraphicsDevice.Viewport.Height / 2) { p2ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 - playerBounds.Height; offsetTop.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2) screenSplit = false; } if (p2ScreenPos.Y < GraphicsDevice.Viewport.Height / 2 + playerBounds.Height && p2ScreenPos.Y > GraphicsDevice.Viewport.Height / 2) { p2ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 + playerBounds.Height; offsetBottom.Y += p2ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2) screenSplit = false; } if (p1ScreenPos.Y < GraphicsDevice.Viewport.Height / 2 + playerBounds.Height && p1ScreenPos.Y > GraphicsDevice.Viewport.Height / 2) { p1ScreenPos.Y = GraphicsDevice.Viewport.Height / 2 + playerBounds.Height; offsetBottom.Y += p1ScreenVel.Y * gameTime.ElapsedGameTime.Milliseconds / 10f; if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2) screenSplit = false; } } if (offsetTop.Y <= offsetBottom.Y + GraphicsDevice.Viewport.Height / 2) { screenSplit = false; offsetBottom.Y = offsetTop.Y - GraphicsDevice.Viewport.Height / 2; } #endregion #region Rock Collisions foreach (Rock r in rocks) { if (Collision.PlayerRockCollision(player1, r)) { continue; } else { Collision.PlayerRockCollision(player2, r); } } #endregion // Rock Collisions if (player1.position.Y <= FINISH || player2.position.Y <= FINISH) { victorySound.Play(); isCompleted = true; if (player1.position.Y < player2.position.Y) victorPlayerNum = 1; else if (player2.position.Y < player1.position.Y) victorPlayerNum = 2; } base.Update(gameTime); } public void Draw(SpriteBatch spriteBatch) { //Draw stuff in the top renderTarget GraphicsDevice.SetRenderTarget(topScreen); GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null); // TODO: Change to LinearWrap before submitting to Dr. Birmingham. #region Top Viewport { spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, cliffRect.Y + (int)offsetTop.Y, cliffRect.Width, cliffRect.Height), Color.White); //Vines foreach (Vine vine in vines) { vine.Draw(spriteBatch, offsetTop); } spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, -3160 + (int)offsetTop.Y, cliffRect.Width, 3), Color.LawnGreen); guitar.Draw(spriteBatch, offsetTop); player1.Draw(spriteBatch, offsetTop); player2.Draw(spriteBatch, offsetTop); ground.Draw(spriteBatch, offsetTop); foreach (Rock r in rocks) { r.Draw(spriteBatch, offsetTop); } } #endregion //Top Viewport spriteBatch.End(); //Draw stuff in the bottom renderTarget; Use an offset GraphicsDevice.SetRenderTarget(bottomScreen); GraphicsDevice.Clear(Color.Gray); spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null); bottomOffset = GraphicsDevice.Viewport.Height; #region Bottom Viewport { spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, cliffRect.Y + (int)offsetBottom.Y, cliffRect.Width, cliffRect.Height), Color.White); //Vines foreach (Vine vine in vines) { vine.Draw(spriteBatch, offsetBottom); } spriteBatch.Draw(cliffTex, new Rectangle(cliffRect.X, -3160 + (int)offsetBottom.Y, cliffRect.Width, 3), Color.LawnGreen); guitar.Draw(spriteBatch, offsetBottom); player1.Draw(spriteBatch, offsetBottom); player2.Draw(spriteBatch, offsetBottom); ground.Draw(spriteBatch, offsetBottom); foreach (Rock r in rocks) { r.Draw(spriteBatch, offsetBottom); } } #endregion //Bottom Viewport spriteBatch.End(); //Draw the renderTargets GraphicsDevice.SetRenderTarget(null); spriteBatch.Begin(); spriteBatch.Draw(topScreen, new Vector2(0, 0), Color.White); spriteBatch.Draw(bottomScreen, new Vector2(0, GraphicsDevice.Viewport.Height / 2), Color.White); //Debugging draw statements //spriteBatch.Draw(test, new Rectangle((int)p1ScreenPos.X, (int)p1ScreenPos.Y, playerBounds.Width, playerBounds.Height), p1); //spriteBatch.Draw(test, new Rectangle((int)p2ScreenPos.X, (int)p2ScreenPos.Y, playerBounds.Width, playerBounds.Height), p2); //spriteBatch.DrawString(font, "bool: " + player1.canjump.ToString(), new Vector2(0, 0), Color.Black); //spriteBatch.DrawString(font, "bool: " + player1.vel.ToString(), new Vector2(0, 50), Color.Orange); //spriteBatch.DrawString(font, player1.position.Y.ToString(), new Vector2(0f, 200f), Color.Yellow); spriteBatch.End(); } } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors using System; using System.Linq; using Generator.Enums; using Generator.Enums.CSharp; using Generator.IO; using Generator.Tables; namespace Generator.Encoder.CSharp { [Generator(TargetLanguage.CSharp)] sealed class CSharpEncoderGenerator : EncoderGenerator { readonly IdentifierConverter idConverter; readonly CSharpEnumsGenerator enumGenerator; public CSharpEncoderGenerator(GeneratorContext generatorContext) : base(generatorContext.Types) { idConverter = CSharpIdentifierConverter.Create(); enumGenerator = new CSharpEnumsGenerator(generatorContext); } protected override void Generate(EnumType enumType) => enumGenerator.Generate(enumType); protected override void Generate((EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] legacy, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] vex, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] xop, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] evex) { GenerateOpCodeOperandKindTables(legacy, vex, xop, evex); GenerateOpTables(legacy, vex, xop, evex); } void GenerateOpCodeOperandKindTables((EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] legacy, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] vex, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] xop, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] evex) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.EncoderNamespace, "OpCodeOperandKinds.g.cs"); using (var writer = new FileWriter(TargetLanguage.CSharp, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); writer.WriteLineNoIndent($"#if {CSharpConstants.OpCodeInfoDefine}"); writer.WriteLine($"namespace {CSharpConstants.EncoderNamespace} {{"); using (writer.Indent()) { writer.WriteLine("static class OpCodeOperandKinds {"); using (writer.Indent()) { Generate(writer, "LegacyOpKinds", null, legacy); Generate(writer, "VexOpKinds", CSharpConstants.VexDefine, vex); Generate(writer, "XopOpKinds", CSharpConstants.XopDefine, xop); Generate(writer, "EvexOpKinds", CSharpConstants.EvexDefine, evex); } writer.WriteLine("}"); } writer.WriteLine("}"); writer.WriteLineNoIndent("#endif"); } void Generate(FileWriter writer, string name, string? define, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] table) { var declTypeStr = genTypes[TypeIds.OpCodeOperandKind].Name(idConverter); if (define is not null) writer.WriteLineNoIndent($"#if {define}"); writer.WriteLineNoIndent($"#if {CSharpConstants.HasSpanDefine}"); writer.WriteLine($"public static System.ReadOnlySpan<byte> {name} => new byte[{table.Length}] {{"); writer.WriteLineNoIndent("#else"); writer.WriteLine($"public static readonly byte[] {name} = new byte[{table.Length}] {{"); writer.WriteLineNoIndent("#endif"); using (writer.Indent()) { foreach (var info in table) writer.WriteLine($"(byte){declTypeStr}.{info.opCodeOperandKind.Name(idConverter)},"); } writer.WriteLine("};"); if (define is not null) writer.WriteLineNoIndent("#endif"); } } void GenerateOpTables((EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] legacy, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] vex, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] xop, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] evex) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.EncoderNamespace, "OpTables.g.cs"); using (var writer = new FileWriter(TargetLanguage.CSharp, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); writer.WriteLineNoIndent($"#if {CSharpConstants.EncoderDefine}"); writer.WriteLine($"namespace {CSharpConstants.EncoderNamespace} {{"); using (writer.Indent()) { writer.WriteLine("static class OpHandlerData {"); using (writer.Indent()) { Generate(writer, "LegacyOps", null, legacy); Generate(writer, "VexOps", CSharpConstants.VexDefine, vex); Generate(writer, "XopOps", CSharpConstants.XopDefine, xop); Generate(writer, "EvexOps", CSharpConstants.EvexDefine, evex); } writer.WriteLine("}"); } writer.WriteLine("}"); writer.WriteLineNoIndent("#endif"); } void Generate(FileWriter writer, string name, string? define, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] table) { var declTypeStr = genTypes[TypeIds.OpCodeOperandKind].Name(idConverter); if (table[0].opHandlerKind != OpHandlerKind.None) throw new InvalidOperationException(); if (define is not null) writer.WriteLineNoIndent($"#if {define}"); writer.WriteLine($"public static readonly Op[] {name} = new Op[{table.Length - 1}] {{"); using (writer.Indent()) { for (int i = 1; i < table.Length; i++) { var info = table[i]; writer.Write("new "); writer.Write(info.opHandlerKind.ToString()); writer.Write("("); var ctorArgs = info.args; for (int j = 0; j < ctorArgs.Length; j++) { if (j > 0) writer.Write(", "); switch (ctorArgs[j]) { case EnumValue value: writer.Write($"{value.DeclaringType.Name(idConverter)}.{value.Name(idConverter)}"); break; case int value: writer.Write(value.ToString()); break; case bool value: writer.Write(value ? "true" : "false"); break; default: throw new InvalidOperationException(); } } writer.WriteLine("),"); } } writer.WriteLine("};"); if (define is not null) writer.WriteLineNoIndent("#endif"); } } protected override void GenerateOpCodeInfo(InstructionDef[] defs) => GenerateTable(defs); void GenerateTable(InstructionDef[] defs) { var allData = GetData(defs).ToArray(); var encFlags1 = allData.Select(a => (a.def, a.encFlags1)).ToArray(); var encFlags2 = allData.Select(a => (a.def, a.encFlags2)).ToArray(); var encFlags3 = allData.Select(a => (a.def, a.encFlags3)).ToArray(); var opcFlags1 = allData.Select(a => (a.def, a.opcFlags1)).ToArray(); var opcFlags2 = allData.Select(a => (a.def, a.opcFlags2)).ToArray(); var encoderInfo = new (string name, (InstructionDef def, uint value)[] values)[] { ("EncFlags1", encFlags1), ("EncFlags2", encFlags2), ("EncFlags3", encFlags3), }; var opCodeInfo = new (string name, (InstructionDef def, uint value)[] values)[] { ("OpcFlags1", opcFlags1), ("OpcFlags2", opcFlags2), }; GenerateTables(defs, encoderInfo, CSharpConstants.EncoderDefine, "EncoderData", "EncoderData.g.cs"); GenerateTables(defs, opCodeInfo, CSharpConstants.OpCodeInfoDefine, "OpCodeInfoData", "OpCodeInfoData.g.cs"); } void GenerateTables(InstructionDef[] defs, (string name, (InstructionDef def, uint value)[] values)[] tableData, string define, string className, string filename) { var fullFilename = CSharpConstants.GetFilename(genTypes, CSharpConstants.EncoderNamespace, filename); using (var writer = new FileWriter(TargetLanguage.CSharp, FileUtils.OpenWrite(fullFilename))) { writer.WriteFileHeader(); writer.WriteLineNoIndent($"#if {define}"); writer.WriteLine($"namespace {CSharpConstants.EncoderNamespace} {{"); using (writer.Indent()) { writer.WriteLine($"static class {className} {{"); using (writer.Indent()) { foreach (var info in tableData) writer.WriteLine($"internal static readonly uint[] {info.name} = Get{info.name}();"); foreach (var info in tableData) { writer.WriteLine(); writer.WriteLine($"static uint[] Get{info.name}() =>"); using (writer.Indent()) { writer.WriteLine($"new uint[{defs.Length}] {{"); using (writer.Indent()) { foreach (var vinfo in info.values) writer.WriteLine($"0x{vinfo.value:X8},// {vinfo.def.Code.Name(idConverter)}"); } writer.WriteLine("};"); } } } writer.WriteLine("}"); } writer.WriteLine("}"); writer.WriteLineNoIndent("#endif"); } } protected override void Generate((EnumValue value, uint size)[] immSizes) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.IcedNamespace, "Encoder.cs"); new FileUpdater(TargetLanguage.CSharp, "ImmSizes", filename).Generate(writer => { writer.WriteLine($"static readonly uint[] s_immSizes = new uint[{immSizes.Length}] {{"); using (writer.Indent()) { foreach (var info in immSizes) writer.WriteLine($"{info.size},// {info.value.Name(idConverter)}"); } writer.WriteLine("};"); }); } void GenerateCases(string filename, string id, EnumValue[] codeValues, params string[] statements) { new FileUpdater(TargetLanguage.CSharp, id, filename).Generate(writer => { if (codeValues.Length == 0) return; foreach (var value in codeValues) writer.WriteLine($"case {value.DeclaringType.Name(idConverter)}.{value.Name(idConverter)}:"); using (writer.Indent()) { foreach (var statement in statements) writer.WriteLine(statement); if (!statements[^1].StartsWith("return ", StringComparison.Ordinal)) writer.WriteLine("break;"); } }); } void GenerateNotInstrCases(string filename, string id, (EnumValue code, string result)[] notInstrStrings) { new FileUpdater(TargetLanguage.CSharp, id, filename).Generate(writer => { foreach (var info in notInstrStrings) writer.WriteLine($"{info.code.DeclaringType.Name(idConverter)}.{info.code.Name(idConverter)} => \"{info.result}\","); }); } protected override void GenerateInstructionFormatter((EnumValue code, string result)[] notInstrStrings) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.EncoderNamespace, "InstructionFormatter.cs"); GenerateNotInstrCases(filename, "InstrFmtNotInstructionString", notInstrStrings); } protected override void GenerateOpCodeFormatter((EnumValue code, string result)[] notInstrStrings, EnumValue[] hasModRM, EnumValue[] hasVsib) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.EncoderNamespace, "OpCodeFormatter.cs"); GenerateNotInstrCases(filename, "OpCodeFmtNotInstructionString", notInstrStrings); GenerateCases(filename, "HasModRM", hasModRM, "return true;"); GenerateCases(filename, "HasVsib", hasVsib, "return true;"); } protected override void GenerateCore() { } protected override void GenerateInstrSwitch(EnumValue[] jccInstr, EnumValue[] simpleBranchInstr, EnumValue[] callInstr, EnumValue[] jmpInstr, EnumValue[] xbeginInstr) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.BlockEncoderNamespace, "Instr.cs"); GenerateCases(filename, "JccInstr", jccInstr, "return new JccInstr(blockEncoder, block, instruction);"); GenerateCases(filename, "SimpleBranchInstr", simpleBranchInstr, "return new SimpleBranchInstr(blockEncoder, block, instruction);"); GenerateCases(filename, "CallInstr", callInstr, "return new CallInstr(blockEncoder, block, instruction);"); GenerateCases(filename, "JmpInstr", jmpInstr, "return new JmpInstr(blockEncoder, block, instruction);"); GenerateCases(filename, "XbeginInstr", xbeginInstr, "return new XbeginInstr(blockEncoder, block, instruction);"); } protected override void GenerateVsib(EnumValue[] vsib32, EnumValue[] vsib64) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.IcedNamespace, "Instruction.cs"); GenerateCases(filename, "Vsib32", vsib32, "vsib64 = false;", "return true;"); GenerateCases(filename, "Vsib64", vsib64, "vsib64 = true;", "return true;"); } protected override void GenerateDecoderOptionsTable((EnumValue decOptionValue, EnumValue decoderOptions)[] values) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.IcedNamespace, "OpCodeInfo.cs"); new FileUpdater(TargetLanguage.CSharp, "ToDecoderOptionsTable", filename).Generate(writer => { foreach (var (_, decoderOptions) in values) writer.WriteLine($"{decoderOptions.DeclaringType.Name(idConverter)}.{decoderOptions.Name(idConverter)},"); }); } protected override void GenerateImpliedOps((EncodingKind Encoding, InstrStrImpliedOp[] Ops, InstructionDef[] defs)[] impliedOpsInfo) { var filename = CSharpConstants.GetFilename(genTypes, CSharpConstants.EncoderNamespace, "InstructionFormatter.cs"); new FileUpdater(TargetLanguage.CSharp, "PrintImpliedOps", filename).Generate(writer => { foreach (var info in impliedOpsInfo) { var feature = CSharpConstants.GetDefine(info.Encoding); if (feature is not null) writer.WriteLineNoIndent($"#if {feature}"); foreach (var def in info.defs) writer.WriteLine($"case {def.Code.DeclaringType.Name(idConverter)}.{def.Code.Name(idConverter)}:"); using (writer.Indent()) { foreach (var op in info.Ops) { writer.WriteLine("WriteOpSeparator();"); writer.WriteLine($"Write(\"{op.Operand}\", upper: {(op.IsUpper ? "true" : "false")});"); } writer.WriteLine("break;"); } if (feature is not null) writer.WriteLineNoIndent("#endif"); } }); } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.Content; using Android.Content.Res; using Android.Database; using Android.Provider; using InstantMessaging = Android.Provider.ContactsContract.CommonDataKinds.Im; using OrganizationData = Android.Provider.ContactsContract.CommonDataKinds.Organization; using Uri = Android.Net.Uri; using WebsiteData = Android.Provider.ContactsContract.CommonDataKinds.Website; namespace Xamarin.Contacts { internal static class ContactHelper { internal static void FillContactExtras( Boolean rawContact, ContentResolver content, Resources resources, String recordId, Contact contact ) { ICursor c = null; String column = (rawContact) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; try { c = content.Query( ContactsContract.Data.ContentUri, null, column + " = ?", new[] {recordId}, null ); if(c == null) { return; } while(c.MoveToNext()) { FillContactWithRow( resources, contact, c ); } } finally { if(c != null) { c.Close(); } } } internal static Address GetAddress( ICursor c, Resources resources ) { Address a = new Address(); a.Country = c.GetString( ContactsContract.CommonDataKinds.StructuredPostal.Country ); a.Region = c.GetString( ContactsContract.CommonDataKinds.StructuredPostal.Region ); a.City = c.GetString( ContactsContract.CommonDataKinds.StructuredPostal.City ); a.PostalCode = c.GetString( ContactsContract.CommonDataKinds.StructuredPostal.Postcode ); AddressDataKind kind = (AddressDataKind)c.GetInt( c.GetColumnIndex( ContactsContract.CommonDataKinds.CommonColumns.Type ) ); a.Type = kind.ToAddressType(); a.Label = (kind != AddressDataKind.Custom) ? ContactsContract.CommonDataKinds.StructuredPostal.GetTypeLabel( resources, kind, String.Empty ) : c.GetString( ContactsContract.CommonDataKinds.CommonColumns.Label ); String street = c.GetString( ContactsContract.CommonDataKinds.StructuredPostal.Street ); String pobox = c.GetString( ContactsContract.CommonDataKinds.StructuredPostal.Pobox ); if(street != null) { a.StreetAddress = street; } if(pobox != null) { if(street != null) { a.StreetAddress += Environment.NewLine; } a.StreetAddress += pobox; } return a; } internal static Contact GetContact( Boolean rawContact, ContentResolver content, Resources resources, ICursor cursor ) { String id = (rawContact) ? cursor.GetString( cursor.GetColumnIndex( ContactsContract.RawContactsColumns.ContactId ) ) : cursor.GetString( cursor.GetColumnIndex( ContactsContract.ContactsColumns.LookupKey ) ); var contact = new Contact( id, !rawContact, content ) { DisplayName = GetString( cursor, ContactsContract.ContactsColumns.DisplayName ) }; FillContactExtras( rawContact, content, resources, id, contact ); return contact; } internal static IEnumerable<Contact> GetContacts( Boolean rawContacts, ContentResolver content, Resources resources ) { Uri curi = (rawContacts) ? ContactsContract.RawContacts.ContentUri : ContactsContract.Contacts.ContentUri; ICursor cursor = null; try { cursor = content.Query( curi, null, null, null, null ); if(cursor == null) { yield break; } foreach(Contact contact in GetContacts( cursor, rawContacts, content, resources, 20 )) { yield return contact; } } finally { if(cursor != null) { cursor.Close(); } } } internal static IEnumerable<Contact> GetContacts( ICursor cursor, Boolean rawContacts, ContentResolver content, Resources resources, Int32 batchSize ) { if(cursor == null) { yield break; } String column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; String[] ids = new String[batchSize]; Int32 columnIndex = cursor.GetColumnIndex( column ); HashSet<String> uniques = new HashSet<String>(); Int32 i = 0; while(cursor.MoveToNext()) { if(i == batchSize) { i = 0; foreach(Contact c in GetContacts( rawContacts, content, resources, ids )) { yield return c; } } String id = cursor.GetString( columnIndex ); if(uniques.Contains( id )) { continue; } uniques.Add( id ); ids[i++] = id; } if(i > 0) { foreach(Contact c in GetContacts( rawContacts, content, resources, ids.Take( i ).ToArray() )) { yield return c; } } } internal static IEnumerable<Contact> GetContacts( Boolean rawContacts, ContentResolver content, Resources resources, String[] ids ) { ICursor c = null; String column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; var whereb = new StringBuilder(); for(Int32 i = 0; i < ids.Length; i++) { if(i > 0) { whereb.Append( " OR " ); } whereb.Append( column ); whereb.Append( "=?" ); } Int32 x = 0; var map = new Dictionary<String, Contact>( ids.Length ); try { Contact currentContact = null; c = content.Query( ContactsContract.Data.ContentUri, null, whereb.ToString(), ids, ContactsContract.ContactsColumns.LookupKey ); if(c == null) { yield break; } Int32 idIndex = c.GetColumnIndex( column ); Int32 dnIndex = c.GetColumnIndex( ContactsContract.ContactsColumns.DisplayName ); while(c.MoveToNext()) { String id = c.GetString( idIndex ); if(currentContact == null || currentContact.Id != id) { // We need to yield these in the original ID order if(currentContact != null) { if(currentContact.Id == ids[x]) { yield return currentContact; x++; } else { map.Add( currentContact.Id, currentContact ); } } currentContact = new Contact( id, !rawContacts, content ) {DisplayName = c.GetString( dnIndex )}; } FillContactWithRow( resources, currentContact, c ); } if(currentContact != null) { map.Add( currentContact.Id, currentContact ); } for(; x < ids.Length; x++) { Contact tContact = null; if(map.TryGetValue( ids[x], out tContact )) { yield return tContact; } } } finally { if(c != null) { c.Close(); } } } internal static Email GetEmail( ICursor c, Resources resources ) { Email e = new Email(); e.Address = c.GetString( ContactsContract.DataColumns.Data1 ); EmailDataKind ekind = (EmailDataKind)c.GetInt( c.GetColumnIndex( ContactsContract.CommonDataKinds.CommonColumns.Type ) ); e.Type = ekind.ToEmailType(); e.Label = (ekind != EmailDataKind.Custom) ? ContactsContract.CommonDataKinds.Email.GetTypeLabel( resources, ekind, String.Empty ) : c.GetString( ContactsContract.CommonDataKinds.CommonColumns.Label ); return e; } internal static InstantMessagingAccount GetImAccount( ICursor c, Resources resources ) { InstantMessagingAccount ima = new InstantMessagingAccount(); ima.Account = c.GetString( ContactsContract.CommonDataKinds.CommonColumns.Data ); //IMTypeDataKind imKind = (IMTypeDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type)); //ima.Type = imKind.ToInstantMessagingType(); //ima.Label = InstantMessaging.GetTypeLabel (resources, imKind, c.GetString (CommonColumns.Label)); IMProtocolDataKind serviceKind = (IMProtocolDataKind)c.GetInt( c.GetColumnIndex( InstantMessaging.Protocol ) ); ima.Service = serviceKind.ToInstantMessagingService(); ima.ServiceLabel = (serviceKind != IMProtocolDataKind.Custom) ? InstantMessaging.GetProtocolLabel( resources, serviceKind, String.Empty ) : c.GetString( InstantMessaging.CustomProtocol ); return ima; } internal static Note GetNote( ICursor c, Resources resources ) { return new Note {Contents = GetString( c, ContactsContract.DataColumns.Data1 )}; } internal static Organization GetOrganization( ICursor c, Resources resources ) { Organization o = new Organization(); o.Name = c.GetString( OrganizationData.Company ); o.ContactTitle = c.GetString( OrganizationData.Title ); OrganizationDataKind d = (OrganizationDataKind)c.GetInt( c.GetColumnIndex( ContactsContract.CommonDataKinds.CommonColumns.Type ) ); o.Type = d.ToOrganizationType(); o.Label = (d != OrganizationDataKind.Custom) ? OrganizationData.GetTypeLabel( resources, d, String.Empty ) : c.GetString( ContactsContract.CommonDataKinds.CommonColumns.Label ); return o; } internal static Phone GetPhone( ICursor c, Resources resources ) { Phone p = new Phone(); p.Number = GetString( c, ContactsContract.CommonDataKinds.Phone.Number ); PhoneDataKind pkind = (PhoneDataKind)c.GetInt( c.GetColumnIndex( ContactsContract.CommonDataKinds.CommonColumns.Type ) ); p.Type = pkind.ToPhoneType(); p.Label = (pkind != PhoneDataKind.Custom) ? ContactsContract.CommonDataKinds.Phone.GetTypeLabel( resources, pkind, String.Empty ) : c.GetString( ContactsContract.CommonDataKinds.CommonColumns.Label ); return p; } internal static Relationship GetRelationship( ICursor c, Resources resources ) { Relationship r = new Relationship {Name = c.GetString( ContactsContract.CommonDataKinds.Relation.Name )}; RelationDataKind rtype = (RelationDataKind)c.GetInt( c.GetColumnIndex( ContactsContract.CommonDataKinds.CommonColumns.Type ) ); switch(rtype) { case RelationDataKind.DomesticPartner: case RelationDataKind.Spouse: case RelationDataKind.Friend: r.Type = RelationshipType.SignificantOther; break; case RelationDataKind.Child: r.Type = RelationshipType.Child; break; default: r.Type = RelationshipType.Other; break; } return r; } //internal static WebsiteType ToWebsiteType (this WebsiteDataKind websiteKind) //{ // switch (websiteKind) // { // case WebsiteDataKind.Work: // return WebsiteType.Work; // case WebsiteDataKind.Home: // return WebsiteType.Home; // default: // return WebsiteType.Other; // } //} internal static String GetString( this ICursor c, String colName ) { return c.GetString( c.GetColumnIndex( colName ) ); } internal static Website GetWebsite( ICursor c, Resources resources ) { Website w = new Website(); w.Address = c.GetString( WebsiteData.Url ); //WebsiteDataKind kind = (WebsiteDataKind)c.GetInt (c.GetColumnIndex (CommonColumns.Type)); //w.Type = kind.ToWebsiteType(); //w.Label = (kind != WebsiteDataKind.Custom) // ? resources.GetString ((int) kind) // : c.GetString (CommonColumns.Label); return w; } internal static AddressType ToAddressType( this AddressDataKind addressKind ) { switch(addressKind) { case AddressDataKind.Home: return AddressType.Home; case AddressDataKind.Work: return AddressType.Work; default: return AddressType.Other; } } internal static EmailType ToEmailType( this EmailDataKind emailKind ) { switch(emailKind) { case EmailDataKind.Home: return EmailType.Home; case EmailDataKind.Work: return EmailType.Work; default: return EmailType.Other; } } internal static InstantMessagingService ToInstantMessagingService( this IMProtocolDataKind protocolKind ) { switch(protocolKind) { case IMProtocolDataKind.Aim: return InstantMessagingService.Aim; case IMProtocolDataKind.Msn: return InstantMessagingService.Msn; case IMProtocolDataKind.Yahoo: return InstantMessagingService.Yahoo; case IMProtocolDataKind.Jabber: return InstantMessagingService.Jabber; case IMProtocolDataKind.Icq: return InstantMessagingService.Icq; case IMProtocolDataKind.Skype: return InstantMessagingService.Skype; case IMProtocolDataKind.GoogleTalk: return InstantMessagingService.Google; case IMProtocolDataKind.Qq: return InstantMessagingService.QQ; default: return InstantMessagingService.Other; } } internal static OrganizationType ToOrganizationType( this OrganizationDataKind organizationKind ) { switch(organizationKind) { case OrganizationDataKind.Work: return OrganizationType.Work; default: return OrganizationType.Other; } } internal static PhoneType ToPhoneType( this PhoneDataKind phoneKind ) { switch(phoneKind) { case PhoneDataKind.Home: return PhoneType.Home; case PhoneDataKind.Mobile: return PhoneType.Mobile; case PhoneDataKind.FaxHome: return PhoneType.HomeFax; case PhoneDataKind.Work: return PhoneType.Work; case PhoneDataKind.FaxWork: return PhoneType.WorkFax; case PhoneDataKind.Pager: case PhoneDataKind.WorkPager: return PhoneType.Pager; default: return PhoneType.Other; } } private static void FillContactWithRow( Resources resources, Contact contact, ICursor c ) { String dataType = c.GetString( c.GetColumnIndex( ContactsContract.DataColumns.Mimetype ) ); switch(dataType) { case ContactsContract.CommonDataKinds.Nickname.ContentItemType: contact.Nickname = c.GetString( c.GetColumnIndex( ContactsContract.CommonDataKinds.Nickname.Name ) ); break; case ContactsContract.CommonDataKinds.StructuredName.ContentItemType: contact.Prefix = c.GetString( ContactsContract.CommonDataKinds.StructuredName.Prefix ); contact.FirstName = c.GetString( ContactsContract.CommonDataKinds.StructuredName.GivenName ); contact.MiddleName = c.GetString( ContactsContract.CommonDataKinds.StructuredName.MiddleName ); contact.LastName = c.GetString( ContactsContract.CommonDataKinds.StructuredName.FamilyName ); contact.Suffix = c.GetString( ContactsContract.CommonDataKinds.StructuredName.Suffix ); break; case ContactsContract.CommonDataKinds.Phone.ContentItemType: contact.phones.Add( GetPhone( c, resources ) ); break; case ContactsContract.CommonDataKinds.Email.ContentItemType: contact.emails.Add( GetEmail( c, resources ) ); break; case ContactsContract.CommonDataKinds.Note.ContentItemType: contact.notes.Add( GetNote( c, resources ) ); break; case OrganizationData.ContentItemType: contact.organizations.Add( GetOrganization( c, resources ) ); break; case ContactsContract.CommonDataKinds.StructuredPostal.ContentItemType: contact.addresses.Add( GetAddress( c, resources ) ); break; case InstantMessaging.ContentItemType: contact.instantMessagingAccounts.Add( GetImAccount( c, resources ) ); break; case WebsiteData.ContentItemType: contact.websites.Add( GetWebsite( c, resources ) ); break; case ContactsContract.CommonDataKinds.Relation.ContentItemType: contact.relationships.Add( GetRelationship( c, resources ) ); break; } } //internal static InstantMessagingType ToInstantMessagingType (this IMTypeDataKind imKind) //{ // switch (imKind) // { // case IMTypeDataKind.Home: // return InstantMessagingType.Home; // case IMTypeDataKind.Work: // return InstantMessagingType.Work; // default: // return InstantMessagingType.Other; // } //} } }